图像的滤波与图像增强的Matlab实现
目的
- 了解 MATLAB 工具箱中的滤波器。
- 掌握空间滤波。
- 学会对图像的空间变换。
内容
A. 用滤波器祛除图像噪声
在数字图像处理中,噪声是一个常见的问题。为了改善图像质量,常用的噪声去除方法包括均值滤波、中值滤波和维纳滤波。在MATLAB中,可以通过不同的滤波器来去除噪声。
示例:用均值滤波、中值滤波、维纳滤波去除图像中的高斯噪声
I = imread('D:\pic\DIP3E_CH04\FigP0438(left).tif'); % 读入原图像
J = imnoise(I, 'gaussian', 0, 0.002); % 加入高斯噪声
% 均值滤波
h = fspecial('average', 3); % 创建一个3x3均值滤波器
I2 = uint8(round(filter2(h, I))); % 对图像进行滤波
% 中值滤波
I3 = medfilt2(J, [3, 3]); % 对噪声图像进行中值滤波
% 维纳滤波
I4 = wiener2(J, [3, 3]); % 对噪声图像进行一次维纳滤波
I5 = wiener2(I4, [3, 3]); % 对维纳滤波结果进行二次维纳滤波
% 显示结果
subplot(2, 3, 1), imshow(I), title('原图像');
subplot(2, 3, 2), imshow(J), title('加噪声图像');
subplot(2, 3, 3), imshow(I2), title('均值滤波后图像');
subplot(2, 3, 4), imshow(I3), title('中值滤波后图像');
subplot(2, 3, 5), imshow(I4), title('维纳滤波后图像');
subplot(2, 3, 6), imshow(I5), title('两次维纳滤波后图像');
B. 空间噪声滤波器
此部分演示了如何生成不同类型的噪声,并应用不同的空间噪声滤波器(如均值滤波、最大值滤波、中值滤波等)去除噪声。
示例:生成带有盐与胡椒噪声的图像并进行滤波处理
% 用imnoise2函数生成带有盐与胡椒噪声的图像
function R = imnoise2(type, M, N, a, b)
if nargin == 1
a = 0; b = 1;
M = 1; N = 1;
elseif nargin == 3
a = 0; b = 1;
end
switch lower(type)
case 'uniform'
R = a + (b - a) * rand(M, N); % 均匀分布噪声
case 'gaussian'
R = a + b * randn(M, N); % 高斯分布噪声
case 'salt & pepper'
if nargin <= 3
a = 0.05; b = 0.05; % 盐与胡椒噪声的比例
end
if (a + b) > 1
error('The sum of a and b must not exceed 1.');
end
R(1:M, 1:N) = 0.5; % 初始灰度值为中性灰色
X = rand(M, N);
c = find(X <= a); % 生成盐噪声
R(c) = 0; % 盐噪声值为0
u = a + b;
c = find(X > a & X <= u); % 生成胡椒噪声
R(c) = 1; % 胡椒噪声值为1
otherwise
error('Unknown distribution type.');
end
end
% 应用滤波器去噪
f = imread('D:\pic\DIP3E_CH04\FigP0438(left).tif');
[M, N] = size(f);
R = imnoise2('salt & pepper', M, N, 0.1, 0); % 生成盐噪声
c = find(R == 0);
gp = f;
gp(c) = 0; % 添加盐噪声
% 使用反调和滤波器
fp = spfilt(gp, 'chmean', 3, 3, 1.5); % 使用正值Q的滤波器
figure, imshow(fp);
C. 用滤波器祛除图像噪声
图像变换方法(如仿射变换)常用于图像增强。下面是如何进行仿射变换和插值的示例。
示例:仿射变换和插值
% 产生一个等角变换图像用于测试
f = checkerboard(50); % 创建一个棋盘格图像
s = 0.8;
theta = pi / 6;
T = [s * cos(theta), s * sin(theta), 0; -s * sin(theta), s * cos(theta), 0; 0, 0, 1]; % 创建仿射变换矩阵
tform = maketform('affine', T); % 创建仿射变换对象
g = imtransform(f, tform); % 应用变换
figure, imshow(g);
% 使用最近邻插值进行图像变换
g2 = imtransform(f, tform, 'nearest'); % 最近邻插值
figure, imshow(g2);
% 使用填充值为0.5的插值
g3 = imtransform(f, tform, 'FillValue', 0.5); % 填充缺失区域为0.5
figure, imshow(g3);
% 进行平移变换
T2 = [1, 0, 0; 0, 1, 0; 50, 50, 1]; % 平移矩阵
tform2 = maketform('affine', T2); % 创建平移变换对象
g4 = imtransform(f, tform2); % 应用平移变换
figure, imshow(g4);
% 自定义坐标范围和填充值
g5 = imtransform(f, tform2, 'XData', [1, 400], 'YData', [1, 400], 'FillValue', 0.5);
figure, imshow(g5);
参考文献
- [Rafael C. Gonzalez, Richard E. Woods, and Steven L. Eddins. 2003. Digital Image Processing Using MATLAB. Prentice-Hall, Inc., USA.]
2657

被折叠的 条评论
为什么被折叠?



