MATLAB编程实现图像的理想低通和高通滤波;巴特沃斯低通和高通滤波;高斯低通和高通滤波;同态滤波的代码要求显示滤波前后的图像和频谱
时间: 2023-06-04 20:08:12 浏览: 103
matlab图像技术:10 高通滤波、高斯滤波、拉普拉斯算子锐化、理想高通滤波、同态滤波
答案:
感谢您的提问。这个问题属于技术问题,可以回答。以下是MATLAB实现图像滤波的代码示例:
% 读取图像
img = imread('example.png');
% 理想低通滤波(以半径r=50为例)
[r, c] = size(img);
D0 = 50;
H = zeros(r, c);
for i = 1:r
for j = 1:c
dist = sqrt((i-r/2)^2+(j-c/2)^2);
if dist <= D0
H(i,j) = 1;
end
end
end
filtered_img = real(ifft2(ifftshift(fftshift(fft2(img)).*H)));
% 显示滤波前后的图像和频谱
figure;
subplot(2,2,1);imshow(img);title('原图');
subplot(2,2,2);imshow(log(abs(fftshift(fft2(img)))+1),[]);title('原图频谱');
subplot(2,2,3);imshow(filtered_img);title('理想低通滤波后');
subplot(2,2,4);imshow(log(abs(fftshift(fft2(filtered_img)))+1),[]);title('滤波后的频谱');
% 巴特沃斯低通滤波(以半径r=50,阶数n=2为例)
D0 = 50; n = 2;
H = zeros(r, c);
for i = 1:r
for j = 1:c
dist = sqrt((i-r/2)^2+(j-c/2)^2);
H(i,j) = 1/(1+(D0/dist)^(2*n));
end
end
filtered_img = real(ifft2(ifftshift(fftshift(fft2(img)).*H)));
% 显示滤波前后的图像和频谱
figure;
subplot(2,2,1);imshow(img);title('原图');
subplot(2,2,2);imshow(log(abs(fftshift(fft2(img)))+1),[]);title('原图频谱');
subplot(2,2,3);imshow(filtered_img);title('巴特沃斯低通滤波后');
subplot(2,2,4);imshow(log(abs(fftshift(fft2(filtered_img)))+1),[]);title('滤波后的频谱');
% 高斯低通滤波(以半径r=50为例)
D0 = 50;
H = zeros(r, c);
for i = 1:r
for j = 1:c
dist = sqrt((i-r/2)^2+(j-c/2)^2);
H(i,j) = exp(-dist^2/(2*D0^2));
end
end
filtered_img = real(ifft2(ifftshift(fftshift(fft2(img)).*H)));
% 显示滤波前后的图像和频谱
figure;
subplot(2,2,1);imshow(img);title('原图');
subplot(2,2,2);imshow(log(abs(fftshift(fft2(img)))+1),[]);title('原图频谱');
subplot(2,2,3);imshow(filtered_img);title('高斯低通滤波后');
subplot(2,2,4);imshow(log(abs(fftshift(fft2(filtered_img)))+1),[]);title('滤波后的频谱');
% 同态滤波(以a=0.25,b=1.5为例)
a = 0.25; b = 1.5;
g = double(img);
% 中心化
g = g - mean2(g);
% FFT变换,得到频谱图
G = fft2(g);
% 构造滤波器
H = zeros(r, c);
for i = 1:r
for j = 1:c
H(i,j) = exp(-a*(i-r/2)^2-b*(j-c/2)^2);
end
end
% 滤波
F = H .* G;
% IFFT变换,得到滤波后的图像
filtered_img = real(ifft2(F));
% 进行反中心化
filtered_img = filtered_img + mean2(img);
% 显示滤波前后的图像和频谱
figure;
subplot(2,2,1);imshow(img);title('原图');
subplot(2,2,2);imshow(log(abs(fftshift(G))+1),[]);title('原图频谱');
subplot(2,2,3);imshow(filtered_img);title('同态滤波后');
subplot(2,2,4);imshow(log(abs(fftshift(F))+1),[]);title('滤波后的频谱');
阅读全文