• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python pyplot.specgram函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.pyplot.specgram函数的典型用法代码示例。如果您正苦于以下问题:Python specgram函数的具体用法?Python specgram怎么用?Python specgram使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了specgram函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: wav_to_spectrogram

def wav_to_spectrogram(audio_path, save_path, spectrogram_dimensions=(64, 64), noverlap=16, cmap="grey_r"):
    """ Creates a spectrogram of a wav file.

    :param audio_path: path of wav file
    :param save_path:  path of spectrogram to save
    :param spectrogram_dimensions: number of pixels the spectrogram should be. Defaults (64,64)
    :param noverlap: See http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html
    :param cmap: the color scheme to use for the spectrogram. Defaults to 'gray_r'
    :return:
    """

    sample_rate, samples = wav.read(audio_path)

    plt.specgram(samples, cmap=cmap, noverlap=noverlap)
    plt.axis("off")
    plt.tight_layout()
    plt.savefig(save_path, bbox_inches="tight", pad_inches=0)
    plt.tight_layout()

    # TODO: Because I cant figure out how to create a plot without padding
    # I am using `.trim()`, It would be better to do this in the plot itself.
    # Also probably better to do the sizing in the plot too.
    with Image(filename=save_path) as i:
        i.trim()
        i.resize(spectrogram_dimensions[0], spectrogram_dimensions[1])
        i.save(filename=save_path)
开发者ID:CosmoCaixa,项目名称:free-spoken-digit-dataset,代码行数:26,代码来源:spectogramer.py


示例2: plot_segment

def plot_segment(segment, window_size, step_size):
    """Plots the waveform, power over time, spectrogram with formants, and power over frequency of a Segment."""
    pyplot.figure()
    pyplot.subplot(2, 2, 1)
    pyplot.plot(numpy.linspace(0, segment.duration, segment.samples), segment.signal)
    pyplot.xlim(0, segment.duration)
    pyplot.xlabel('Time (s)')
    pyplot.ylabel('Sound Pressure')
    pyplot.subplot(2, 2, 2)
    steps, power = segment.power(window_size, step_size)
    pyplot.plot(steps, power)
    pyplot.xlim(0, segment.duration)
    pyplot.xlabel('Time (s)')
    pyplot.ylabel('Power (dB)')
    pyplot.subplot(2, 2, 3)
    pyplot.specgram(segment.signal, NFFT=window_size, Fs=segment.sample_rate, noverlap=step_size)
    formants = segment.formants(window_size, step_size, 2)
    pyplot.plot(numpy.linspace(0, segment.duration, len(formants)), formants, 'o')
    pyplot.xlim(0, segment.duration)
    pyplot.xlabel('Time (s)')
    pyplot.ylabel('Frequency (Hz)')
    pyplot.subplot(2, 2, 4)
    frequencies, spectrum = segment.power_spectrum(window_size, step_size)
    pyplot.plot(frequencies / 1000, 10 * numpy.log10(numpy.mean(spectrum, axis=0)))
    pyplot.xlabel('Frequency (kHz)')
    pyplot.ylabel('Power (dB)')
开发者ID:tim-shea,项目名称:speechvis,代码行数:26,代码来源:segment.py


示例3: creat_img

def creat_img(a,str_data,nchannels,sampwidth,framerate,nframes):
    #f = wave.open(r"C:/py/soudn/static/img/m"+a+".wav", "rb")
 
    # 读取格式信息
    # (nchannels, sampwidth, framerate, nframes, comptype, compname)
    #params = f.getparams()
    #nchannels, sampwidth, framerate, nframes = params[:4]
    #str_data = f.readframes(nframes)
    #f.close()
    #将波形数据转换为数组
    wave_data = np.fromstring(str_data, dtype=np.short)
    wave_data.shape = -1, nchannels
    wave_data = wave_data.T
    time = np.arange(0, nframes) * (1.0 / framerate)

    wave_data = wave_data/32768.0
    
    plt.subplot(211)
    plt.title('Amplitude Fig')
    plt.ylabel('Amplitude')
    plt.plot(time,wave_data[0])

    plt.subplot(212)
    plt.title('Spectrogram Fig')
    plt.xlabel('Time')
    plt.ylabel('Frequency')
    plt.specgram(wave_data[0], NFFT=1024, Fs=framerate, noverlap=400)
    plt.ylim(200,2500)
    plt.savefig("C:/py/soudn/static/img/m"+a+".png")
开发者ID:rosickey,项目名称:number-Voice-recognition,代码行数:29,代码来源:todo.py


示例4: plot_me

def plot_me(signal, i, imax, MySampleRate = SampleRate, NFFT = 8192, noverlap = 1024):
  a = pyplot.subplot(imax, 2, 2 * i + 1)
  pyplot.title("Left %i" % MySampleRate)
  pyplot.specgram(signal[0], NFFT = NFFT, Fs = MySampleRate, noverlap = noverlap )
  a = pyplot.subplot(imax, 2, 2 * (i + 1))
  pyplot.title("Right %i" % MySampleRate)
  pyplot.specgram(signal[1], NFFT = NFFT, Fs = MySampleRate, noverlap = noverlap )
开发者ID:kzantow,项目名称:QtVST,代码行数:7,代码来源:oversampling.py


示例5: plot_wav_and_spec

def plot_wav_and_spec(wav_path, f0):
  wav = get_wav(wav_path)
  fs = wav.getframerate()
  nf = wav.getnframes()
  ns = nf/float(fs)
  wav = fromstring(wav.readframes(-1), 'Int16')
  
  fig = pyplot.figure()
  pyplot.title(wav_path)
  w = pyplot.subplot(311)
  w.set_xlim(right=nf)
  w.plot(wav)
  pyplot.xlabel("Frames")
  s = pyplot.subplot(312)
  pyplot.specgram(wav, Fs=fs)
  s.set_xlim(right=ns)
  s.set_ylim(top=8000)
  if f0:
    f = pyplot.subplot(313)
    x_points = [(ns/len(f0))*x for x in range(1, len(f0)+1)]
    y_points = [x for x in f0]
    pyplot.plot(x_points, y_points)
    f.set_xlim(right=ns)
  pyplot.xlabel("Seconds")
  pyplot.show()
开发者ID:RasmusD,项目名称:SiRe,代码行数:25,代码来源:visualisation_tools.py


示例6: analize_dat

 def analize_dat(self, file_path, start, length, window, overlap):
     target_path = self._get_dat_target_path(file_path)
     start_sample = start * self.fs
     end_sample = start_sample + length * self.fs
     signal = []
     with open(target_path) as f:
         for i, line in enumerate(f):
             if len(line.strip()) and line[0] == ';':
                 continue
             if i < start_sample:
                 continue
             if i >= end_sample:
                 break
             vals = self._parse_line(line)
             if len(vals) > 2:
                 signal.append(vals[1])
     np_signal = np.array(signal)
     del signal
     plt.specgram(
         np_signal,
         NFFT = window,
         Fs = self.fs,
         window = mlab.window_hanning,
         scale_by_freq = True,
         noverlap = overlap)
     plt.draw()
开发者ID:ihor-pyvovarnyk,项目名称:oae-sound-processing-tool,代码行数:26,代码来源:fft_analysis.py


示例7: spectrum

def spectrum(signal):
    plt.specgram(
        signal,
        Fs=44100)
    plt.ylim([0, 22050])
    plt.savefig('spectrum.png')
    plt.clf()
开发者ID:motobiker2008,项目名称:aotm,代码行数:7,代码来源:function.py


示例8: write_results

 def write_results(self, kiwi_result, individual_calls, filename, audio, rate, segmented_sounds):
     # sample_name_with_dir = filename.replace(os.path.split(os.path.dirname(filename))[0], '')[1:]              
     self.Log.info('%s: %s' % (filename.replace('/Recordings',''), kiwi_result))
     
     self.DevLog.info('<h2>%s</h2>' % kiwi_result)
     self.DevLog.info('<h2>%s</h2>' % filename.replace('/Recordings',''))
     self.DevLog.info('<audio controls><source src="%s" type="audio/wav"></audio>', 
                  filename.replace('/var/www/','').replace('/Recordings',''))    
     
     # Plot spectrogram
     plt.ioff()
     plt.specgram(audio, NFFT=2**11, Fs=rate)
     # and mark on it with vertical lines found audio features
     for i, (start, end) in enumerate(segmented_sounds):
         start /= rate
         end /= rate
         plt.plot([start, start], [0, 4000], lw=1, c='k', alpha=0.2, ls='dashed')
         plt.plot([end, end], [0, 4000], lw=1, c='g', alpha=0.4)
         plt.text(start, 4000, i, fontsize=8)
         if individual_calls[i] == 1:
             plt.plot((start + end) / 2, 3500, 'go')
         elif individual_calls[i] == 2:
             plt.plot((start + end) / 2, 3500, 'bv')
     plt.axis('tight')
     title = plt.title(kiwi_result)
     title.set_y(1.03)
     spectrogram_sample_name = filename + '.png'
     plt.savefig(spectrogram_sample_name)
     plt.clf()
     path = spectrogram_sample_name.replace('/var/www/','').replace('/Recordings','')
     self.DevLog.info('<img src="%s" alt="Spectrogram">', path)
     self.DevLog.info('<hr>')
开发者ID:edwardabraham,项目名称:Ornithokrites,代码行数:32,代码来源:reporting.py


示例9: plotSpectrogram

	def plotSpectrogram(self,N=4096,title='Spectrogramme'):
		plt.clf()
		plt.specgram(self.signal,N,self.framerate)
		plt.colorbar()
		plt.xlabel('Temps (en secondes)')
		plt.ylabel('Frequence (en Hz)')
		plt.title(title + ', Fe=' + str(self.framerate) + ' (' + str(N) + ' points)')
开发者ID:Afnarel,项目名称:SSII-Python,代码行数:7,代码来源:Sound.py


示例10: analyze

 def analyze(self):
     data = (
         self.prepare_numpy_matrix()
     )  # np.hstack(self.data.signal_data(self.slice)) #filter_low_high_pass(np.hstack(self.data.signal_data(self.slice)))
     plt.specgram(data, NFFT=self.nfft * self.schema.sampling_rate_hz, Fs=self.schema.sampling_rate_hz)
     plt.axis([0, 30, 0, 35])
     self.make_plot(self.file_name)
开发者ID:NeuralProsthesisLab,项目名称:unlock,代码行数:7,代码来源:analyzer.py


示例11: t_hist_specgram

def t_hist_specgram(t_hist, time):
    time_step = (time[-1]-time[0])/len(time)
    plt.figure()
    plt.specgram(t_hist, NFFT=256, Fs=1./time_step)
    plt.xlabel('Time (s)'); plt.ylabel('Frequency (Hz)')
    plt.xlim([0, time[-1]-time[0]])
    plt.show()
开发者ID:sballin,项目名称:phantom_viewer,代码行数:7,代码来源:spectra.py


示例12: test_read_wave

def test_read_wave():
    f = Sndfile("../fcjf0/sa1.wav", 'r')
    data = f.read_frames(46797)
    data_arr = np.array(data)
    #print data_arr
    pyplot.figure()
    pyplot.specgram(data_arr)
    pyplot.show()
开发者ID:omarelshenawy,项目名称:SpeechRecognitionCourse,代码行数:8,代码来源:read_wav.py


示例13: viz_sound

def viz_sound(sound, name, npts=1000):
    plt.figure()
    plt.specgram(sound)
    plt.title(name)

    plt.figure()
    plt.plot(sound[:npts])
    plt.title(name)
开发者ID:ellisonbg,项目名称:py4science,代码行数:8,代码来源:sound_wavfiles.py


示例14: plot_specgram

def plot_specgram(sound_names, raw_sounds):
    i = 1
    for n, f in zip(sound_names, raw_sounds):
        plt.subplot(10, 1, i)
        specgram(np.array(f), Fs=66650)
        plt.title(n.title())
        i += 1
    plt.suptitle("Figure 2: Spectrogram", x=0.5, y=0.915, fontsize=18)
    plt.show()
开发者ID:adamloch,项目名称:Sound-EC50,代码行数:9,代码来源:plot_wav.py


示例15: show_spectrogram

def show_spectrogram(data, date, file_time):
    plt.specgram(data,  pad_to=nfft, NFFT=nfft, noverlap=noverlap, Fs=fs)
    plt.title(date + "T" + file_time + "Z")
    plt.ylim(0, 600)
    plt.yticks(np.arange(0, 601, 50.0))
    plt.xlabel("Time (sec)")
    plt.ylabel("Frequencies (hz)")
    plt.show()
    plt.close()
开发者ID:jlstack,项目名称:BeeVisualization,代码行数:9,代码来源:ModifiedPickler.py


示例16: generate_spectrogram

def generate_spectrogram(wav_file):
	# Method to generate the spectrogram
	sound_info, frame_rate = generate_sound_data(wav_file)
	plt.subplot(111)
	plt.title("Spectrogram of %r" %sound)
	plt.xlabel("Time in (s)")
	plt.ylabel("Frequency in Hz")
	plt.specgram(sound_info, Fs=frame_rate)
	plt.savefig(sound_source+"/"+sound+"_spectrogram.png")
开发者ID:darkhood,项目名称:Sound_Forensics_ASR,代码行数:9,代码来源:spectrogram_generation.py


示例17: spectrogram

def spectrogram():
    fs, data = sc.io.wavfile.read('/home/zechthurman/Songscape/03. Kali 47 (Original Mix).wav')
    t = data.size/500
    dt = 0.1
    NFFT = 1024
    Fs = int(1.0/dt)  # the sampling frequency

    plt.specgram(data[:,1], NFFT=NFFT, Fs=Fs, noverlap=900, cmap= plt.cm.gist_heat)
    plt.show()
开发者ID:zthurman,项目名称:Songscape,代码行数:9,代码来源:Songscape.py


示例18: plot_specgram

def plot_specgram(sound_names, raw_sounds):
	i = 1
	fig = plt.figure(figsize(25,60), dpi = 900)
	for n, f in zip(sound_names, raw_sounds):
		plt.subplot(10,1,i)
		specgram(np.array(f), Fs=22050)
		plt.title(n.title())
		i += 1
	plt.suptitle('Figure 2: spectogram', x=.5, y=.915, fontsize=18)
	plt.show()
开发者ID:sventers,项目名称:hello,代码行数:10,代码来源:c_urban_sound_classify.py


示例19: wav_specgram

def wav_specgram(filename):
    import scipy
    import matplotlib.pyplot as plt

    rate, signal = scipy.io.wavfile.read(filename)
    if signal.ndim > 1:
        signal = signal[:, 0]

    plt.specgram(signal, Fs=rate, xextent=(0, 0.1))
    plt.show()
开发者ID:HuiChangZhai,项目名称:huichangzhai.github.io,代码行数:10,代码来源:App.py


示例20: main

def main(path):
    # Connect to the cs server with the proper credentials.
    session = FTP()
    session.connect("cs.appstate.edu")
    user = raw_input("Type your username.")
    passwd = getpass.getpass("Type your password.")
    session.login(user, passwd)
    session.cwd(path)
    try:
        session.mkd("../Spectrograms")
    except error_perm:
        pass

    # Gets the flac files in the passed in directory
    match = "*.flac"
    count = 1

    # Print the total number of .mp3 files that are in the directory,
    # and go through them all
    print "Total number of files: " + str(len(session.nlst(match)))

    left_index = 1
    right_index = 1
    for name in session.nlst(match):
        read = StringIO.StringIO()
        session.retrbinary("RETR " + name, read.write)

        data = read.getvalue()
        bee_rate, bee_data = get_data_from_flac(data)

        plt.specgram(bee_data, pad_to=nfft, NFFT=nfft, noverlap=noverlap, Fs=fs)
        plt.title(name)
        jpeg_temp = tempfile.NamedTemporaryFile(suffix=".jpeg")
        plt.savefig(jpeg_temp.name)
        plt.close()

        spec = open(jpeg_temp.name, 'r')
        if "left" in name:
            session.storbinary("STOR ../Spectrograms/%05d_left.jpeg" % left_index, spec)
            left_index += 1
        if "right" in name:
            session.storbinary("STOR ../Spectrograms/%05d_right.jpeg" % right_index, spec)
            right_index += 1
        spec.close()
        jpeg_temp.close()

        print "File number: " + str(count)
        count += 1

        # Close the StringIO
        read.close()

    # Close the FTP connection
    session.quit()
    print "Done."
开发者ID:jlstack,项目名称:BeeVisualization,代码行数:55,代码来源:sshscript.py



注:本文中的matplotlib.pyplot.specgram函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pyplot.spy函数代码示例发布时间:2022-05-27
下一篇:
Python pyplot.show函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap