How to Draw Contours in OpenCV Python

You can draw contours in OpenCV Python by following the given steps. I highly recommend you get the “Computer Vision: Models, Learning, and Inference Book” to learn Computer Vision.

How to Draw Contours in OpenCV Python
How to Draw Contours in OpenCV Python

Step 1

Import the OpenCV library. If OpenCV is not installed in your system then first install it using This Method.

import cv2 
#cv2 is used for OpenCV library

Step 2

Now read the image from the location. In my case “C:\\AiHints” is the location and “black2.jpg” is the name of the image. Change it according to your image location and name.

image = cv2.imread("C:\\AiHints\\black2.jpg")
#imread is use to read an image from a location
Original Image

Step 3

Now convert the image into a gray scale for better results.

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

Step 4

Now apply the threshold on gray scale image according to your selected image.

ret,thresh_img = cv2.threshold(gray,127,255,0)

Step 5

In this step, apply the cv2.findcontours function on the thresh image to find all the boundary points of the object.

contours, hierarchy = cv2.findContours(thresh_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

Step 6

Now draw the all the contours on the original image. The third value -1 is for drawing all the contours. The forth value is for color selection i.e. red in this code. At the end, 3 is for the thickness of the boundary. You can change color and thickness according to your requirement.

#If third value is -1, all contours are drawn.
contours_img = cv2.drawContours(image,contours,-1,(0,0,255),3)

Step 7

To display the image in a specified window use ”imshow” function.

cv2.imshow("Contours Image",contours_img)

Step 8

“waitKey(0)” will display a window until any key is pressed. “destroyAllWindows()” will destroy all the windows that we created.

cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Contours on Image using OpenCV

Leave a Comment

Your email address will not be published.