2D DFT in image processing in python
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)