Sunday 17 December 2023

OpenCV: Detect edges using Canny edge detector

‘cv2.Canny’ method is used to detect the edge in a digital image using Canny edge detector algorithm.

Signature

edges = cv2.Canny(image, lowerThreshold, upperThreshold[, edges[, apertureSize[, L2gradient]]])

 

Following table summarizes the parameters of Canny method.

 

Parameter

Description

image

Input image

lowerThreshold and upperThreshold

a.   Pixels with gradient values below lowerThreshold are considered non-edges, and

b.   pixels with gradient values above upperThreshold are considered strong edges.

c.    Pixels with gradient values between lowerThreshold and upperThreshold are considered weak edges and are included if they are connected to strong edges.

edges

It is an optional parameter, represents output image where the detected edges are stored

apertureSize

It is an optional parameter, represent the size of the Sobel kernel used to find the intensity gradient.

L2gradient

It is an optional boolean parameter. If it is set to True, then a more accurate L2-norm gradient calculation should be used. It is set to False by default

 

Example

canny = cv.Canny(image, 120, 150)

 

How to choose lower and upper values in Canny method?

Choosing the right threshold values for the Canny edge detection method is an important step in the process. A higher threshold will result in fewer edges being detected, while a lower threshold will result in more edges being detected. In general,

a.   you can start with lower threshold values and increase them gradually until you are satisfied with the result.

b.   Use a higher upper threshold if you want to detect strong edges only.

c.    Use a lower upper threshold if you want to detect weak edges as well.

d.   Use a higher lower threshold if you want to reduce noise in the output image.

e.   Use a lower lower threshold if you want to detect even faint edges.

 

canny_edge_detection.py

import cv2 as cv

image = cv.imread('gateway_of_india.png')
cv.imshow('Original image', image)

canny = cv.Canny(image, 120, 150)
cv.imshow('Original image with threshold 120 and 150', canny)

canny = cv.Canny(image, 120, 400)
cv.imshow('Original image with threshold 120 and 400', canny)

cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

 

Output

Original Image

 


 

Edges with thresholds 120 and 150

 


Edges with thresholds 120 and 400

 


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment