用python写一个自适应中值滤波加局部阈值改进Canny算子的程序
时间: 2023-09-26 16:06:44 浏览: 121
以下是Python实现自适应中值滤波加局部阈值改进Canny算子的程序:
```python
import cv2
import numpy as np
def adaptive_median_filter(img, max_window_size):
h, w = img.shape
filtered = np.zeros((h, w), np.uint8)
for y in range(h):
for x in range(w):
filtered[y, x] = img[y, x]
window_size = 3
while window_size <= max_window_size:
window = img[max(0, y - window_size // 2):min(h, y + window_size // 2 + 1),
max(0, x - window_size // 2):min(w, x + window_size // 2 + 1)]
median = np.median(window)
min_val, max_val = np.min(window), np.max(window)
if min_val < median < max_val:
if min_val < img[y, x] < max_val:
filtered[y, x] = img[y, x]
else:
filtered[y, x] = median
break
else:
window_size += 2
return filtered
def local_threshold_canny(img, threshold_ratio=0.33, kernel_size=3):
blurred = cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
v = np.median(blurred)
lower = int(max(0, (1.0 - threshold_ratio) * v))
upper = int(min(255, (1.0 + threshold_ratio) * v))
edged = cv2.Canny(blurred, lower, upper)
return edged
def adaptive_median_filter_canny(img, max_window_size=15, threshold_ratio=0.33, kernel_size=3):
filtered = adaptive_median_filter(img, max_window_size)
edged = local_threshold_canny(filtered, threshold_ratio, kernel_size)
return edged
```
其中,adaptive_median_filter_canny()函数是自适应中值滤波加局部阈值改进Canny算子的组合函数,有四个参数:img表示输入图像,max_window_size表示最大窗口大小(默认为15),threshold_ratio表示阈值比例(默认为0.33),kernel_size表示高斯滤波器的卷积核大小(默认为3)。程序首先对输入图像进行自适应中值滤波,然后对滤波后的图像进行局部阈值改进Canny算子,得到边缘图像。
阅读全文