def uncompress_image(compressed_image, level, im_shape):

    # Breaking Compressed Wavlet of Image into RGB Layers (Wavlet Compression works on 2D arrays only)
    arr_r_compressed = compressed_image[:, :, 0]
    arr_g_compressed = compressed_image[:, :, 1]
    arr_b_compressed = compressed_image[:, :, 2]

    x_shape, y_shape = im_shape
    slices = generate_wavlet_slices(x_shape, y_shape, level=level)

    # Converting Compressed Coefficients back into Original Wavlet form (which the pywt library can work with)
    r_coeff = pywt.array_to_coeffs(arr_r_compressed,
                                   slices,
                                   output_format='wavedecn')
    g_coeff = pywt.array_to_coeffs(arr_g_compressed,
                                   slices,
                                   output_format='wavedecn')
    b_coeff = pywt.array_to_coeffs(arr_b_compressed,
                                   slices,
                                   output_format='wavedecn')

    # Using PYWT to uncompress the wavlet coefficients back into their image form
    r_reconstructed = pywt.waverecn(r_coeff, 'db2',
                                    mode='periodization').astype(np.uint8)
    g_reconstructed = pywt.waverecn(g_coeff, 'db2',
                                    mode='periodization').astype(np.uint8)
    b_reconstructed = pywt.waverecn(b_coeff, 'db2',
                                    mode='periodization').astype(np.uint8)

    # Stacking the uncompressed R. G. B. images into the final RGB image
    reconstructed_im = (np.stack(
        (r_reconstructed, g_reconstructed, b_reconstructed),
        2)).astype(np.uint8)

    return reconstructed_im
Example #2
0
 def unpack(self,chunk):
     upacked_chunk = np.empty((minimal.args.frames_per_chunk,2),dtype=np.int32)
     reconstructed_chunk =np.empty((minimal.args.frames_per_chunk+(self.padding*2),2),dtype=np.int32)
     chunk_number,chunk = super().unpack(chunk)
     
     decomposition_0 =wt.array_to_coeffs(chunk[:,0],self.slices,output_format='wavedec')
     decomposition_1 =wt.array_to_coeffs(chunk[:,1],self.slices,output_format='wavedec')
     
     reconstructed_chunk[:, 0] = np.rint(wt.waverec(decomposition_0, self.wavelet)).astype(np.int16)
     reconstructed_chunk[:, 1] = np.rint(wt.waverec(decomposition_1, self.wavelet)).astype(np.int16)
     
     upacked_chunk = reconstructed_chunk[self.padding:(minimal.args.frames_per_chunk+self.padding)]
     return chunk_number,upacked_chunk
Example #3
0
def test_wavedecn_coeff_reshape_even():
    # verify round trip is correct:
    #   wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn
    # This is done for wavedec{1, 2, n}
    rng = np.random.RandomState(1234)
    params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec},
              'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2},
              'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}}
    N = 28
    for f in params:
        x1 = rng.randn(*([N] * params[f]['d']))
        for mode in pywt.Modes.modes:
            for wave in wavelist:
                w = pywt.Wavelet(wave)
                maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len)
                if maxlevel == 0:
                    continue

                coeffs = params[f]['dec'](x1, w, mode=mode)
                coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)
                coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices,
                                               output_format=f)
                x1r = params[f]['rec'](coeffs2, w, mode=mode)

                assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
Example #4
0
def hfilter(diff_image, var_image, threshold=1, ndamp=10):
    """
    This code was inspired from: https://github.com/spacetelescope/sprint_notebooks/blob/master/lucy_damped_haar.ipynb
    I believe it was initially written by Justin Ely: https://github.com/justincely
    It was buggy and not working properly with every image sizes.
    I have thus exchanged it by using pyWavelet (pywt) and a custom function htrans
    to calculate the matrix for the var_image.
    """
    him, coeff_slices = pywt.coeffs_to_array(pywt.wavedec2(
        diff_image.astype(np.float), 'haar'),
                                             padding=0)
    dvarim = htrans(var_image.astype(np.float))

    sqhim = ((him / threshold)**2) / dvarim
    index = np.where(sqhim < 1)

    if len(index[0]) == 0:
        return diff_image

    # Eq. 8 of White is derived leading to N*x^(N-1)-(N-1)*x^N  :DOI: 10.1117/12.176819
    sqhim = sqhim[index] * (ndamp * sqhim[index]**(ndamp - 1) -
                            (ndamp - 1) * sqhim[index]**ndamp)
    him[index] = sign(threshold * np.sqrt(dvarim[index] * sqhim), him[index])

    return pywt.waverec2(
        pywt.array_to_coeffs(him, coeff_slices, output_format='wavedec2'),
        'haar')[:diff_image.shape[0], :diff_image.shape[1]]
Example #5
0
def test_wavedecn_coeff_reshape_even():
    # verify round trip is correct:
    #   wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn
    # This is done for wavedec{1, 2, n}
    rng = np.random.RandomState(1234)
    params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec},
              'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2},
              'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}}
    N = 28
    for f in params:
        x1 = rng.randn(*([N] * params[f]['d']))
        for mode in pywt.Modes.modes:
            for wave in wavelist:
                w = pywt.Wavelet(wave)
                maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len)
                if maxlevel == 0:
                    continue

                coeffs = params[f]['dec'](x1, w, mode=mode)
                coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)
                coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices,
                                               output_format=f)
                x1r = params[f]['rec'](coeffs2, w, mode=mode)

                assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
Example #6
0
def test_wavedecn_coeff_reshape_axes_subset():
    # verify round trip is correct when only a subset of axes are transformed:
    #   wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn
    # This is done for wavedec{1, 2, n}
    rng = np.random.RandomState(1234)
    mode = 'symmetric'
    w = pywt.Wavelet('db2')
    N = 16
    ndim = 3
    for axes in [(-1, ), (0, ), (1, ), (0, 1), (1, 2), (0, 2), None]:
        x1 = rng.randn(*([N] * ndim))
        coeffs = pywt.wavedecn(x1, w, mode=mode, axes=axes)
        coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs, axes=axes)
        if axes is not None:
            # if axes is not None, it must be provided to coeffs_to_array
            assert_raises(ValueError, pywt.coeffs_to_array, coeffs)

        # mismatched axes size
        assert_raises(ValueError, pywt.coeffs_to_array, coeffs,
                      axes=(0, 1, 2, 3))
        assert_raises(ValueError, pywt.coeffs_to_array, coeffs,
                      axes=())

        coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices)
        x1r = pywt.waverecn(coeffs2, w, mode=mode, axes=axes)

        assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
Example #7
0
 def inverse(self, m, wv = 'db4'):
     msyn = np.zeros(mesh.nC)
     coeff_wv = pywt.wavedecn(msyn.reshape(self.mesh.nCx,self.mesh.nCy,order = 'F'),wv, mode = 'per')
     array_wv = pywt.coeffs_to_array(coeff_wv)
     coeff_back = pywt.array_to_coeffs(m.reshape(array_wv[0].shape, order = 'F'),array_wv[1])
     coeff_m = pywt.waverecn(coeff_back,wv, mode = 'per')
     return Utils.mkvc(coeff_m)
Example #8
0
    def wavelet_denoise(
            im,
            mother_wavelet: str = "db1",  # Daubechies wavelet 1
            levels: int = 4,
            keep: float = 1 / 1e2,  # percent
    ):
        """

        :param im:
        :type im:"""

        coef = pywt.wavedec2(im, wavelet=mother_wavelet, level=levels)

        coef_array, coef_slices = pywt.coeffs_to_array(coef)

        Csort = numpy.sort(numpy.abs(coef_array.reshape(-1)))

        coef_filt = pywt.array_to_coeffs(
            coef_array * (numpy.abs(coef_array) > Csort[int(
                numpy.floor((1 - keep) * len(Csort)))]),
            coef_slices,
            output_format=CoeffFormatEnum.wavedec2.value,
        )

        recon = pywt.waverec2(coef_filt, wavelet=mother_wavelet)

        return recon
Example #9
0
 def recompose(self, data, coeff_slices, chnl):
     data[:, chnl] = np.around(
         pywt.waverec(
             pywt.array_to_coeffs(data[:, chnl],
                                  coeff_slices,
                                  output_format="wavedec"), "bior3.5",
             "periodization"))
def ista_algorithm_2d(wavelet, noisy_image, l):
    # Create a matrix of 0s and getting it's wavelet coefficients
    x = fwd_transform(np.zeros(noisy_image.shape), wavelet)

    # Converting coefficients to array for calculation
    x_arr, x_slices = pywt.coeffs_to_array(x)

    # Creating a list of errors
    error_log = []
    # Setting inital error to maximum
    error_old = np.finfo(np.float64).max
    # Run loop until error condition is satisfied
    while True:
        # Soft thresholding
        x_arr = pywt.threshold(x_arr + pywt.coeffs_to_array(
            fwd_transform(noisy_image - inv_transform(x, wavelet),
                          wavelet))[0],
                               l / 2,
                               mode='soft')

        # Converting array back to coefficients
        x = pywt.array_to_coeffs(x_arr, x_slices, 'wavedec2')

        # Calculating error
        error = np.power(
            np.linalg.norm(noisy_image - inv_transform(x, wavelet), 2),
            2) + np.linalg.norm(x_arr, 1) * l
        error_log.append(error)
        # Error condition for the loop to break
        if (error_old - error) / error_old < 1e-7:
            break
        error_old = error

    return inv_transform(x, wavelet), error_log
Example #11
0
 def record_send_and_play(self, indata, outdata, frames, time, status):
     #print(indata)
     #indata[:,0] = self.DWT(indata[:,0])
     coeffs_in_subbands = wt.wavedec(indata[:,0], wavelet=self.wavelet, level=self.levels, mode=self.padding)
     for i in range(len(coeffs_in_subbands)):
         #print(coeffs_in_subbands[i][0], self.gain[i])
         coeffs_in_subbands[i] *= self.gain[i]
     coeffs = wt.coeffs_to_array(coeffs_in_subbands)[0].astype(self.precision_type)
     signs = coeffs & self.sign_mask
     magnitudes = abs(coeffs)
     coeffs = signs | magnitudes
     self.send(coeffs.reshape((self.frames_per_chunk,1)))
     coeffs = self._buffer[self.played_chunk_number % self.cells_in_buffer][:,0]
     signs = coeffs >> self.precision_bits_1
     magnitudes = coeffs & self.magnitude_mask
     coeffs = magnitudes + magnitudes*signs*2
     coeffs_in_subbands = wt.array_to_coeffs(coeffs.astype(np.float32), self.slices, output_format="wavedec")
     for i in range(len(coeffs_in_subbands)):
         #print(type(coeffs_in_subbands[i][0]), self.gain[i])
         coeffs_in_subbands[i] /= self.gain[i]
     chunk = np.around(wt.waverec(coeffs_in_subbands, wavelet=self.wavelet, mode=self.padding)).astype(self.precision_type)
     #chunk[:,0] = self.iDWT(chunk[:,0])
     self._buffer[self.played_chunk_number % self.cells_in_buffer][:,0] = chunk
     #print(chunk)
     self.play(outdata)
     if __debug__:
         self._number_of_received_bitplanes.value += self.received_bitplanes_per_chunk[self.played_chunk_number % self.cells_in_buffer]
     self.received_bitplanes_per_chunk[self.played_chunk_number % self.cells_in_buffer] = 0
Example #12
0
 def init(self, args):
     Intercom_DWT.init(self, args)
     zeros = np.zeros(self.frames_per_chunk)
     coeffs = wt.wavedec(zeros, wavelet=self.wavelet, level=self.levels, mode=self.padding)
     arr, slices = wt.coeffs_to_array(coeffs)
     energy = []
     subband = 0
     for i in range(self.levels,-1,-1):
         base = self.frames_per_chunk >> (i+1)
         base_div_2 = self.frames_per_chunk >> (i+2)
         coeff_index = base+base_div_2
         arr[coeff_index] = self.frames_per_chunk
         coeffs = wt.array_to_coeffs(arr, slices, output_format="wavedec")
         samples = wt.waverec(coeffs, wavelet=self.wavelet, mode=self.padding)
         arr[coeff_index] = 0
         energy.append(self.energy(samples))
         print("intercom_wdwt: coeff_index={} energy={}".format(coeff_index, energy[subband]))
         subband += 1
     min_energy = min(energy)
     print("intercom_mdwt: min_energy={}".format(min_energy))
     self.gain = []
     subband = 0
     for i in energy:
         self.gain.append(energy[subband] / min_energy)
         print("intercom_mdwt: gain[{}]={}".format(subband, self.gain[subband]))
         subband += 1
Example #13
0
    def record_send_and_play_stereo(self, indata, outdata, frames, time, status):
        indata[:,0] -= indata[:,1]
        self.send(indata)

        #We get the chunk from the coefficients buffer
        chunk = self.buffer_coeffs[self.played_chunk_number % self.cells_in_buffer]
        #Once we get the chunk, we reset the buffer
        self.buffer_coeffs[self.played_chunk_number % self.cells_in_buffer] = np.zeros((self.frames_per_chunk, 2), dtype=np.int32)
        #We divide the data by the factor to restore it
        chunk = np.divide(chunk, factor)

        #For each channel, we make the inverse discrete wavelet transform of the indata
        for i in range(self.number_of_channels):
            coeffs_from_arr = pywt.array_to_coeffs(chunk[:,i], self.coeff_slices, output_format="wavedec")
            sample = pywt.waverec(coeffs_from_arr, wavelet=wavelet, mode=padding)
            chunk[:,i] = sample

        #We parse the chunk to int16 to play the data
        chunk = chunk.astype(np.int16)

        signs = chunk >> 15
        magnitudes = chunk & 0x7FFF
        #chunk = ((~signs & magnitudes) | ((-magnitudes) & signs))
        chunk = magnitudes + magnitudes*signs*2
        self._buffer[self.played_chunk_number % self.cells_in_buffer]  = chunk

        self._buffer[self.played_chunk_number % self.cells_in_buffer][:,0] += self._buffer[self.played_chunk_number % self.cells_in_buffer][:,1]
        self.play(outdata)

        self.received_bitplanes_per_chunk [self.played_chunk_number % self.cells_in_buffer] = 0
Example #14
0
    def dwt(self):
        #imLists = [IMAGEPATH + "a01_1.tif", IMAGEPATH + "a01_2.tif"]
        start = time.time()
        self.show_Image_DWt(self.image1)
        self.show_Image_DWt(self.image2)

        # show_DWt1D()
        coeffs = self.calculate_coeffs(self.image1)
        arr, coeff_slices = pywt.coeffs_to_array(coeffs)
        #show_DWt1D(coeffs)
        # show_Image_DWt(coeffs,target)
        #self.show_DWt1D()

        coeffs2 = self.calculate_coeffs(self.image2)
        arr2, coeff_slices2 = pywt.coeffs_to_array(coeffs2)
        startPCA = time.time()
        # p=PCA()
        #array = p.PCA(arr, arr2)#FusionMethod
        f = Fusion(arr, arr2)
        array = f.PCA()
        endPCA = time.time()
        print('Gesamtzeit PCA: {:5.3f}s'.format(endPCA - startPCA))
        coeffs_from_arr = pywt.array_to_coeffs(array,
                                               coeff_slices,
                                               output_format='wavedecn')
        #self.show_DWt1D()
        self.target = pywt.waverecn(coeffs_from_arr, wavelet='db1')
        self.plot()
        end = time.time()
        print('Gesamtzeit DWT: {:5.3f}s'.format((end - start) -
                                                (endPCA - startPCA)))
        print('Gesamtzeit DWT and PCA: {:5.3f}s'.format(end - start))
        return self.target
Example #15
0
 def _transform(self, m, wv = 'db4'):
     msyn = np.zeros(mesh.nC)
     coeff_map = pywt.wavedecn(msyn.reshape(self.mesh.nCx,self.mesh.nCy,order = 'F'),wv, mode = 'per')
     array_map = pywt.coeffs_to_array(coeff_map)
     coeff_map = pywt.array_to_coeffs(m.reshape(array_map[0].shape,order= 'F'),array_map[1])
     coeff_back_map = pywt.waverecn(coeff_map,wv, mode = 'per')
     return Utils.mkvc(coeff_back_map)
Example #16
0
    def record_send_and_play_stereo(self, indata, outdata, frames, time,
                                    status):
        indata[:, 0] -= indata[:, 1]
        self.send(indata)
        chunk = self.buffer_coeffs[self.played_chunk_number %
                                   self.cells_in_buffer]
        self.buffer_coeffs[self.played_chunk_number %
                           self.cells_in_buffer] = np.zeros(
                               (self.frames_per_chunk, 2), dtype=np.int32)

        # Inversed wavelet for both channels
        for i in range(self.number_of_channels):
            coeffs_from_arr = pywt.array_to_coeffs(chunk[:, i],
                                                   self.coeff_slices,
                                                   output_format="wavedec")
            sample = pywt.waverec(coeffs_from_arr, wavelet="db1", mode="per")
            chunk[:, i] = sample

        # We need to cast it as int16 to play
        chunk = chunk.astype(np.int16)

        # Same as dfc
        signs = chunk >> 15
        magnitudes = chunk & 0x7FFF
        chunk = magnitudes + magnitudes * signs * 2
        self._buffer[self.played_chunk_number % self.cells_in_buffer] = chunk
        self._buffer[self.played_chunk_number %
                     self.cells_in_buffer][:, 0] += self._buffer[
                         self.played_chunk_number % self.cells_in_buffer][:, 1]
        self.play(outdata)
        self.received_bitplanes_per_chunk[self.played_chunk_number %
                                          self.cells_in_buffer] = 0
Example #17
0
def calc_wavelet_th(line, wavelet_name, count_process, max_process, sgm_n,
                    coef_m, smoothing):
    len_line = len(line)
    rep_line = line[::-1] + line[::] + line[::-1]
    coeffs = pywt.wavedecn(rep_line, wavelet_name[count_process])
    list_, sep_ = pywt.coeffs_to_array(coeffs)
    m_max = int(np.log2(len(list_)))  ### m(frequency) filter ###
    for m in range(1, m_max + 1):
        for n in range(2**(m_max - m), 2**(m_max - m) * 2):
            if m > m_max * coef_m[count_process] and n != 0:
                list_[n] = 0
    lambda_ = np.sqrt(2.0 * np.log(
        len(rep_line))) * sgm_n[count_process]  ### n(location) filter ##
    #    plt.plot(np.arange(len(list_)),list_);plt.hlines(lambda_,xmin=0,xmax=len(list_));
    list_ = [
        x if (i < len(list_) * 0.01 or np.abs(x) > lambda_) else 0
        for i, x in enumerate(list_)
    ]
    #    plt.plot(np.arange(len(list_)),list_);plt.hlines(-lambda_,xmin=0,xmax=len(list_));plt.show();
    coeffs = pywt.array_to_coeffs(list_, sep_)
    reline = pywt.waverecn(coeffs, wavelet_name[count_process])
    #    plt.plot(np.arange(len(reline)),reline);plt.plot(np.arange(len(rep_line)),rep_line);plt.show();
    if count_process != max_process - 1:
        res = calc_wavelet_th(list(reline[len_line:len_line * 2]),
                              wavelet_name, count_process + 1, max_process,
                              sgm_n, coef_m, smoothing)
    else:
        if smoothing:
            res = calc_wavelet_smooth(list(reline[len_line:len_line * 2]),
                                      'Haar', 3)
        else:
            res = list(reline[len_line:len_line * 2])
    return res
Example #18
0
def Daubechies_opt(M, par=2, lvl=1):
    I = int(np.sum(def_matrix))
    (nx, ny) = def_matrix.shape
    wave = 'db' + str(par)
    md = 'periodization'

    Q = nn.Conv2d(1, I, kernel_size=nx, stride=1, padding=0)
    Q.bias.data = torch.zeros(I)

    ind = np.nonzero(def_matrix)
    Z = np.zeros((nx, ny))

    for index in range(I):
        i = ind[0][index]
        j = ind[1][index]
        Z[i, j] = 1

        pat_coefs = pywt.wavedec2(Z, wave, mode=md, level=lvl)
        [temp, arr] = pywt.coeffs_to_array(pat_coefs)

        pat_temp = pywt.array_to_coeffs(Z, arr, output_format='wavedec2')
        pat = pywt.waverec2(pat_temp, wave)
        pat = torch.from_numpy(pat)

        Z[i, j] = 0
        Q.weight.data[index, 0, :, :] = pat
    Q.bias.requires_grad = False
    Q.weight.requires_grad = False

    return Q
Example #19
0
def test_wavedecn_coeff_reshape_axes_subset():
    # verify round trip is correct when only a subset of axes are transformed:
    #   wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn
    # This is done for wavedec{1, 2, n}
    rng = np.random.RandomState(1234)
    mode = 'symmetric'
    w = pywt.Wavelet('db2')
    N = 16
    ndim = 3
    for axes in [(-1, ), (0, ), (1, ), (0, 1), (1, 2), (0, 2), None]:
        x1 = rng.randn(*([N] * ndim))
        coeffs = pywt.wavedecn(x1, w, mode=mode, axes=axes)
        coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs, axes=axes)
        if axes is not None:
            # if axes is not None, it must be provided to coeffs_to_array
            assert_raises(ValueError, pywt.coeffs_to_array, coeffs)

        # mismatched axes size
        assert_raises(ValueError,
                      pywt.coeffs_to_array,
                      coeffs,
                      axes=(0, 1, 2, 3))
        assert_raises(ValueError, pywt.coeffs_to_array, coeffs, axes=())

        coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices)
        x1r = pywt.waverecn(coeffs2, w, mode=mode, axes=axes)

        assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
Example #20
0
    def record_send_and_play_stereo(self, indata, outdata, frames, time,
                                    status):

        #Binaural calculation L=L-R
        indata[:, 0] -= indata[:, 1]

        #send indata
        self.send(indata)

        #start recovering samples out of coefficient arrays
        for ch in range(self.number_of_channels):
            #Get received coefficient array from buffer for channel X
            arr_chan = self._buffer_coeffs[self.played_chunk_number %
                                           self.cells_in_buffer][:, ch]
            #Inverse precision calculation
            arr_chan = np.divide(arr_chan, factor_precision)
            #Get coefficientes from array with help of saved slice structure
            coeffs_chan = wt.array_to_coeffs(arr_chan,
                                             self.slice_structure,
                                             output_format="wavedec")

            #Get samples with help of inverse DWT transform
            recover = wt.waverec(coeffs_chan, wavelet=wavelet, mode=padding)

            #Check if overlappinf is active
            if (overlap > 0):
                #Delete first and last overlapping samples
                self._buffer[self.played_chunk_number %
                             self.cells_in_buffer][:, ch] = (recover.astype(
                                 np.int16))[+(overlap // 2):-(overlap // 2)]
            else:
                self._buffer[self.played_chunk_number %
                             self.cells_in_buffer][:, ch] = (recover.astype(
                                 np.int16))

        #Clean coefficient buffer position
        self._buffer_coeffs[self.played_chunk_number %
                            self.cells_in_buffer] = self.generate_zero_arr()

        #Inverse sign magnitude calculation
        chunk = self._buffer[self.played_chunk_number % self.cells_in_buffer]
        signs = chunk >> 15
        magnitudes = chunk & 0x7FFF
        chunk = magnitudes + magnitudes * signs * 2

        #Write chunk with correct sign and magnitude to play-buffer
        self._buffer[self.played_chunk_number % self.cells_in_buffer] = chunk

        #Inverse binaural calculation L=L+R
        self._buffer[self.played_chunk_number %
                     self.cells_in_buffer][:, 0] += self._buffer[
                         self.played_chunk_number % self.cells_in_buffer][:, 1]

        #Play data
        self.play(outdata)
        self._buffer[self.played_chunk_number %
                     self.cells_in_buffer] = self.generate_zero_chunk()
        self.received_bitplanes_per_chunk[self.played_chunk_number %
                                          self.cells_in_buffer] = 0
Example #21
0
 def recon(self,z1):
     """
     Wavelet reconstruction:  coefficients -> image
     """
     coeffs = pywt.array_to_coeffs(z1, self.coeff_slices, \
         output_format='wavedec2')
     z0 = pywt.waverec2(coeffs, wavelet=self.wavelet, mode=self.mode)
     return z0
Example #22
0
 def WT(self, wav_x):
     """
         Computes the adjoint Wavelet transform from a vectorized image.
     """
     wav_x = np.reshape(wav_x, (self.m, self.m))
     x = self.WT_operator(
         pywt.array_to_coeffs(wav_x, self.coeffs, output_format='wavedec2'))
     return np.reshape(x, (self.N, 1))
Example #23
0
def iDWT(s0, wave, levels, coeff_slices=None, mode='zero'):
    """
    returns full scale iDWT of s0 with multiple levels
    """
    sz = s0.shape[0]
    if coeff_slices is None:
        coeff_slices = default_slices(levels, sz)
    c = pywt.array_to_coeffs(s0, coeff_slices, output_format='wavedec2')
    return pywt.waverec2(c, 'db4', mode='periodization')
Example #24
0
 def iDWT(self, coeffs_in_array):
     #return coeffs_in_array
     coeffs_in_subbands = wt.array_to_coeffs(coeffs_in_array,
                                             self.slices,
                                             output_format="wavedec")
     return np.around(
         wt.waverec(coeffs_in_subbands,
                    wavelet=self.wavelet,
                    mode=self.padding)).astype(self.sample_type)
Example #25
0
 def _rmatvec(self, x):
     x = np.reshape(x, self.dimsd)
     x = pywt.array_to_coeffs(x, self.sl, output_format="wavedec2")
     y = pywt.waverec2(x,
                       wavelet=self.waveletadj,
                       mode="periodization",
                       axes=self.dirs)
     y = self.pad.rmatvec(y.ravel())
     return y
Example #26
0
 def deriv(self, m, v=None, wv = 'db4'):
     if v is not None:
         coeff_wv = pywt.wavedecn(v.reshape(self.mesh.nCx,self.mesh.nCy,order = 'F'),wv, mode = 'per')
         array_wv = pywt.coeffs_to_array(coeff_wv)
         coeff_back = pywt.array_to_coeffs(v,array_wv[1])
         coeff_m = pywt.waverecn(coeff_back,wv, mode = 'per')
         return Utils.mkvc(coeff_m)        
     else:
         print "not implemented"
Example #27
0
def inverse_wavelet_transform(w_coeffs_rgb, coeff_slices, x_shape):
    x_hat = np.zeros(x_shape)
    for i in range(w_coeffs_rgb.shape[0]):
        w_coeffs_list = pywt.array_to_coeffs(w_coeffs_rgb[i, :, :],
                                             coeff_slices)
        x_hat[0, :, :, i] = pywt.waverecn(w_coeffs_list,
                                          wavelet='db4',
                                          mode='periodization')
    return x_hat
Example #28
0
 def unpack(self, packed_chunk, dtype=minimal.Minimal.SAMPLE_TYPE):
     chunk_number, chunk = super().unpack(packed_chunk, dtype)
     decomposition_left = pywt.array_to_coeffs(chunk[:, 0],
                                               self.slices,
                                               output_format="wavedec")
     decomposition_right = pywt.array_to_coeffs(chunk[:, 1],
                                                self.slices,
                                                output_format="wavedec")
     reconstructed_chunk_left = pywt.waverec(decomposition_left,
                                             wavelet=self.wavelet,
                                             mode="per")
     reconstructed_chunk_right = pywt.waverec(decomposition_right,
                                              wavelet=self.wavelet,
                                              mode="per")
     reconstructed_chunk = np.empty((minimal.args.frames_per_chunk, 2),
                                    dtype=dtype)
     reconstructed_chunk[:, 0] = reconstructed_chunk_left[:]
     reconstructed_chunk[:, 1] = reconstructed_chunk_right[:]
     return chunk_number, reconstructed_chunk
Example #29
0
 def _rmatvec(self, x):
     if self.reshape:
         x = np.reshape(x, self.dimsd)
     x = pywt.array_to_coeffs(x, self.sl, output_format='wavedecn')
     y = pywt.waverecn(x,
                       wavelet=self.waveletadj,
                       mode='periodization',
                       axes=(self.dir, ))
     y = self.pad.rmatvec(y.ravel())
     return y
    def get_coef(self, wanted_scale):
        data = self.CoefMatrix

        mat = np.array([])
        for i in np.arange(self.ntrials):
            C = pywt.array_to_coeffs(data[i, :],
                                     self.slices,
                                     output_format='wavedec')
            temp = np.hstack([C[i] for i in wanted_scale])
            mat = np.hstack((mat, temp))
        return np.reshape(mat, (self.ntrials, -1))
Example #31
0
def get_image_array_from_coeffs(img_coeffs_array, img_coeffs_slices, wavelet):
	# Input: image_coefficient array, the image coefficient slices and the wavelet type
	# Output: reconstructed image array
	temp_layers = []

	for i in range(3):
		temp_tuple = pywt.array_to_coeffs(img_coeffs_array[i], img_coeffs_slices[i], output_format="wavedec2")
		temp_layers.append(pywt.waverec2(temp_tuple, wavelet))

	image_array = np.stack(temp_layers, axis=0)
	return image_array
Example #32
0
 def DWT_synthesize(self, coefs, slices, wavelet_name="db10"):
     """
     Returns the original array from a numpy array that contains the
     wavelet coefficients.
     """
     wavelet = pywt.Wavelet(wavelet_name)
     samples = np.empty(coefs.shape, dtype=np.int32)
     decomposition_0 = pywt.array_to_coeffs(coefs[:, 0],
                                            slices,
                                            output_format="wavedec")
     decomposition_1 = pywt.array_to_coeffs(coefs[:, 1],
                                            slices,
                                            output_format="wavedec")
     samples[:, 0] = np.rint(
         pywt.waverec(decomposition_0, wavelet=wavelet,
                      mode="per")).astype(np.int32)
     samples[:, 1] = np.rint(
         pywt.waverec(decomposition_1, wavelet=wavelet,
                      mode="per")).astype(np.int32)
     return samples
Example #33
0
def test_waverec_invalid_inputs():
    # input must be list or tuple
    assert_raises(ValueError, pywt.waverec, np.ones(8), 'haar')

    # input list cannot be empty
    assert_raises(ValueError, pywt.waverec, [], 'haar')

    # 'array_to_coeffs must specify 'output_format' to perform waverec
    x = [3, 7, 1, 1, -2, 5, 4, 6]
    coeffs = pywt.wavedec(x, 'db1')
    arr, coeff_slices = pywt.coeffs_to_array(coeffs)
    coeffs_from_arr = pywt.array_to_coeffs(arr, coeff_slices)
    message = "Wrong coefficient format, if using 'array_to_coeffs' please specify the 'output_format' parameter"
    assert_raises_regex(AttributeError, message, pywt.waverec, coeffs_from_arr, 'haar')
Example #34
0
def PrintReconstructions(coeffs, n):
    arr, coeff_slices = pywt.coeffs_to_array(coeffs)

    #Removing Details
    for i in range(n,len(coeff_slices)):
        arr[coeff_slices[i]['ad']] = 0
        arr[coeff_slices[i]['dd']] = 0
        arr[coeff_slices[i]['da']] = 0
        
    D1 = pywt.array_to_coeffs(arr, coeff_slices)
    dCat = pywt.waverecn(D1, wavelet)
    
    plt.figure()
    plt.title('Reconstructed with level %i of details' %(n-1))
    plt.imshow(dCat,cmap=colormap)
    return
Example #35
0
def test_waverecn_coeff_reshape_odd():
    # verify round trip is correct:
    #   wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn
    rng = np.random.RandomState(1234)
    x1 = rng.randn(35, 33)
    for mode in pywt.Modes.modes:
        for wave in ['haar', ]:
            w = pywt.Wavelet(wave)
            maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len)
            if maxlevel == 0:
                continue
            coeffs = pywt.wavedecn(x1, w, mode=mode)
            coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)
            coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices)
            x1r = pywt.waverecn(coeffs2, w, mode=mode)
            # truncate reconstructed values to original shape
            x1r = x1r[[slice(s) for s in x1.shape]]
            assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
Example #36
0
File: haar.py Project: scholi/pySPM
def hfilter(diff_image, var_image, threshold=1, ndamp=10):
    """
    This code was inspired from: https://github.com/spacetelescope/sprint_notebooks/blob/master/lucy_damped_haar.ipynb
    I believe it was initially written by Justin Ely: https://github.com/justincely
    It was buggy and not working properly with every image sizes.
    I have thus exchanged it by using pyWavelet (pywt) and a custom function htrans
    to calculate the matrix for the var_image.
    """
    him, coeff_slices = pywt.coeffs_to_array(pywt.wavedec2(diff_image.astype(np.float), 'haar'), padding=0)
    dvarim = htrans(var_image.astype(np.float))
    
    sqhim = ((him/threshold)**2)/dvarim
    index = np.where(sqhim < 1)
    
    if len(index[0]) == 0:
        return diff_image
    
    # Eq. 8 of White is derived leading to N*x^(N-1)-(N-1)*x^N  :DOI: 10.1117/12.176819
    sqhim = sqhim[index] * (ndamp * sqhim[index]**(ndamp-1) - (ndamp-1)*sqhim[index]**ndamp)
    him[index] = sign(threshold*np.sqrt(dvarim[index] * sqhim), him[index])
    
    return pywt.waverec2(pywt.array_to_coeffs(him, coeff_slices, output_format='wavedec2'), 'haar')[:diff_image.shape[0],:diff_image.shape[1]]
Example #37
0
def inverse_wavelet_transform(w_coeffs_rgb, coeff_slices, x_shape):
    x_hat = np.zeros(x_shape)
    for i in range(w_coeffs_rgb.shape[0]):
        w_coeffs_list = pywt.array_to_coeffs(w_coeffs_rgb[i,:,:], coeff_slices)
        x_hat[0,:,:,i] = pywt.waverecn(w_coeffs_list, wavelet='db4', mode='periodization')
    return x_hat