annotate utils/SegUtil.py @ 0:26838b1f560f

initial commit of a segmenter project
author mi tian
date Thu, 02 Apr 2015 18:09:27 +0100
parents
children c11ea9e0357f
rev   line source
mi@0 1 """
mi@0 2 Useful functions that are quite common for music segmentation
mi@0 3 """
mi@0 4 '''
mi@0 5 Modified and more funcs added.
mi@0 6 Mi Tian, April 2015.
mi@0 7 '''
mi@0 8
mi@0 9 __author__ = "Oriol Nieto"
mi@0 10 __copyright__ = "Copyright 2014, Music and Audio Research Lab (MARL)"
mi@0 11 __license__ = "GPL"
mi@0 12 __version__ = "1.0"
mi@0 13 __email__ = "oriol@nyu.edu"
mi@0 14
mi@0 15 import copy
mi@0 16 import numpy as np
mi@0 17 import os
mi@0 18 import scipy
mi@0 19 from scipy.spatial import distance
mi@0 20 from scipy.ndimage import filters, zoom
mi@0 21 from scipy import signal
mi@0 22 import pylab as plt
mi@0 23 from scipy.spatial.distance import squareform, pdist
mi@0 24
mi@0 25
mi@0 26 def lognormalize_chroma(C):
mi@0 27 """Log-normalizes chroma such that each vector is between -80 to 0."""
mi@0 28 C += np.abs(C.min()) + 0.1
mi@0 29 C = C/C.max(axis=0)
mi@0 30 C = 80 * np.log10(C) # Normalize from -80 to 0
mi@0 31 return C
mi@0 32
mi@0 33
mi@0 34 def normalize_matrix(X):
mi@0 35 """Nomalizes a matrix such that it's maximum value is 1 and minimum is 0."""
mi@0 36 X += np.abs(X.min())
mi@0 37 X /= X.max()
mi@0 38 return X
mi@0 39
mi@0 40
mi@0 41 def ensure_dir(directory):
mi@0 42 """Makes sure that the given directory exists."""
mi@0 43 if not os.path.exists(directory):
mi@0 44 os.makedirs(directory)
mi@0 45
mi@0 46
mi@0 47 def median_filter(X, M=8):
mi@0 48 """Median filter along the first axis of the feature matrix X."""
mi@0 49 for i in xrange(X.shape[1]):
mi@0 50 X[:, i] = filters.median_filter(X[:, i], size=M)
mi@0 51 return X
mi@0 52
mi@0 53
mi@0 54 def compute_gaussian_krnl(M):
mi@0 55 """Creates a gaussian kernel following Foote's paper."""
mi@0 56 g = signal.gaussian(M, M / 3., sym=True)
mi@0 57 G = np.dot(g.reshape(-1, 1), g.reshape(1, -1))
mi@0 58 G[M / 2:, :M / 2] = -G[M / 2:, :M / 2]
mi@0 59 G[:M / 2, M / 2:] = -G[:M / 2, M / 2:]
mi@0 60 return G
mi@0 61
mi@0 62
mi@0 63 def compute_ssm(X, metric="seuclidean"):
mi@0 64 """Computes the self-similarity matrix of X."""
mi@0 65 D = distance.pdist(X, metric=metric)
mi@0 66 D = distance.squareform(D)
mi@0 67 D /= D.max()
mi@0 68 return 1 - D
mi@0 69
mi@0 70
mi@0 71 def compute_nc(X, G):
mi@0 72 """Computes the novelty curve from the self-similarity matrix X and
mi@0 73 the gaussian kernel G."""
mi@0 74 N = X.shape[0]
mi@0 75 M = G.shape[0]
mi@0 76 nc = np.zeros(N)
mi@0 77
mi@0 78 for i in xrange(M / 2, N - M / 2 + 1):
mi@0 79 nc[i] = np.sum(X[i - M / 2:i + M / 2, i - M / 2:i + M / 2] * G)
mi@0 80
mi@0 81 # Normalize
mi@0 82 nc += nc.min()
mi@0 83 nc /= nc.max()
mi@0 84 return nc
mi@0 85
mi@0 86
mi@0 87 def resample_mx(X, incolpos, outcolpos):
mi@0 88 """
mi@0 89 Method from Librosa
mi@0 90 Y = resample_mx(X, incolpos, outcolpos)
mi@0 91 X is taken as a set of columns, each starting at 'time'
mi@0 92 colpos, and continuing until the start of the next column.
mi@0 93 Y is a similar matrix, with time boundaries defined by
mi@0 94 outcolpos. Each column of Y is a duration-weighted average of
mi@0 95 the overlapping columns of X.
mi@0 96 2010-04-14 Dan Ellis dpwe@ee.columbia.edu based on samplemx/beatavg
mi@0 97 -> python: TBM, 2011-11-05, TESTED
mi@0 98 """
mi@0 99 noutcols = len(outcolpos)
mi@0 100 Y = np.zeros((X.shape[0], noutcols))
mi@0 101 # assign 'end times' to final columns
mi@0 102 if outcolpos.max() > incolpos.max():
mi@0 103 incolpos = np.concatenate([incolpos,[outcolpos.max()]])
mi@0 104 X = np.concatenate([X, X[:,-1].reshape(X.shape[0],1)], axis=1)
mi@0 105 outcolpos = np.concatenate([outcolpos, [outcolpos[-1]]])
mi@0 106 # durations (default weights) of input columns)
mi@0 107 incoldurs = np.concatenate([np.diff(incolpos), [1]])
mi@0 108
mi@0 109 for c in range(noutcols):
mi@0 110 firstincol = np.where(incolpos <= outcolpos[c])[0][-1]
mi@0 111 firstincolnext = np.where(incolpos < outcolpos[c+1])[0][-1]
mi@0 112 lastincol = max(firstincol,firstincolnext)
mi@0 113 # default weights
mi@0 114 wts = copy.deepcopy(incoldurs[firstincol:lastincol+1])
mi@0 115 # now fix up by partial overlap at ends
mi@0 116 if len(wts) > 1:
mi@0 117 wts[0] = wts[0] - (outcolpos[c] - incolpos[firstincol])
mi@0 118 wts[-1] = wts[-1] - (incolpos[lastincol+1] - outcolpos[c+1])
mi@0 119 wts = wts * 1. /sum(wts)
mi@0 120 Y[:,c] = np.dot(X[:,firstincol:lastincol+1], wts)
mi@0 121 # done
mi@0 122 return Y
mi@0 123
mi@0 124
mi@0 125 def chroma_to_tonnetz(C):
mi@0 126 """Transforms chromagram to Tonnetz (Harte, Sandler, 2006)."""
mi@0 127 N = C.shape[0]
mi@0 128 T = np.zeros((N, 6))
mi@0 129
mi@0 130 r1 = 1 # Fifths
mi@0 131 r2 = 1 # Minor
mi@0 132 r3 = 0.5 # Major
mi@0 133
mi@0 134 # Generate Transformation matrix
mi@0 135 phi = np.zeros((6, 12))
mi@0 136 for i in range(6):
mi@0 137 for j in range(12):
mi@0 138 if i % 2 == 0:
mi@0 139 fun = np.sin
mi@0 140 else:
mi@0 141 fun = np.cos
mi@0 142
mi@0 143 if i < 2:
mi@0 144 phi[i, j] = r1 * fun(j * 7 * np.pi / 6.)
mi@0 145 elif i >= 2 and i < 4:
mi@0 146 phi[i, j] = r2 * fun(j * 3 * np.pi / 2.)
mi@0 147 else:
mi@0 148 phi[i, j] = r3 * fun(j * 2 * np.pi / 3.)
mi@0 149
mi@0 150 # Do the transform to tonnetz
mi@0 151 for i in range(N):
mi@0 152 for d in range(6):
mi@0 153 denom = float(C[i, :].sum())
mi@0 154 if denom == 0:
mi@0 155 T[i, d] = 0
mi@0 156 else:
mi@0 157 T[i, d] = 1 / denom * (phi[d, :] * C[i, :]).sum()
mi@0 158
mi@0 159 return T
mi@0 160
mi@0 161
mi@0 162 def most_frequent(x):
mi@0 163 """Returns the most frequent value in x."""
mi@0 164 return np.argmax(np.bincount(x))
mi@0 165
mi@0 166
mi@0 167 def pick_peaks(nc, L=16, plot=False):
mi@0 168 """Obtain peaks from a novelty curve using an adaptive threshold."""
mi@0 169 offset = nc.mean() / 3
mi@0 170 th = filters.median_filter(nc, size=L) + offset
mi@0 171 peaks = []
mi@0 172 for i in xrange(1, nc.shape[0] - 1):
mi@0 173 # is it a peak?
mi@0 174 if nc[i - 1] < nc[i] and nc[i] > nc[i + 1]:
mi@0 175 # is it above the threshold?
mi@0 176 if nc[i] > th[i]:
mi@0 177 peaks.append(i)
mi@0 178 if plot:
mi@0 179 plt.plot(nc)
mi@0 180 plt.plot(th)
mi@0 181 for peak in peaks:
mi@0 182 plt.axvline(peak, color="m")
mi@0 183 plt.show()
mi@0 184 return peaks
mi@0 185
mi@0 186
mi@0 187 def recurrence_matrix(data, k=None, width=1, metric='sqeuclidean', sym=False):
mi@0 188 '''
mi@0 189 Note: Copied from librosa
mi@0 190
mi@0 191 Compute the binary recurrence matrix from a time-series.
mi@0 192
mi@0 193 ``rec[i,j] == True`` <=> (``data[:,i]``, ``data[:,j]``) are
mi@0 194 k-nearest-neighbors and ``|i-j| >= width``
mi@0 195
mi@0 196 :usage:
mi@0 197 >>> mfcc = librosa.feature.mfcc(y=y, sr=sr)
mi@0 198 >>> R = librosa.segment.recurrence_matrix(mfcc)
mi@0 199
mi@0 200 >>> # Or fix the number of nearest neighbors to 5
mi@0 201 >>> R = librosa.segment.recurrence_matrix(mfcc, k=5)
mi@0 202
mi@0 203 >>> # Suppress neighbors within +- 7 samples
mi@0 204 >>> R = librosa.segment.recurrence_matrix(mfcc, width=7)
mi@0 205
mi@0 206 >>> # Use cosine similarity instead of Euclidean distance
mi@0 207 >>> R = librosa.segment.recurrence_matrix(mfcc, metric='cosine')
mi@0 208
mi@0 209 >>> # Require mutual nearest neighbors
mi@0 210 >>> R = librosa.segment.recurrence_matrix(mfcc, sym=True)
mi@0 211
mi@0 212 :parameters:
mi@0 213 - data : np.ndarray
mi@0 214 feature matrix (d-by-t)
mi@0 215
mi@0 216 - k : int > 0 or None
mi@0 217 the number of nearest-neighbors for each sample
mi@0 218
mi@0 219 Default: ``k = 2 * ceil(sqrt(t - 2 * width + 1))``,
mi@0 220 or ``k = 2`` if ``t <= 2 * width + 1``
mi@0 221
mi@0 222 - width : int > 0
mi@0 223 only link neighbors ``(data[:, i], data[:, j])``
mi@0 224 if ``|i-j| >= width``
mi@0 225
mi@0 226 - metric : str
mi@0 227 Distance metric to use for nearest-neighbor calculation.
mi@0 228
mi@0 229 See ``scipy.spatial.distance.cdist()`` for details.
mi@0 230
mi@0 231 - sym : bool
mi@0 232 set ``sym=True`` to only link mutual nearest-neighbors
mi@0 233
mi@0 234 :returns:
mi@0 235 - rec : np.ndarray, shape=(t,t), dtype=bool
mi@0 236 Binary recurrence matrix
mi@0 237 '''
mi@0 238
mi@0 239 t = data.shape[1]
mi@0 240
mi@0 241 if k is None:
mi@0 242 if t > 2 * width + 1:
mi@0 243 k = 2 * np.ceil(np.sqrt(t - 2 * width + 1))
mi@0 244 else:
mi@0 245 k = 2
mi@0 246
mi@0 247 k = int(k)
mi@0 248
mi@0 249 def _band_infinite():
mi@0 250 '''Suppress the diagonal+- of a distance matrix'''
mi@0 251
mi@0 252 band = np.empty((t, t))
mi@0 253 band.fill(np.inf)
mi@0 254 band[np.triu_indices_from(band, width)] = 0
mi@0 255 band[np.tril_indices_from(band, -width)] = 0
mi@0 256
mi@0 257 return band
mi@0 258
mi@0 259 # Build the distance matrix
mi@0 260 D = scipy.spatial.distance.cdist(data.T, data.T, metric=metric)
mi@0 261
mi@0 262 # Max out the diagonal band
mi@0 263 D = D + _band_infinite()
mi@0 264
mi@0 265 # build the recurrence plot
mi@0 266 rec = np.zeros((t, t), dtype=bool)
mi@0 267
mi@0 268 # get the k nearest neighbors for each point
mi@0 269 for i in range(t):
mi@0 270 for j in np.argsort(D[i])[:k]:
mi@0 271 rec[i, j] = True
mi@0 272
mi@0 273 # symmetrize
mi@0 274 if sym:
mi@0 275 rec = rec * rec.T
mi@0 276
mi@0 277 return rec
mi@0 278
mi@0 279
mi@0 280 def getMean(feature, winlen, stepsize):
mi@0 281 means = []
mi@0 282 steps = int((feature.shape[0] - winlen + stepsize) / stepsize)
mi@0 283 for i in xrange(steps):
mi@0 284 means.append(np.mean(feature[i*stepsize:(i*stepsize+winlen), :], axis=0))
mi@0 285 return np.array(means)
mi@0 286
mi@0 287
mi@0 288 def getStd(feature, winlen, stepsize):
mi@0 289 std = []
mi@0 290 steps = int((feature.shape[0] - winlen + stepsize) / stepsize)
mi@0 291 for i in xrange(steps):
mi@0 292 std.append(np.std(feature[i*stepsize:(i*stepsize+winlen), :], axis=0))
mi@0 293 return np.array(std)
mi@0 294
mi@0 295
mi@0 296 def getDelta(feature):
mi@0 297 delta_feature = np.vstack((np.zeros((1, feature.shape[1])), np.diff(feature, axis=0)))
mi@0 298 return delta_feature
mi@0 299
mi@0 300
mi@0 301 def getSSM(feature_array, metric='cosine', norm='simple', reduce=False):
mi@0 302 '''Compute SSM given input feature array.
mi@0 303 args: norm: ['simple', 'remove_noise']
mi@0 304 '''
mi@0 305 dm = pairwise_distances(feature_array, metric=metric)
mi@0 306 dm = np.nan_to_num(dm)
mi@0 307 if norm == 'simple':
mi@0 308 ssm = 1 - (dm - np.min(dm)) / (np.max(dm) - np.min(dm))
mi@0 309 if reduce:
mi@0 310 ssm = reduceSSM(ssm)
mi@0 311 return ssm
mi@0 312
mi@0 313
mi@0 314 def reduceSSM(ssm, maxfilter_size = 2, remove_size=50):
mi@0 315 reduced_ssm = ssm
mi@0 316 reduced_ssm[reduced_ssm<0.75] = 0
mi@0 317 # # reduced_ssm = maximum_filter(reduced_ssm,size=maxfilter_size)
mi@0 318 # # reduced_ssm = morphology.remove_small_objects(reduced_ssm.astype(bool), min_size=remove_size)
mi@0 319 local_otsu = otsu(reduced_ssm, disk(5))
mi@0 320 local_otsu = (local_otsu.astype(float) - np.min(local_otsu)) / (np.max(local_otsu) - np.min(local_otsu))
mi@0 321 reduced_ssm = reduced_ssm - 0.6*local_otsu
mi@0 322 return reduced_ssm
mi@0 323
mi@0 324
mi@0 325 def upSample(feature_array, step):
mi@0 326 '''Resample downsized tempogram features, tempoWindo should be in accordance with input features'''
mi@0 327 # print feature_array.shape
mi@0 328 sampleRate = 44100
mi@0 329 stepSize = 1024.0
mi@0 330 # step = np.ceil(sampleRate/stepSize/5.0)
mi@0 331 feature_array = zoom(feature_array, (step,1))
mi@0 332 # print 'resampled', feature_array.shape
mi@0 333 return feature_array
mi@0 334
mi@0 335
mi@0 336 def normaliseFeature(feature_array):
mi@0 337 '''Normalise features column wisely.'''
mi@0 338 feature_array[np.isnan(feature_array)] = 0.0
mi@0 339 feature_array[np.isinf(feature_array)] = 0.0
mi@0 340 feature_array = (feature_array - np.min(feature_array, axis=-1)[:,np.newaxis]) / (np.max(feature_array, axis=-1) - np.min(feature_array, axis=-1))[:,np.newaxis]
mi@0 341 feature_array[np.isnan(feature_array)] = 0.0
mi@0 342 feature_array[np.isinf(feature_array)] = 0.0
mi@0 343
mi@0 344 return feature_array
mi@0 345
mi@0 346
mi@0 347 def verifyPeaks(peak_canditates, dev_list):
mi@0 348 '''Verify peaks from the 1st round detection by applying adaptive thresholding to the deviation list.'''
mi@0 349
mi@0 350 final_peaks = copy(peak_canditates)
mi@0 351 dev_list = np.array([np.mean(x) for x in dev_list]) # get average of devs of different features
mi@0 352 med_dev = median_filter(dev_list, size=5)
mi@0 353 # print dev_list, np.min(dev_list), np.median(dev_list), np.mean(dev_list), np.std(dev_list)
mi@0 354 dev = dev_list - np.percentile(dev_list, 50)
mi@0 355 # print dev
mi@0 356 for i, x in enumerate(dev):
mi@0 357 if x < 0:
mi@0 358 final_peaks.remove(peak_canditates[i])
mi@0 359 return final_peaks
mi@0 360
mi@0 361
mi@0 362 def envelopeFollower(xc, AT, RT, prevG, scaler=1):
mi@0 363 '''Follows the amplitude envelope of input signal xc.'''
mi@0 364
mi@0 365 g = np.zeros_like(xc)
mi@0 366 length = len(xc)
mi@0 367
mi@0 368 for i in xrange(length):
mi@0 369 xSquared = xc[i] ** 2
mi@0 370 # if input is less than the previous output use attack, otherwise use the release
mi@0 371 if xSquared < prevG:
mi@0 372 coeff = AT
mi@0 373 else:
mi@0 374 coeff = RT
mi@0 375 g[i] = (xSquared - prevG)*coeff + prevG
mi@0 376 g[i] *= scaler
mi@0 377 prevG = g[i]
mi@0 378
mi@0 379 return g
mi@0 380
mi@0 381
mi@0 382 def getEnvPeaks(sig, sig_env, size=1):
mi@0 383 '''Finds peaks in the signal envelope.
mi@0 384 args: sig (1d array): orignal input signal
mi@0 385 sig_env (list): position of the signal envelope.
mi@0 386 size: ranges to locate local maxima in the envelope as peaks.
mi@0 387 '''
mi@0 388 envelope = sig[sig_env]
mi@0 389 peaks = []
mi@0 390 if len(envelope) > 1 and envelope[0] > envelope[1]:
mi@0 391 peaks.append(sig_env[0])
mi@0 392 for i in xrange(size, len(envelope)-size-1):
mi@0 393 if envelope[i] > np.max(envelope[i-size:i]) and envelope[i] > np.max(envelope[i+1:i+size+1]):
mi@0 394 peaks.append(sig_env[i])
mi@0 395 return peaks