非极大值抑制算法实现,参考这位博主的:
https://blog.csdn.net/qq_45717425/article/details/120641010
import cv2
import numpy as np
import matplotlib.pyplot as plt
def NMS(grad,gradx,grady):
[h,w]=np.shape(grad)
weight=np.zeros((h,w))
result=np.zeros((h,w))
grad1 =np.zeros((h,w))
grad2 =np.zeros((h,w))
grad3 =np.zeros((h,w))
grad4 =np.zeros((h,w))
gradTemp1 =np.zeros((h,w))
gradTemp2 =np.zeros((h,w))
#留出一圈像素进行缓冲
for i in range(2,h-1):
for j in range(2,w-1):
if grad[i,j]==0:
result[i,j]=0
else:
if abs(grady[i,j]>gradx[i,j]):
weight[i,j]=gradx[i,j]/grady[i,j]
grad2[i,j]=grad[i-1,j]
grad4[i,j]=grad[i+1,j]
if grady[i,j]*gradx[i,j]>0:
grad1[i,j]=grad[i-1,j-1]
grad3[i,j]=grad[i+1,j+1]
else:
grad1[i,j]=grad[i-1,j+1]
grad3[i,j]=grad[i+1,j-1]
else:
weight[i,j]=grady[i,j]/gradx[i,j]
grad2[i,j]=grad[i,j-1]
grad4[i,j]=grad[i,j+1]
if grady[i,j]*gradx[i,j]>0:
grad1[i,j]=grad[i-1,j-1]
grad3[i,j]=grad[i+1,j+1]
else:
grad1[i,j]=grad[i+1,j-1]
grad3[i,j]=grad[i-1,j+1]
gradTemp1[i,j]= weight[i,j]*grad1[i,j]+(1-weight[i,j])*grad2[i,j]
gradTemp2[i,j]=weight[i,j]*grad3[i,j]+(1-weight[i,j])*grad4[i,j]
if grad[i,j] >= gradTemp1[i,j] and grad[i,j] >= gradTemp2[i,j]:
result[i,j] = grad[i,j]
else:
result[i,j] =0
return result
附上手动sobel代码
#纯手搓sobel
def sobel_filter2(img):
sp = img.shape
height = sp[0]
weight = sp[1]
sx = np.array([[-1,0,1],[-2,0,2],[-1,0,1]])
sy = np.array([[-1,-2,-1],[0,0,0],[1,2,1]])
dSobel = np.zeros((height,weight))
Gx = np.zeros(img.shape)
Gy = np.zeros(img.shape)
for i in range(height-2):
for j in range(weight-2):
Gx[i + 1, j + 1] = abs(np.sum(img[i:i + 3, j:j + 3] * sx))
Gy[i + 1, j + 1] = abs(np.sum(img[i:i + 3, j:j + 3] * sy))
dSobel[i+1, j+1] =np.sqrt(Gx[i+1, j+1]**2+Gy[i+1, j+1]**2)
return dSobel,Gx,Gy
调用函数运行
img = cv2.imread(r"C:\Users\Cosine\Desktop\175.jpg", cv2.IMREAD_GRAYSCALE)
grad,gradx,grady= sobel_filter2(img)
NMSfigure=NMS(grad,gradx,grady)
sobel=np.array(grad,dtype=np.uint8)
NMSfigure=np.array(NMSfigure,dtype=np.uint8)
cv2.imshow('Original Image', img)
cv2.imshow('sobel', sobel)
cv2.imshow('NMSfigure', NMSfigure)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果