绘制信号的频谱

时间:2014-07-19 08:06:04

标签: python numpy fft

from numpy.fft import fft
from numpy import array
a = array([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]
print( ' '.join("%5.3f" % abs(f) for f in fft(a)) )

我正在使用此代码获取信号的fft,但我如何绘制fft。 感谢

1 个答案:

答案 0 :(得分:4)

以下是我编写的用于绘制wav文件的示例。 它稍微复杂一点,因为它通过平均左右声道来处理立体声声音文件。它描绘了信号和fft。

from __future__ import print_function, division
import wave
import numpy as np
import matplotlib.pyplot as plt

wr = wave.open('input.wav', 'r')
sz = wr.getframerate()
q = 5  # time window to analyze in seconds
c = 12  # number of time windows to process
sf = 1.5  # signal scale factor

for num in range(c):
    print('Processing from {} to {} s'.format(num*q, (num+1)*q))
    avgf = np.zeros(int(sz/2+1))
    snd = np.array([])
    # The sound signal for q seconds is concatenated. The fft over that
    # period is averaged to average out noise.
    for j in range(q):
        da = np.fromstring(wr.readframes(sz), dtype=np.int16)
        left, right = da[0::2]*sf, da[1::2]*sf
        lf, rf = abs(np.fft.rfft(left)), abs(np.fft.rfft(right))
        snd = np.concatenate((snd, (left+right)/2))
        avgf += (lf+rf)/2
    avgf /= q
    # Plot both the signal and frequencies.
    plt.figure(1)
    a = plt.subplot(211)  # signal
    r = 2**16/2
    a.set_ylim([-r, r])
    a.set_xlabel('time [s]')
    a.set_ylabel('signal [-]')
    x = np.arange(44100*q)/44100
    plt.plot(x, snd)
    b = plt.subplot(212)  # frequencies
    b.set_xscale('log')
    b.set_xlabel('frequency [Hz]')
    b.set_ylabel('|amplitude|')
    plt.plot(abs(avgf))
    plt.savefig('simple{:02d}.png'.format(num))
    plt.clf()

下面是它生成的一个图。由于我的自定义matplotlibrc,颜色等等与默认值不同。

Sample output image of fft plot script