简体   繁体   中英

Filtering an image in the DFT domain in matlab

I want to apply the following filter to an image:

h = [1/4 1/16 1/4; 
     1/16 1/8 1/16; 
     1/4 1/16 1/4;]

I follow the steps bellow but i don't get the correct result. Can anyone help me? I can't find what is wrong with my steps. Here is the code:

I = imread('cameraman512.jpg');
h = [1/4 1/16 1/4; 1/16 1/8 1/16; 1/4 1/16 1/4;]

%padding image
Ip = padarray(I,[512 512],'post');
figure();
imshow(Ip);

%padding filter
Hp = padarray(h,[512 512],'post');
figure();
imshow(Hp);

%image fourier
dftI = fft2(I);
figure();
imshow(dftI);

% filter fourier
dftH = fft2(H);
figure();
imshow(dftH);

%shifting image and filter
I = fftshift(Ip);
figure();
imshow(I,[]);

 H = fftshift(Hp);
 figure();
 imshow(H,[]);

G = dftI.*dftH;
figure();
imshow(G);

g=real(ifft2(G));
figure();
imshow(G);

It seems to me that you have a bit of work to do to understand what you are asked in this assignment. Here is an example of code to get you started.

Calculating the DFT of both the image and the filter:

dftI = fft2(I);
dftH = fft2(h, 512, 512);

Note that fft2 has a built-in padding feature, that is what the 512 arguments are about.


Edit alternative padding per @OliverCharlesworth comment

dftI = fft2(I, size(I,1)+size(h,1)-1, size(I,2)+size(h,2)-1);
dftH = fft2(h, size(I,1)+size(h,1)-1, size(I,2)+size(h,2)-1);

The final image has to be cropped accordingly.


If you want to display the magnitudes of the DFTs, with the zeroth frequency in the middle, you can use fftshift that way (I'm showing them on a log scale for clarity):

subplot(1,2,1), imshow(log10(abs(fftshift(dftI))), [])
subplot(1,2,2), imshow(log10(abs(fftshift(dftH))), []) 

的DFT

Since convolutions in the spatial domain are equivalent to multiplications in the frequency domain (with the usual restrictions, linearity etc.), you can multiply the DFTs:

G = dftH .* dftI;
imfilt = ifft2(G);

The result on the image:

        Original                          Filtered

结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM