Exemple #1
0
def getAnnWavSec(wavFi,
                 annFi,
                 t0Label='startTime',
                 tfLabel='endTime',
                 label='label',
                 sr=None):
    '''read annotated sections from a waveform

    Parameters
    ----------
    wavFi : string
        path to wav file
    annFi : string (*.txt)
        path to annotations file,  if None => the whole waveform is returned
        Annotations are assumed to be in a list of dictionaries, see annT.parseAupFile
    t0Label : string
        name of the dictionary label for the start time (used by annT.parseAupFile)
    tfLabel : string
        name of the dictionary label for the end time (used by annT.parseAupFile)
    label : string
        name of the dictionary label with the annotation tag (used by annT.parseAupFile)

    Returns
    -------
    sectionsLi : list of dictionaries
        mapping label of the annotation section to the waveform
        { <label>, <waveFormSection (np.array)> }
        [ { <label>, <waveFormSection> }, ... , { <label>, <waveFormSection> }]
    '''

    sr = loadWaveform(wavFi, 0, 0, sr=sr)[1]
    #waveform, fs = sT.wav2waveform(wavFi)  # read wav

    if annFi is None:  # no annotations given
        return ([{
            label: os.path.basename(wavFi),
            'waveform': loadWaveform(wavFi, 0, None, sr=sr)[0]
        }], sr)
    else:
        sectionsLi = []
        annLi = annT.parseAupFile(annFi)  # read annotations
    for annDi in annLi:
        t0 = annDi[t0Label]
        tf = annDi[tfLabel]
        l = annDi[label]
        item = {label: l, 'waveform': loadWaveform(wavFi, t0, tf, sr=sr)[0]}
        #getWavSec(waveform, fs, t0, tf)}
        sectionsLi.append(item)

    return sectionsLi, sr
def plotAnnotatedSpectro(wavFi, annFi, outDir, callAsTitle=True, figsize=None, dpi=None,
                         labelsHeight=10, cmapName='seismic', lw = 1, **kwargs): 
    '''
    plots the spectrogram with it's annotations
    Parameters
    ----------    
        wavAnnCollection  : collection of paths to wavs and annotations files
        outDir : dir where the plots will be saved
        labelHeight : dictionary with the names of the labels and the height
        dpi : size of the image
        lw : line width for the annotated section
    '''
    ## wav file
    try:
        waveForm, fs = sT.wav2waveform(wavFi)
    except:
        return False
    M, ff, tf, _ = sT.spectralRep(waveForm, fs)#plt.specgram(waveForm, Fs=fs)
    plt.ioff()
    fig, ax = plt.subplots(figsize=figsize)

    ax.imshow(M.T, aspect='auto', origin='bottom', #interpolation='nearest', 
              extent=[0, tf, 0, fs/2/1000.], **kwargs)
    ax.set_xlabel('time (s)')
    ax.set_ylabel('frequency (KHz)')
    ### read annotations
    annD = annT.parseAupFile(annFi)
    ## custom ann clrs
    idx2labs = list(set([item['label'] for item in annD]))
    labs2idx  = { idx2labs[i] : i  for i in range(len(idx2labs)) }
    cmap = plt.cm.get_cmap( cmapName, len(idx2labs))    
    
    annLabel=''
    ### annotate
    for item in annD: # plot call segments - black line
        ax.hlines(labelsHeight, float(item['startTime']), float(item['endTime']), 
                  colors=cmap(labs2idx[item['label']]) , lw=lw)
        annLabel += '{}  '.format(item['label']) #read labels
        
    if callAsTitle:
        ax.set_title('{}'.format(annLabel))
        
    #if callAsTitle: ax.set_title('{}'.format(fp.parseHeikesNameConv(wavFi)['call']))    
    outPl = os.path.join( outDir, os.path.basename(wavFi).replace('wav', 'png'))
    plt.savefig(outPl, dpi=dpi)
    del fig, ax
    return outPl