for the physical laboratory our professor gave us a task to make analysis of a frequency spectrum of a plucked string. After the sound acquisition we were given a script to perform a FFT.
After the FFT we now have several frequency peaks.
He then told us that we have to calculate the intensity of each peak separately. I am new to this topic, so I am asking for your help how to alter the given code to get as an output peak intensity let's say from 760 to 765 Hz.
The code is here:
from scipy.fftpack import fft,ifft
import matplotlib.pyplot as plt
from scipy.signal import blackman
data = np.loadtxt("mic.txt")
x = data[:,0]
y = data[:,1]
fy = fft(y)
print np.sum(y),"==",fy[0]
n = len(x)
t = x[-1]
fx = np.linspace(0,n/t,n)
plt.plot(fx[0:n/2],np.abs(fy[0:n/2]))
plt.xlabel("frequency (Hz)")
plt.show()
I would appreciate your help, Matthew
By peak intensity I assume you mean the magnitude of each peak (of course it can be normalized). I used scipy.signal.find_peaks
to get the peaks in the spectrum. Because FFT returns complex values, I used it on the absolute value of y. This is a generic example, so finding the maximums is not that trivial in most cases. There are other peak detection tools, such as scipy.signal.find_peaks_cwt
, or peakutils
package. From the scipy tutorials here is a minimal working example:
import numpy as np
from scipy.fft import fft
import matplotlib.pyplot as plt
from scipy.signal import find_peaks
N = 600
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0 * np.pi * x) + 0.5 * np.sin(80.0 * 2.0 * np.pi * x)
yf = fft(y)
xf = np.linspace(0.0, 1.0 / (2.0 * T), N//2)
# finding the peaks in the absolute value of y
y_abs = 2.0 / N * np.abs(yf[0:N//2])
peakind, _ = find_peaks(y_abs)
plt.plot(xf, y_abs)
# plotting the peaks
plt.plot(xf[peakind], y_abs[peakind], 'k.')
plt.grid()
plt.show()
The magnitue of the peaks is just
>>> y_abs[peakind]
[0.70947072 0.4914645 ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.