canny python实现
时间: 2023-09-06 14:09:04 浏览: 82
Canny边缘检测是一种常用的边缘检测算法,Python实现如下:
```python
import cv2
import numpy as np
# 读取图像
img = cv2.imread('image.jpg', 0)
# 高斯滤波
img = cv2.GaussianBlur(img, (3,3), 0)
# 计算梯度
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
mag, ang = cv2.cartToPolar(gx, gy, angleInDegrees=True)
# 非极大值抑制
rows, cols = img.shape
for i in range(1, rows - 1):
for j in range(1, cols - 1):
if (ang[i, j] <= 22.5 and ang[i, j] > -22.5) or (ang[i, j] > 157.5 and ang[i, j] <= -157.5):
if mag[i, j] >= mag[i, j-1] and mag[i, j] >= mag[i, j+1]:
img[i, j] = mag[i, j]
else:
img[i, j] = 0
elif (ang[i, j] > 22.5 and ang[i, j] <= 67.5) or (ang[i, j] > -157.5 and ang[i, j] <= -112.5):
if mag[i, j] >= mag[i-1, j-1] and mag[i, j] >= mag[i+1, j+1]:
img[i, j] = mag[i, j]
else:
img[i, j] = 0
elif (ang[i, j] > 67.5 and ang[i, j] <= 112.5) or (ang[i, j] > -112.5 and ang[i, j] <= -67.5):
if mag[i, j] >= mag[i-1, j] and mag[i, j] >= mag[i+1, j]:
img[i, j] = mag[i, j]
else:
img[i, j] = 0
elif (ang[i, j] > 112.5 and ang[i, j] <= 157.5) or (ang[i, j] > -67.5 and ang[i, j] <= -22.5):
if mag[i, j] >= mag[i-1, j+1] and mag[i, j] >= mag[i+1, j-1]:
img[i, j] = mag[i, j]
else:
img[i, j] = 0
# 双阈值处理
high_threshold = np.max(img) * 0.8
low_threshold = high_threshold * 0.5
rows, cols = img.shape
for i in range(rows):
for j in range(cols):
if img[i, j] >= high_threshold:
img[i, j] = 255
elif img[i, j] <= low_threshold:
img[i, j] = 0
else:
img[i, j] = 50
# 滞后阈值处理
img = cv2.Canny(img, 50, 150)
# 显示图像
cv2.imshow('Canny Edge Detection', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
以上代码中,先读取图像,然后进行高斯滤波,接着计算梯度、进行非极大值抑制、双阈值处理和滞后阈值处理,最后显示图像。
阅读全文