Пример #1
0
def waveletsTransformContinue(signalPath, wf, wf_param, dt, dj,
                              affichageSpectrogram):
    '''
    Calcule la transformee en ondelettes continue du signal
    :param signalPath: Le chemin du signal audio
    :param wf: La fonction de l'ondelette ('morlet', 'paul', 'dog')
    :param wf_param: Parametre de la l'ondelette (8 pour morlet, 2 pour dog et paul)
    :param dt: Pas (10ms par exemple)
    :param dj: Resolution de l'echelle (plus dj est petit plus la resolution est fine)
    :return: la transformee en ondelettes continue du signal, matrice 40*len(signal)
    '''

    # Load the wav file, y is the data and sr the sampling frequency
    signal, fe = librosa.load(signalPath)

    scales = wave.autoscales(len(signal), dt=dt, dj=dj, wf=wf, p=wf_param)
    spec = wave.cwt(signal, dt=dt, scales=scales, wf=wf, p=wf_param)
    spec = np.abs(spec)
    wvtransform = spec.transpose()
    wvtransform = moyennerMatrice(
        wvtransform
    )  #A decommenter si l'on veut avoir une matrice 40*len(signal)
    if affichageSpectrogram:
        afficherSpec(wvtransform, fe, dt)
    return wvtransform
Пример #2
0
 def plotCWT(self, order=6):
     from mlpy.wavelet import cwt, autoscales, fourier_from_scales
     import matplotlib.pyplot as plt
     omega0 = order
     #compute scales 
     scales = autoscales(N=self.getNumberOfSamples(), dt=self.getSamplingStep(), dj=0.05, wf='morlet', p=omega0)        
     
     spec = cwt(self.getSeries(), dt=self.getSamplingStep(), scales=scales, wf='morlet', p=omega0)
     
     freq = fourier_from_scales(scales, 'morlet', omega0)
     
     # approximate scales through frequencies
     #freq = (omega0 + np.sqrt(2.0 + omega0**2))/(4*np.pi * scale[1:])
     #get as fourier freqs
     
     
     plt.figure()
     ax1 = plt.subplot(211)
     ax2 = plt.subplot(212, sharex=ax1)
     
     t = np.arange( self.getNumberOfSamples() ) * self.x_step_ + self.x_start_
     
     ax1.plot(self.getPositionVector(), self.y_, 'k')
     extent=[t[0], t[-1], freq[0], freq[-1]]
     img = ax2.imshow(np.abs(spec), extent=extent, aspect='auto') 
     
     #plt.colorbar(img)
     plt.show()
     return extent,spec
def mlpy_cwt(x, fs, filename, wv='morlet' ):
    from matplotlib import pyplot as plt
    import mlpy.wavelet as wave
    omega0 = 0
    #fs=1e6
    fact=2048
    t = np.arange(len(x)) / fs
    #scales = wave.autoscales(N=x.shape[0], dt=1/fs, dj=0.4875, wf=wv, p=omega0)
    #X = wave.cwt(x=x, dt=1/fs, scales=scales, wf=wv, p=omega0)

    scales = wave.autoscales(N=x.shape[0], dt=1.0/fs, dj=.025, wf=wv, p=omega0)
    X = wave.cwt(x=x, dt=1/fs, scales=scales, wf=wv, p=omega0)
    
    fig = plt.figure(1)
    ax1 = plt.subplot(2,1,1)
    p1 = ax1.plot(t,x)
    ax1.autoscale_view(tight=True)
    ax2 = plt.subplot(2,1,2)
    freq = (omega0 + np.sqrt(2.0 + omega0 ** 2)) / (4 * np.pi * scales[1:])
        #print "frequencies are ", freq
    freqs=[math.pow(i,-1) for i in wave.fourier_from_scales(scales, wv, omega0)]
            #print "api freqs are ", freqs
    p2 = ax2.imshow(np.abs(X), interpolation='nearest',aspect='auto', extent=[t[0], t[-1], freq[-1], freq[0]], vmax=abs(X).max(), vmin=-abs(X).max()  )
    twin_ax = ax2.twinx()
    twin_ax.set_xlim(t[0], t[-1])
    twin_ax.set_ylim(freq[-1], freq[0])
    twin_ax.set_yscale('log')
    ax2.tick_params(which='both', labelleft=False, left=False)
    twin_ax.tick_params(which='both', labelleft=True, left=True, labelright=False)
    
    #fig.colorbar(p2)
    fig.savefig(filename+'_'+wv+'.pdf')
    fig.clf()
Пример #4
0
def scaleogram(data, samp_rate = 100.0,wavelet = 'morlet' ,bb=6,what = 'Amp',axis = None):
    """
    Computes and plots logarithmic spectrogram of the input trace.

    :param data: Input data
    :param sample_rate: Samplerate in Hz
    :param log: True logarithmic frequency axis, False linear frequency axis
    :param per_lap: Percent of overlap
    :param nwin: Approximate number of windows.
    :param outfile: String for the filename of output file, if None
        interactive plotting is activated.
    :param format: Format of image to save
    :param axis: Plot into given axis, this deactivates the format and
        outfile option
    """
    # enforce float for samp_rate
    samp_rate = float(samp_rate)

    # nfft needs to be an integer, otherwise a deprecation will be raised


    dscale = 0.1
    dtime = 1./samp_rate
    npts = data.shape[0]
    tt = np.arange(0,npts/samp_rate,1/samp_rate)
    xx = ml.autoscales(N=data.shape[0], dt=dtime, dj=dscale, wf=wavelet, p=bb)
    X = ml.cwt(x=data, dt=dtime, scales=xx, wf=wavelet, p=bb)
    freq = ml.fourier_from_scales(xx, wavelet, bb)
    freq = 1./freq

#    amp = X
    amp = np.abs(X)
    phase = np.angle(X)

    if not axis:
        fig = plt.figure()
        ax = fig.add_subplot(111)

    else:
        ax = axis

    ax.set_yscale('log')
    if what == 'Amp':
        im=ax.pcolormesh(tt,freq,amp)
    else:
        im=ax.pcolormesh(tt,freq,phase)

    # set correct way of axis, whitespace before and after with window
    # length

    ax.axis('tight')
    # ax.set_xlim(0, end)
    ax.grid(False)
    ax.set_xlabel('Time [s]')
    ax.set_ylabel('Frequency [Hz]')

    if axis:
        return ax, im
Пример #5
0
 def __init__(self, spectrum):
     """Initializes instance of Spectrum class."""
     self.spectrum = spectrum
     self.scales = wave.autoscales(N=spectrum.shape[0],
                                   dt=1,
                                   dj=0.25,
                                   wf='dog',
                                   p=2)
     self.freq0 = 0
     self.wSize = 5 if len(self.scales) > 5 else len(self.scales) - 1
     self._transformation = wave.cwt(spectrum,
                                     dt=1,
                                     scales=self.scales,
                                     wf='dog',
                                     p=2)
     self._rec = None
def all_in_one(x, fs, filename, wv='morlet',  nfft=2048 ):
    from matplotlib import pyplot as plt
    import mlpy.wavelet as wave
    omega0 = 0
    #fs=1e6
    t = np.arange(len(x)) / fs
    #scales = wave.autoscales(N=x.shape[0], dt=1/fs, dj=0.4875, wf=wv, p=omega0)
    #X = wave.cwt(x=x, dt=1/fs, scales=scales, wf=wv, p=omega0)
                                
    scales = wave.autoscales(N=x.shape[0], dt=1.0/fs, dj=.025, wf=wv, p=omega0)
    X = wave.cwt(x=x, dt=1/fs, scales=scales, wf=wv, p=omega0)
    
    fig = plt.figure(1)
    
    ax1 = plt.subplot(3,1,1)
    p1 = ax1.plot(t,x)
    ax1.autoscale_view(tight=True)
    ax2 = plt.subplot(3,1,2)
    freq = (omega0 + np.sqrt(2.0 + omega0 ** 2)) / (4 * np.pi * scales[1:])
    #print "frequencies are ", freq
    freqs=[math.pow(i,-1) for i in wave.fourier_from_scales(scales, wv, omega0)]
    #print "api freqs are ", freqs
    p2 = ax2.imshow(np.abs(X), interpolation='nearest',aspect='auto', extent=[t[0], t[-1], freq[-1], freq[0]], vmax=abs(X).max(), vmin=-abs(X).max()  )
    twin_ax = ax2.twinx()
    twin_ax.set_xlim(t[0], t[-1])
    twin_ax.set_ylim(freq[-1], freq[0])
    twin_ax.set_yscale('log')
    ax2.tick_params(which='both', labelleft=False, left=False)
    twin_ax.tick_params(which='both', labelleft=True, left=True, labelright=False)
    #fig.colorbar(p2, ax=ax2).set_label("Amplitude (dB)") #fig.colorbar(p2)
    
    ax3 = plt.subplot(3,1,3)
    wrapper = lambda fn : np.blackman(fn)
    #wrapper = lambda n : np.hamming(n)
    #wrapper = lambda n : np.hanning(n)
    Pxx, freqs, time, im = ax3.specgram(x, NFFT=nfft,  Fs=fs, detrend=pylab.detrend_none, window=wrapper(nfft), noverlap=nfft/2)
    #Pxx, freqs, time, im = ax3.specgram(x, Fs=fs, NFFT=nfft)
    #fig.colorbar(im, ax=ax3).set_label("Amplitude (dB)")
    ax3.set_xlim(t[0], t[-1])
    fig.savefig(filename+'_all'+'.pdf')
    fig.clf()
def waveletsTransformContinue(signalPath, wf, wf_param, dt, dj, affichageSpectrogram):
    '''
    Calcule la transformee en ondelettes continue du signal
    :param signalPath: Le chemin du signal audio
    :param wf: La fonction de l'ondelette ('morlet', 'paul', 'dog')
    :param wf_param: Parametre de la l'ondelette (8 pour morlet, 2 pour dog et paul)
    :param dt: Pas (10ms par exemple)
    :param dj: Resolution de l'echelle (plus dj est petit plus la resolution est fine)
    :return: la transformee en ondelettes continue du signal, matrice 40*len(signal)
    '''

    # Load the wav file, y is the data and sr the sampling frequency
    signal, fe = librosa.load(signalPath)

    scales = wave.autoscales(len(signal), dt=dt, dj=dj, wf=wf, p=wf_param)
    spec = wave.cwt(signal, dt=dt, scales=scales, wf=wf, p=wf_param)
    spec= np.abs(spec)
    wvtransform=spec.transpose()
    wvtransform= moyennerMatrice(wvtransform) #A decommenter si l'on veut avoir une matrice 40*len(signal)
    if affichageSpectrogram:
        afficherSpec(wvtransform,fe,dt)
    return wvtransform
Пример #8
0
    def cwt(self, t1,t2,  scale = None, xs = None, postFunc =  lambda x:x, p = 20):       
        # if isinstance(postFunc, None):
        #     postFunc = lambda x:x
        if isinstance(scale, type(None)):
            scale = np.arange(1,129)       
        self.scale = scale
        # self.freqs = 1. / self.scale * p
        self.freqs = 1. / self.scale * p
        # self.freqs = self.bitrate / self.scale

#         self.scale = np.arange(1,100)
        # tmax = 0.1

        if isinstance( xs, type(None)):
            ts,xs = self.trimto(t1,t2)
        # ts,xs = self.trimto(t1,t2)
            
#         xs = xs/ np.std(xs)
#         self.ts

        # wavelet = pywt.ContinuousWavelet( self.motherwave, )
        # wavelet.center_frequency = 1
        # coef, freqs = pywt.cwt( xs, scale,  wavelet,
        #     # sampling_period = self.bitrate,
        #     sampling_period = 1./self.bitrate,
        #     )

        # coef = scipy.signal.cwt(xs, getattr(scipy.signal,self.motherwave),
        # widths = self.scale,  )
        coef = mlpywt.cwt( xs, 1./self.bitrate, self.scale, wf = self.motherwave, p = p )
        # coef = mlpywt.cwt( xs, 1, self.scale, wf = self.motherwave, p = p )
        coef = postFunc(coef)
        freqs = None
        self.coef = coef
        # self.freqs= freqs
        return coef,freqs
Пример #9
0
def scaleogram(data,
               samp_rate=100.0,
               wavelet='morlet',
               bb=6,
               what='Amp',
               axis=None):
    """
    Computes and plots logarithmic spectrogram of the input trace.

    :param data: Input data
    :param sample_rate: Samplerate in Hz
    :param log: True logarithmic frequency axis, False linear frequency axis
    :param per_lap: Percent of overlap
    :param nwin: Approximate number of windows.
    :param outfile: String for the filename of output file, if None
        interactive plotting is activated.
    :param format: Format of image to save
    :param axis: Plot into given axis, this deactivates the format and
        outfile option
    """
    # enforce float for samp_rate
    samp_rate = float(samp_rate)

    # nfft needs to be an integer, otherwise a deprecation will be raised

    dscale = 0.1
    dtime = 1. / samp_rate
    npts = data.shape[0]
    tt = np.arange(0, npts / samp_rate, 1 / samp_rate)
    xx = ml.autoscales(N=data.shape[0], dt=dtime, dj=dscale, wf=wavelet, p=bb)
    X = ml.cwt(x=data, dt=dtime, scales=xx, wf=wavelet, p=bb)
    freq = ml.fourier_from_scales(xx, wavelet, bb)
    freq = 1. / freq

    #    amp = X
    amp = np.abs(X)
    phase = np.angle(X)

    if not axis:
        fig = plt.figure()
        ax = fig.add_subplot(111)

    else:
        ax = axis

    ax.set_yscale('log')
    if what == 'Amp':
        im = ax.pcolormesh(tt, freq, amp)
    else:
        im = ax.pcolormesh(tt, freq, phase)

    # set correct way of axis, whitespace before and after with window
    # length

    ax.axis('tight')
    # ax.set_xlim(0, end)
    ax.grid(False)
    ax.set_xlabel('Time [s]')
    ax.set_ylabel('Frequency [Hz]')

    if axis:
        return ax, im
Пример #10
0
def ratio_scaleogram(data1,data2, samp_rate = 100.0,wavelet = 'morlet' ,bb=6,what = 'Amp',axis = None):
    """
    Computes and plots logarithmic spectrogram of the input trace.

    :param data: Input data
    :param sample_rate: Samplerate in Hz
    :param log: True logarithmic frequency axis, False linear frequency axis
    :param per_lap: Percent of overlap
    :param nwin: Approximate number of windows.
    :param outfile: String for the filename of output file, if None
        interactive plotting is activated.
    :param format: Format of image to save
    :param axis: Plot into given axis, this deactivates the format and
        outfile option
    """
    # enforce float for samp_rate
    samp_rate = float(samp_rate)

    # nfft needs to be an integer, otherwise a deprecation will be raised


    dscale = 0.05
    dtime = 1./samp_rate
    npts = data1.shape[0]
    tt = np.arange(0,npts/samp_rate,1/samp_rate)
    xx = ml.autoscales(N=data1.shape[0], dt=dtime, dj=dscale, wf=wavelet, p=bb)
    X = ml.cwt(x=data1, dt=dtime, scales=xx, wf=wavelet, p=bb)
    Y = ml.cwt(x=data2, dt=dtime, scales=xx, wf=wavelet, p=bb)
    freq = ml.fourier_from_scales(xx, wavelet, bb)
    freq = 1./freq

    XY = np.abs(X*Y.conjugate())
    YY = np.abs(Y*Y.conjugate())
    XX = np.abs(X*X.conjugate())
    ss,st = XY.shape

    s = np.arange(dscale,0.6,dscale)

    i= 0
    Tl = bb
    while i < ss:
        bt = np.kaiser(Tl*(i+1),0)
        XY[i,:] = np.convolve(XY[i,:],bt,'same')
        XX[i,:] = np.convolve(XX[i,:],bt,'same')
        YY[i,:] = np.convolve(YY[i,:],bt,'same')
        i += 1

    Tf = bb
    i = 0
    while i < st:
        s = np.kaiser(Tf,0)
        XY[:,i] = np.convolve(XY[:,i],s,'same')
        XX[:,i] = np.convolve(XX[:,i],s,'same')
        YY[:,i] = np.convolve(YY[:,i],s,'same')
        i += 1

    Coh = (np.abs(XY)**2)/(np.abs(XX) * np.abs(YY))


    if not axis:
        fig = plt.figure()
        ax = fig.add_subplot(111)

    else:
        ax = axis

    ax.set_yscale('log')
    im=ax.pcolormesh(tt,freq,Coh)

    # set correct way of axis, whitespace before and after with window
    # length

    ax.axis('tight')
    # ax.set_xlim(0, end)
    ax.grid(False)
    ax.set_xlabel('Time [s]')
    ax.set_ylabel('Frequency [Hz]')

    if axis:
        return ax, im
for i in range(0, len(fkinv.real)):
    print >> open('fft.inv', 'a'), fkinv.real[i]

# calculate wavelet scales
scales = wave.autoscales(N=x_pad.shape[0], dt=dt, dj=dj, wf=wf, p=p)

# convert scales to fourier periods and output
period = wave.fourier_from_scales(scales, wf=wf, p=p)
outfile = open("scales.periods", 'w')
scale_len = len(scales)
for i in range(0, scale_len):
    print >> open("scales.periods",
                  'a'), i, scales[i], period[i], 1. / period[i]

# perform continuous wavelet transform and output
X = wave.cwt(x=x_pad, dt=dt, scales=scales, wf=wf, p=p)
power = (np.abs(X))**2.
sumpow = power.mean(axis=1)
outfile = open("sumpower.fp", 'w')
for i in range(0, scale_len):
    print >> open('sumpower.fp', 'a'), sumpow[i] / xlen, period[
        i], 1. / period[i], scales[i], sumpow[i] / (scales[i] * xlen)

# calculate cone of influence (dog wavelet)
coi = scales * (2**0.5)
outfile = open("coi.h", 'w')
np.savetxt("coi.h", coi)

# perform inverse transform to check correct scales have been used
x_icwt = wave.icwt(X=X, dt=dt, scales=scales, wf=wf, p=p)
x_icwt = x_icwt * recon_factor  # equation 11 in Torrance and Compo (1998).
    def callback(self,data):
        
        try:
           #self.cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
           self.cv_image = self.bridge.imgmsg_to_cv2(data, "mono8")
        except CvBridgeError as e:
          print(e)

        self.cv_image = cv2.blur(self.cv_image, (5,5))  
        #gray = cv2.cvtColor(self.cv_image, cv2.COLOR_BGR2GRAY)
        gray= self.cv_image.copy()
    
                #vise = self.cv_image.copy()
        #self.t0=time.time()-self.t0
        #print self.t0
        #print self.flag
        #print self.proceso
        #print '___'    


        if self.selection and self.flag:
            x0, y0, x1, y1 = self.selection
            x1=x0+30
            y1=y0+30
            self.selection=x0,y0,x1,y1
            
            print x0
            print x1
            print y0
            print y1

            #self.track_window = (x0-30, y0-30, x1-x0+30, y1-y0+30)
            self.track_window = (x0, y0, x1, y1)
            self.flag=False

            vis_roi = gray[y0:y1, x0:x1]
            cv2.bitwise_not(vis_roi, vis_roi)
            cv2.rectangle(gray,(x0,y0),(x1,y1),75,1)
            self.trackers.append(vis_roi)
            cv2.imshow("Image window", gray)
            cv2.setMouseCallback("Image window", self.onmouse)
            

        #    edge = cv2.Canny(self.cv_image[y0:y1, x0:x1], self.thrs1, self.thrs2, apertureSize=3)
        #    vise = vise[y0:y1, x0:x1]
        #    vise[edge != 0] = (255self.trackers.append(tracker)        #    cv2.imshow('edge', vise)
    
        #    x=np.mean(gray[y0:y1, x0:x1])
        #    self.datos.append(x)

        
 #       self.cv_image = cv2.blur(self.cv_image, (5,5))
        #if not self.flag:
        
        if self.flag:
            cv2.imshow("Image window", gray)
            cv2.setMouseCallback("Image window", self.onmouse)
           
        # cv2.waitKey(1)
        if not self.flag and self.proceso:
            x0, y0, x1, y1 = self.selection
            #if self.cuenta<2148 :     #256:
            if self.cuenta<1124 :     #256:
                self.trackers.append(gray[y0:y1, x0:x1])
                self.cuenta+=1

                if self.cuenta==1:
                    self.t0=time.time()    
                #print self.cuenta
            else:

                print x0
                print x1
                print y0 
                print y1
                self.t0=time.time()-self.t0 
                print self.t0
                self.proceso=False
                self.flag=True
                self.cuenta=0
                i=0.0
                for tracker in self.trackers:
                    i+=1
                    
                    cv2.imwrite('Pulso2_%i.bmp'%i,tracker)
                    x=np.mean(tracker)
                    self.datos.append(x)
                    self.f.write(str(x))
                    self.f.write(' ')
                    #print x
                
                ndatos=np.array(self.datos)
                N=float(len(ndatos))
                
                ndatos=ndatos[51:N-50]
                #ndatos=ndatos[:N-1]
                #[1:]
                
                print len(ndatos)
                print '___'
                #print ndatos

                scales = wave.autoscales(N=ndatos.shape[0], dt=1, dj=0.25, wf='dog', p=2)
                X = wave.cwt(x=ndatos, dt=1, scales=scales, wf='dog', p=2)
                #Xf=X[15:,:]   #quita las bajas frecuencias

                #scales=scales[15:]
                #Xf=X[:15,:]   #quita las altas frecuencias 

                #scales=scales[:15]

                #Xf=X[15:18,:]   #quita las altas frecuencias 

                #scales=scales[15:18]    
                #Xf=X[15:25,:]   #quita las altas frecuencias 
                #scales=scales[15:25]    
                Xf=X[18:25,:]   #quita las altas frecuencias 
                scales=scales[18:25]    


                X2=wave.icwt(Xf, dt=1, scales=scales, wf='dog', p=2)



                fig = plt.figure(1)
                ax1 = plt.subplot(2,2,1)
                p1 = ax1.plot(ndatos)
                #ax1.autoscale_view(tight=True)

                ax2 = plt.subplot(2,2,2)
                p2 = ax2.imshow(np.abs(X), origin='lower', extent=[-4,4,-1,1], aspect=4)                
                #p2 = ax2.imshow(np.abs(X), interpolation='nearest')                
                #ax2.autoscale_view(tight=True)            
        

                ax3 = plt.subplot(2,2,3)
                p3 = ax3.imshow(np.abs(Xf),origin='lower', extent=[-4,4,-1,1], aspect=4)
                #p3 = ax3.imshow(np.abs(Xf), interpolation='nearest')
                #ax3.autoscale_view(tight=True)

                ax4 = plt.subplot(2,2,4)
                p4 = ax4.plot(np.abs(X2))
                #ax4.autoscale_view(tight=True)
                #plt.show()
                #self.datos=[]
                #ndatos=[]
                self.trackers = []
                self.datos=[]    
                #print len(ndatos)


                # Number of sample points
                nN = len(X2)
                # sample spacing
                #T = 1.0 / 60.0
                T=.01862
                x = np.linspace(0.0, nN*T, nN)
                yf = fft(X2)
                xf = np.linspace(0.0, 1.0/(2.0*T), nN/2)

                plt.figure(2)
                plt.subplot(211)
                plt.plot(X2)

                plt.subplot(212)
                plt.plot(xf*60, 2.0/nN * np.abs(yf[0:nN/2]))
                plt.show()

                
                #print self.trackers.shape
        
        ch =cv2.waitKey(1) 

        if ch== 27:
        # Number of sample points

            #Nd = len(self.datos)
            #print type(self.datos)
            print 'N'
            #print self.datos.shape
 

        if ch == ord ('c'):
            
            self.selection = None       
            self.flag= True
            self.trackers = []
            self.datos=[]


        if ch == ord ('i'):    
            self.proceso=True
            self.flag= False
            print 'i'
            print self.selection
    def callback(self,data):
        
        try:
           #self.cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
	       self.cv_image = self.bridge.imgmsg_to_cv2(data, "mono8")
        except CvBridgeError as e:
          print(e)
        #gray = cv2.cvtColor(self.cv_image, cv2.COLOR_BGR2GRAY)
        gray= self.cv_image.copy()
        vise = self.cv_image.copy()
        
        
        
        if self.selection:
            x0, y0, x1, y1 = self.selection
            self.track_window = (x0, y0, x1-x0, y1-y0)
            self.flag=True
            vis_roi = gray[y0:y1, x0:x1]
            cv2.bitwise_not(vis_roi, vis_roi)
            cv2.rectangle(gray,(x0,y0),(x1,y1),75,1)

            edge = cv2.Canny(self.cv_image[y0:y1, x0:x1], self.thrs1, self.thrs2, apertureSize=3)
            vise = vise[y0:y1, x0:x1]
            vise[edge != 0] = (255)
            cv2.imshow('edge', vise)
    
            x=np.mean(gray[y0:y1, x0:x1])
            self.datos.append(x)





        
 #       self.cv_image = cv2.blur(self.cv_image, (5,5))
        cv2.imshow("Image window", gray)
        cv2.setMouseCallback("Image window", self.onmouse)
           
       # cv2.waitKey(1)
        
        if cv2.waitKey(1) == 27:
        # Number of sample points

            #Nd = len(self.datos)
            #print type(self.datos)
            #print N
            #print self.datos.shape
            ndatos=np.array(self.datos)
            x=ndatos[5:]
            #[1:]
            N=float(len(ndatos))
            print N

            scales = wave.autoscales(N=x.shape[0], dt=1, dj=0.25, wf='dog', p=2)
            X = wave.cwt(x=x, dt=1, scales=scales, wf='dog', p=2)
            Xf=X[15:,:]


            scales=scales[15:]
            X2=wave.icwt(Xf, dt=1, scales=scales, wf='dog', p=2)



            fig = plt.figure(1)
            ax1 = plt.subplot(2,2,1)
            p1 = ax1.plot(x)
            ax1.autoscale_view(tight=True)

            ax2 = plt.subplot(2,2,2)
            p2 = ax2.imshow(np.abs(X), interpolation='nearest')
            
    

            ax3 = plt.subplot(2,2,4)
            p3 = ax3.imshow(np.abs(Xf), interpolation='nearest')

            ax4 = plt.subplot(2,2,3)
            p4 = ax4.plot(np.abs(X2))
            plt.show()
            self.datos=[]


            # Number of sample points
            N = len(X2)
            # sample spacing
            T = 1.0 / 60.0
            x = np.linspace(0.0, N*T, N)
            yf = fft(X2)
            xf = np.linspace(0.0, 1.0/(2.0*T), N/2)

            plt.figure(2)
            plt.subplot(211)
            plt.plot(X2)

            plt.subplot(212)
            plt.plot(xf, 2.0/N * np.abs(yf[0:N/2]))
            plt.show()
sig2 = sig2.tolist()

sig_data = sig + sig1 + sig2
print(type(sig_data))
# plt.plot(sig_data)
# plt.show()





import mlpy.wavelet as wave
x = np.random.sample(512)

scales = wave.autoscales(N=x.shape[0], dt=1, dj=0.25, wf='Morlet', p=2)
X = wave.cwt(x=x, dt=1, scales=scales, wf='Morlet', p=2)

fig = plt.figure(1)
ax1 = plt.subplot(2,1,1)
p1 = ax1.plot(x)
ax1.autoscale_view(tight=True)
ax2 = plt.subplot(2,1,2)
p2 = ax2.imshow(np.abs(X), interpolation='nearest')
plt.show()





'''
# Transform data by raising to  complex exponent
cmplx_thet = np.exp(2*math.pi*(theta)*complex(0,1)/360) 
cmplx_mean = np.mean(cmplx_thet)
cmplx_thet = cmplx_thet - np.mean(cmplx_thet) # subtract mean

# padding
[cmplx_thet_pad, cmplx_thet_pad_orig] = wave.pad(x,method='zeros')
cmplx_thet_pad = cmplx_thet # no padding

# calculate wavelet scales
scales = wave.autoscales(N=cmplx_thet_pad.shape[0], dt=dt, dj=dj, wf=wf, p=p)
# convert scales to fourier periods
period = wave.fourier_from_scales(scales,wf=wf,p=p)
# perform continuous wavelet transform
transformed = wave.cwt(x=cmplx_thet_pad, dt=dt, scales=scales, wf=wf, p=p)

# Calculate bearing as function of (k,x)
bearings = ((np.angle(transformed+cmplx_mean))*360/(2*math.pi))%360

# Calculate power as function of (k,x)
power = np.abs(transformed+cmplx_mean)**2
# Set axes for figures 
x_axis = x
y_axis = period # y_axis is wavenumbers units (m-1)

print("### Visualising results ###")
      
# Plot the scalogram of bearings
plt.pcolormesh(x_axis,y_axis,bearings,cmap='twilight')
plt.yscale('log')