How to find patterns in a chessboard using OpenCV Python?


We could find chessboard corners in an image using cv2.findChessboardCorners() and to draw the chessboard corners with a pattern, we could use cv2.drawChessboardCorners(). Look at the below syntaxes for these two methods −

ret, corners = cv2.findChessboardCorners(img, patterSize, None)
cv2.drawChessboardCorners(img, patternSize, corners,ret)

Steps

To find the patterns in a chessboard, you can use the steps given below −

  • Import the required library. In all the following examples, the required Python library is OpenCV. Make sure you have already installed it.

  • Read the input image of a chessboard using cv2.imread() and convert it to grayscale using cv2.cvtColor().

  • Find the chessboard corners in a chessboard image using cv2.findChessboardCorners(). It returns two output parameters ret and corners. The ret is True if the chessboard corners are detected in the image. The corners are the coordinates of the detected chessboard corners in (x,y) format.

  • Draw the chessboard corners and pattern on the original input image using cv2.drawChessboardCorners()

  • Display the image with the drawn chessboard pattern,

Let's have a look at some examples for more clear understanding.

Input Image

We will use this image as an input file in the examples below.


Example

In this Python program, we find the patterns in the input image.

# import required libraries import cv2 # read input image img = cv2.imread('left01.jpg') # convert the input image to a grayscale gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv2.findChessboardCorners(gray, (7,6),None) # if chessboard corners are detected if ret == True: # Draw and display the corners img = cv2.drawChessboardCorners(img, (7,6), corners,ret) cv2.imshow('Chessboard',img) cv2.waitKey(0) cv2.destroyAllWindows()

When we execute the above code, it will produce the following output window −


Example

In this Python program, we will see how to solve the same problem in a different way −

# import required libraries import cv2 # read input image img = cv2.imread('left01.jpg') # convert the input image to a grayscale gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv2.findChessboardCorners(gray, (7,6),None) # terminating criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) if ret == True: corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria) # Draw and display the corners img = cv2.drawChessboardCorners(img, (7,6), corners,ret) cv2.imshow('Chessboard',img) cv2.waitKey(0) cv2.destroyAllWindows()

On execution, it will produce the following output


Updated on: 05-Dec-2022

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements