用matlab编写一个程序,实现:输入一副图像(灰度图像),实现理想低通、巴特沃斯低通、高斯低通滤波、理想高通、巴特沃斯高通、高斯高通滤波,输出滤波结果图。
时间: 2023-06-15 11:03:38 浏览: 407
以下是MATLAB代码实现:
```matlab
%% 读入图像
img = imread('lena_gray.jpg');
img = im2double(img);
figure(1)
subplot(2,3,1)
imshow(img)
title('原图');
%% 理想低通滤波
D0 = 50; %截止频率
[M,N] = size(img);
u = 0:M-1;
v = 0:N-1;
idx = find(u>M/2);
u(idx) = u(idx)-M;
idy = find(v>N/2);
v(idy) = v(idy)-N;
[V,U] = meshgrid(v,u);
D = sqrt(U.^2+V.^2);
H = double(D<=D0);
F = fft2(img);
G = H.*F;
g = real(ifft2(G));
subplot(2,3,2);
imshow(g)
title('理想低通滤波')
%% 巴特沃斯低通滤波
D0 = 50; %截止频率
n = 2; %阶数
[M,N] = size(img);
u = 0:M-1;
v = 0:N-1;
idx = find(u>M/2);
u(idx) = u(idx)-M;
idy = find(v>N/2);
v(idy) = v(idy)-N;
[V,U] = meshgrid(v,u);
D = sqrt(U.^2+V.^2);
H = 1./(1+(D/D0).^(2*n));
F = fft2(img);
G = H.*F;
g = real(ifft2(G));
subplot(2,3,3);
imshow(g)
title('巴特沃斯低通滤波')
%% 高斯低通滤波
D0 = 50; %截止频率
[M,N] = size(img);
u = 0:M-1;
v = 0:N-1;
idx = find(u>M/2);
u(idx) = u(idx)-M;
idy = find(v>N/2);
v(idy) = v(idy)-N;
[V,U] = meshgrid(v,u);
D = sqrt(U.^2+V.^2);
H = exp(-(D.^2)/(2*(D0^2)));
F = fft2(img);
G = H.*F;
g = real(ifft2(G));
subplot(2,3,4);
imshow(g)
title('高斯低通滤波')
%% 理想高通滤波
D0 = 50; %截止频率
[M,N] = size(img);
u = 0:M-1;
v = 0:N-1;
idx = find(u>M/2);
u(idx) = u(idx)-M;
idy = find(v>N/2);
v(idy) = v(idy)-N;
[V,U] = meshgrid(v,u);
D = sqrt(U.^2+V.^2);
H = double(D>=D0);
F = fft2(img);
G = H.*F;
g = real(ifft2(G));
subplot(2,3,5);
imshow(g)
title('理想高通滤波')
%% 巴特沃斯高通滤波
D0 = 50; %截止频率
n = 2; %阶数
[M,N] = size(img);
u = 0:M-1;
v = 0:N-1;
idx = find(u>M/2);
u(idx) = u(idx)-M;
idy = find(v>N/2);
v(idy) = v(idy)-N;
[V,U] = meshgrid(v,u);
D = sqrt(U.^2+V.^2);
H = 1./(1+(D0./D).^(2*n));
F = fft2(img);
G = H.*F;
g = real(ifft2(G));
subplot(2,3,6);
imshow(g)
title('巴特沃斯高通滤波')
```
以上代码实现了六种滤波器的效果展示,其中理想滤波器、巴特沃斯滤波器和高斯滤波器分别实现了低通和高通两种模式。
阅读全文