Canny边缘检测算法的流程如下所示:
在某一角度范围内,我们将这一范围内的最大值保留,其余的都置为0.
代码如下:
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
def show(img):
if img.ndim == 2:
plt.imshow(img,cmap='gray')
else:
plt.imshow(cv.cvtColor(img,cv.COLOR_RGB2BGR))
plt.show()
img = cv.imread('E:/DataSolve/sc.jpg',0)
#编程实现Canny算法
#1. 平滑
img_blur = cv.GaussianBlur(img,(5,5),2)
#2. 计算梯度
gradX = cv.Sobel(img,cv.CV_64F,1,0)
gradY = cv.Sobel(img,cv.CV_64F,0,1)
R = np.abs(gradX)+np.abs(gradY)
T = np.arctan(gradY/(gradX+1e-3))#计算角度
#3.细化边缘
h,w = R.shape
img_thin = np.zeros_like(R)#生成和R一样的,但是里面全是0的矩阵
for i in range(1,h-1):
for j in range(1,w-1):
theta = T[i,j]
if -np.pi/8 <= theta< np.pi/8:
if R[i,j] == max([R[i,j],R[i,j-1],R[i,j+1]]):
img_thin[i,j]=R[i,j]
elif -3*np.pi / 8 <= theta <-np.pi / 8:
if R[i,j] == max([R[i,j],R[i-1,j+1],R[i+1,j-1]]):
img_thin[i,j]=R[i,j]
elif np.pi / 8 <= theta < 3*np.pi / 8:
if R[i,j] == max([R[i,j],R[i-1,j-1],R[i+1,j+1]]):
img_thin[i,j]=R[i,j]
else:
if R[i,j] == max([R[i,j],R[i-1,j],R[i+1,j]]):
img_thin[i, j] = R[i, j]
#4. 双阈值抑制
th1 = 10
th2 = 50
h,w = img_thin.shape
img_edge = np.zeros_like(img_thin,dtype=np.uint8)
for i in range(1,h-1):
for j in range(1,w-1):
if img_thin[i,j]>=th2:
img_edge[i,j]=255
elif img_thin[i,j]>th1:
around = img_thin[i-1:i+2,j-1:j+2]
if(around.max()>= th2):
img_edge[i,j]=255
show(np.hstack([img,img_edge]))
效果不是那么尽如人意,一方面是参数设置问题,另一方面就是opencv中封装的方法是经过优化的,而我们自己实现的,则有些“粗糙”。不过思想是正确的,缺的就是方法上的改进。