Canny边缘检测
cannny算法介绍
非极大值抑制:在获得梯度和方向,去除所有不是边界的点。
实现方向:逐渐遍历像素点,判断当前像素点是否是周围像素点中具有相同方向梯度的最大值。是保留,不是则为0.
cannny代码实现
edges=cv2.Canny(image,threshold1,threshold2)
edges:处理结果
image:原始图像
threshold1:minVal
threshold2:maxVal
如果想让边界细节更多,则把threshold1和threshold2设小些。
代码如下:
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()
运行截图:
先计算梯度 后使用Canny算法
不计算梯度 直接使用Canny算法
blurred = cv.GaussianBlur(image, (3, 3), 0)#高斯模糊,降低噪声。canny对噪声比较敏感,也不能模糊太厉害,去掉了边缘信息。
edge_output = cv.Canny(xgrad, ygrad, 50, 150)
#edge_output = cv.Canny(gray, 50, 150)
是相同的
高阈值应该是低阈值的3倍