How to detect contours in an Image in Python using OpenCV – easy project – 2022

In today’s blog, we will see that how we can detect contours in an image using the cv2 module. Talking about contouring it is a very useful operation when our use case involves geological terrain images or studying weather maps, etc.

Let’s do it…

Step 1 – Importing required packages.

import cv2
import matplotlib.pyplot as plt

Step 2 – Let’s read the image….

img = cv2.imread('contours.png')
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

Here we are reading the image and just converting it from BGR to RGB.

Our original image

Step 3 – Convert it to grayscale for thresholding.

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

You might be thinking that why are we converting it to Grayscale when it’s already gray. The answer is that it might look like it is gray but it is still having 3 channels (R, G, B), and as we know that grayscale images have only 1 channel that’s why we need to convert it to grayscale.

Step 4 – Thresholding the image to detect contours.

ret, thresh = cv2.threshold(gray, 125, 255, 0)

For finding the contours we have to threshold the image so that it is completely converted to a binary image.

Step 5 – Let’s detect contours…

Syntax: cv2.findContours(src, contour_retrieval, contours_approximation)

Parameters:

srcInput Image of n – dimensional array(n = 2,3) but preferred 2-dim binary images for better result.
contour_retrievalThis is contour retrieval mode. Possible values are :
a) cv2.RETR_TREE
b) cv2.RETR_EXTERNAL
c) cv2.RETR_LIST
d) cv2.RETR_CCOMP etc.
contours_approximationThis is the contour approximation method. Possible values are :
a) cv2.CHAIN_APPROX_NONE
b) cv2.CHAIN_APPROX_SIMPLE
c) cv2.CHAIN_APPROX_TC89_L1
d) cv2.CHAIN_APPROX_TC89_KCOS
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

NOTE: You can read more about hierarchy here.

Step 6 – Lets draw these contours on our original image.

copy_img = img.copy()
cv2.drawContours(copy_img,contours,-1,(0,0,255),2)
  • We will be making a copy of our original image using img.copy() to draw contours on that copy image so that our original image is preserved.
  • To draw contours we use cv2.drawContours() method. The first argument represents the image source, the second argument represents the contours that should be passed as a Python list, the third argument is used as an index of Contours, and other arguments are used for color thickness.

Step 7 – Finally let’s plot the results.

titles = ['original','contours']
imgs = [img, copy_img]
for i in range (2):
    plt.subplot(1,2,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.title(titles[i])
    plt.imshow(imgs[i])
plt.show()
detect contours
Final results…

Note: Here blue color depicts the contours.

Lets see the whole code…

import cv2
import matplotlib.pyplot as plt

img = cv2.imread('contours.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

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

ret, thresh = cv2.threshold(gray, 125, 255, 0)

# detect contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

copy_img = img.copy()
cv2.drawContours(copy_img, contours, -1, (0, 0, 255), 2)

titles = ['original', 'contours']
imgs = [img, copy_img]

for i in range(2):
    plt.subplot(1, 2, i+1)
    plt.xticks([])
    plt.yticks([])
    plt.title(titles[i])
    plt.imshow(imgs[i])
plt.show()

Do let me know if there’s any query regarding how to detect contours by contacting me on email or LinkedIn.

So this is all for this blog folks, thanks for reading it and I hope you are taking something with you after reading this and till the next time ?…

Read my previous post: HOW TO PLOT COLOR CHANNELS HISTOGRAM OF AN IMAGE IN PYTHON USING OPENCV

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projectsFlask projects at machinelearningprojects.net.

Leave a Comment

Your email address will not be published.