In this post on Edge Detection Using OpenCV, I will explain an important image processing function known as edge detection. Basically, edge detection results in a new image that contains the outlines or edges of the given image.
Canny Edge Detection Method
Basically, Canny Edge Detection is a step-by-step procedure that requires the image to be converted into grayscale first. In short, the Canny Edge Detection method follows the steps mentioned below.
- At first, a 5X5 Gaussian Filter performs the noise reduction. As a result, we get a smoothened image.
- After that, the Intensity Gradient of the image is determined.
- Once we get the magnitude and direction of the gradient, all unwanted pixels that do not constitute the edge are removed. Hence, we get the resulting image with thin edges.
- Finally, Hysteresis Thresholding is performed to determine which ones are the actual edges. For this purpose, this method requires two values of threshold – minVal and maxVal. While the edges with an intensity gradient more than the value of maxVal are the actual edges. On the other hand, it discards all those edges whose intensity gradient is lower than the value of minVal.
Example of Edge Detection Using OpenCV Using Canny Edge Detection Method
As an illustration, first, we retrieve the image using imread() method of OpenCV. Further, we convert it into a grayscale image using the cvtColor() method. Finally, we call the Canny() method by providing the grayscale image and the values of two thresholds.
import cv2 import numpy as np import matplotlib.pyplot as plt mypic=cv2.imread("f3.png") plt.imshow(mypic) plt.show() graypic=cv2.cvtColor(mypic, cv2.COLOR_BGR2GRAY) plt.imshow(graypic, cmap="gray") plt.show() detected=cv2.Canny(graypic, 10, 110) plt.imshow(detected, cmap="gray") plt.show()