用python写一个自适应中值滤波和局部阈值改进Canny算子的程序
时间: 2023-10-01 21:04:35 浏览: 151
以下是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
```
局部阈值改进Canny算子:
```python
import cv2
import numpy as np
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
```
其中,自适应中值滤波函数adaptive_median_filter()有两个参数:img表示输入图像,max_window_size表示最大窗口大小。程序会在每个像素点处进行自适应中值滤波,窗口大小从3开始逐渐增加,直到窗口大小等于max_window_size为止。
局部阈值改进Canny算子函数local_threshold_canny()有三个参数:img表示输入图像,threshold_ratio表示阈值比例(默认为0.33),kernel_size表示高斯滤波器的卷积核大小(默认为3)。程序首先对图像进行高斯模糊,然后计算模糊后图像的中值v,最终的低阈值和高阈值分别为v×(1-threshold_ratio)和v×(1+threshold_ratio),然后将Canny算子应用于模糊后图像,得到边缘图像。
阅读全文