Get Image Contour Using cv2.findContours() in Python OpenCV

In this tutorial, we will introduce how to use python opencv cv2.findContours() to get image contour.

Tutorial to Get Image Contour Using cv2.findContours() in Python OpenCV

1.Read an image

import cv2
img = cv2.imread('py1.jpg')

2.Convert image to grayscale  image

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

3.Find the threshold

retval, thresh = cv2.threshold(gray_img, 127, 255, 0)
img_contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

4.Draw the contours on the image using drawContours()

cv2.drawContours(img, img_contours, -1, (0, 255, 0))

5.Display image

cv2.imshow('Image Contours', img)
cv2.waitKey(0)

Get Image Contour Using cv2.findContours() in Python OpenCV

If you plan to detect the contour shape, you can read:

Detect Polygon Shape in Image Using OpenCV in Python