用双门限端点检测实现代码
时间: 2024-01-02 13:03:18 浏览: 89
好的,以下是用Python实现的双门限端点检测代码:
```python
import numpy as np
import matplotlib.pyplot as plt
def double_threshold_edge_detection(img, low_threshold_ratio=0.05, high_threshold_ratio=0.15):
"""
双门限端点检测算法
:param img: 输入的灰度图像
:param low_threshold_ratio: 低阈值比例,默认为0.05
:param high_threshold_ratio: 高阈值比例,默认为0.15
:return:
"""
# 计算阈值
assert 0 <= low_threshold_ratio <= 1, "low_threshold_ratio must be in [0, 1]"
assert 0 <= high_threshold_ratio <= 1, "high_threshold_ratio must be in [0, 1]"
low_threshold = np.max(img) * low_threshold_ratio
high_threshold = np.max(img) * high_threshold_ratio
# 双门限检测
edge = np.zeros_like(img)
strong_edge_row, strong_edge_col = np.where(img >= high_threshold)
weak_edge_row, weak_edge_col = np.where((img <= high_threshold) & (img >= low_threshold))
edge[strong_edge_row, strong_edge_col] = 2
edge[weak_edge_row, weak_edge_col] = 1
# 连通性分析
h, w = img.shape
for i in range(1, h - 1):
for j in range(1, w - 1):
if edge[i, j] == 1:
if np.max(edge[i-1:i+2, j-1:j+2]) == 2:
edge[i, j] = 2
else:
edge[i, j] = 0
return edge
# 测试
img = plt.imread('lena.png')
gray_img = np.dot(img[..., :3], [0.299, 0.587, 0.114]) # 转换为灰度图像
edge = double_threshold_edge_detection(gray_img)
plt.imshow(edge, cmap='gray')
plt.show()
```
其中,`double_threshold_edge_detection`函数用于实现双门限端点检测算法。首先,根据输入的灰度图像计算出低阈值和高阈值。然后,将图像中大于等于高阈值的像素点标记为强边缘,将图像中低于高阈值但高于等于低阈值的像素点标记为弱边缘,其余的像素点标记为非边缘。接着,对于每个弱边缘像素点,如果其8邻域内存在强边缘像素点,则将其标记为强边缘,否则将其标记为非边缘。最后,返回标记结果。
我们可以使用`plt.imread`函数读取一张图片,然后将其转换为灰度图像,再使用`double_threshold_edge_detection`函数进行边缘检测,并使用`plt.imshow`函数显示结果。
阅读全文