def decoderDiagnostics(waveform=None): if waveform is None: waveform = badPacketWaveforms[-1] Fs_eff = Fs / upsample_factor ac = wifi.autocorrelate(waveform) ac_t = np.arange(ac.size) * 16 / Fs_eff synch = wifi.synchronize(waveform) / float(Fs_eff) pl.figure(2) pl.clf() pl.subplot(211) pl.specgram(waveform, NFFT=64, noverlap=64 - 1, Fc=Fc, Fs=Fs_eff, interpolation='nearest', window=lambda x: x) pl.xlim(0, waveform.size / Fs_eff) yl = pl.ylim() pl.vlines(synch, *yl) pl.ylim(*yl) pl.subplot(212) pl.plot(ac_t, ac) yl = pl.ylim() pl.vlines(synch, *yl) pl.ylim(*yl) pl.xlim(0, waveform.size / Fs_eff)
def plotSpec(d1, d2, fs2): ln1 = len(d1) ln2 = len(d2) fs2 = fs2 * 1.0 time_s = ln1 / fs2 pl.subplot(321) pl.plot(d1) pl.subplot(322) pl.plot(d2) pl.subplot(323) pxx, freq, t, cax = pl.specgram(d1, Fs=fs2) pl.subplot(324) pxx, freq, t, cax = pl.specgram(d2, Fs=fs2) pl.subplot(325) yf = fftpack.fft(d1) xf = fftpack.fftfreq(ln1, 1 / fs2) yf = 2.0 / ln1 * np.abs(yf[0:ln1 / 2]) pl.plot(xf[1:int(100 * time_s)], yf[1:int(100 * time_s)]) pl.subplot(326) yf = fftpack.fft(d2) xf = fftpack.fftfreq(ln2, 1 / fs2) yf = 2.0 / ln2 * np.abs(yf[0:ln2 / 2]) pl.plot(xf[1:int(100 * time_s)], yf[1:int(100 * time_s)]) pl.show()
def graph_spectrogram(wav_file): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(19, 12)) pylab.axes(frameon = False) pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig('pngs/%s.png' % os.path.splitext(wav_file)[0], bbox_inches = 'tight') sleep(60)
def spectrogram(t, x, Fs, NFFT=256): ax1 = pylab.subplot(211) pylab.plot(t, x) pylab.subplot(212, sharex=ax1) pylab.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=NFFT/2, cmap=pylab.cm.gist_heat)
def graph_spectrogram(wav_file): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.title('spectrogram of %r' % wav_file) pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig('spectrogram.png')
def spectrogram(Y, Fs): s = Y.shape if len(Y.shape) > 1: ch = s[1] else: ch = 1 #Ym = numpy.sum( Y , 1 ) / float(ch) for j in numpy.arange(ch): pyplot.subplot(210 + j + 1) pylab.specgram(Y[:, j], NFFT=Fs, Fs=Fs, cmap='gnuplot2') mean_x = numpy.array([0, s[0] * (1 / Fs)]) mean_x = numpy.array([mean, mean]) pyplot.axis([0, s[0] * (1 / Fs), 0, Fs / 2.0]) pyplot.title("Channel %d" % j) pyplot.xlabel('Time [sec]') pyplot.ylabel('Freq. [Hz]') pyplot.grid(True) pyplot.title("Channel: %d" % int(j + 1)) pyplot.show()
def predict(): start_time = time.time() file = request.files['image'] if file: filename = file.filename file_path = os.path.join(filename) print("file path ",file_path) file.save(file_path) tempImageFile = tempfile.mktemp(".jpg") sound_info, frame_rate = get_wav_info(file_path) pylab.axis('off') # no axis pylab.axes([0., 0., 1., 1.], frameon=False, xticks=[], yticks=[]) pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig(tempImageFile) pylab.savefig("tempImageFile.jpg") pylab.close() st = "0" * 1 test_feat = list(st) img = skimage.io.imread(tempImageFile) img_resized = resize(img, (100,100), anti_aliasing=True, mode='reflect') test_feat[0] = img_resized test_feat = np.asarray(test_feat) y = clf1.predict(test_feat[0].reshape(1,-1)) print("result ",y) data = {"time": str(time.time() - start_time), "result": str(y)} js = json.dumps(data) res = Response(js, status=200, mimetype="application/json") return res
def graph_spectrogram(wav_file,i): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(0.28, 0.28)) pylab.subplot(111) pylab.axis('off') pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig("sound_"+str(i)+".png",transparent=True)
def graph_spectrogram(wav_file): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.title('spectrogram of %r' % wav_file) pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig('D:\spectrogram.png')
def makeimg(wav): global callpath global imgpath fs, frames = wavfile.read(os.path.join(callpath, wav)) pylab.ion() # generate specgram pylab.figure(1) # generate specgram pylab.specgram( frames, NFFT=256, Fs=22050, detrend=pylab.detrend_none, window=numpy.hamming(256), noverlap=192, cmap=pylab.get_cmap('Greys')) x_width = len(frames)/fs pylab.ylim([0,11025]) pylab.xlim([0,round(x_width,3)-0.006]) img_path = os.path.join(imgpath, wav.replace(".wav",".png")) pylab.savefig(img_path) return img_path
def graph_spectrogram(wav_file): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.title('spectrogram of %r' % wav_file) pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig('spectrogram - %s' % os.path.splitext(wav_file)[0])
def spectogram_librosa(_wav_file_,flag): (sig, rate) = librosa.load(_wav_file_, sr=None, mono=True, dtype=np.float32) pylab.specgram(sig, Fs=rate) if flag==0: pylab.savefig(_wav_file_+'spec_input.png') else: pylab.savefig(_wav_file_+'spec_output.png')
def draw_channel_with_spectrogram(stream, channel_id): ''' Draw one channel of given ID within its original range ''' time = stream.get_channel_sample_timestamps(channel_id, 0, 10000) # scale time to seconds: scale_factor_for_second = Q_(1, time[1]).to(ureg.s).magnitude time_in_sec = time[0] * scale_factor_for_second signal = stream.get_channel_in_range(channel_id, 0, 10000) sampling_frequency = stream.channel_infos[ channel_id].sampling_frequency.magnitude # already in Hz pl.figure(figsize=(20, 12)) # time domain axtp = pl.subplot(211) pl.plot(time_in_sec, signal[0]) pl.xlabel('Time (%s)' % time[1]) pl.ylabel('Voltage (%s)' % signal[1]) pl.title('Sampled signal (%s)' % stream.label) # frequency domain pl.subplot(212) pl.specgram(signal[0], NFFT=512, noverlap=128, Fs=sampling_frequency, cmap=pl.cm.gist_heat, scale_by_freq=False) pl.xlabel('Time (%s)' % time[1]) pl.ylabel('Frequency (Hz)') pl.show()
def spectrogram(Y, Fs): s = Y.shape if len(Y.shape) > 1: ch = s[1] else: ch = 1 # Ym = numpy.sum( Y , 1 ) / float(ch) for j in numpy.arange(ch): pyplot.subplot(210 + j + 1) pylab.specgram(Y[:, j], NFFT=Fs, Fs=Fs, cmap="gnuplot2") mean_x = numpy.array([0, s[0] * (1 / Fs)]) mean_x = numpy.array([mean, mean]) pyplot.axis([0, s[0] * (1 / Fs), 0, Fs / 2.0]) pyplot.title("Channel %d" % j) pyplot.xlabel("Time [sec]") pyplot.ylabel("Freq. [Hz]") pyplot.grid(True) pyplot.title("Channel: %d" % int(j + 1)) pyplot.show()
def run_cnn(filename, cnn_th): sound_info, frame_rate = get_wav_info(filename) #Use Pylab to draw spectograph on canvas and then take image from canvas. fig = pylab.figure(num=None, figsize=(19, 12)) fig.add_axes([0, 0, 1, 1]) pylab.specgram(sound_info, Fs=frame_rate) fig.tight_layout() pylab.axis('off') pylab.draw() fig.canvas.draw() image_from_plot = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) image_from_plot = image_from_plot.reshape( fig.canvas.get_width_height()[::-1] + (3, )) im = PILImage.fromarray(image_from_plot) im = im.resize((150, 150)) img_tensor = image.img_to_array(im) img_tensor = np.expand_dims(img_tensor, axis=0) img_tensor /= 255. pylab.close() y = model_CNN.predict(img_tensor) if y < cnn_th: r = random.randint(1, 1000000) #I am saving all activations, which I can use later to improve prediction. audiofile = 'Activations/Record-' + str(r) + '.wav' os.rename(filename, audiofile) print("C NN: " + str(y)) return True return False
def call_spec(): global y, NFFT, Fsamp, Fcentre, foverlap, detrend, _window, _type, fmod, chan_name, diag_name print len(y), NFFT, foverlap, _type, fmod ax = pl.subplot(111) z = _window(y) if _type == 'F': shot = callback.get_shot() print("shot=%d") % shot data = device.acq.getdata(shot, diag_name) if chan_name == '': try: ch = data.channels print("Choosing from", [chn.name for chn in ch]) name = ch[channel_number].name except: print "Failed to open channel database - try mirnov_1_8" name = 'mirnov_1_8' name = 'mirnov_linear_2' else: name = chan_name # data = pyfusion.load_channel(shot,name) # data = pyfusion.acq.getdata(shot_number, diag_name) if type(data) == type(None): return (False) if _window == local_none: windowfn = pl.window_none # else: windowfn=pl.window_hanning elif _window == local_hanning: windowfn = pl.window_hanning else: windowfn = _window(arange(NFFT)) clim = (-60, 20) # eventually make this adjustable # colorbar commented out because it keeps adding itself data.plot_spectrogram(NFFT=NFFT, windowfn=windowfn, noverlap=foverlap * NFFT, channel_number=channel_number) # colorbar=True, clim=clim) # colorbar() # used to come up on a separate page, fixed, but a little clunky - leave for now return (True) elif _type == 'T': # some matplotlib versions don't know about Fc pl.specgram( z * y, NFFT=NFFT, Fs=Fsamp, detrend=detrend, # window = _window noverlap=foverlap * NFFT, cmap=cmap) elif _type == 'L': pl.plot(20 * log10(abs(fft.fft(y * z)))) elif _type == 'W': pl.plot(z) elif _type == 'C': pl.plot(hold=0) else: raise ' unknown plot type "' + _type + '"'
def evaluate(self, case): """ Evaluate the target. Create an audio spectrogram based off of the given audio file and add it to the results. :param case: A case returned by ``enumerate``. For this unit,\ the ``enumerate`` function is not used. :return: None. This function should not return any data. """ # Generate the artifact's (no creation, effectively grab the path) linear_path, _ = self.generate_artifact("spectrogram_linear.png", create=False) dB_path, _ = self.generate_artifact("spectrogram_dB.png", create=False) # Prettify the audio spectrogram output. pylab.style.use(["seaborn-dark"]) pylab.tight_layout() sound_info, frame_rate = get_info(self.target.path) # If we fail to get info, then stop this unit/ if sound_info is None and frame_rate is None: return # Stop the unit pylab.figure(num=None, figsize=(18, 10), frameon=False) pylab.specgram( x=sound_info, Fs=2, NFFT=1024, mode="magnitude", scale="linear", sides="onesided", ) # Do not display axes in the spectrogram image file. pylab.gca().axes.get_yaxis().set_visible(False) pylab.gca().axes.get_xaxis().set_visible(False) pylab.savefig(linear_path, pad_inches=0, bbox_inches="tight", bbox_extra_artists=[]) pylab.specgram( x=sound_info, Fs=2, NFFT=1024, mode="magnitude", scale="dB", sides="onesided", ) pylab.savefig(dB_path, pad_inches=0, bbox_inches="tight", bbox_extra_artists=[]) # Register the figures with the manager self.manager.register_artifact(self, linear_path) self.manager.register_artifact(self, dB_path)
def graph_spectrogram(au_file, i, j, name): sound_info, frame_rate = get_info(au_file, name) pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig('images/spectrogram' + str(j) + str(i) + '.png') pylab.close()
def generate_spectogram(filename): sound_info, frame_rate = get_wav_info('./recordings/' + filename) pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.title('Spectrogram of %r' % filename) pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig('images/spectrogram' + filename + '.png') pylab.show()
def generate_Spectrogram(): return pylab.specgram(samples, Fs=fs) #pylab.figure(num=None, figsize=(19, 12)) #pylab.subplot(111) #pylab.title('spectrogram of %r' % wav_file) Sxx = pylab.specgram(sound_info, Fs=frame_rate) #pylab.savefig('spectrogram1.png') return Sxx
def frequency_plot(channel_one): pylab.specgram(channel_one, Fs=44100) pylab.xlabel("Time (s) (equivalent to distance)") pylab.ylabel("Frequency") ax=pylab.gca() ax.xaxis.set_major_formatter(FormatStrFormatter('%0.4f')) ax.yaxis.set_major_formatter(FormatStrFormatter('%0.0f')) pylab.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.1)
def graph_spectrogram(wav_file, class_, filename): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(256, 256)) pylab.subplot(111) pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig( '/Users/Janjua/Desktop/ESC-50-master/dataset/{}/{}.png'.format( class_, filename))
def gen_spectrogram(self, wav_file): self.file_count = self.file_count + 1 self.sound_info, self.frame_rate = self.get_wave_info(wav_file) pl.figure(num=None, figsize=(19, 12)) pl.subplot(111) pl.title('spectrogram of %r' % wav_file) pl.specgram(self.sound_info, Fs=self.frame_rate) pl.savefig(os.getcwd() + self.img_path_save + str(self.file_count))
def make_spectrogram(): sound_info, frame_rate = get_wav_info("Bad_Apple.wav") pylab.figure(num=None, figsize=(30, 40)) pylab.subplot(111) pylab.title('spectrogram of %r' % "Bad_Apple.wav") pylab.specgram(sound_info, Fs=frame_rate, detrend='linear') pylab.gray() pylab.savefig('spectrogram.png')
def plot_spectrogram(input_data, windowfn=None, channel_number=0, filename=None, coloraxis=None, noverlap=0, NFFT=None, **kwargs): import pylab as pl if windowfn == None: windowfn = pl.window_hanning # look in the config file section Plots for NFFT = 1234 # Dave - how about a method to allow this in one line # e.g. pyfusion.config.numgetdef('Plots','NFFT', 2048) # usage: # if (NFFT==None): NFFT = pyfusion.config.numgetdef('Plots','NFFT', 2048) # # also nice to have pyfusion.config.re-read() if NFFT == None: try: NFFT = (eval(pyfusion.config.get('Plots', 'NFFT'))) except: NFFT = 2048 pl.specgram(input_data.signal.get_channel(channel_number), NFFT=NFFT, noverlap=noverlap, Fs=input_data.timebase.sample_freq, window=windowfn, **kwargs) #accept multi or single channel data (I think?) if coloraxis != None: pl.clim(coloraxis) else: try: pl.clim(eval(pyfusion.config.get('Plots', 'coloraxis'))) except: pass # look in the config file section Plots for a string like FT_Axis = [0,0.08,0,500] # don't quote try: pl.axis(eval(pyfusion.config.get('Plots', 'FT_Axis'))) except: pass try: pl.title("%d, %s" % (input_data.meta['shot'], input_data.channels[channel_number].name)) except: pl.title("%d, %s" % (input_data.meta['shot'], input_data.channels.name)) if filename != None: pl.savefig(filename) else: pl.show()
def graph_spectrogram(wav_file): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(8, 5)) pylab.subplot(111) #pylab.title('spectrogram of %r' % wav_file) pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig("/home/divinelink/Desktop/ASR-System/spectrograms/" + os.path.splitext(wav_file)[0] + '.png') plt.close()
def graph_spectrogram(full_path, wavfile): sound_info, frame_rate = get_wav_info(full_path) pylab.figure(num=None, figsize=(2.27, 2.27)) pylab.subplot(111) pylab.title('spectrogram of %r' % wavfile) pylab.specgram(sound_info, Fs=frame_rate) name = os.path.splitext(wavfile)[0] + '.png' print name pylab.savefig(name)
def graph_spectrogram(wav_file): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(8, 6)) pylab.subplot(111) pylab.title('spectrogram of %r' % wav_file) pylab.ylabel('Frequency') pylab.xlabel('Time') pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig('spectrogram.png')
def graph_spectrogram(wav_file): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.title('spectrogram of %r' % wav_file) pylab.specgram(sound_info, Fs=frame_rate) pylab.scatter(wordBoundary(path_to_file), [5000 for i in range(len((wordBoundary(path_to_file))))], color='r')
def graph_spectrogram(wav_file): sound_info, frame_rate = get_wav_info(wav_file) #pylab.figure(num=None, figsize=(19, 12)) #pylab.subplot(111) #pylab.title('spectrogram of %r' % wav_file) pylab.specgram(sound_info, Fs=frame_rate) spec_img_path = wav_file.split('.')[0] + '.png' pylab.savefig(spec_img_path) return spec_img_path
def spektrogramy(): sred_r,sred_s=np.average(o1_bez,axis=0),np.average(o1_sty,axis=0) py.subplot(121) py.specgram(sred_r, Fs=fs, scale_by_freq=True) py.title('ref') py.subplot(122) py.specgram(sred_s, Fs=fs, scale_by_freq=True) py.title('stym') py.show()
def audio_to_spectrogram(self): sound_info, frame_rate = self.get_wav_info(self.audiopath) fig = pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.axes([0, 0, 1, 1]) pylab.axis('off') pylab.specgram(sound_info, Fs=frame_rate) filename = "/home/mitchell/Documents/speech_data_files/spectrograms/spectrogram_v0" pylab.savefig(filename)
def Wav2Spec(audio_file): filename = audio_file.split('.')[0] sound_info, frame_rate = get_wav_info(audio_file) pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig(f'{filename}3.png') pylab.close()
def graph_spectrogram(wav_file,name): sound_info, frame_rate = get_wav_info(wav_file) # By default generated spectrograms are of size 19 cm x 12 cm. This can be changed by changing the values in figsize argument # Eg figsize=(5,5) will generate images of size 5 cm x 5 cm pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.axis('off') pylab.specgram(sound_info, Fs=frame_rate) pylab.savefig(name+".png",transparent=True)
def graph_spectrogram(self, save=False): sound_info, frame_rate = self.get_wav_info() pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.title('spectrogram of %r' % self.path) pylab.specgram(sound_info, Fs=frame_rate) pylab.show() if save: pylab.savefig('spectrogram.png')
def graph_spectrogram(wav_file, fn): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(2.56,2.56)) #pylab.subplot(111) #pylab.title('spectrogram of %r' % wav_file) pylab.specgram(sound_info, Fs=frame_rate) plt.axis('off') # plt.axis('off') #pylab.savefig('./zzzz/0000.png') pylab.savefig(fn + "_그만해.png")
def graph_spectrogram(wav_file): #amount = len([name for name in os.listdir('/home/mitchell/Documents/speech_data_files/spectrograms') if os.path.isfile(name)]) sound_info, frame_rate = get_wav_info(wav_file) fig = pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.axes([0, 0, 1, 1]) pylab.axis('off') pylab.specgram(sound_info, Fs=frame_rate) filename = "/home/mitchell/Documents/speech_data_files/spectrograms/spectrogram_v0" pylab.savefig(filename)
def plot_spectrogram(input_data, windowfn=None, units='kHz', channel_number=0, filename=None, coloraxis=None, noverlap=0,NFFT=None, **kwargs): import pylab as pl if windowfn == None: windowfn=pl.window_hanning # look in the config file section Plots for NFFT = 1234 # Dave - how about a method to allow this in one line # e.g. pyfusion.config.numgetdef('Plots','NFFT', 2048) # usage: # if (NFFT==None): NFFT = pyfusion.config.numgetdef('Plots','NFFT', 2048) # # also nice to have pyfusion.config.re-read() if NFFT == None: try: NFFT=(int(pyfusion.config.get('Plots','NFFT'))) except: NFFT = 2048 print(NFFT) if units.lower() == 'khz': ffact = 1000. else: ffact =1. xextent=(min(input_data.timebase),max(input_data.timebase)) pl.specgram(input_data.signal.get_channel(channel_number), NFFT=NFFT, noverlap=noverlap, Fs=input_data.timebase.sample_freq/ffact, window=windowfn, xextent=xextent, **kwargs) #accept multi or single channel data (I think?) if coloraxis != None: pl.clim(coloraxis) else: try: pl.clim(eval(pyfusion.config.get('Plots','coloraxis'))) except: pass # look in the config file section Plots for a string like # FT_Axis = [0,0.08,0,500e3] don't quote try: #pl.axis(eval(pyfusion.config.get('Plots','FT_Axis'))) # this is clumsier now we need to consider freq units. axt = eval(pyfusion.config.get('Plots','FT_Axis')) pl.axis([axt[0], axt[1], axt[2]/ffact, axt[3]/ffact]) except: pass # but override X if we have zoomed in bdb if 'reduce_time' in input_data.history: pl.xlim(np.min(input_data.timebase),max(input_data.timebase)) try: pl.title("%d, %s"%(input_data.meta['shot'], input_data.channels[channel_number].name)) except: pl.title("%d, %s"%(input_data.meta['shot'], input_data.channels.name)) if filename != None: pl.savefig(filename) else: pl.show()
def spectrogram(self, inputSignal=None, tempo=120): if inputSignal is None: inputSignal = self.data NFFT = int(8.0 * self.samplingRate / float(tempo)) noverlap = NFFT >> 2 if (len(inputSignal.shape) == 2): Pxx, freqs, bins, im = pylab.specgram(inputSignal[:, 0], NFFT=NFFT, Fs=self.samplingRate, noverlap=noverlap) return [Pxx, freqs, bins] else: Pxx, freqs, bins, im = pylab.specgram(inputSignal, NFFT=NFFT, Fs=self.samplingRate, noverlap=noverlap) return [Pxx, freqs, bins]
def plot(self, noverlap=0, cmap=cm.binary, window_length=20): """ Function to give Praat-style waveform + spectrogram + textgrid plot time is given in sec units """ # plot waveform subplot(3, 1, 1) plot(self.time, self.data, color='black', linewidth=0.2) # plot spectrogram subplot(3, 1, 2) nfft = int(float((window_length * self.rate)) / 1000) specgram(self.data, NFFT=nfft, noverlap=noverlap, cmap=cmap)
def plotPartialSpectrogram(self, timeStart, timeEnd, inputSignal=None, tempo=120): if inputSignal is None: inputSignal = self.data startIndex = timeStart * self.samplingRate stopIndex = timeEnd * self.samplingRate NFFT = int(8.0 * self.samplingRate / float(tempo)) noverlap = NFFT >> 2 if (len(inputSignal.shape) == 2): Pxx, freqs, bins, im = pylab.specgram(inputSignal[startIndex:stopIndex, 0], NFFT=NFFT, Fs=self.samplingRate, noverlap=noverlap) pylab.show() else: Pxx, freqs, bins, im = pylab.specgram(inputSignal[startIndex:stopIndex], NFFT=NFFT, Fs=self.samplingRate, noverlap=noverlap) pylab.show()
def call_spec(): global y,NFFT,Fsamp,Fcentre,foverlap,detrend,_window, _type, fmod, chan_name, diag_name, hold print len(y), NFFT,foverlap, _type, fmod ax = pl.subplot(111) z=_window(y) if _type=='F': shot=callback.get_shot() print("shot={s}".format(s=shot)) data = device.acq.getdata(shot, diag_name) if chan_name=='': try: ch=data.channels print("Choosing from", [chn.name for chn in ch]) name=ch[channel_number].name except: print "Failed to open channel database - try mirnov_1_8" name='mirnov_1_8' name='mirnov_linear_2' else: name=chan_name # data = pyfusion.load_channel(shot,name) # data = pyfusion.acq.getdata(shot_number, diag_name) if type(data)==type(None): return(False) if _window==local_none: windowfn=pl.window_none # else: windowfn=pl.window_hanning elif _window==local_hanning: windowfn=pl.window_hanning else: windowfn=_window(arange(NFFT)) clim=(-70,0) # eventually make this adjustable if hold==0: pl.clf() # colorbar commented out because it keeps adding itself data.plot_spectrogram(NFFT=NFFT, windowfn=windowfn, noverlap=foverlap*NFFT, channel_number=channel_number) # colorbar=True, clim=clim) # colorbar() # used to come up on a separate page, fixed, but a little clunky - leave for now return(True) elif _type == 'T': # some matplotlib versions don't know about Fc pl.specgram(z*y, NFFT=NFFT, Fs=Fsamp, detrend=detrend, # window = _window noverlap=foverlap*NFFT, cmap=cmap) elif _type == 'L': pl.plot(20*log10(abs(fft.fft(y*z)))) elif _type == 'W': pl.plot(z) elif _type =='C': pl.plot(hold=0) else: raise ' unknown plot type "' + _type +'"'
def graph_spectrogram(wav_file): sound_info, frame_rate = get_wav_info(wav_file) pylab.figure(num=None, figsize=(8, 6)) pylab.subplot(111) pylab.title('spectrogram of %r' % wav_file) pylab.specgram(sound_info, Fs=frame_rate, NFFT=4096, noverlap=4000, ) pylab.grid(True) pylab.axis((0.1, 1.85, 600, 2600)) pylab.yticks([ 740.0, 830.6, 932.6, 1108.7, 1244.5, 1480.0, 1661.2, 1864.66, 2217.46, 2489.0]) file_name, file_ext = os.path.splitext(wav_file) pylab.savefig('%s.%s' % (file_name, 'png'))
def read_word(word): try: data = W.read('words/%s.wav' % word) except: return freq = int(data[0]) # 16,000 if not freq == 16000: raise Exception('shit wrong freq') freq = freq / DOWN_SAMPLE wav_data = down_sample_vect(data[1]) if len(wav_data) > LIMIT or len(wav_data) < LIMIT * 0.9: return data = (data[0], center_vect(wav_data)) overlap_size = int(0.01 * freq) # 10ms ==> 160 Pxx, freqs, bins, im = P.specgram(x=data[1], NFFT = 256, Fs=freq, noverlap=overlap_size) #P.plot(data[1]) #import pdb; pdb.set_trace() print Pxx.shape # For now, cut the spectrogram to make it fit # TODO: should use PCA instead if not Pxx.shape == (129, 4): raise Exception('shape mismatched') global counter counter += 1 print len(data[1]) return (data[1], Pxx)
def extract_features(fname, bdir, sox, htk_mfc, mfc_extension, stereo_wav, gammatones, spectrograms, filterbanks): #def extract_features(fname, bdir): if fname[-4:] != '.wav': return rawfname = bdir+'/'+fname[:-4]+'.rawaudio' wavfname = bdir+'/'+fname tempfname = bdir+'/'+fname[:-4]+'_temp.wav' # temp fname with .wav for sox mfccfname = bdir+'/'+fname[:-4]+mfc_extension if sox: shutil.move(wavfname, tempfname) call(['sox', tempfname, wavfname]) #call(['sox', '-G', tempfname, '-r 16k', wavfname]) # w/o headers, sox uses extension shutil.move(tempfname, rawfname) if htk_mfc: call(['HCopy', '-C', 'wav_config', wavfname, mfccfname]) srate = 16000 #srate, sound = wavfile.read(wavfname) sound, srate = readwav(wavfname) if stereo_wav and len(sound.shape) == 2: # in mono sound is a list sound = 0.5 * (sound[:, 0] + sound[:, 1]) # for stereo wav, sum both channels if gammatones: gammatonefname = bdir+'/'+fname[:-4]+'_gamma.npy' tmp_snd = loadsound(wavfname) gamma_cf = erbspace(20*Hz, 20*kHz, N_GAMMATONES_FILTERS) gamma_fb = Gammatone(tmp_snd, gamma_cf) with open(gammatonefname, 'w') as o_f: npsave(o_f, gamma_fb.process()) if spectrograms: powerspec, _, _, _ = specgram(sound, NFFT=int(srate * SPECGRAM_WINDOW), Fs=srate, noverlap=int(srate * SPECGRAM_OVERLAP)) # TODO specgramfname = bdir+'/'+fname[:-4]+'_specgram.npy' with open(specgramfname, 'w') as o_f: npsave(o_f, powerspec.T) if filterbanks: # convert to Mel filterbanks fbanks = Spectral(nfilt=N_FBANKS, # nb of filters in mel bank alpha=0.97, # pre-emphasis do_dct=False, # we do not want MFCCs compression='log', fs=srate, # sampling rate lowerf=50, # lower frequency frate=FBANKS_RATE, # frame rate wlen=FBANKS_WINDOW, # window length nfft=1024, # length of dft do_deltas=False, # speed do_deltasdeltas=False # acceleration ) sound /= np.abs(sound).max(axis=0) # TODO put that as option fbank = fbanks.transform(sound) fbanksfname = bdir+'/'+fname[:-4]+'_fbanks.npy' with open(fbanksfname, 'w') as o_f: npsave(o_f, fbank) # TODO wavelets scattergrams / scalograms print "dealt with file", wavfname
def LFPPowerPerTrial_SingleBand_PerChannel_Timestamps(lfp,timestamps,Avg_Fs,channels,t_start,t_before,t_after,freq_window): ''' This method computes the power in a single band defined by power_band over sliding windows in the range [window_start_times-time_before,window_start_times + time_after]. This is done per trial and then a plot of power in the specified band is produce with time in the x-axis and trial in the y-axis. This is done per channel. Main difference with LFPPowerPerTrial_SingleBand_PerChannel is that t_start is in seconds and we don't assume a fixed time between samples. Inputs: - lfp: lfp data arrange in an array of data x channel - timestamps: time stamps for lfp samples, which may occur at irregular intervals - channels: list of channels for which to apply this method - Fs: sampling rate of data in lfp_data array in Hz - t_start: window start times in units of s - t_before: length of time in s to look at before the alignment times in window_start_times - t_after: length of time in s to look at after the alignment times - freq_window: list defining the window of frequencies to look at, should be of the form power_band = [f_min,f_max] ''' # Set up plotting variables # Set up matrix for plotting peak powers for chann in channels: trial_power = [] trial_times = [] for i, time in enumerate(t_start): lfp_snippet = [] lfp_snippet = [lfp[ind,chann] for ind in range(0,len(timestamps)) if (timestamps[ind] <= time + t_after)&(time - t_before <= timestamps[ind])] lfp_snippet = np.array(lfp_snippet) Sxx,f,t, fig = specgram(lfp_snippet,NFFT = 128,Fs=Avg_Fs,noverlap=56,scale_by_freq=False) f_band_ind = [ind for ind in range(0,len(f)) if (f[ind] <= freq_window[1])&(freq_window[0] <= f[ind])] f_band = np.sum(Sxx[f_band_ind,:],axis=0) f_band_norm = f_band/np.sum(f_band) trial_power.append(f_band_norm) trial_times.append(t) power_mat = np.zeros([len(t_start),len(trial_power[0])]) for ind in range(0,len(t_start)): if len(trial_power[ind]) == len(trial_power[0]): power_mat[ind,:] = trial_power[ind] else: power_mat[ind,:] = np.append(trial_power[ind],np.zeros(len(trial_power[0])-len(trial_power[ind]))) dx, dy = float(t_before+t_after)/len(t), 1 y, x = np.mgrid[slice(0,len(t_start),dy), slice(-t_before,t_after,dx)] cmap = plt.get_cmap('RdBu') plt.figure() plt.title('Channel %i - Power in band [%f,%f]' % (chann,freq_window[0],freq_window[1])) plt.pcolormesh(x,y,power_mat,cmap=cmap) plt.ylabel('Trial num') plt.xlabel('Time (s)') plt.axis([x.min(),x.max(),y.min(),y.max()]) plt.show() return Sxx, f, t
def decoderDiagnostics(waveform=None): if waveform is None: waveform = badPacketWaveforms[-1] Fs_eff = Fs/upsample_factor ac = wifi.autocorrelate(waveform) ac_t = np.arange(ac.size)*16/Fs_eff synch = wifi.synchronize(waveform)/float(Fs_eff) pl.figure(2) pl.clf() pl.subplot(211) pl.specgram(waveform, NFFT=64, noverlap=64-1, Fc=Fc, Fs=Fs_eff, interpolation='nearest', window=lambda x:x) pl.xlim(0, waveform.size/Fs_eff) yl = pl.ylim(); pl.vlines(synch, *yl); pl.ylim(*yl) pl.subplot(212) pl.plot(ac_t, ac) yl = pl.ylim(); pl.vlines(synch, *yl); pl.ylim(*yl) pl.xlim(0, waveform.size/Fs_eff)
def main(): input = [] correct_types = [] strict_input = [] strict_types = [] FILES = "files.dat" random.seed(time.time()) # file_list = open(FILES,'r') file_list = sys.argv[1:] for line in file_list: f_name = line f_type = file_type(line) # sys.stderr.write("%s %d\n"%(f_name,f_type)) data_file = wave.open(f_name, "r") frame_rate = data_file.getframerate() frames = data_file.readframes(data_file.getnframes()) signal = np.fromstring(frames, "Int16") Pxx, freqs, bins, im = pylab.specgram(signal, Fs=frame_rate) combined_max_amp = np.amax(Pxx, axis=1) combined_mean_amp = np.mean(Pxx, axis=1) deg = 10 sm_amp = smoothListGaussian(combined_mean_amp, degree=deg) # pca_data = Normalize(sm_amp) svm_data = np.array(sm_amp) input.append(svm_data) correct_types.append(f_type) if random.random() >= 0.5: strict_input.append(svm_data) strict_types.append(f_type) data_file.close() if len(input) == 0: sys.stderr.write("No input files\n") exit(1) svc = svm.SVC(kernel="linear") # linear OR poly OR rbf # svc = svm.SVC(kernel='poly',degree=2) # svc = svm.SVC(kernel='rbf') # svc.fit(input, types) svc.fit(strict_input, strict_types) new_types = svc.predict(input) for i in range(TYPES_NUM): print new_types[i * 10 : i * 10 + 10] sys.stderr.write("%2.2f\n" % predict_quality(new_types, correct_types))
def graph_spectrogram(wav_file, Specgram_path, dir_path): try: sound_info, frame_rate = get_wav_info(wav_file) except Exception as e: print e return pylab.figure(num=None, figsize=(19, 12)) pylab.subplot(111) pylab.title('spectrogram of %r' % os.path.basename(wav_file).strip('.WAV').strip('.wav')) pylab.specgram(sound_info, Fs=frame_rate, cmap=cm.Greys) Specgram_dir = Specgram_path + dir_path.strip('.') + '/' Specgram_file_name = Specgram_dir + os.path.basename(wav_file).strip('.WAV').strip('.wav')+'.png' if not os.path.exists(Specgram_dir): os.makedirs(Specgram_dir) pylab.savefig(Specgram_file_name)
def update(self, data): sdata = pylab.specgram(data, Fs=44100) data_mean = np.mean(sdata[0], 1) curr_max = max(data_mean) if (curr_max > self.data_mean_max): self.data_mean_max = curr_max self.parent.spectrogram.setYRange(0, self.data_mean_max) xr = (len(sdata[1])/2) self.spec_data.setData(sdata[1][0:xr], data_mean[0:xr])
def process(folder, debug=False, htk_mfc=False, forcemfcext=False, stereo_wav=False, gammatones=False, spectrograms=False): """ debug output? HCopy for MFCC? wav are stereo? produce gammatones? """ # first find if we produce normalized MFCC, otherwise note it in the ext # because we can then normalize on the whole corpus with another py script mfc_extension = '.mfc_unnorm' wcfg = open('wav_config', 'r') for line in wcfg: if "ENORMALISE" in line: mfc_extension = '.mfc' if forcemfcext: mfc_extension = '.mfc' print "MFC extension:", mfc_extension # run through all the folders and files in the path "folder" # and put a header to the waves, save the originals as .rawaudio # use HCopy to produce MFCC files according to "wav_config" file for d, ds, fs in os.walk(folder): for fname in fs: if fname[-4:] != '.wav': continue rawfname = d+'/'+fname[:-4]+'.rawaudio' wavfname = d+'/'+fname tempfname = d+'/'+fname[:-4]+'_temp.wav' # temp fname with .wav for sox mfccfname = d+'/'+fname[:-4]+mfc_extension shutil.move(wavfname, tempfname) call(['sox', tempfname, wavfname]) # w/o headers, sox uses extension shutil.move(tempfname, rawfname) if htk_mfc: call(['HCopy', '-C', 'wav_config', wavfname, mfccfname]) sr = 16000 sr, sound = wavfile.read(wavfname) if stereo_wav and len(sound.shape) == 2: # in mono sound is a list sound = sound[:,1] # for stereo wav, arbitrarily take channel 1 if gammatones: from brian import Hz, kHz from brian.hears import loadsound, erbspace, Gammatone gammatonefname = d+'/'+fname[:-4]+'_gamma.npy' tmp_snd = loadsound(wavfname) cf = erbspace(20*Hz, 20*kHz, N_GAMMATONES_FILTERS) fb = Gammatone(tmp_snd, cf) with open(gammatonefname, 'w') as of: numpy.save(of, fb.process()) if spectrograms: from pylab import specgram Pxx, freqs, bins, im = specgram(sound, NFFT=int(sr * SPECGRAM_WINDOW), Fs=sr, noverlap=int(sr * SPECGRAM_OVERLAP)) specgramfname = d+'/'+fname[:-4]+'_specgram.npy' with open(specgramfname, 'w') as of: numpy.save(of, Pxx.T) print "dealt with file", wavfname
def specgram(filename): # Define contants nframes = 4000 print filename f = aifc.open(filename, "r") strsig = f.readframes(nframes) f.close() x = numpy.fromstring(strsig, numpy.short).byteswap() a = pylab.specgram(x) return a[0]
def examplePS6000(): fig=plt.figure() plt.ion() plt.show() print "Attempting to open..." ps = ps6000.PS6000() #Example of simple capture res = ps.setSamplingFrequency(250E6, 4096) sampleRate = res[0] print "Sampling @ %f MHz, %d samples"%(res[0]/1E6, res[1]) ps.setChannel("A", "AC", 50E-3) blockdata = np.array(0) for i in range(0, 50): ps.runBlock() while(ps.isReady() == False): time.sleep(0.01) print "Sampling Done" data = ps.getDataV("A", 4096) blockdata = np.append(blockdata, data) ##Simple FFT #print "FFT In Progress" #[freqs, FFTdb] = fft(data, res[0]) #plt.clf() #plt.plot(freqs, FFTdb) #plt.draw() start = (i - 5) * 4096 if start < 0: start = 0 #Spectrum Graph, keeps growing plt.clf() plt.specgram(blockdata[start:], NFFT=4096, Fs=res[0], noverlap=512) plt.xlabel('Measurement #') plt.ylabel('Frequency (Hz)') plt.draw() ps.close()
def show_spectrum(signal, Fsample = 8000): Pxx, freqs, t, plot = pylab.specgram( signal, NFFT=128, Fs = Fsample, detrend=pylab.detrend_none, window=pylab.window_hanning, noverlap=int(128 * 0.5)) pylab.show()
def ShowSpectogram(analyzer): try: import pylab except: print "Warning: module pylab (from matplotlib) could not be found. No charts will be displayed." return print "Producing Wave Time-Domain and Frequency-Domain charts... (close graph window to continue)" pylab.subplot(211) size = len(analyzer.data) timeRangeData = [1.0*analyzer.duration*i/size for i in xrange(size)] pylab.plot( timeRangeData, analyzer.data) pylab.title("Time-Domain") pylab.subplot(212) pylab.specgram(analyzer.data, NFFT=analyzer.GetBaseDFTBlockSize(), Fs=analyzer.frameRate, scale_by_freq=False, sides='default') pylab.title("Spectogram (Frequency-Domain)") pylab.show()
def getSpectrogramFeatures(X): """returns spectrogram features""" specFeatures = [] for i, x in enumerate(X): print "...making spectrogram features for instance: %d ...." % (i + 1) specgramx = pl.specgram(x)[0] filteredX = signal.wiener(specgramx) specFeatures.append(filteredX.reshape(filteredX.size)) pl.close() return np.array(specFeatures)
def gen_spcgrm(tankname,channel,cutoffs=(0,250),binsize=50): r = io.TdtIO(dirname=tankname) bl = r.read_block(lazy=False,cascade=True) for analogsig in bl.segments[0].analogsignals: if analogsig.name[:4]=='LFP2': analogsig.channel_index +=96 if (analogsig.name[:3]=='LFP')&(analogsig.channel_index==channel): data = analogsig srate = analogsig.sampling_rate spec,freqs,bins,im=specgram(data,Fs=srate,NFFT=binsize,noverlap=0) return
def main(): from .monitor import MatplotlibMonitor logging.basicConfig(level=logging.INFO) device = "/dev/rfcomm9" if len(sys.argv) > 1: device = sys.argv[1] collector = DataCollector(device, os.path.expanduser("~/pythinkgear_data"), monitor=MatplotlibMonitor(period=128)) session_id = collector.collect(SAMPLING_FREQUENCY * 60 * 10) data = collector.get_session(session_id) print "collected %d samples" % data.shape[0] print "mean: %0.3f" % data.mean() print "standard deviation: %0.3f" % data.std() pl.subplot(211) pl.title("Raw signal from the MindSet") pl.plot(data) pl.subplot(212) pl.specgram(data) pl.title("Spectrogram") pl.show()