用matlab写一个中值滤波器
时间: 2023-11-13 21:05:22 浏览: 74
中值滤波器是一种常用的滤波器,用于去除图像中的噪声。下面是用MATLAB编写的一个中值滤波器的代码:
```matlab
function output = median_filter(input, mask_size)
% input: 输入图像
% mask_size: 滤波器大小
[m, n] = size(input);
% 填充边界
input_padded = padarray(input, [mask_size, mask_size], 'symmetric');
% 初始化输出图像
output = zeros(m, n);
% 对每个像素进行中值滤波
for i = 1:m
for j = 1:n
% 提取当前像素周围的像素
neighbors = input_padded(i:i+2*mask_size, j:j+2*mask_size);
% 计算中值
median_value = median(neighbors(:));
% 更新输出图像
output(i, j) = median_value;
end
end
% 转换为uint8类型
output = uint8(output);
end
```
上述代码中,`input`是输入图像,`mask_size`是滤波器的大小。首先,我们对输入图像进行边界填充,填充的大小为`mask_size`。然后,对于每个像素,提取其周围大小为`(2*mask_size+1)×(2*mask_size+1)`的像素,计算其中值,并将中值赋给当前像素。最后,将输出图像转换为`uint8`类型。
可以通过以下代码测试中值滤波器:
```matlab
% 读取图像
img = imread('lena.png');
% 将图像转换为灰度图像
img_gray = rgb2gray(img);
% 加入噪声
noise_img = imnoise(img_gray, 'salt & pepper', 0.05);
% 中值滤波
output = median_filter(noise_img, 3);
% 显示结果
figure;
subplot(1, 2, 1);
imshow(noise_img);
title('With noise');
subplot(1, 2, 2);
imshow(output);
title('After median filter');
```
阅读全文
相关推荐














