2D DFT in image processing in python I try to compute 2D DFT in a greyscale image with this formula:



I write the code bellow with python

def DFT2D(image):
    data = np.asarray(image)
    M, N = image.size # (img x, img y)
    dft2d = np.zeros((M,N))
    for k in range(M):
        for l in range(N):
            sum_matrix = 0.0
            for m in range(M):
                for n in range(N):
                    e = cmath.exp(- 2j * np.pi * ((k * m) / M + (l * n) / N))
                    sum_matrix +=  data[m,n] * e
            dft2d[k,l] = sum_matrix
    return dft2d


I think I have some problems because I do not get the expected result. I get the image below:



I do not know where is the problem in my code!



I don't want to use a built-in function, I assume this should be work but maybe it has some mathematical issue. when I get a result matrix and convert it to image it does not as same as expected DFT image
So I think it's mostly missing the line

    dft2d = np.zeros((M,N),dtype=complex)


in your code. Otherwise your sum may not end up being complex.

And then you can't then plot the resulting image... because that needs to be real-valued.

I modified your code so that it sort of works (but is very slow). See below.  This results in something more like what you expect --- though because of the indexing, the peak is in the top-left corner rather than the middle.  There's probably something like Matlab's fftshift function that will center it for you.





Updated Code Below

import numpy as np
import matplotlib.pyplot as plt
import PIL
import cmath

def DFT2D(image):
    data = np.asarray(image)
    M, N = image.size # (img x, img y)
    dft2d = np.zeros((M,N),dtype=complex)
    for k in range(M):
        for l in range(N):
            sum_matrix = 0.0
            for m in range(M):
                for n in range(N):
                    e = cmath.exp(- 2j * np.pi * ((k * m) / M + (l * n) / N))
                    sum_matrix +=  data[m,n,1] * e
            dft2d[k,l] = sum_matrix
    return dft2d

img = PIL.Image.open("example.jpg")
img2 = img.resize((50,50))
plt.imshow(img2)
dft = DFT2D(img2)
plt.imshow(dft.real)