Please help me understand the following MATLAB code for Ideal Low pass filter. I am unable to understand the Part2 in the below code. Please explain me why we are doing like this.
I have read the Rafael C. Gonzalez's Digital Image Processing Using Matlab 2E which explains my question but I couldn't understand properly. It will be helpful if someone could explain me clearly.
Note: Dogbert, my understanding is that applying transform to an image help to separate low and high frequency components. Top left contains more low freq coefficients where as bottom right contains high freq coefficients. The Low frequency components contains over all detail (approximation) where as the high frequency components contains smaller details in an image. In low pass filter, frequencies below the cut-off freq are allowed to pass and the freqs above the cut-off is blocked.
%IDEAL LOW-PASS FILTER
%Part 1
function idealfilter(X,P) % X is the input image and P is the cut-off freq
f=imread(X); % reading an image X
[M,N]=size(f); % Saving the the rows of X in M and columns in N
F=fft2(double(f)); % Taking Fourier transform to the input image
%Part 2 % I don't understand this part
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);
%Part 3
H=double(D<=P); % Comparing with the cut-off frequency
G=H.*F; % Convolution with the Fourier transformed image
g=real(ifft2(double(G))); % Inverse Fourier transform
imshow(f),figure,imshow(g,[ ]); % Displaying input and output image
end
I tried to run each commands in Part2 individually for M= 8 and N=8. I get
u=0:(M-1); ==> u = 0 1 2 3 4 5 6 7
v=0:(N-1); ==> v = 0 1 2 3 4 5 6 7
idx=find(u>M/2); ==> idx = 6 7 8
u(idx)=u(idx)-M; ==> 0 1 2 3 4 -3 -2 -1
idy=find(v>N/2); ==> idy = 6 7 8
v(idy)=v(idy)-N; ==> 0 1 2 3 4 -3 -2 -1
[V,U]=meshgrid(v,u); ==>
V=
0 1 2 3 4 -3 -2 -1
0 1 2 3 4 -3 -2 -1
0 1 2 3 4 -3 -2 -1
0 1 2 3 4 -3 -2 -1
0 1 2 3 4 -3 -2 -1
0 1 2 3 4 -3 -2 -1
0 1 2 3 4 -3 -2 -1
0 1 2 3 4 -3 -2 -1
U =
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4
-3 -3 -3 -3 -3 -3 -3 -3
-2 -2 -2 -2 -2 -2 -2 -2
-1 -1 -1 -1 -1 -1 -1 -1
I am unsure why they are doing like this. Please help me understand this MATLAB code. And also help me understand why they have to used fftshift
in the below MATLAB code. I did read the MATLAB documentation but I couldn't understand it properly. If possible explain with an example. Thanks in advance. Help me learn.
%This code is used to Butterworth lowpass filter
close all;
clear all;
clc;
im=imread('lean.jpg');
fc=20;%Cutoff frequency
n=1;
[co,ro] = size(im);
cx = round(co/2); % find the center of the image
cy = round (ro/2);
imf=fftshift(fft2(im));
H=zeros(co,ro);
for i = 1 : co
for j =1 : ro
d = (i-cx).^2 + (j-cy).^ 2;
H(i,j) = 1/(1+((d/fc/fc).^(2*n)));
end;
end;
outf = imf .* H;
out = abs(ifft2(outf));
imshow(im),title('Original Image'),figure,imshow(uint8(out)),title('Lowpass Filterd Image')