Shape Detection

Learn to detect shapes.

In this lesson, we’ll learn to detect shapes. It’ll help us find different types of shapes in our image. It can be used for data collection in scientific and various other fields.

First, we need to convert our image to grayscale. Converting the image to grayscale is really important, because it helps us find the edges properly. We use the edge detection algorithm to detect edges, along with the retrieval algorithm to detect shapes:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Convert to a canny image

To convert an image to a Canny image, we use the cv2.Canny() function of the OpenCv library. This function requires three parameters:

  • The first parameter is the input image. - The second parameter is the minimum value of the intensity gradient, and the third parameter is the maximum value of the intensity gradient.
  • The third parameter is the maximum value of the intensity gradient.
imgCanny = cv2.Canny(gray,50,50)

This function converts the image to black and white, highlighting the edges of the contours. It makes the work of the contour retrieval algorithm easier.

Detect shapes

To detect shapes, we use the cv2.findContours() function of the OpenCV library. This function requires three parameters, which are listed below:

  • The first parameter is the Canny image.

  • The second parameter is the mode to find the contours. We use cv2.RETR_EXTERNAL to find the external contours. It is one of the mode of contour retrieval algorithm. It is used to retrieve only the outer contours.

  • The third parameter is the contour approximation method. For this, we use cv2.CHAIN_APPROX_NONE. It stores all the contours found by our retrieval algorithm.

contours,hierarchy = cv2.findContours(imgCanny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

Shapes are detected by the retrieval algorithms, which look for the edges in the canny image to detect the shapes.

Note: All the shapes detected will be stored inside the contours variable. We use this variable to draw the contours.

Draw contours

To draw contours, we use the cv2.drawContours() function of the OpenCV library. We need to give five parameters to the function—they are listed below:

  • img is the image on which we want to draw contours.
  • cnt is the contours that we detected using the cv2.findContours() function.
  • contourindex is the number of contours we want to draw. For example, if we only want to draw the third contour, we give the value 2. In this example, we enter the value -1 because we want to draw all the contours.
  • blueColor adds blue color to the contours.
  • thickness is the thickness of the contours.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy