Source code for sensors.Utilities.signal_to_png

import os
import matplotlib
import matplotlib.pyplot as plt
import scipy.signal as sg
from scipy.io import wavfile
import numpy as np
# disable display
matplotlib.use('Agg')


[docs]def create_png_from_signal(signal_file, png_filename, decimation_factor): """Function that saves a ``png`` file of the input audio signal and its PSD to the specified file name. :param signal_file: absolute path to signal file :type signal_file: string :param png_filename: file name of created `png` :type png_filename: string :param decimation_factor: downsampling factor :type decimation_factor: int :return: False flag for png save in progress (computation ended) :rtype: bool """ samplerate, signal = wavfile.read(signal_file) signal = signal/32768.0 time = len(signal)/samplerate * 1000 max_f_khz = samplerate/decimation_factor/2 signal_resamp = sg.resample_poly(signal, 1, decimation_factor, padtype='edge') t_signal = np.linspace(0, time, len(signal_resamp)) PSD_signal = 10*np.log10(sg.welch(signal_resamp, fs=samplerate/decimation_factor, window='hann', nperseg=512, noverlap=256+128)[1]) f_PSD = np.linspace(0, max_f_khz, len(PSD_signal)) plt.rc('axes', labelsize=8) plt.rc('figure', titlesize=10) plt.rc('xtick', labelsize=8) plt.rc('ytick', labelsize=8) fig, axes = plt.subplots(2, 1) fig.suptitle('Wingbeat Signal and PSD', y=0.93) axes[0].plot(t_signal, signal_resamp, linewidth=0.5, color='#024768') axes[0].set_xlim([0, time]) axes[0].yaxis.set_major_formatter('{x:.0e}') axes[0].set_xlabel('discrete time [ms]') axes[0].set_ylabel('signal []') axes[0].set_facecolor('#eaeaea') axes[1].plot(f_PSD, PSD_signal, linewidth=0.5, color='#024768') axes[1].set_xlim([0, max_f_khz]) axes[1].set_xlabel('discrete frequency [Hz]') axes[1].set_ylabel('[dB]') axes[1].set_facecolor('#eaeaea') fig.set_size_inches(5.5, 6) fig.savefig(png_filename) plt.close('all') # return save in progress False return False