设计自适应中值滤波器,通过添加高斯、盐和胡椒噪声生成噪声图像,使用所设计的自适应中值滤波器对图像进行去噪,的代码
时间: 2024-03-13 20:46:19 浏览: 79
好的,以下是使用Matlab设计自适应中值滤波器进行去噪的代码:
```matlab
% 读入图像并显示
I = imread('lena.png');
figure,imshow(I);
% 添加高斯、盐和胡椒噪声
J1 = imnoise(I,'gaussian',0,0.01);
J2 = imnoise(I,'salt & pepper',0.1);
J3 = imnoise(I,'speckle',0.04);
figure,imshow(J1),title('高斯噪声');
figure,imshow(J2),title('盐和胡椒噪声');
figure,imshow(J3),title('乘性噪声');
% 自适应中值滤波器
K1 = J1;
K2 = J2;
K3 = J3;
[m,n] = size(I);
for i = 1:m
for j = 1:n
% 对每个像素点进行处理
window = J1(max(1,i-2):min(m,i+2),max(1,j-2):min(n,j+2));
Zmin = min(window(:));
Zmax = max(window(:));
Zmed = median(window(:));
A1 = Zmed - Zmin;
A2 = Zmed - Zmax;
if A1 > 0 && A2 < 0
B1 = J1(i,j) - Zmin;
B2 = J1(i,j) - Zmax;
if B1 > 0 && B2 < 0
K1(i,j) = J1(i,j);
else
K1(i,j) = Zmed;
end
else
K1(i,j) = Zmed;
end
window = J2(max(1,i-2):min(m,i+2),max(1,j-2):min(n,j+2));
Zmin = min(window(:));
Zmax = max(window(:));
Zmed = median(window(:));
A1 = Zmed - Zmin;
A2 = Zmed - Zmax;
if A1 > 0 && A2 < 0
B1 = J2(i,j) - Zmin;
B2 = J2(i,j) - Zmax;
if B1 > 0 && B2 < 0
K2(i,j) = J2(i,j);
else
K2(i,j) = Zmed;
end
else
K2(i,j) = Zmed;
end
window = J3(max(1,i-2):min(m,i+2),max(1,j-2):min(n,j+2));
Zmin = min(window(:));
Zmax = max(window(:));
Zmed = median(window(:));
A1 = Zmed - Zmin;
A2 = Zmed - Zmax;
if A1 > 0 && A2 < 0
B1 = J3(i,j) - Zmin;
B2 = J3(i,j) - Zmax;
if B1 > 0 && B2 < 0
K3(i,j) = J3(i,j);
else
K3(i,j) = Zmed;
end
else
K3(i,j) = Zmed;
end
end
end
% 显示去噪后的图像
figure,imshow(K1),title('高斯噪声去噪后');
figure,imshow(K2),title('盐和胡椒噪声去噪后');
figure,imshow(K3),title('乘性噪声去噪后');
```
其中,自适应中值滤波器的实现是按照算法步骤逐个像素点进行处理,判断窗口内的像素是否需要进行中值滤波。最终得到去噪后的图像,可以与添加噪声前的原始图像进行对比。
阅读全文