canny算子python代码实现
时间: 2024-10-01 22:12:13 浏览: 32
Canny边缘检测是一种广泛使用的图像处理技术,用于识别图像中的边缘。它包含两个步骤:高斯滤波和平滑后的梯度计算,然后通过非极大值抑制(Non-Maximum Suppression)以及双阈值(Double Thresholding)确定边缘。以下是Python中使用OpenCV库实现Canny边缘检测的基本代码:
```python
import cv2
import numpy as np
def canny(image_path):
# 读取图片
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# 高斯滤波
blurred = cv2.GaussianBlur(image, (5, 5), 0)
# 计算梯度X和Y
sobelx = cv2.Sobel(blurred, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(blurred, cv2.CV_64F, 0, 1, ksize=3)
# 计算梯度幅值和方向
abs_sobelxy = np.sqrt(np.power(sobelx, 2) + np.power(sobely, 2))
gradient_angle = np.arctan2(sobely, sobelx)
# 非极大值抑制
aperture_size = 3
dir_threshold = np.pi / 6
abs_grad_dir = np.copy(abs_sobelxy)
abs_grad_dir[abs_grad_dir < dir_threshold] = 0
abs_grad_dir[(abs_grad_dir >= dir_threshold) & (gradient_angle > aperture_size)] = 2 * dir_threshold
abs_grad_dir[(abs_grad_dir >= dir_threshold) & (gradient_angle <= -aperture_size)] = 2 * dir_threshold - np.pi
# 双阈值
low_threshold = 50
high_threshold = 150
edges = np.zeros_like(abs_grad_dir)
edges[(abs_grad_dir >= low_threshold) & (abs_grad_dir < high_threshold)] = 255
return edges
# 使用函数并显示结果
image_path = 'your_image.jpg' # 替换为你要处理的图片路径
edges = canny(image_path)
cv2.imshow("Canny Edges", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文