2D Discrete Fourier Transform and Inverse DFT

137 views Asked by At

I am currently implementing 2D DFT and IDFT for images, and the response of my IDFT is not the same from the original image. It is intriguing because the generated image looks inverted. I don't know if I am considering all the terms. Maybe I would have to work with the phase, but I don't know how. Here is my code for DFT

var
i, j, k, M, N, u, v, x, y:integer; 
aux: extended; 
Real, Imaginario, Mag, IMag, Vagxy:TMatriz; 
Vag:TVetorE;
 
M:=16; 
N:=16; 
SetLength(Mag, M, N); //Magnitudes
ZeraMatriz(Mag, M, N);
SetLength(Real, M, N);
SetLength(Imaginario, M, N);
aux:=2*pi;
for u:=0 to M-1 do
    for v:=0 to N-1 do
        begin
             ZeraMatriz(Real, M, N);
             ZeraMatriz(Imaginario, M, N);
             for x:=0 to M-1 do  
                 for y:=0 to N-1 do  
                    begin
                         Real[u,v]:=Real[u,v]+(Vagxy[x,y]*cos(aux*(((u*x)/M)+(v*y)/N)));
                         Imaginario[u,v]:=Imaginario[u,v]-(Vagxy[x,y]*sin(aux*(((u*x)/M)+(v*y)/N)));
                         //Form1.Memo.Lines.Add(IntToStr(Form1.Memo.Lines.Count)+'     Vag:  '+FloattoStr(Vagxy[x,y])+ 'x'+ InttoStr(x)+ 'y'+ InttoStr(y));
                    end;
              Mag[u,v]:=sqrt(Power(Real[u,v],2)+Power(Imaginario[u,v],2));
              //Form1.Memo.Lines.Add(IntToStr(Form1.Memo.Lines.Count)+'     Mag:  '+FloattoStr(Mag[u,v]));
        end;

And here is my code for IDFT

M:=16; 
N:=16; 
aux:=2*pi;
SetLength(IMag, M, N);
ZeraMatriz(IMag, M, N);
SetLength(Real, M, N);
SetLength(Imaginario, M, N);
for x:=0 to M-1 do
    for y:=0 to N-1 do
        begin
             ZeraMatriz(Real, M, N);
             ZeraMatriz(Imaginario, M, N);
             for u:=0 to M-1 do  
                 for v:=0 to N-1 do  
                    begin
                         Real[x,y]:=Real[x,y]+(Mag[u,v]*cos(aux*(((u*x)/M)+(v*y)/N)));
                         Imaginario[x,y]:=Imaginario[x,y]+(Mag[u,v]*sin(aux*(((u*x)/M)+(v*y)/N)));
                    end;
             IMag[x,y]:=(sqrt(Power(Real[x,y],2)+Power(Imaginario[x,y],2)))/(M*N);
        end;

// shows image
k:=0;
for y := 0 to N-1 do
    for x := 0 to M-1 do
        begin
             Vag[k]:=IMag[x,y];
             k:=k+1;
        end;

I want to understand if my code is correct and if not I want to know where. I have no idea why I can't get back the original image after performing IDFT on the DFTed image.

0

There are 0 answers