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.
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
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
Now convert the image into a gray scale for better results.
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
Now apply the threshold on gray scale image according to your selected image.
ret,thresh_img = cv2.threshold(gray,127,255,0)
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)
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)
To display the image in a specified window use ”imshow” function.
“waitKey(0)” will display a window until any key is pressed. “destroyAllWindows()” will destroy all the windows that we created.