Reputation: 51
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);
Upvotes: 1
Views: 655
Reputation: 3574
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))), [])
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
Upvotes: 3