Contour Detection with OpenCV (Canny Edge Detector) in Python

What do the image contours mean?

Perhaps this is the first query that many of you have. A contour in an image is an outline of visible objects. Usually, boundary pixels with the same color and intensity are referred to as a certain contour. It’s quite simple to locate and draw contours in images using OpenCV. The cv2.Canny function in OpenCV has already done the implementation for us.

In this tutorial, we will learn how to locate and draw contours in Python using OpenCV (Canny Edge Detector,  a multi-step technique designed to detect the edges of any image input).

The canny edge detector includes the following features, which you can read about in more detail here.

  1. Gaussian smoothing
  2. calculating the gradient’s direction and magnitude
  3. Non-maxima suppression
  4. Double thresholding
  5. Edge tracking through hysteresis

So, let’s get this tutorial started…

First and foremost, make sure that you have imported all of the necessary Python packages.

#import necessary modules
import cv2
import numpy as np

We’ll now use cv2.findContours() to extract the contours from the thresholded image. Find the greatest area contour next.

def getContours(img):
    contours,_ = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area>500:
            cv2.drawContours(imgContours,cnt,-1,(255,0,0),4)
            peri = cv2.arcLength(cnt,True)
            approx = cv2.approxPolyDP(cnt,0.02*peri,True)
            objCor = len(approx)
            x, y, w, h = cv2.boundingRect(approx)
            
         
            cv2.rectangle(imgContours,(x,y),(x+w,y+h),(0,255,0),2)

Load the image first, then begin preprocessing. We almost always want to apply edge detection to a single channel, grayscale image. Grayscale image guarantees that there won’t be as much noise during the edge detection procedure, which will make canny detection easier.

#reading the image
img = cv2.imread('image.jpg')
imgContours = img.copy()
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#Canny edge detection can be used to detect edges in an RGB image by separating the Red, Green, and Blue channels and then merging the results back together
imgCanny = cv2.Canny(imgGray,100,100)
getContours(imgCanny)

img_hor = np.hstack((imgGray,imgCanny))


#Show the result
cv2.imshow('Shapes',img_hor)
cv2.waitKey(0)

It’s all finished, yay! Let us have a look at the results.

So, we have successfully spotted contours with the canny edge detector. We hope you found this tutorial helpful.

 

 

Leave a Reply

Your email address will not be published.