Canny edge detection
Introduction to cannny algorithm
Non-maximum suppression: When obtaining the gradient and direction, remove all points that are not boundaries.
Realization direction: Gradually traverse the pixels to determine whether the current pixel is the maximum value with the same gradient in the surrounding pixels. It is reserved, otherwise it is 0.
The cannny code implements
edges=cv2.Canny(image,threshold1,threshold2)
edges: processing result
image: original image
threshold1:minVal
threshold2:maxVal
If you want more boundary details, set threshold1 and threshold2 smaller.
code show as below:
import cv2 as cv
import numpy as np
def edge_demo(image):
blurred = cv.GaussianBlur(image, (3, 3), 0)#为什么要GaussianBlur?
#因为blur可以降低噪声,Canny算法对噪声敏感,降噪之后效果要好,也不能模糊太厉害,去掉了边缘信息。
gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY)
#X Gradient
xgrad = cv.Sobel(gray, cv.CV_16SC1, 1, 0) #x和y方向的结果
# Y Gradient
ygrad = cv.Sobel(gray, cv.CV_16SC1, 0, 1)
#edge
edge_output = cv.Canny(xgrad, ygrad, 50, 150)#低阈值50.高阈值150
#或者直接用cv.Canny
#edge_output = cv.Canny(gray, 50, 150)#低阈值50.高阈值150
cv.imshow("Canny Edge", edge_output)
dst = cv.bitwise_and(image, image, mask=edge_output)
cv.imshow("Color Edge", dst)
src = cv.imread("C:/Users/lenovo/Desktop/opencv/daima/banknum/template-matching-ocr/images/lena.jpg") #读取图片位置
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
edge_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()
Run screenshot:
first calculate the gradient and then use the Canny algorithm
Use Canny algorithm without calculating gradient
blurred = cv.GaussianBlur(image, (3, 3), 0)#Gaussian Blur, reduce noise. Canny is more sensitive to noise, and can't blur too much, removing edge information.
edge_output = cv.Canny(xgrad, ygrad, 50, 150)
#edge_output = cv.Canny(gray, 50, 150)
is the same The
high threshold should be 3 times the low threshold