Mercurial > hg > segmentation
comparison novelty.py @ 0:26838b1f560f
initial commit of a segmenter project
author | mi tian |
---|---|
date | Thu, 02 Apr 2015 18:09:27 +0100 |
parents | |
children | c11ea9e0357f |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:26838b1f560f |
---|---|
1 #!/usr/bin/env python | |
2 # encoding: utf-8 | |
3 """ | |
4 novelty.py | |
5 | |
6 Created by mi tian on 2015-04-02. | |
7 Copyright (c) 2015 __MyCompanyName__. All rights reserved. | |
8 """ | |
9 | |
10 import sys, os | |
11 import numpy as np | |
12 from scipy.signal import correlate2d, convolve2d | |
13 | |
14 # from utils.PeakPickerUtil import PeakPicker | |
15 | |
16 def getNoveltyCurve(ssm, kernel_size, normalise=False): | |
17 '''Return novelty score from ssm.''' | |
18 | |
19 kernel_size = int(np.floor(kernel_size/2.0) + 1) | |
20 stripe = getDiagonalSlice(ssm, kernel_size) | |
21 kernel = gaussian_kernel(kernel_size) | |
22 xc = convolve2d(stripe,kernel,mode='same') | |
23 xc[abs(xc)>1e+10]=0.00001 | |
24 | |
25 novelty = xc[int(np.floor(xc.shape[0]/2.0)),:] | |
26 novelty = [0.0 if (np.isnan(x) or np.isinf(x) or x > 1e+100) else x for x in novelty] | |
27 | |
28 if normalise: | |
29 novelty = (novelty - np.min(novelty)) / (np.max(novelty) - np.min(novelty)) | |
30 return novelty | |
31 | |
32 def getDiagonalSlice(ssm, width): | |
33 ''' Return a diagonal stripe of the ssm given its width, with 45 degrees rotation. | |
34 Note: requres 45 degrees rotated kernel also.''' | |
35 w = int(np.floor(width/2.0)) | |
36 length = len(np.diagonal(ssm)) | |
37 stripe = np.zeros((2*w+1,length)) | |
38 # print 'diagonal', length, w, stripe.shape | |
39 for i in xrange(-w, w+1) : | |
40 stripe[w+i,:] = np.hstack(( np.zeros(int(np.floor(abs(i)/2.0))), np.diagonal(ssm,i), np.zeros(int(np.ceil(abs(i)/2.0))) )) | |
41 return stripe | |
42 | |
43 def gaussian_kernel(size): | |
44 '''Create a gaussian tapered 45 degrees rotated checkerboard kernel. | |
45 TODO: Unit testing: Should produce this with kernel size 3: | |
46 0.1353 -0.3679 0.1353 | |
47 0.3679 1.0000 0.3679 | |
48 0.1353 -0.3679 0.1353 | |
49 ''' | |
50 n = float(np.ceil(size / 2.0)) | |
51 kernel = np.zeros((size,size)) | |
52 for i in xrange(1,size+1) : | |
53 for j in xrange(1,size+1) : | |
54 gauss = np.exp( -4.0 * (np.square( (i-n)/n ) + np.square( (j-n)/n )) ) | |
55 # gauss = 1 | |
56 if np.logical_xor( j - n > np.floor((i-n) / 2.0), j - n > np.floor((n-i) / 2.0) ) : | |
57 kernel[i-1,j-1] = -gauss | |
58 else: | |
59 kernel[i-1,j-1] = gauss | |
60 | |
61 return kernel | |
62 | |
63 def getNoveltyPeaks(ssm, kernel_size, peak_picker, normalise=False): | |
64 '''Detect segment boundaries in the ssm.''' | |
65 novelty = getNoveltyCurve(ssm, kernel_size, normalise=False) | |
66 smoothed_novelty, novelty_peaks = peak_picker.process(novelty) | |
67 | |
68 return novelty, smoothed_novelty, novelty_peaks |