使用python实现canny边缘算法
时间: 2023-07-31 07:04:35 浏览: 52
好的,以下是使用Python实现Canny边缘算法的代码:
```python
import cv2
# 读取图片
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# 高斯滤波
img_blur = cv2.GaussianBlur(img, (3, 3), 0)
# 计算梯度
sobelx = cv2.Sobel(img_blur, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(img_blur, cv2.CV_64F, 0, 1, ksize=3)
grad = cv2.sqrt(cv2.addWeighted(cv2.pow(sobelx, 2.0), 1.0, cv2.pow(sobely, 2.0), 1.0, 0.0))
# 非极大值抑制
gradient_direction = cv2.phase(sobelx, sobely, angleInDegrees=True)
gradient_direction = gradient_direction % 180
gradient_direction[gradient_direction < 22.5] = 0
gradient_direction[(gradient_direction >= 22.5) & (gradient_direction < 67.5)] = 45
gradient_direction[(gradient_direction >= 67.5) & (gradient_direction < 112.5)] = 90
gradient_direction[(gradient_direction >= 112.5) & (gradient_direction < 157.5)] = 135
gradient_direction[gradient_direction >= 157.5] = 0
nms = cv2.copyMakeBorder(grad, 1, 1, 1, 1, cv2.BORDER_CONSTANT, value=0)
for i in range(1, nms.shape[0] - 1):
for j in range(1, nms.shape[1] - 1):
if gradient_direction[i - 1, j - 1] == 0:
if nms[i, j] < nms[i, j - 1] or nms[i, j] < nms[i, j + 1]:
nms[i, j] = 0
elif gradient_direction[i - 1, j - 1] == 45:
if nms[i, j] < nms[i - 1, j + 1] or nms[i, j] < nms[i + 1, j - 1]:
nms[i, j] = 0
elif gradient_direction[i - 1, j - 1] == 90:
if nms[i, j] < nms[i - 1, j] or nms[i, j] < nms[i + 1, j]:
nms[i, j] = 0
else:
if nms[i, j] < nms[i - 1, j - 1] or nms[i, j] < nms[i + 1, j + 1]:
nms[i, j] = 0
nms = nms[1:-1, 1:-1]
# 双阈值检测
threshold_low = 0.05 * grad.max()
threshold_high = 0.15 * grad.max()
edges = cv2.Canny(img, threshold_low, threshold_high)
# 显示结果
cv2.imshow('Original Image', img)
cv2.imshow('Canny Edge Detection', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这段代码首先使用`cv2.imread`函数读取图片,然后使用`cv2.GaussianBlur`函数进行高斯滤波,降低噪声的影响,接着使用`cv2.Sobel`函数计算梯度,然后进行非极大值抑制,最后使用双阈值检测得到边缘图像。最后使用`cv2.imshow`函数显示原图和边缘图像。