Numpy fft2 频移

信息处理 fft 傅里叶变换 频率 麻木的
2022-02-04 15:56:07

我不明白如何在 fft2 或更高维度上进行频移。有人可以解释一下吗?

将 numpy 导入为 np
将 matplotlib.pyplot 导入为 plt
从 mpl_toolkits.mplot3d 导入 Axes3D

%matplotlib 内联

numb_steps = 100
x = np.linspace(-10, 10, numb_steps)
y = np.linspace(-10, 10, numb_steps)

X,Y = np.meshgrid(x,y)

R = 1

Z = np.zeros((100, 100))
# 圆圈
对于我在范围内(numb_steps):
    对于范围内的 j(numb_steps):
        如果 x[i]**2+y[j]**2 > R:
            Z[i,j] = 0
        别的:
            Z[i,j] = 1



无花果 = plt.figure()
ax = fig.gca(投影='3d')
ax.plot_surface(X,Y,Z)

在此处输入图像描述

我只能得到那些情节

无花果 = plt.figure()
ax = fig.gca(投影='3d')

Z_fft = np.fft.fft2(Z)
FreqCompRows = np.fft.fftfreq(Z.shape[0],d=2)
FreqCompCols = np.fft.fftfreq(Z.shape[1],d=2)
FreqCompRows = np.fft.fftshift(FreqCompRows)
FreqCompCols = np.fft.fftshift(FreqCompCols)

S,D = np.meshgrid(FreqCompRows, FreqCompCols)

ax.plot_surface(S, D, np.abs(Z_fft))

在此处输入图像描述

plt.imshow(np.abs(Z_fft))

plt.xticks(范围(len(x_ax)), np.round(x_ax))
plt.yticks(范围(len(y_ax)),np.round(y_ax))

在此处输入图像描述

PS是的,刻度重叠也是我的问题

1个回答

您可以使用 scipy.fftpack (sfft) 而不是 np.fft 来解决此问题,因为 sfft 实现可以直接用于二维数组,因此您不必以复杂的方式进行操作(ba dum tsss)。

在您的代码标题中,添加:

import scipy.fftpack as sfft

然后,要计算 fft 并移动频谱,请使用:

Z_fft = sfft.fft2(Z)
Z_shift = sfft.fftshift(Z_fft)

然后将获得的光谱很好地安排用于图像显示:

plt.figure(4)
plt.imshow(np.abs(Z_shift))

在此处输入图像描述

此外,您构建圆圈的方式似乎过于复杂,您可以使用 boolean 语法来利用 python 的语法:

X,Y = np.meshgrid(x,y)
Z = X**2+Y**2
R = 1
Z[Z > R] = 0;Z[Z > 0] = 1;

我在这里所做的是使用您创建的网格来计算圆方程结果,以 Z 的形式。然后我测试 Z 的所有高于 R 的值,将它们设为零,将其他值设为 1。

我的代码如下:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import scipy.fftpack as sfft # you have to import this package

plt.close('all')

numb_steps = 100
x = np.linspace(-10, 10, numb_steps)
y = np.linspace(-10, 10, numb_steps)

#constructing the disk in a simpler manner
X,Y = np.meshgrid(x,y)
Z = X**2+Y**2
R = 1
Z[Z > R] = 0;Z[Z > 0] = 1;

# Here, use sfft routines instead of np.fft
Z_fft = sfft.fft2(Z)
Z_shift = sfft.fftshift(Z_fft)
FreqCompRows = np.fft.fftfreq(Z.shape[0],d=2)
FreqCompCols = np.fft.fftfreq(Z.shape[1],d=2)
FreqCompRows = np.fft.fftshift(FreqCompRows)
FreqCompCols = np.fft.fftshift(FreqCompCols)

S,D = np.meshgrid(FreqCompRows, FreqCompCols)

# plotting your disk signal image
fig = plt.figure(1) 
ax = fig.gca(projection='3d')
ax.plot_surface(X,Y,Z)

# plotting "3D" fft non-shifted
fig = plt.figure(2)
ax = fig.gca(projection='3d')
ax.plot_surface(S, D, np.abs(Z_fft))

# plotting images of FFT's
plt.figure(3)
plt.imshow(np.abs(Z_fft))

plt.figure(4)
plt.imshow(np.abs(Z_shift))