What is Canny edge detection

Canny edge detection is a kind of edge detection method using multistage edge detection algorithm. This method was published by John F. Canny in 1986.

Canny edge detection is mainly divided into four steps:

(1) Denoising. Noise will affect the accuracy of edge detection, so the noise should be filtered out first.

(2) Calculate the amplitude and direction of the gradient

(3) Non-maximum inhibition, that is, make the edge “thin” appropriately.

(4) Determine the edge. A double threshold algorithm is used to determine the final edge information.

In the actual image edge detection, we usually first use gaussian filter to remove image noise (1), then calculate the amplitude and Angle of the gradient (2), and then traverse the pixel points in the image to remove all non-edge points (3). Finally, the virtual edge generated by noise is removed to obtain the final edge information. (4)

In OpenCV, it provides the cv2.canny () function for Canny edge detection, which is fully defined as follows:

def Canny(image, threshold1, threshold2, edges=None, apertureSize=None, L2gradient=None) :
Copy the code

Image: 8-bit input image

Threshold1: indicates the first threshold during processing

Threshold2: Indicates the second threshold during processing

Edges: calculated images of edges

ApertureSize: apertureSize of the Sobel filter

L2gradient: identifies the image gradient amplitude. It is a Boolean type and defaults to False. If True, the more accurate L2 norm is used for the calculation, which is the sum of the squares of the derivatives in both directions. Otherwise, the L1 norm (directly adding the absolute values of the derivatives in both directions) is used. The mathematical formula is as follows:

Gets the edges of the image

Now that we know the definition of the method and how it is implemented. Next, let’s get the edge information of the image through a program. The specific code is as follows:

import cv2

img = cv2.imread("4.jpg", cv2.IMREAD_UNCHANGED)
result1=cv2.Canny(img,100.200)
result2=cv2.Canny(img,30.90)
cv2.imshow("img", img)
cv2.imshow("result1", result1)
cv2.imshow("result2", result2)
cv2.waitKey()
cv2.destroyAllWindows()
Copy the code

After running, the result is as shown in the figure below:

It can be seen that the image information obtained by Canny edge detection is almost the same as the effect achieved by the separation of the cool character contour of Douyin. Yes, in fact, douyin’s cool character contour separation effects can be achieved using Canny edge detection.