自适应加权中值滤波算法matlab
时间: 2023-09-02 19:08:38 浏览: 208
自适应加权中值滤波算法(Adaptive Weighted Median Filter)是一种常用的非线性滤波算法,可用于去除高斯噪声、脉冲噪声等。
Matlab代码实现如下:
```matlab
function [output_img] = AWMedianFilter(input_img, max_window_size)
% 自适应加权中值滤波
% input_img: 输入图像
% max_window_size: 最大窗口尺寸
[m, n] = size(input_img);
output_img = zeros(m, n); % 输出图像
padding_size = floor(max_window_size/2);
for i = 1:m
for j = 1:n
cur_pixel = input_img(i,j); % 当前像素值
window_size = 3; % 窗口大小从3开始
while window_size <= max_window_size
padding = floor(window_size/2);
window = input_img(max(i-padding,1):min(i+padding,m), ...
max(j-padding,1):min(j+padding,n)); % 提取窗口
if cur_pixel > min(window(:)) && cur_pixel < max(window(:))
% 计算加权中值
sorted_window = sort(window(:));
center_pixel = sorted_window(padding+1);
left_window = sorted_window(1:padding);
right_window = sorted_window(padding+2:end);
left_weight = sum(center_pixel-left_window) / padding;
right_weight = sum(right_window-center_pixel) / padding;
output_img(i,j) = center_pixel + 0.5 * (left_weight - right_weight);
break; % 找到加权中值,跳出循环
else
window_size = window_size + 2; % 窗口大小加2
end
end
if window_size > max_window_size % 最大窗口尺寸内无法找到加权中值,取原像素值
output_img(i,j) = cur_pixel;
end
end
end
output_img = uint8(output_img); % 转为uint8类型
end
```
调用方法:
```matlab
input_img = imread('lena.png');
output_img = AWMedianFilter(input_img, 7);
imshow(input_img), title('原图');
figure, imshow(output_img), title('滤波后的图像');
```
阅读全文