我们从Python开源项目中,提取了以下7个代码示例,用于说明如何使用matplotlib.mlab.specgram()。
def __spectrogram(self,data,samp_rate,window,per_lap,wlen,mult): samp_rate = float(samp_rate) if not wlen: wlen = samp_rate/100.0 npts=len(data) nfft = int(self.__nearest_pow_2(wlen * samp_rate)) if nfft > npts: nfft = int(self.__nearest_pow_2(npts / 8.0)) if mult is not None: mult = int(self.__nearest_pow_2(mult)) mult = mult * nfft nlap = int(nfft * float(per_lap)) end = npts / samp_rate window = signal.get_window(window,nfft) specgram, freq, time = mlab.specgram(data, Fs=samp_rate,window=window,NFFT=nfft, pad_to=mult, noverlap=nlap) return specgram,freq,time # Sort data by experimental conditions and plot spectrogram for analog signals (e.g. LFP)
def save_specgram_to_file(data, filename, n_fft=512, fs=44100, overlap=192): """Spectrogram""" params = { "NFFT": n_fft, "Fs": fs, "noverlap": overlap } P, freqs, bins = mlab.specgram(data.copy(), **params) Z = np.log10(np.flipud(P)) xextent = 0, np.amax(bins) xmin, xmax = xextent extent = xmin, xmax, freqs[0], freqs[-1] plt.figure(figsize=[20,6]) im = plt.imshow(Z, extent=extent) plt.axis('auto') plt.xlim([0.0, bins[-1]]) plt.ylim([0, 44100 / 2]) plt.savefig(filename)
def standard_specgram(signal): "Return specgram matrix, made using the audio-layer config" return np.array(specgram(signal, NFFT=audioframe_len, noverlap=audioframe_len-audioframe_stride, window=np.hamming(audioframe_len))[0][specbinlow:specbinlow+specbinnum,:], dtype=float32)
def create_spectrogram(data, n_fft=512, fs=44100, overlap=192, norm=False): params = { "NFFT": n_fft, "Fs": fs, "noverlap": overlap } _specgram, freqs, bins = mlab.specgram(data.copy(), **params) _specgram = preprocess(_specgram) if norm: return min_max_scale(_specgram) / 255. return _specgram
def audioToFilteredSpectrogram(data, expandByOne = True, dropZeroColumnsPercent = 0.95): # calculate the spectogram tempSpec = np.log10(mlab.specgram(data, NFFT=512, noverlap=256, Fs=16000)[0]) # drop higher frequencies tempSpec = tempSpec[0:200,:] tempSpecFiltered = np.copy(tempSpec) # we analize the spectogram by 20x30 sized cells # to achieve better accuray the size of this cell should be finetuned rowBorders = np.ceil(np.linspace(0,tempSpec.shape[0], 20)) columnBorders = np.hstack((np.ceil(np.arange(0,tempSpec.shape[1], 30)), tempSpec.shape[1])) rowBorders = [ int(x) for x in rowBorders ] columnBorders = [ int(x) for x in columnBorders ] keepCells = np.ones((len(rowBorders)-1, len(columnBorders)-1)) # we create a mask for the spectogram: we scan the spectogram with the 20x30 sized # cell and create 0 mask based on the mean and std of the spectogram calculated for the cells and rows for i in range(len(rowBorders)-1): row_mean = np.mean(tempSpec[rowBorders[i]:rowBorders[i+1],:]) row_std = np.std(tempSpec[rowBorders[i]:rowBorders[i+1],:]) for j in range(len(columnBorders)-1): cell_mean = np.mean(tempSpec[rowBorders[i]:rowBorders[i+1],columnBorders[j]:columnBorders[j+1]]) cell_max_top10_mean = np.mean(np.sort(tempSpec[rowBorders[i]:rowBorders[i+1],columnBorders[j]:columnBorders[j+1]], axis=None)[-10:]) if (cell_mean < 0 or ((cell_max_top10_mean) < (row_mean + row_std)*1.5)): keepCells[i,j]=0 # expand by ones (see above) if expandByOne: keepCells = expandOnes(keepCells) # apply the mask to the spectogram for i in range(keepCells.shape[0]): for j in range(keepCells.shape[1]): if not keepCells[i,j]: tempSpecFiltered[rowBorders[i]:rowBorders[i+1],columnBorders[j]:columnBorders[j+1]] = 0 # drop zero columns # the amount of zero values along axis 0 (frequency) is calculated for every column (timeslice) # and it is dropped, if the number of zero values is higher than the dropZeroColumnsPercent # eg. dropZeroColumnsPercent=0.95, than a column (timeslice) is dropped, if more than 95% of the values (frequencies) is 0 tempSpecFilteredBackup = np.copy(tempSpecFiltered) tempSpecFiltered = np.delete(tempSpecFiltered, np.nonzero((tempSpecFiltered==0).sum(axis=0) > tempSpecFiltered.shape[0]*dropZeroColumnsPercent), axis=1) # if every row was 0 than use the backed up spectogram if tempSpecFiltered.shape[1] == 0: tempSpecFiltered = tempSpecFilteredBackup return tempSpec, tempSpecFiltered; # function to return most common classes in the dataset
def fingerprint(channel_samples, Fs=DEFAULT_FS, wsize=DEFAULT_WINDOW_SIZE, wratio=DEFAULT_OVERLAP_RATIO, fan_value=DEFAULT_FAN_VALUE, amp_min=DEFAULT_AMP_MIN, plots=False): # show samples plot if plots: plt.plot(channel_samples) plt.title('%d samples' % len(channel_samples)) plt.xlabel('time (s)') plt.ylabel('amplitude (A)') plt.show() plt.gca().invert_yaxis() # FFT the channel, log transform output, find local maxima, then return # locally sensitive hashes. # FFT the signal and extract frequency components # plot the angle spectrum of segments within the signal in a colormap arr2D = mlab.specgram( channel_samples, NFFT=wsize, Fs=Fs, window=mlab.window_hanning, noverlap=int(wsize * wratio))[0] # show spectrogram plot if plots: plt.plot(arr2D) plt.title('FFT') plt.show() # apply log transform since specgram() returns linear array arr2D = 10 * np.log10(arr2D) # calculates the base 10 logarithm for all elements of arr2D arr2D[arr2D == -np.inf] = 0 # replace infs with zeros # find local maxima local_maxima = get_2D_peaks(arr2D, plot=plots, amp_min=amp_min) msg = ' local_maxima: %d of frequency & time pairs' print colored(msg, attrs=['dark']) % len(local_maxima) # return hashes return generate_hashes(local_maxima, fan_value=fan_value)