我们从Python开源项目中,提取了以下8个代码示例,用于说明如何使用matplotlib.pyplot.specgram()。
def run_phase_reconstruction_example(): fs, d = fetch_sample_speech_tapestry() # actually gives however many components you say! So double what .m file # says fftsize = 512 step = 64 X_s = np.abs(stft(d, fftsize=fftsize, step=step, real=False, compute_onesided=False)) X_t = iterate_invert_spectrogram(X_s, fftsize, step, verbose=True) """ import matplotlib.pyplot as plt plt.specgram(d, cmap="gray") plt.savefig("1.png") plt.close() plt.imshow(X_s, cmap="gray") plt.savefig("2.png") plt.close() """ wavfile.write("phase_original.wav", fs, soundsc(d)) wavfile.write("phase_reconstruction.wav", fs, soundsc(X_t))
def harmonics(): synth = WaveSynth() freq = 1500 num_harmonics = 6 h_all = synth.harmonics(freq, 1, [(n, 1/n) for n in range(1, num_harmonics+1)]) even_harmonics = [(1, 1)] # always include fundamental tone harmonic even_harmonics.extend([(n, 1/n) for n in range(2, num_harmonics*2, 2)]) h_even = synth.harmonics(freq, 1, even_harmonics) h_odd = synth.harmonics(freq, 1, [(n, 1/n) for n in range(1, num_harmonics*2, 2)]) h_all.join(h_even).join(h_odd) import matplotlib.pyplot as plot plot.title("Spectrogram") plot.ylabel("Freq") plot.xlabel("Time") plot.specgram(h_all.get_frame_array(), Fs=synth.samplerate, noverlap=90, cmap=plot.cm.gist_heat) plot.show()
def implot(arr, scale=None, title="", cmap="gray"): import matplotlib.pyplot as plt if scale is "specgram": # plotting part mag = 20. * np.log10(np.abs(arr)) # Transpose so time is X axis, and invert y axis so # frequency is low at bottom mag = mag.T[::-1, :] else: mag = arr f, ax = plt.subplots() ax.matshow(mag, cmap=cmap) plt.axis("off") x1 = mag.shape[0] y1 = mag.shape[1] def autoaspect(x_range, y_range): """ The aspect to make a plot square with ax.set_aspect in Matplotlib """ mx = max(x_range, y_range) mn = min(x_range, y_range) if x_range <= y_range: return mx / float(mn) else: return mn / float(mx) asp = autoaspect(x1, y1) ax.set_aspect(asp) plt.title(title)
def run_phase_vq_example(): def _pre(list_of_data): # Temporal window setting is crucial! - 512 seems OK for music, 256 # fruit perhaps due to samplerates n_fft = 256 step = 32 f_r = np.vstack([np.abs(stft(dd, n_fft, step=step, real=False, compute_onesided=False)) for dd in list_of_data]) return f_r, n_fft, step def preprocess_train(list_of_data, random_state): f_r, n_fft, step = _pre(list_of_data) clusters = copy.deepcopy(f_r) return clusters def apply_preprocess(list_of_data, clusters): f_r, n_fft, step = _pre(list_of_data) f_clust = f_r # Nondeterministic ? memberships, distances = vq(f_clust, clusters) vq_r = clusters[memberships] d_k = iterate_invert_spectrogram(vq_r, n_fft, step, verbose=True) return d_k random_state = np.random.RandomState(1999) fs, d = fetch_sample_speech_fruit() d1 = d[::9] d2 = d[7::8][:5] # make sure d1 and d2 aren't the same! assert [len(di) for di in d1] != [len(di) for di in d2] clusters = preprocess_train(d1, random_state) fix_d1 = np.concatenate(d1) fix_d2 = np.concatenate(d2) vq_d2 = apply_preprocess(d2, clusters) wavfile.write("phase_train_no_agc.wav", fs, soundsc(fix_d1)) wavfile.write("phase_vq_test_no_agc.wav", fs, soundsc(vq_d2)) agc_d1, freq_d1, energy_d1 = time_attack_agc(fix_d1, fs, .5, 5) agc_d2, freq_d2, energy_d2 = time_attack_agc(fix_d2, fs, .5, 5) agc_vq_d2, freq_vq_d2, energy_vq_d2 = time_attack_agc(vq_d2, fs, .5, 5) """ import matplotlib.pyplot as plt plt.specgram(agc_vq_d2, cmap="gray") #plt.title("Fake") plt.figure() plt.specgram(agc_d2, cmap="gray") #plt.title("Real") plt.show() """ wavfile.write("phase_train_agc.wav", fs, soundsc(agc_d1)) wavfile.write("phase_test_agc.wav", fs, soundsc(agc_d2)) wavfile.write("phase_vq_test_agc.wav", fs, soundsc(agc_vq_d2))
def fm(): synth = WaveSynth(samplerate=8000) from matplotlib import pyplot as plot freq = 2000 lfo1 = Sine(1, amplitude=0.4, samplerate=synth.samplerate) s1 = synth.sine(freq, duration=3, fm_lfo=lfo1) plot.title("Spectrogram") plot.ylabel("Freq") plot.xlabel("Time") plot.specgram(s1.get_frame_array(), Fs=synth.samplerate, noverlap=90, cmap=plot.cm.gist_heat) plot.show() with Output(nchannels=1, samplerate=22050) as out: synth = WaveSynth(samplerate=22050) freq = 440 lfo1 = Linear(5, samplerate=synth.samplerate) lfo1 = EnvelopeFilter(lfo1, 1, 0.5, 0.5, 0.5, 1) s1 = synth.sine(freq, duration=3, fm_lfo=lfo1) s_all = s1.copy() out.play_sample(s1) lfo1 = Sine(1, amplitude=0.2, samplerate=synth.samplerate) s1 = synth.sine(freq, duration=2, fm_lfo=lfo1) s_all.join(s1) out.play_sample(s1) lfo1 = Sine(freq/17, amplitude=0.5, samplerate=synth.samplerate) s1 = synth.sine(freq, duration=2, fm_lfo=lfo1) s_all.join(s1) out.play_sample(s1) lfo1 = Sine(freq/6, amplitude=0.5, samplerate=synth.samplerate) s1 = synth.sine(freq, duration=2, fm_lfo=lfo1) s_all.join(s1) out.play_sample(s1) lfo1 = Sine(1, amplitude=0.4, samplerate=synth.samplerate) s1 = synth.triangle(freq, duration=2, fm_lfo=lfo1) s_all.join(s1) out.play_sample(s1) freq = 440*2 lfo1 = Sine(freq/80, amplitude=0.4, samplerate=synth.samplerate) s1 = synth.triangle(freq, duration=2, fm_lfo=lfo1) s_all.join(s1) out.play_sample(s1) # s_all.write_wav("fmtestall.wav") out.wait_all_played()
def plot_clusters(A, clust_arr, ax=None, doplot=False, dosave=None): # Inputs: # A: Result from Analysis class (A.run_analysis() must have already been run. # clust_arr: Array of the clusters we want to plot. eg: [1,4,6] will plot clusters 1,4 and 6 # ax: if ax is supplied, will plot it on the specified axes # Outputs: # A graph. if clust_arr == "all": clust_arr = np.unique(A.z.cluster_assignments) class CycledList: def __init__(self, arr): self.arr = arr return def __getitem__(self, key): return self.arr[np.mod(key, len(self.arr))] plot_colors = CycledList(["silver", "darkorchid", "royalblue", "red", "chartreuse", "gold", "olivedrab", "mediumspringgreen", "lightseagreen", "darkcyan", "deepskyblue", "c", "sienna", "m", "mediumvioletred", "lightsalmon"]) if ax is None: plt.figure(figsize=(11, 8.5), dpi=100, facecolor="w", edgecolor="k") plt.specgram(A.results[0][2][0, :], NFFT=1024, Fs=1./np.mean(np.diff(A.results[0][3])), noverlap=128, xextent=[A.results[0][3][0], A.results[0][3][-1]]) if clust_arr is not None: for cl in clust_arr: mask = (A.z.cluster_assignments == cl) plt.plot(A.z.feature_obj.misc_data_dict["time"][mask], A.z.feature_obj.misc_data_dict["freq"][mask], color=plot_colors[cl], marker="o", linestyle="None", markersize=A.markersize) # Cause I'm lazy. if dosave is not None and "toroidal" in dosave.lower(): plt.title("Shot 159243 Toroidal Array") if dosave is not None and "poloidal" in dosave.lower(): plt.title("Shot 159243 Poloidal Array") plt.xlabel("Time (ms)") plt.ylabel("Freq (kHz)") plt.xlim([750, 850]) plt.ylim([45, 250]) if doplot: plt.show() if dosave is not None: plt.savefig(dosave) else: ax.specgram(A.results[0][2][0, :], NFFT=1024, Fs=1. / np.mean(np.diff(A.results[0][3])), noverlap=128, xextent=[A.results[0][3][0], A.results[0][3][-1]]) if clust_arr is not None: for cl in clust_arr: mask = (A.z.cluster_assignments == cl) ax.plot(A.z.feature_obj.misc_data_dict["time"][mask], A.z.feature_obj.misc_data_dict["freq"][mask], color=plot_colors[cl], marker="o", linestyle="None", markersize=A.markersize) return