Canny边缘检测算法代码
时间: 2023-11-20 07:46:39 浏览: 78
以下是使用Python实现的Canny边缘检测算法代码:
```python
import cv2
import numpy as np
def canny_edge_detection(image, sigma=0.33):
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Calculate the median of the grayscale image
median = np.median(gray)
# Set the lower and upper thresholds using the median of the grayscale image
lower_threshold = int(max(0, (1.0 - sigma) * median))
upper_threshold = int(min(255, (1.0 + sigma) * median))
# Apply Gaussian blur to reduce noise
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
# Apply Canny edge detection with the lower and upper thresholds
edges = cv2.Canny(blurred, lower_threshold, upper_threshold)
return edges
```
该函数接受一个图像和一个可选的sigma参数作为输入,并返回一个包含边缘信息的二值图像。sigma参数用于计算Canny算法的阈值,可以调整Canny算法的敏感度。默认值为0.33,即使用中值滤波器计算的中值加减sigma倍数的值作为低阈值和高阈值。
阅读全文