Python OpenCV cv2 Find Contours in Image

OpenCV – Contours of Image

Contour in image is an outline on the objects present in the image. The significance of the objects depend on the requirement and threshold you choose.

In this tutorial, we shall learn how to find contours in an image, using Python OpenCV library.

Step to find contours in an image

To find contours in an image, follow these steps:

  1. Read image as grey scale image.
  2. Use cv2.threshold() function to obtain the threshold image.
  3. Use cv2.findContours() and pass the threshold image and necessary parameters.
  4. findContours() returns contours. You can draw it on the original image or a blank image.

Examples

1. Find contours in given image

In this example, we will take the following image and apply the above said steps to find the contours.

Input Image

Python OpenCV cv2 Find Contours in Image

In this example, we will write the contours to a new binary image.

Python Program

import cv2
import numpy as np

img = cv2.imread('D:/original.png', cv2.IMREAD_UNCHANGED)

# Convert img to grey
img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# Set a thresh
thresh = 100

# Get threshold image
ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)

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

# Create an empty image for contours
img_contours = np.zeros(img.shape)

# Draw the contours on the empty image
cv2.drawContours(img_contours, contours, -1, (0,255,0), 3)

# Save image
cv2.imwrite('D:/contours.png',img_contours)
Copy

Output Image

Python OpenCV - Find Contours in Image - cv2.findContours()

In the above python program, we have taken a threshold value of 100. If you change the threshold, the contours also change. Let us take threshold value as 128 and see the result.

Python OpenCV - Find Contours in Image - cv2.findContours()

Based on the color distribution and characteristics of your source image, you have to choose a threshold value.

Summary

In this Python OpenCV Tutorial, we learned how to find contours in image using Python OpenCV library.

Code copied to clipboard successfully 👍