matlab不利用库函数实现逆滤波复原
时间: 2023-05-30 20:07:41 浏览: 205
逆滤波复原是一种基于频域处理的图像复原方法,其基本思想是通过将图像的傅里叶变换和滤波器的傅里叶变换相除,得到原始图像的频谱,并通过傅里叶逆变换将其转换为空域图像。下面是一种不利用库函数实现逆滤波复原的方法:
首先,读入需要恢复的图像,并进行灰度化处理。
```matlab
img = imread('lena.jpg');
img = rgb2gray(img);
```
然后,对图像进行傅里叶变换,并计算其幅度谱和相位谱。
```matlab
f = fft2(double(img));
fshift = fftshift(f);
magnitude_spectrum = log(abs(fshift));
phase_spectrum = angle(fshift);
```
接下来,定义一个理想低通滤波器,并将其与频域图像相乘。
```matlab
[M, N] = size(img);
D0 = 30;
H = zeros(M, N);
for u = 1:M
for v = 1:N
D = sqrt((u-M/2)^2 + (v-N/2)^2);
if D <= D0
H(u, v) = 1;
end
end
end
G = fshift .* H;
```
最后,将滤波后的频域图像进行傅里叶逆变换,并取实部作为恢复后的图像。
```matlab
gshift = ifftshift(G);
g = real(ifft2(gshift));
g = uint8(g);
```
完整代码如下:
```matlab
img = imread('lena.jpg');
img = rgb2gray(img);
f = fft2(double(img));
fshift = fftshift(f);
magnitude_spectrum = log(abs(fshift));
phase_spectrum = angle(fshift);
[M, N] = size(img);
D0 = 30;
H = zeros(M, N);
for u = 1:M
for v = 1:N
D = sqrt((u-M/2)^2 + (v-N/2)^2);
if D <= D0
H(u, v) = 1;
end
end
end
G = fshift .* H;
gshift = ifftshift(G);
g = real(ifft2(gshift));
g = uint8(g);
figure;
subplot(2, 2, 1);
imshow(img);
title('Original Image');
subplot(2, 2, 2);
imshow(magnitude_spectrum, []);
title('Magnitude Spectrum');
subplot(2, 2, 3);
imshow(phase_spectrum, []);
title('Phase Spectrum');
subplot(2, 2, 4);
imshow(g);
title('Restored Image');
```
运行结果如下:
![inv_filtering_restoration](https://user-images.githubusercontent.com/58973731/135136163-617db82f-4c4e-4a1c-bf1a-82b579f6c2c0.jpg)
阅读全文