def htrans(A): h0 = A res = [] while h0.shape[0]>1 and h0.shape[1]>1: h0, (hx, hy, hc) = pywt.dwt2(h0, 'haar') res = [(h0, h0, h0)]+res out, _ = pywt.coeffs_to_array([h0]+res, padding=1) return out
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
def pack(self, chunk_number, chunk): if chunk_number != 1: self.previous_chunk = self.current_chunk.copy() self.current_chunk = self.next_chunk.copy() self.next_chunk = chunk.copy() self.extended_chunk = np.concatenate([ self.previous_chunk[-self.number_of_overlaped_samples:], self.current_chunk, self.next_chunk[:self.number_of_overlaped_samples] ]) coefficients = np.empty_like(self.extended_chunk, dtype=np.int32) decomposition_left = pywt.wavedec(self.extended_chunk[:, 0], wavelet=self.wavelet, level=self.levels, mode="per") coefficients_0, slices = pywt.coeffs_to_array(decomposition_left) decomposition_right = pywt.wavedec(self.extended_chunk[:, 1], wavelet=self.wavelet, level=self.levels, mode="per") coefficients_1, slices = pywt.coeffs_to_array(decomposition_right) coefficients[:, 0] = np.rint(coefficients_0).astype(np.int32) coefficients[:, 1] = np.rint(coefficients_1).astype(np.int32) return super().pack(chunk_number, coefficients)
def batchwavelet(x_batch, level=1, db='db1', image_dim=32): halfdim = int(image_dim // 2) x_batchnew = np.zeros( (x_batch.shape[0], halfdim, halfdim, 12)).astype('float32') for i in range(0, x_batch.shape[0]): #Y layer coeffs = pywt.wavedecn(x_batch[i, :, :, 0], level=level, wavelet=db) coeff_array, _ = pywt.coeffs_to_array(coeffs) x_batchnew[i, :, :, 0] = coeff_array[0:halfdim, 0:halfdim] x_batchnew[i, :, :, 1] = coeff_array[0:halfdim, halfdim:halfdim * 2] x_batchnew[i, :, :, 2] = coeff_array[halfdim:halfdim * 2, 0:halfdim] x_batchnew[i, :, :, 3] = coeff_array[halfdim:halfdim * 2, halfdim:halfdim * 2] #cb coeffs = pywt.wavedecn(x_batch[i, :, :, 1], level=level, wavelet=db) coeff_array, _ = pywt.coeffs_to_array(coeffs) x_batchnew[i, :, :, 4] = coeff_array[0:halfdim, 0:halfdim] x_batchnew[i, :, :, 5] = coeff_array[0:halfdim, halfdim:halfdim * 2] x_batchnew[i, :, :, 6] = coeff_array[halfdim:halfdim * 2, 0:halfdim] x_batchnew[i, :, :, 7] = coeff_array[halfdim:halfdim * 2, halfdim:halfdim * 2] #cr coeffs = pywt.wavedecn(x_batch[i, :, :, 2], level=level, wavelet=db) coeff_array, _ = pywt.coeffs_to_array(coeffs) x_batchnew[i, :, :, 8] = coeff_array[0:halfdim, 0:halfdim] x_batchnew[i, :, :, 9] = coeff_array[0:halfdim, halfdim:halfdim * 2] x_batchnew[i, :, :, 10] = coeff_array[halfdim:halfdim * 2, 0:halfdim] x_batchnew[i, :, :, 11] = coeff_array[halfdim:halfdim * 2, halfdim:halfdim * 2] return x_batchnew
def compress_image(image, level, compression_threshold): # Breaking Image into RGB Layers (Wavlet Compression works on 2D arrays only) r = image[:, :, 0] g = image[:, :, 1] b = image[:, :, 2] # Compressing each layer into it's wavlet coefficients # With the level defined in the function r_coeff = pywt.wavedec2(r, 'db2', mode='periodization', level=level) g_coeff = pywt.wavedec2(g, 'db2', mode='periodization', level=level) b_coeff = pywt.wavedec2(b, 'db2', mode='periodization', level=level) # Breaking each Coefficient into it's coefficient array, and a metadata variable (doesnt change from image to image, only changed based on original size) arr_r = pywt.coeffs_to_array(r_coeff)[0] arr_g = pywt.coeffs_to_array(g_coeff)[0] arr_b = pywt.coeffs_to_array(b_coeff)[0] # Getting actual value threshold (below what value of pixel to keep in image) based on percent_threshold provided above threshold_r = get_threshold(arr_r, compression_threshold) threshold_g = get_threshold(arr_g, compression_threshold) threshold_b = get_threshold(arr_b, compression_threshold) # Compressing each coefficient array based on calculated value threshold arr_r_compressed = arr_r * (abs(arr_r) > (threshold_r)) arr_g_compressed = arr_g * (abs(arr_g) > (threshold_g)) arr_b_compressed = arr_b * (abs(arr_b) > (threshold_b)) compressed_image = (np.stack( (arr_r_compressed, arr_g_compressed, arr_b_compressed), 2)) return compressed_image
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
def send(self, indata): # Same as empty signs = indata & 0x8000 magnitudes = abs(indata) indata = signs | magnitudes # Changes for both channels the wavelet # First channel coeffs = pywt.wavedec(indata[:, 0], "db1", mode="per", level=4) array, slices = pywt.coeffs_to_array(coeffs) self.buffer_send[:, 0] = array.astype(np.int32) # Second channel coeffs = pywt.wavedec(indata[:, 1], "db1", mode="per", level=4) array, slices = pywt.coeffs_to_array(coeffs) self.buffer_send[:, 1] = array.astype(np.int32) # Same as intercom_empty self.NOBPTS = int(0.75 * self.NOBPTS + 0.25 * self.NORB) self.NOBPTS += self.skipped_bitplanes[(self.played_chunk_number + 1) % self.cells_in_buffer] self.skipped_bitplanes[(self.played_chunk_number + 1) % self.cells_in_buffer] = 0 self.NOBPTS += 1 if self.NOBPTS > self.max_NOBPTS: self.NOBPTS = self.max_NOBPTS last_BPTS = -1 for bitplane_number in range(self.max_NOBPTS - 1, last_BPTS, -1): self.send_bitplane(self.buffer_send, bitplane_number) self.recorded_chunk_number = (self.recorded_chunk_number + 1) % self.MAX_CHUNK_NUMBER
def get_dwt(shape, wname, levels): """ returns discrete wavelet transforms for a given image shape """ # get slices for pywt array <--> coeff conversion coeffs = pywt.wavedec2(np.zeros(shape), wname, levels) x0, dwt_slices = coeffs_to_array(coeffs) # discrete wavelet transform idwt = lambda x: pywt.waverec2(array_to_coeffs(x, dwt_slices, 'wavedec2'), wname) dwt = lambda x: coeffs_to_array(pywt.wavedec2(x, wname, levels))[0] return dwt, idwt
def get_swt(shape, wname, levels): """ returns stationary wavelet transforms for a given image shape """ # get slices for pywt array <--> coeff conversion coeffs = pywt.swt2(np.zeros(shape), wname, levels, trim_approx=True) _, swt_slices = coeffs_to_array(coeffs) # stationary/undecimated wavelet transform iswt = lambda x: pywt.iswt2(array_to_coeffs(x, swt_slices, 'wavedec2'), wname) swt = lambda x: coeffs_to_array( pywt.swt2(x, wname, levels, trim_approx=True))[0] return swt, iswt
def pack(self,chunk_number,chunk): coefs = np.empty(chunk.shape, dtype=np.int32) decomposition_0 = wt.wavedec(chunk[:,0],self.wavelet, level=self.levels) decomposition_1 = wt.wavedec(chunk[:,1],self.wavelet, level=self.levels) coefs_0, slices = wt.coeffs_to_array(decomposition_0) coefs_1, slices = wt.coeffs_to_array(decomposition_1) coefs[:, 0] = np.rint(coefs_0).astype(np.int32) coefs[:, 1] = np.rint(coefs_1).astype(np.int32) packet_chunk = super().pack(chunk_number,coefs) return packet_chunk, slices
def hard_threshold(tr, chan, coefs, coefsNoise): """ """ logger = logging.getLogger(__name__) cArray, cSlices = pywt.coeffs_to_array(coefs) cArrayN, cSlicesN = pywt.coeffs_to_array(coefsNoise) rmsSignal = np.sqrt(np.mean(cArray**2)) rmsNoise = np.sqrt(np.mean(cArrayN**2)) tr.StoN = rmsSignal/rmsNoise logger.info("Channel %s: S/N: %.1f" % (chan, tr.StoN,)) return tr
def DWT(signal, wave, levels, mode='periodization'): """ returns full scale DWT of signal with multiple levels """ c = pywt.wavedec2(signal, 'db4', mode='periodization', level=levels) output, bye = pywt.coeffs_to_array(c) return output
def default_slices(levels, n): c = pywt.wavedec2(np.zeros((n, n)), 'db4', mode='periodization', level=levels) bye, slices = pywt.coeffs_to_array(c) return slices
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
def initialize_sigma_tau(self, primal): self.dtype = primal.dtype self.op = operators.TransformDecimatedWavelet( primal.shape, wavelet=self.wavelet, level=self.level, axes=self.axes, pad_on_demand=self.pad_on_demand) self.sigma = [ np.ones(self.op.sub_band_shapes[0], self.dtype) * self.scaling_func_mult[0] ] for ii_l in range(self.level): d = {} for label in self.op.sub_band_shapes[ii_l + 1].keys(): d[label] = np.ones(self.op.sub_band_shapes[ii_l + 1][label], self.dtype) * self.scaling_func_mult[ii_l] self.sigma.append(d) self.sigma, _ = pywt.coeffs_to_array(self.sigma, axes=self.axes) self.norm.assign_data(None, sigma=self.sigma) tau = np.ones_like(self.scaling_func_mult) * ((2**self.ndims) - 1) tau[0] += 1 return self.weight * np.sum(tau / self.scaling_func_mult)
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)
def pack(self, chunk_number, chunk): decomposition_left = pywt.wavedec(chunk[:, 0], wavelet=self.wavelet, level=self.levels, mode="per") coefficients_0, slices = pywt.coeffs_to_array(decomposition_left) decomposition_right = pywt.wavedec(chunk[:, 1], wavelet=self.wavelet, level=self.levels, mode="per") coefficients_1, slices = pywt.coeffs_to_array(decomposition_right) coefficients = np.empty_like(chunk, dtype=np.int32) coefficients[:, 0] = coefficients_0[:] coefficients[:, 1] = coefficients_1[:] return super().pack(chunk_number, coefficients)
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)
def __init__(self, dims, dir=0, wavelet='haar', level=1, dtype='float64'): if pywt is None: raise ModuleNotFoundError(pywt_message) _checkwavelet(wavelet) if isinstance(dims, int): dims = (dims, ) # define padding for length to be power of 2 ndimpow2 = max(2**ceil(log(dims[dir], 2)), 2**level) pad = [(0, 0)] * len(dims) pad[dir] = (0, ndimpow2 - dims[dir]) self.pad = Pad(dims, pad) self.dims = dims self.dir = dir self.dimsd = list(dims) self.dimsd[self.dir] = ndimpow2 # apply transform to find out slices _, self.sl = \ pywt.coeffs_to_array(pywt.wavedecn(np.ones(self.dimsd), wavelet=wavelet, level=level, mode='periodization', axes=(self.dir,)), axes=(self.dir,)) self.wavelet = wavelet self.waveletadj = _adjointwavelet(wavelet) self.level = level self.reshape = True if len(self.dims) > 1 else False self.shape = (int(np.prod(self.dimsd)), int(np.prod(self.dims))) self.dtype = np.dtype(dtype) self.explicit = False
def test_coeffs_to_array(): # single element list returns the first element a_coeffs = [ np.arange(8).reshape(2, 4), ] arr, arr_slices = pywt.coeffs_to_array(a_coeffs) assert_allclose(arr, a_coeffs[0]) assert_allclose(arr, arr[arr_slices[0]]) assert_raises(ValueError, pywt.coeffs_to_array, []) # invalid second element: array as in wavedec, but not 1D assert_raises(ValueError, pywt.coeffs_to_array, [ a_coeffs[0], ] * 2) # invalid second element: tuple as in wavedec2, but not a 3-tuple assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs[0], (a_coeffs[0], )]) # coefficients as None is not supported assert_raises(ValueError, pywt.coeffs_to_array, [ None, ]) assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs, (None, None, None)]) # invalid type for second coefficient list element assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs, None]) # use an invalid key name in the coef dictionary coeffs = [np.array([0]), dict(d=np.array([0]), c=np.array([0]))] assert_raises(ValueError, pywt.coeffs_to_array, coeffs)
def __init__(self,nrow=256,ncol=256,wavelet='db4',level=3,fwd_mode='recon',\ dtype=np.float64,name=None): # Save parameters self.wavelet = wavelet self.level = level shape0 = (nrow,ncol) shape1 = (nrow,ncol) dtype0 = dtype dtype1 = dtype if pywt.Wavelet(wavelet).orthogonal: svd_avail = True #SVD calculation assumes an orthogonal wavelet else: svd_avail = False BaseLinTrans.__init__(self, shape0, shape1, dtype0, dtype1,\ svd_avail=svd_avail,name=name) # Set the mode to periodic to make the wavelet orthogonal self.mode = 'periodization' # Send a zero image to get the coefficient slices im = np.zeros((nrow,ncol)) coeffs = pywt.wavedec2(im, wavelet=self.wavelet, level=self.level, \ mode=self.mode) _, self.coeff_slices = pywt.coeffs_to_array(coeffs) # Confirm that fwd_mode is valid if (fwd_mode != 'recon') and (fwd_mode != 'analysis'): raise common.VpException('fwd_mode must be recon or analysis') self.fwd_mode = fwd_mode
def mul_wavelet_dec(imArray): shape = imArray.shape fig, axes = plt.subplots(2, 4, figsize=[14, 8]) max_lev = 3 # how many levels of decomposition to draw label_levels = 3 # how many levels to explicitly label on the plots for level in range(0, max_lev + 1): if level == 0: # show the original image before decomposition axes[0, 0].set_axis_off() axes[1, 0].imshow(imArray, cmap=plt.cm.gray) axes[1, 0].set_title('Image') axes[1, 0].set_axis_off() continue # plot subband boundaries of a standard DWT basis draw_2d_wp_basis(shape, wavedec2_keys(level), ax=axes[0, level], label_levels=label_levels) axes[0, level].set_title('{} level\ndecomposition'.format(level)) # compute the 2D DWT c = pywt.wavedec2(imArray, 'haar', mode='periodization', level=level) # normalize each coefficient array independently for better visibility c[0] /= np.abs(c[0]).max() for detail_level in range(level): c[detail_level + 1] = [d / np.abs(d).max() for d in c[detail_level + 1]] # show the normalized coefficients arr, slices = pywt.coeffs_to_array(c) axes[1, level].imshow(arr, cmap=plt.cm.gray) axes[1, level].set_title('Coefficients\n({} level)'.format(level)) axes[1, level].set_axis_off()
def get_conv_res_wavelets(X, sel_idx, wavelet='db1', level=1): sel_idx_a, sel_idx_d = sel_idx wave_coefs_a = [] wave_coefs_d = [] number_of_patches, _ = X.shape for i in range(number_of_patches): curr_patch = X[i] curr_coefs = pywt.wavedecn(curr_patch, wavelet=wavelet, level=level, mode='per') curr_coefs, coefs_slices = pywt.coeffs_to_array(curr_coefs) curr_a = curr_coefs[coefs_slices[0]] wave_coefs_a.append(curr_a) wave_coefs_d.append(curr_coefs[len(curr_a):]) if sel_idx_a is not None: wave_coefs_a = np.asarray(wave_coefs_a) wave_coefs_d = np.asarray(wave_coefs_d) wave_conv_res_a = wave_coefs_a[:, sel_idx_a] wave_conv_res_d = wave_coefs_d[:, sel_idx_d] return np.concatenate([wave_conv_res_a, wave_conv_res_d], axis=1) else: wave_coefs_d = np.asarray(wave_coefs_d) wave_conv_res_d = wave_coefs_d[:, sel_idx_d] return wave_conv_res_d
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
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)
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) return Utils.mkvc(array_wv[0]) else: print "not implemented"
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)
def send(self, indata): signs = indata & 0x8000 magnitudes = abs(indata) indata = signs | magnitudes # for chIndex in range(self.number_of_channels): coeffs = pywt.wavedec(indata[:, chIndex], wavelet='db1', mode="periodization") arr_float, slices = pywt.coeffs_to_array(coeffs) self.aux_array[:, chIndex] = np.multiply(arr_float, 10) self.NOBPTS = int(0.75 * self.NOBPTS + 0.25 * self.NORB) self.NOBPTS += self.skipped_bitplanes[(self.played_chunk_number + 1) % self.cells_in_buffer] self.skipped_bitplanes[(self.played_chunk_number + 1) % self.cells_in_buffer] = 0 self.NOBPTS += 1 if (self.NOBPTS > self.max_NOBPTS): self.NOBPTS = self.max_NOBPTS last_BPTS = self.max_NOBPTS - self.NOBPTS - 1 for bitplane_number in range(self.max_NOBPTS - 1, last_BPTS, -1): # self.send_bitplane(self.aux_array, bitplane_number) self.recorded_chunk_number = (self.recorded_chunk_number + 1) % self.MAX_CHUNK_NUMBER
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]]
def __init__(self): if __debug__: print("Running Temporal_decorrelation_simple.__init__") super().__init__() if __debug__: print("InterCom (Temporal_decorrelation_simple) is running") self.levels = minimal.args.number_of_levels print("Number of levels =", minimal.args.number_of_levels) self.wavelet_name = "coif2" self.wavelet = pywt.Wavelet(self.wavelet_name) if (self.levels == 0): self.number_of_overlaped_samples = 0 else: self.number_of_overlaped_samples = 1 << math.ceil( math.log(self.wavelet.dec_len * self.levels) / math.log(2)) #print("Size current chunk:", self.current_chunk.shape) temp_chunk = super().generate_zero_chunk() temp_decomposition = pywt.wavedec(temp_chunk[:, 0], wavelet=self.wavelet, level=self.levels, mode="per") temp_coefficients, self.slices = pywt.coeffs_to_array( temp_decomposition)
def get_coeffs_slices(self): zeros = np.zeros(shape=self.frames_per_chunk) coeffs = wt.wavedec(zeros, wavelet=self.wavelet, level=self.levels, mode=self.padding) return wt.coeffs_to_array(coeffs)[1]
def test_array_to_coeffs_invalid_inputs(): coeffs = pywt.wavedecn(np.ones(2), 'haar') arr, arr_slices = pywt.coeffs_to_array(coeffs) # empty list of array slices assert_raises(ValueError, pywt.array_to_coeffs, arr, []) # invalid format name assert_raises(ValueError, pywt.array_to_coeffs, arr, arr_slices, 'foo')
def wavelet_transform(x): w_coeffs_rgb = [] # np.zeros(x.shape[3], np.prod(x.shape)) for i in range(x.shape[3]): w_coeffs_list = pywt.wavedec2(x[0,:,:,i], 'db4', level=None, mode='periodization') w_coeffs, coeff_slices = pywt.coeffs_to_array(w_coeffs_list) w_coeffs_rgb.append(w_coeffs) w_coeffs_rgb = np.array(w_coeffs_rgb) return w_coeffs_rgb, coeff_slices
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')
def test_coeffs_to_array_padding(): rng = np.random.RandomState(1234) x1 = rng.randn(32, 32) mode = 'symmetric' coeffs = pywt.wavedecn(x1, 'db2', mode=mode) # padding=None raises a ValueError when tight packing is not possible assert_raises(ValueError, pywt.coeffs_to_array, coeffs, padding=None) # set padded values to nan coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs, padding=np.nan) npad = np.sum(np.isnan(coeff_arr)) assert_(npad > 0) # pad with zeros coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs, padding=0) assert_(np.sum(np.isnan(coeff_arr)) == 0) assert_(np.sum(coeff_arr == 0) == npad) # Haar case with N as a power of 2 can be tightly packed coeffs_haar = pywt.wavedecn(x1, 'haar', mode=mode) coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs_haar, padding=None) # shape of coeff_arr will match in this case, but not in general assert_equal(coeff_arr.shape, x1.shape)
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
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)
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]]
def test_coeffs_to_array(): # single element list returns just the first element a_coeffs = [np.arange(8).reshape(2, 4), ] arr = pywt.coeffs_to_array(a_coeffs) assert_allclose(arr, a_coeffs[0]) assert_raises(ValueError, pywt.coeffs_to_array, []) # invalid second element: array as in wavedec, but not 1D assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs[0], ] * 2) # invalid second element: tuple as in wavedec2, but not a 3-tuple assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs[0], (a_coeffs[0], )]) # coefficients as None is not supported assert_raises(ValueError, pywt.coeffs_to_array, [None, ]) assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs, (None, None, None)]) # invalid type for second coefficient list element assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs, None]) # use an invalid key name in the coef dictionary coeffs = [np.array([0]), dict(d=np.array([0]), c=np.array([0]))] assert_raises(ValueError, pywt.coeffs_to_array, coeffs)
for ix, x in enumerate(xp[:-1]): for iy, y in enumerate(yp[:-1]): slices = [slice(x, xp[ix+1]), slice(y, yp[iy+1])] val = rstate.rand(1)[0] img[slices] = val return img # create an anisotropic piecewise constant image img = mondrian((128, 128)) # perform DWT coeffs_dwt = pywt.wavedecn(img, wavelet='db1', level=None) # convert coefficient dictionary to a single array coeff_array_dwt, _ = pywt.coeffs_to_array(coeffs_dwt) # perform fully seperable DWT fswavedecn_result = pywt.fswavedecn(img, wavelet='db1') nnz_dwt = np.sum(coeff_array_dwt != 0) nnz_fswavedecn = np.sum(fswavedecn_result.coeffs != 0) print("Number of nonzero wavedecn coefficients = {}".format(np.sum(nnz_dwt))) print("Number of nonzero fswavedecn coefficients = {}".format(np.sum(nnz_fswavedecn))) img = mondrian() fig, axes = plt.subplots(1, 3) imshow_kwargs = dict(cmap=plt.cm.gray, interpolation='nearest') axes[0].imshow(img, **imshow_kwargs) axes[0].set_title('Anisotropic Image')
plt.imshow(dCat,cmap=colormap) return colormap=plt.get_cmap('gray') cat = imageio.imread('/home/az/Desktop/Wavelets/Imagem/Im.jpg') cat = cat[:,:,0] plt.figure() plt.title('Original Image') plt.imshow(cat,cmap=colormap) wavelet = 'db2' lv = 7 coeffs = pywt.wavedecn(cat, wavelet, level=lv) arr, coeff_slices = pywt.coeffs_to_array(coeffs) for n in range(1,len(coeff_slices)): PrintReconstructions(coeffs,n) plt.figure() vec = [np.linalg.norm(arr[coeff_slices[0]])] for i in range(1,7): vec.append(np.linalg.norm(arr[coeff_slices[i]['dd']])) vec = vec/np.linalg.norm(vec) plt.plot([0,1,2,3,4,5,6], vec, 'o') plt.grid() plt.show()
import numpy as np from matplotlib import pyplot as plt import pywt img = pywt.data.camera().astype(float) # Fully separable transform fswavedecn_result = pywt.fswavedecn(img, 'db2', 'periodization', levels=4) # Standard DWT coefs = pywt.wavedec2(img, 'db2', 'periodization', level=4) # convert DWT coefficients to a 2D array mallat_array, mallat_slices = pywt.coeffs_to_array(coefs) fig, (ax1, ax2) = plt.subplots(1, 2) ax1.imshow(np.abs(mallat_array)**0.25, cmap=plt.cm.gray, interpolation='nearest') ax1.set_axis_off() ax1.set_title('Mallat decomposition\n(wavedec2)') ax2.imshow(np.abs(fswavedecn_result.coeffs)**0.25, cmap=plt.cm.gray, interpolation='nearest') ax2.set_axis_off() ax2.set_title('Fully separable decomposition\n(fswt)') plt.show()
fig, axes = plt.subplots(2, 4, figsize=[14, 8]) for level in range(0, max_lev + 1): if level == 0: # show the original image before decomposition axes[0, 0].set_axis_off() axes[1, 0].imshow(x, cmap=plt.cm.gray) axes[1, 0].set_title('Image') axes[1, 0].set_axis_off() continue # plot subband boundaries of a standard DWT basis draw_2d_wp_basis(shape, wavedec2_keys(level), ax=axes[0, level], label_levels=label_levels) axes[0, level].set_title('{} level\ndecomposition'.format(level)) # compute the 2D DWT c = pywt.wavedec2(x, 'db2', mode='periodization', level=level) # normalize each coefficient array independently for better visibility c[0] /= np.abs(c[0]).max() for detail_level in range(level): c[detail_level + 1] = [d/np.abs(d).max() for d in c[detail_level + 1]] # show the normalized coefficients arr, slices = pywt.coeffs_to_array(c) axes[1, level].imshow(arr, cmap=plt.cm.gray) axes[1, level].set_title('Coefficients\n({} level)'.format(level)) axes[1, level].set_axis_off() plt.tight_layout() plt.show()
def pansharpenWavelet(self): '''function pansharpenWavelet(self): This is an instance method that returns a Python list of 3 or 4 NumPy arrays containing the pan-sharpened Red,Green,Blue, and optionally, NIR bands. These bands will have been created using the Wavelet pan-sharpening method Returns: list: Python list[] containing 3 or 4 NumPy arrays using wavelet method. ''' # read Panchromatic,Multispectral Geotiffs into GDAL objects dsPan = gdal.Open(self.pan) dsMulti = gdal.Open(self.multi) # read Panchromatic,Red,Green,Blue bands into 2D NumPy arrays pan = dsPan.GetRasterBand(1).ReadAsArray() blue = dsMulti.GetRasterBand(3).ReadAsArray().astype(float) green = dsMulti.GetRasterBand(2).ReadAsArray().astype(float) red = dsMulti.GetRasterBand(1).ReadAsArray().astype(float) d = dsMulti.RasterCount nrows,ncols = pan.shape if d == 3: image = np.zeros((nrows,ncols,d),dtype=np.float32) image[:,:,0] = red image[:,:,1] = green image[:,:,2] = blue elif d == 4: NIR = dsMulti.GetRasterBand(1).ReadAsArray().astype(float) image[:,:,3] = NIR else: dsPan,dsMulti = None,None return [] level = 0 wavelet_type = 'haar' coeffs = pywt.wavedec2( pan, wavelet=wavelet_type, level=level) panvec,coeff_slices,coeff_shapes = pywt.ravel_coeffs(coeffs) reconstvec = np.tile( panvec.T , (d,1)).T n=panvec.shape[0] lowresvec = np.zeros((n,d),dtype=np.float32) for band in range(d): lowresCoeffs = pywt.wavedec2( image[:,:,band], wavelet=wavelet_type, level=level) lowresArr,arrSlices = pywt.coeffs_to_array(lowresCoeffs) lowresvec[:,band] = np.reshape(lowresArr,(nrows*ncols,)) for j in range( 0 , coeff_shapes[0][0] * coeff_shapes[0][1] ): reconstvec[ j,:] = lowresvec[j,:] sharpened = np.zeros((nrows,ncols,d),dtype=np.float32) for band in range(d): p = np.reshape( reconstvec[:,band], (nrows,ncols)) fcoeffs = pywt.wavedec2(p,wavelet_type,level=level) out=pywt.waverec2(fcoeffs,wavelet_type) sharpened[:,:,band] = out redsharp = sharpened[:,:,0] greensharp = sharpened[:,:,1] bluesharp = sharpened[:,:,2] if d == 4: NIRsharp = sharpened[:,:,3] return [redsharp,greensharp,bluesharp,NIRsharp] elif d == 3: return [redsharp,greensharp,bluesharp] else: return []