当前位置: 首页 微信名字

canny边缘检测算法(canny边缘检测算法代码)

时间:2023-07-13 作者: 小编 阅读量: 1 栏目名: 微信名字 文档下载

Canny边缘检测算法是一种经典的边缘检测方法,常用于图像处理和计算机视觉领域。此外,算法还可以进一步优化,例如通过使用积分图像提高效率等。

Canny边缘检测算法是一种经典的边缘检测方法,常用于图像处理和计算机视觉领域。以下是一个简单的Canny边缘检测算法的示例代码:

```python

import cv2

import numpy as np

def canny_edge_detection(image):

# 转换为灰度图

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 高斯模糊去噪声

blurred = cv2.GaussianBlur(gray, (3, 3), 0)

# 计算图像梯度

gradient_x = cv2.Sobel(blurred, cv2.CV_64F, 1, 0, ksize=3)

gradient_y = cv2.Sobel(blurred, cv2.CV_64F, 0, 1, ksize=3)

gradient_magnitude = np.sqrt(np.square(gradient_x) + np.square(gradient_y))

gradient_magnitude = np.uint8(gradient_magnitude)

gradient_direction = np.arctan2(gradient_y, gradient_x) * 180 / np.pi

# 非极大值抑制

suppressed = np.zeros_like(gradient_magnitude)

for i in range(1, gradient_magnitude.shape[0]-1):

for j in range(1, gradient_magnitude.shape[1]-1):

direction = gradient_direction[i, j]

if (0 <= direction < 22.5) or (157.5 <= direction <= 180) or (-22.5 <= direction < 0) or (-180 <= direction < -157.5):

if (gradient_magnitude[i, j] >= gradient_magnitude[i, j+1]) and (gradient_magnitude[i, j] >= gradient_magnitude[i, j-1]):

suppressed[i, j] = gradient_magnitude[i, j]

elif (22.5 <= direction < 67.5) or (-157.5 <= direction < -112.5):

if (gradient_magnitude[i, j] >= gradient_magnitude[i-1, j+1]) and (gradient_magnitude[i, j] >= gradient_magnitude[i+1, j-1]):

suppressed[i, j] = gradient_magnitude[i, j]

elif (67.5 <= direction < 112.5) or (-112.5 <= direction < -67.5):

if (gradient_magnitude[i, j] >= gradient_magnitude[i-1, j]) and (gradient_magnitude[i, j] >= gradient_magnitude[i+1, j]):

suppressed[i, j] = gradient_magnitude[i, j]

elif (112.5 <= direction < 157.5) or (-67.5 <= direction < -22.5):

if (gradient_magnitude[i, j] >= gradient_magnitude[i-1, j-1]) and (gradient_magnitude[i, j] >= gradient_magnitude[i+1, j+1]):

suppressed[i, j] = gradient_magnitude[i, j]

# 双阈值检测和边缘连接

threshold_low = 0.05 * np.max(suppressed)

threshold_high = 0.09 * np.max(suppressed)

thresholded = np.zeros_like(suppressed)

thresholded[suppressed >= threshold_high] = 255

strong_edge_indices = np.argwhere(suppressed >= threshold_high)

weak_edge_indices = np.argwhere((suppressed >= threshold_low) & (suppressed < threshold_high))

for i, j in weak_edge_indices:

if np.max(thresholded[max(0,i-1):min(suppressed.shape[0],i+2), max(0,j-1):min(suppressed.shape[1],j+2)]) == 255:

thresholded[i, j] = 255

return thresholded

# 加载图像

image = cv2.imread('image.jpg')

# 应用Canny边缘检测算法

edges = canny_edge_detection(image)

# 显示结果

cv2.imshow("Canny Edge Detection", edges)

cv2.waitKey(0)

cv2.destroyAllWindows()

```

请注意,在实际应用中,可能需要对算法参数进行调整以获得最佳结果。此外,算法还可以进一步优化,例如通过使用积分图像提高效率等。