Unable to match results when implementing 3D DFT
Вопрос
I am trying to implement a 3D DFT but I am running into some trouble. What I believe I should do is to just do 3 consecutive 1D DFTs, one in each direction. Assuming that the 1D DFT is correct, can you see what is wrong with this code:
def dft3d(self, real3d, img3d, nx, ny, nz, dir):
#Transform depth
for i in range(nx):
for j in range(ny):
real = numpy.zeros(nz)
img = numpy.zeros(nz)
for k in range(nz):
real[k] = real3d[i][j][k]
img[k] = img3d[i][j][k]
self.dft(real, img, nz, 1) #This was indented too much. It should work now.
for k in range(nz):
real3d[i][j][k] = real[k]
img3d[i][j][k] = img[k]
#Transform cols
for k in range(nz):
for i in range(nx):
real = numpy.zeros(ny)
img = numpy.zeros(ny)
for j in range(ny):
real[j] = real3d[i][j][k]
img[j] = img3d[i][j][k]
self.dft(real, img, ny, 1)
for j in range(ny):
real3d[i][j][k] = real[j]
img3d[i][j][k] = img[j]
#Transform rows
for j in range(ny):
for k in range(nz):
real = numpy.zeros(nx)
img = numpy.zeros(nx)
for i in range(nx):
real[i] = real3d[i][j][k]
img[i] = img3d[i][j][k]
self.dft(real, img, nx, 1)
for i in range(nx):
real3d[i][j][k] = real[i]
img3d[i][j][k] = img[i]
I know there are built in versions of this in python, but I can't use those. I'm just testing my algorithm in python so I can compare results of my algorithm and the built in ones. As far as I could tell it worked fine for both 1D and 2D transforms, but once I expanded it to 3D the results no longer match. Does anyone know what is wrong?
Решение
The first instance of self.dft
is indented too far.
Other than that, I see nothing wrong from the code provided.
As a side note, if you are using numpy
as your code suggests, you can simplify your code significantly even without resorting to the built-in DFT/FFT.
For example, you can index a 3D numpy array like data3D[i, j, k]
. You can slice by doing data3D[:, j, k]
, data3D[i, :, k]
, data3D[:, :, k]
, etc., instead of assigning individual elements one at a time within a for loop.