【发布时间】:2021-10-27 18:26:19
【问题描述】:
我在保存数字时遇到了问题。此代码对信号进行 FFT,之后应将 FFT 保存在 .png 中的单独文件中。第一个图没问题,但后面的图都是以前的FFT,这可能是一个典型的问题,你知道如何解决它吗?
import numpy as np
import matplotlib.pyplot as plt
import glob
txt_files = glob.glob("*.pom") #format of files
print(txt_files)
for i in range(len(txt_files)):
mat = np.genfromtxt(txt_files[i])
#x = np.delete(mat, [0, 6] , axis=0)
a = np.delete(mat, 0, axis=1)
b = mat[1, 0] - mat[0, 0]
std = a.std()
mean = a.mean()
print(std, mean)
Fs = 5000 # sumpling freq IF TIME IN FIRST COLUMN
tstep = 1 / Fs # sumple time interval
N = np.size(a) # number of samples
t = np.linspace(0, (N - 1) * tstep, N) # time step
fstep = Fs / N
f = np.linspace(0, (N - 1) * fstep, N) # freq step
X = np.fft.fft2(a)
X_mag = np.abs(X) / N
f_plot = f[0:int(N / 2 + 1)]
X_mag_plot = 2 * X_mag[0:int(N / 2 + 1)]
X_mag_plot[0] = X_mag_plot[0] / 2
plt.plot(f_plot, X_mag_plot, "-k", linewidth=0.5)
plt.xlabel('Frequency [Hz]')
plt.ylabel('Amplitude')
plt.xscale("log")
plt.axis([1, 1000, 0, 0.01])
plt.grid(True)
#plt.text(45, .025, r'$\mu=100,\ \sigma=15$', backgroundcolor="w")
plt.text(300, 0.01, f'std={std:.3f} \nmean={mean:.3f}', backgroundcolor="w")
#plt.show()
np.savetxt(txt_files[i] + "_Widmo.txt", X_mag_plot, delimiter="\t")
plt.savefig(txt_files[i] + ".png", dpi=250)
if i == 1:
np.savetxt(txt_files[0] + "_Fs.txt", f_plot, delimiter="\t")
del f_plot
del X_mag_plot
del txt_files[i]
【问题讨论】:
-
嗨,我想,你需要在保存后清除图像,为下一个循环做好准备。为此,您可以将
plt.clf()放在plt.savefig之后。如果这有帮助,请告诉我。
标签: python python-3.x matplotlib fft