# coding=utf-8
import cv2
import numpy as np
imput0="W:/PY/WDPY/ceshi/sswhd (5).jpg"
img = cv2.imread( imput0, 0 )
img = cv2.GaussianBlur( img, (3, 3), 0 )
#高斯平滑处理原图像降噪
canny = cv2.Canny( img, 20, 100 )
#canny算子处理调用Canny函数,指定阈值
cv2.imshow( 'Canny', canny )
cv2.waitKey( 0 )
cv2.destroyAllWindows()
另外可以自定义函数,不过运行CannyAlogrithm(img,30,50)报错,出现不知道什么问题,。嘿嘿,未完待续
def CannyAlogrithm(image,MINThreshold,MAXThreshold):
image = GaussianSmooth(image)
Gx = SobelAlogrithm(image,"horizontal")
Gy = SobelAlogrithm(image,"vertical")
G = np.sqrt(np.square(Gx.astype(np.float64))+np.square(Gy.astype(np.float64)))
G = G*(255/np.max(G)).astype(np.uint8)
cita = np.arctan2(Gy.astype(np.float64),Gx.astype(np.float64))
nms_image = NonmaximumSuppression(G,cita)
nms_image = (nms_image*(255/np.max(nms_image))).astype(np.uint8)
usemap = np.zeros(nms_image.shape)
high_list = []
for i in range(nms_image.shape[0]):
for j in range(nms_image.shape[1]):
if nms_image[i,j]>MAXThreshold:
high_list.append((i,j))
direct = [(0,1),(1,1),(-1,1),(-1,-1),(1,-1),(1,0),(-1,0),(0,-1)]
def DFS(stepmap,start):
route = [start]
while route:
now = route.pop()
if usemap[now] == 1:
break
usemap[now] = 1
for dic in direct:
next_coodinate = (now[0]+dic[0],now[1]+dic[1])
if next_coodinate[0]<stepmap.shape[0]-1 and next_coodinate[0]>=0 \
and next_coodinate[1]<stepmap.shape[1]-1 and next_coodinate[1]>=0 \
and not usemap[next_coodinate] and nms_image[next_coodinate]>MINThreshold:
route.append(next_coodinate)
for i in high_list:
DFS(nms_image,i)
return nms_image*usemap