python实现canny边缘检测算法
时间: 2023-09-30 11:12:13 浏览: 149
Canny边缘检测是一种经典的图像边缘检测算法,下面是Python实现代码:
```python
import cv2
import numpy as np
# 读取图片
img = cv2.imread('image.jpg')
# 灰度化处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 高斯平滑滤波
gaussian = cv2.GaussianBlur(gray, (5, 5), 0)
# 计算梯度
sobelx = cv2.Sobel(gaussian, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(gaussian, cv2.CV_64F, 0, 1, ksize=3)
mag = np.sqrt(sobelx**2 + sobely**2)
mag = np.uint8(mag)
# 非极大值抑制
height, width = mag.shape
non_max = np.zeros((height, width), dtype=np.uint8)
for i in range(1, height - 1):
for j in range(1, width - 1):
if sobelx[i, j] == 0:
tangent = 1e5
else:
tangent = sobely[i, j] / sobelx[i, j]
if mag[i, j] >= mag[i-1, j-1] * tangent and mag[i, j] >= mag[i+1, j+1] * tangent:
non_max[i, j] = 255
elif mag[i, j] >= mag[i-1, j] and mag[i, j] >= mag[i+1, j]:
non_max[i, j] = 255
elif mag[i, j] >= mag[i, j-1] * tangent and mag[i, j] >= mag[i, j+1] * tangent:
non_max[i, j] = 255
elif mag[i, j] >= mag[i, j-1] and mag[i, j] >= mag[i, j+1]:
non_max[i, j] = 255
# 双阈值和连接边缘
weak = 75
strong = 255
result = np.zeros((height, width), dtype=np.uint8)
result[mag > weak] = 1
result[mag > strong] = 255
for i in range(1, height - 1):
for j in range(1, width - 1):
if result[i, j] == 1:
if result[i-1, j-1] == 255 or result[i-1, j] == 255 or result[i-1, j+1] == 255 or result[i, j-1] == 255 or result[i, j+1] == 255 or result[i+1, j-1] == 255 or result[i+1, j] == 255 or result[i+1, j+1] == 255:
result[i, j] = 255
else:
result[i, j] = 0
# 显示图片
cv2.imshow('Canny Edge Detection', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
以上代码中使用了OpenCV库实现了Canny边缘检测算法,其中包括灰度化处理、高斯平滑滤波、计算梯度、非极大值抑制、双阈值和连接边缘等步骤,最终结果显示在窗口中。
阅读全文