candy算子检测边缘代码
时间: 2024-04-21 13:30:06 浏览: 11
下面是使用OpenCV库实现Canny算子边缘检测的代码示例:
```python
import cv2
# 读入图像并灰度化处理
img = cv2.imread('image.jpg', 0)
# 高斯滤波,去除噪声
img = cv2.GaussianBlur(img, (3, 3), 0)
# 计算梯度
sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
grad = cv2.sqrt(sobelx ** 2 + sobely ** 2)
grad = cv2.convertScaleAbs(grad)
# 非极大值抑制
gx = cv2.convertScaleAbs(sobelx)
gy = cv2.convertScaleAbs(sobely)
gradient_direction = cv2.phase(sobelx, sobely, angleInDegrees=True)
rows, cols = img.shape
for i in range(1, rows - 1):
for j in range(1, cols - 1):
if (0 <= gradient_direction[i, j] < 22.5) or (157.5 <= gradient_direction[i, j] <= 180):
if (grad[i, j] > grad[i, j - 1]) and (grad[i, j] > grad[i, j + 1]):
gx[i, j] = grad[i, j]
gy[i, j] = 0
elif (22.5 <= gradient_direction[i, j] < 67.5):
if (grad[i, j] > grad[i - 1, j - 1]) and (grad[i, j] > grad[i + 1, j + 1]):
gx[i, j] = grad[i, j]
gy[i, j] = 0
elif (67.5 <= gradient_direction[i, j] < 112.5):
if (grad[i, j] > grad[i - 1, j]) and (grad[i, j] > grad[i + 1, j]):
gx[i, j] = grad[i, j]
gy[i, j] = 0
elif (112.5 <= gradient_direction[i, j] < 157.5):
if (grad[i, j] > grad[i - 1, j + 1]) and (grad[i, j] > grad[i + 1, j - 1]):
gx[i, j] = grad[i, j]
gy[i, j] = 0
# 双阈值处理
threshold_low = 50
threshold_high = 150
edge_output = cv2.Canny(gx, gy, threshold_low, threshold_high)
cv2.imshow('Original Image', img)
cv2.imshow('Canny Edge Detection', edge_output)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`cv2.imread()`用于读入图像并灰度化处理,`cv2.GaussianBlur()`进行高斯滤波,`cv2.Sobel()`计算梯度,`cv2.phase()`计算梯度方向,非极大值抑制、双阈值处理和边缘连接则使用`cv2.Canny()`函数实现。最后使用`cv2.imshow()`显示原始图像和边缘检测结果。