def test_per_axis_wavelets_and_modes(): # tests seperate wavelet and edge mode for each axis. rstate = np.random.RandomState(1234) data = rstate.randn(16, 16, 16) # wavelet can be a string or wavelet object wavelets = (pywt.Wavelet('haar'), 'sym2', 'db4') # mode can be a string or a Modes enum modes = ('symmetric', 'periodization', pywt._extensions._pywt.Modes.reflect) coefs = pywt.dwtn(data, wavelets, modes) assert_allclose(pywt.idwtn(coefs, wavelets, modes), data, atol=1e-14) coefs = pywt.dwtn(data, wavelets[:1], modes) assert_allclose(pywt.idwtn(coefs, wavelets[:1], modes), data, atol=1e-14) coefs = pywt.dwtn(data, wavelets, modes[:1]) assert_allclose(pywt.idwtn(coefs, wavelets, modes[:1]), data, atol=1e-14) # length of wavelets or modes doesn't match the length of axes assert_raises(ValueError, pywt.dwtn, data, wavelets[:2]) assert_raises(ValueError, pywt.dwtn, data, wavelets, mode=modes[:2]) assert_raises(ValueError, pywt.idwtn, coefs, wavelets[:2]) assert_raises(ValueError, pywt.idwtn, coefs, wavelets, mode=modes[:2]) # dwt2/idwt2 also support per-axis wavelets/modes data2 = data[..., 0] coefs2 = pywt.dwt2(data2, wavelets[:2], modes[:2]) assert_allclose(pywt.idwt2(coefs2, wavelets[:2], modes[:2]), data2, atol=1e-14)
def dwtfft(data, level=6, wname='db10', sigma=2): """ Remove ring artifacts. Parameters ---------- data : ndarray Input stack of projections. level : scalar, optional Number of DWT levels. wname : str, optional Type of the wavelet filter. sigma : scalar, optional Damping parameter in Fourier space. References ---------- - Optics Express, Vol 17(10), 8567-8591(2009) """ for n in range(data.shape[1]): # Wavelet decomposition. im = data[:, n, :] cH = [] cV = [] cD = [] for m in range(level): im, (cHt, cVt, cDt) = pywt.dwt2(im, wname) cH.append(cHt) cV.append(cVt) cD.append(cDt) # FFT transform of horizontal frequency bands. for m in range(level): # FFT fcV = np.fft.fftshift(np.fft.fft(cV[m], axis=0)) my, mx = fcV.shape # Damping of ring artifact information. y_hat = (np.arange(-my, my, 2, dtype='float')+1) / 2 damp = 1 - np.exp(-np.power(y_hat, 2) / (2 * np.power(sigma, 2))) fcV = np.multiply(fcV, np.transpose(np.tile(damp, (mx, 1)))) # Inverse FFT. cV[m] = np.real(np.fft.ifft(np.fft.ifftshift(fcV), axis=0)) # Wavelet reconstruction. nim = im for m in range(level)[::-1]: nim = nim[0:cH[m].shape[0], 0:cH[m].shape[1]] nim = pywt.idwt2((nim, (cH[m], cV[m], cD[m])), wname) nim = nim[0:data.shape[0], 0:data.shape[2]] data[:, n, :] = nim return data
def _embed(self): container = EmbeddingMethodStack.rgb_2_ycbcr(self.container) stego = numpy.copy(container) self.watermark = skimage.color.rgb2gray(self.watermark) self.watermark = scipy.misc.imresize(self.watermark, (numpy.divide(container.shape[0], 64), numpy.divide(container.shape[1], 64)), interp='bicubic') super(ElahianEmbedder, self)._embed() watermark_bitstream = EmbeddingMethodStack.matrix_2_bitstream(self.watermark.astype(numpy.uint8)) position = EmbeddingMethodStack.pseudo_rand_mask_create(numpy.asarray((numpy.divide(container.shape[0], 8), numpy.divide(container.shape[1], 8)))) self.aux[ElahianMethodConfig.AUX_POSITION] = position c1a, (c1h, c1v, c1d) = pywt.dwt2(container[:, :, 0], self.aux[ElahianMethodConfig.AUX_WAVELET]) c2a, (c2h, c2v, c2d) = pywt.dwt2(c1a, self.aux[ElahianMethodConfig.AUX_WAVELET]) c3a, (c3h, c3v, c3d) = pywt.dwt2(c2a, self.aux[ElahianMethodConfig.AUX_WAVELET]) x = position[:, 1] y = position[:, 0] c3ae = numpy.copy(c3a) # print c3ae.shape, watermark_bitstream.shape, position.shape for k in range(watermark_bitstream.size - 1): c3ae[y[k], x[k]] = c3a[y[k], x[k]] + self.aux[ElahianMethodConfig.AUX_G] * watermark_bitstream[k] c2ae = pywt.idwt2((c3ae, (c3h, c3v, c3d)), self.aux[ElahianMethodConfig.AUX_WAVELET]) c1ae = pywt.idwt2((c2ae, (c2h, c2v, c2d)), self.aux[ElahianMethodConfig.AUX_WAVELET]) stego[:, :, 0] = pywt.idwt2((c1ae, (c1h, c1v, c1d)), self.aux[ElahianMethodConfig.AUX_WAVELET]) stego = EmbeddingMethodStack.ycbcr_2_rgb(stego, self.container.dtype) # print stego.shape, self.watermark.shape, self.container.shape return stego
def test_idwt2_none_coeffs(): data = np.array([[0, 1, 2, 3], [1, 1, 1, 1], [1, 4, 2, 8]]) data = data + 1j*data # test with complex data cA, (cH, cV, cD) = pywt.dwt2(data, 'haar', axes=(1, 1)) # verify setting coefficients to None is the same as zeroing them cD = np.zeros_like(cD) result_zeros = pywt.idwt2((cA, (cH, cV, cD)), 'haar', axes=(1, 1)) cD = None result_none = pywt.idwt2((cA, (cH, cV, cD)), 'haar', axes=(1, 1)) assert_equal(result_zeros, result_none)
def _extract(self): c_a = numpy.zeros((numpy.divide(self.container.shape[0], 2), numpy.divide(self.container.shape[1], 2), self.container.shape[2]), dtype=numpy.single) c_h = numpy.copy(c_a) c_v = numpy.copy(c_a) c_d = numpy.copy(c_a) self.watermark = numpy.zeros(self.aux[EmbeddingMethodConfig.AUX_STEGO_SIZE], dtype=self.container.dtype) for i in range(self.container.ndim): c_a[:, :, i], (c_h[:, :, i], c_v[:, :, i], c_d[:, :, i]) = pywt.dwt2(self.container[:, :, i], self.aux[DeyMethodConfig.AUX_WAVELET]) caw, (chw, cvw, cdw) = pywt.dwt2(self.stego[:, :, i], self.aux[DeyMethodConfig.AUX_WAVELET]) cas = (caw - (1 - self.aux[DeyMethodConfig.AUX_G]) * c_a[:, :, i]) / self.aux[DeyMethodConfig.AUX_G] chs = (chw - (1 - self.aux[DeyMethodConfig.AUX_G]) * c_h[:, :, i]) / self.aux[DeyMethodConfig.AUX_G] cvs = (cvw - (1 - self.aux[DeyMethodConfig.AUX_G]) * c_v[:, :, i]) / self.aux[DeyMethodConfig.AUX_G] cds = (cdw - (1 - self.aux[DeyMethodConfig.AUX_G]) * c_d[:, :, i]) / self.aux[DeyMethodConfig.AUX_G] size = cas.shape[0] / 2 LL = (cas[0:size, 0:size] + chs[0:size, 0:size] + cvs[0:size, 0:size] + cds[0:size, 0:size]) / 4 LH = (cas[size:2 * size, 0:size] + chs[size:2 * size, 0:size] + cvs[size:2 * size, 0:size] + cds[ size:2 * size, 0:size]) / 4 HL = (cas[0:size, size:2 * size] + chs[0:size, size:2 * size] + cvs[0:size, size:2 * size] + cds[0:size, size:2 * size]) / 4 HH = (cas[size:2 * size, size:2 * size] + chs[size:2 * size, size:2 * size] + cvs[size:2 * size, size:2 * size] + cds[size:2 * size, size:2 * size]) / 4 self.watermark[:, :, i] = pywt.idwt2((LL, (LH, HL, HH)), self.aux[DeyMethodConfig.AUX_WAVELET]) super(DeyExtractor, self)._extract() return self.watermark
def recompose(image, coarse, wtype): print image.shape # nothing to be done: case in which coarse is the size of image if coarse.shape == image.shape: return coarse coeffs2 = pywt.dwt2(image,wtype,axes=(0,1)) if coeffs2[0].shape == coarse.shape: ncoarse = coarse*2.0 elif coeffs2[0].shape[0] > coarse.shape[0] and coeffs2[0].shape[1] > coarse.shape[1]: ncoarse = recompose(coeffs2[0],coarse*2.0,wtype) else: print "ERROR: Are you sure that \'%s\' is the right wavelet? Sizes don't match!"%wtype print image.shape print coarse.shape exit() #adjust size of upsampled version isz = coeffs2[0].shape ncoarse = ncoarse[0:isz[0],0:isz[1],:] ncoeffs2 = (ncoarse, coeffs2[1]) ret = pywt.idwt2(ncoeffs2,wtype,axes=(0,1)) return ret
def recompose(prefix, levels, suffix, wtype, cur=0): print prefix+str(cur)+suffix image = piio.read(prefix+str(cur)+suffix) print image.shape if levels==1: # if last level return image LL = 2 * recompose(prefix,levels-1,suffix, wtype, cur+1) ## 2 compensates the factor used in decompose coeffs2 = pywt.dwt2(image,wtype,axes=(0,1)) if coeffs2[0].shape != LL.shape: print "ERROR: Are you sure that \'%s\' is the right wavelet? Sizes don't match!"%wtype exit() ncoeffs2 = (LL, coeffs2[1]) ret = pywt.idwt2(ncoeffs2,wtype, axes=(0,1)) # adjust size of the upsampled image ret = ret[:image.shape[0],:image.shape[1],:] print ret.shape return ret
def build_im(decoded_data, height, width, wavelet, q): LL = (np.cumsum(np.array(decoded_data[0:int(height/2 * width/2)]))).reshape(height/2, width/2) LH = (np.array(decoded_data[int(height/2 * width/2):2*int(height/2 * width/2)])*q).reshape(height/2, width/2) HL = (np.array(decoded_data[2*int(height/2 * width/2):3*int(height/2 * width/2)])*q).reshape(height/2, width/2) HH = (np.array(decoded_data[3*int(height/2 * width/2):4*int(height/2 * width/2)])*q).reshape(height/2, width/2) im = pywt.idwt2( (LL, (LH, HL, HH)), wavelet,mode='periodization' ) show(im) return im
def _embed(self, img, payload, k): rand = Random(self.seed) cA, (cH, cV, cD) = dwt2(img, self.mother) cD2 = cD.reshape(cD.size) for bit in iterbits(payload): seq = numpy.array([int(rand.random() > 0.95) for _ in range(cD2.size)]) if bit: cD2 += k * seq return idwt2((cA, (cH, cV, cD2.reshape(cD.shape))), self.mother)[:img.shape[0],:img.shape[1]]
def test_ignore_invalid_keys(): data = np.array([[0, 4, 1, 5, 1, 4], [0, 5, 6, 3, 2, 1], [2, 5, 19, 4, 19, 1]]) wavelet = pywt.Wavelet("haar") LL, (HL, LH, HH) = pywt.dwt2(data, wavelet) d = {"aa": LL, "da": HL, "ad": LH, "dd": HH, "foo": LH, "a": HH} assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet), pywt.idwtn(d, wavelet), atol=1e-15)
def _recreate16(self, subbands, wavelet): """ Recreate the original from the 16 subbands. Parameters ---------- subbands : list of 16 numpy arrays giving the subbands wavelet : string, giving the pywavelets name of the wavelet to use Returns ------- img : numpy array, inverting the effect of _decompose16 """ LL = pywt.idwt2((subbands[0], tuple(subbands[1:4])), wavelet, mode='per') details = [] for i in xrange(1,4): details.append(pywt.idwt2((subbands[4*i], tuple(subbands[4*i+1:4*i+4])), wavelet, mode='per')) return pywt.idwt2((LL, tuple(details)), wavelet, mode='per')
def inversa(coefficientes,escala):#Funcion para recuperar original inv=pywt.idwt2(coefficientes,'haar')#Funcion inversa pixeles=escala.load() ancho,alto=escala.size for i in range(ancho): for j in range(alto): nuevo=int(inv[i,j]) pixeles[i,j]=(nuevo,nuevo,nuevo) return escala
def main(): #quantization factor. Might change try: input_file_name = sys.argv[1] print "Attempting to open %s..." % input_file_name input_file = open(sys.argv[1], 'rb') except: print "Unable to open input file. Qutting." quit() try: output_file_name = sys.argv[2] print "Attempting to open %s..." % output_file_name output_file = open(sys.argv[2], 'wb') except: print "Unable to open output file. Qutting." quit() header = json.loads(input_file.readline()) code_dict = json.loads(input_file.readline()) print header height = int(header['height']) width = int(header['width']) wavelet = header['wavelet'] q = int(header['q']) decode_dict = {v.encode() : k for k, v in code_dict.iteritems()} binary_data = input_file.read() binary_string = "" for byte in binary_data: binary_string += format(ord(byte),'08b') decdoed_data = [] while len(decdoed_data) != 4*(0.5*height * 0.5*width): sub_str = "" i = 0 while sub_str not in decode_dict: sub_str = binary_string[0:i] i=i+1 decdoed_data += [int(decode_dict[sub_str])] binary_string = binary_string[i-1:] print height, width print decdoed_data LL = (np.cumsum(np.array(decdoed_data[0:int(height/2 * width/2)]))).reshape(height/2, width/2) LH = (np.array(decdoed_data[int(height/2 * width/2):2*int(height/2 * width/2)])*q).reshape(height/2, width/2) HL = (np.array(decdoed_data[2*int(height/2 * width/2):3*int(height/2 * width/2)])*q).reshape(height/2, width/2) HH = (np.array(decdoed_data[3*int(height/2 * width/2):4*int(height/2 * width/2)])*q).reshape(height/2, width/2) show(LL) im = pywt.idwt2( (LL, (LH, HL, HH)), wavelet,mode='periodization' ) show(im) scipy.misc.toimage(im).save(output_file)
def test_dwt2_idwt2_dtypes(): wavelet = pywt.Wavelet("haar") for dt_in, dt_out in zip(dtypes_in, dtypes_out): x = np.ones((4, 4), dtype=dt_in) errmsg = "wrong dtype returned for {0} input".format(dt_in) cA, (cH, cV, cD) = pywt.dwt2(x, wavelet) assert_(cA.dtype == cH.dtype == cV.dtype == cD.dtype, "dwt2: " + errmsg) x_roundtrip = pywt.idwt2((cA, (cH, cV, cD)), wavelet) assert_(x_roundtrip.dtype == dt_out, "idwt2: " + errmsg)
def _embed(self, img, payload, k): cA, (cH, cV, cD) = dwt2(img, self.mother) arr = self._interleave(cH, cV, cD) chunk_size = arr.size // self.total_bits sequence_of = (self.seq0[:chunk_size], self.seq1[:chunk_size]) for i, bit in enumerate(iterbits(payload)): seq = sequence_of[bit] arr[i * chunk_size: i * chunk_size + seq.size] += k * seq w, h = img.shape cH2, cV2, cD2 = self._deinterleave(arr, cH, cV, cD) return idwt2((cA, (cH2, cV2, cD2)), self.mother)[:w,:h]
def _embed(self, img, payload, k): cA, (cH, cV, cD) = dwt2(img, self.mother) w, h = cH.shape cH2 = cH.reshape(cH.size) cV2 = cV.reshape(cV.size) chunk_size = cH2.size // (self.total_bits // 2) assert chunk_size >= self.seq0.size for i, bit in enumerate(iterbits(payload)): dst = (cH2, cV2)[i % 2] seq = (self.seq0, self.seq1)[bit] dst[(i//2)*chunk_size:(i//2)*chunk_size + seq.size] += k * seq return idwt2((cA, (cH2.reshape(w, h), cV2.reshape(w, h), cD)), self.mother)[:img.shape[0],:img.shape[1]]
def _embed(self, img, payload, k): cA, (cH, cV, cD) = dwt2(img.astype(float), self.mother) vec = self._interleave(cH, cV, cD) chunk_size = vec.size // self.total_bits sequences = self._generate_sequences(chunk_size) for i, bit in enumerate(iterbits(payload)): offset = i * chunk_size vec[offset : offset + chunk_size] += k * sequences[bit] #vec[i : self.total_bits*chunk_size : self.total_bits] += k * sequences[bit] w, h = img.shape cH2, cV2, cD2 = self._deinterleave(vec, cH, cV, cD) return idwt2((cA, (cH2, cV2, cD2)), self.mother)[:w,:h]
def test_ignore_invalid_keys(): data = np.array([ [0, 4, 1, 5, 1, 4], [0, 5, 6, 3, 2, 1], [2, 5, 19, 4, 19, 1]]) wavelet = pywt.Wavelet('haar') LL, (HL, LH, HH) = pywt.dwt2(data, wavelet) d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH, 'foo': LH, 'a': HH} assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet), pywt.idwtn(d, wavelet), atol=1e-15)
def test_idwtn_missing(): # Test to confirm missing data behave as zeroes data = np.array([ [0, 4, 1, 5, 1, 4], [0, 5, 6, 3, 2, 1], [2, 5, 19, 4, 19, 1]]) wavelet = pywt.Wavelet('haar') LL, (HL, _, HH) = pywt.dwt2(data, wavelet) d = {'aa': LL, 'da': HL, 'dd': HH} assert_allclose(pywt.idwt2((LL, (HL, None, HH)), wavelet), pywt.idwtn(d, 'haar'), atol=1e-15)
def insert(self, cover_image): # Instancias necesarias itools = ImageTools() # Embedding of Copyright Information (robust watermarking) # Convirtiendo a modelo de color YCbCr cover_ycbcr_array = itools.rgb2ycbcr(cover_image) # Tomando componente Y cover_array = cover_ycbcr_array[:, :, 0] # Wavelet Transform LL, [LH, HL, HH] = pywt.dwt2(cover_array, 'haar') # Watermark resize self.watermark_proccesing(LL.shape) colums = len(LL[0]) print("Creando posisciones random") val = [x for x in range(self.cant_posibilidades)] random.shuffle(val) self.v = val[:self.len_watermark_list] print("Insertando") # Embedding for i in range(self.len_watermark_list): px = self.v[i] // colums py = self.v[i] - (px * colums) if self.watermark_list[i] == 255: if HL[px, py] <= LH[px, py]: T = abs(LH[px, py]) - abs(HL[px, py]) A3w = T + HL[px][py] HL[px, py] = A3w + (LH[px, py] + HL[px, py]) / 2.0 else: if LH[px, py] <= HL[px, py]: T = abs(HL[px, py]) - abs(LH[px, py]) A2w = T + LH[px, py] LH[px, py] = A2w + (LH[px, py] + HL[px, py]) / 2.0 # Inverse transform cover_ycbcr_array[:, :, 0] = pywt.idwt2((LL, (LH, HL, HH)), 'haar') image_rgb_array = itools.ycbcr2rgb(cover_ycbcr_array) # Generating the watermarked image watermarked_image = Image.fromarray(image_rgb_array) return watermarked_image
def test_idwtn_idwt2(): data = np.array([[0, 4, 1, 5, 1, 4], [0, 5, 6, 3, 2, 1], [2, 5, 19, 4, 19, 1]]) wavelet = pywt.Wavelet("haar") LL, (HL, LH, HH) = pywt.dwt2(data, wavelet) d = {"aa": LL, "da": HL, "ad": LH, "dd": HH} for mode in pywt.Modes.modes: assert_allclose( pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode=mode), pywt.idwtn(d, wavelet, mode=mode), rtol=1e-14, atol=1e-14, )
def _embed(self, img, payload, k): cA, (cH, cV, cD) = dwt2(img, self.mother) w, h = cH.shape cH2 = cH.reshape(cH.size) cV2 = cV.reshape(cV.size) chunk_size = cH2.size // (self.total_bits // 2) assert chunk_size >= self.seq0.size for i, bit in enumerate(iterbits(payload)): dst = (cH2, cV2)[i % 2] seq = (self.seq0, self.seq1)[bit] dst[(i // 2) * chunk_size:(i // 2) * chunk_size + seq.size] += k * seq return idwt2((cA, (cH2.reshape(w, h), cV2.reshape(w, h), cD)), self.mother)[:img.shape[0], :img.shape[1]]
def __idwtChannels(self, Wa, Wh, Wv, Wd, wavelet_name, channels=3): fm = [] # fm contains [channel, height, width] # not using coarsest level if Wa is not None: Wa_aux = [] for w in Wa: # setting shape problem : extend approximation to horizontal detail (could've chosen any other detail) if w.shape != Wh[0, :, :].shape: Wa_aux.append(cv2.resize(w, Wh[0, :, :].shape[::-1])) else: Wa_aux.append(w) # calculate inverse wavelet transform with scaling factor limit for c in range(self._channelNumber): fm.append( pywt.idwt2( (Wa_aux[c], (Wh[c, :, :], Wv[c, :, :], Wd[c, :, :])), wavelet_name)**2 / self._scalingFactor) else: # setting shape problem : doesnt happen with previous extension for c in range(self._channelNumber): fm.append( pywt.idwt2((None, (Wh[c, :, :], Wv[c, :, :], Wd[c, :, :])), self._waveletType)**2 / self._scalingFactor) return np.array(fm)
def inner_embed(self, B, signature): w, h = B.shape[:2] LL, (HL, LH, HH) = pywt.dwt2(np.array(B[:32 * (w // 32), :32 * (h // 32)]), 'haar') LL_1, (HL_1, LH_1, HH_1) = pywt.dwt2(LL, 'haar') LL_2, (HL_2, LH_2, HH_2) = pywt.dwt2(LL_1, 'haar') LL_3, (HL_3, LH_3, HH_3) = pywt.dwt2(LL_2, 'haar') LL_4, (HL_4, LH_4, HH_4) = pywt.dwt2(LL_3, 'haar') bi_int_part, frac_part, combo_neg_idx, _ = self._gene_embed_space(HH_4) HH_4 = self._embed_sig(bi_int_part, frac_part, combo_neg_idx, signature) LL_3 = pywt.idwt2((LL_4, (HL_4, LH_4, HH_4)), 'haar') LL_2 = pywt.idwt2((LL_3, (HL_3, LH_3, HH_3)), 'haar') LL_1 = pywt.idwt2((LL_2, (HL_2, LH_2, HH_2)), 'haar') LL = pywt.idwt2((LL_1, (HL_1, LH_1, HH_1)), 'haar') B[:32 * (w // 32), :32 * (h // 32)] = pywt.idwt2((LL, (HL, LH, HH)), 'haar') return B
def recontract_img_from_dwt_coef(coeff_dwt): (coeffs_r, coeffs_g, coeffs_b) = coeff_dwt reRed = pywt.idwt2(coeffs_r, 'haar') reGreen = pywt.idwt2(coeffs_g, 'haar') reBlue = pywt.idwt2(coeffs_b, 'haar') (width, height) = reRed.shape print('image shape : ', reRed.shape) print(type(reRed[0][0])) dwt_img = Image.new('RGB', (width, height), (0, 0, 20)) for i in range(width): for j in range(height): R = reRed[i][j] # R = (R/reMaxRed)*160.0 G = reGreen[i][j] # G = (G/reMaxGreen)*85.0 B = reBlue[i][j] # B = (B/reMaxBlue)*100.0 new_value = (int(R), int(G), int(B)) dwt_img.putpixel((i, j), new_value) dwt_img.save('lena_re.png') return dwt_img
def test_idwtn_idwt2_complex(): data = np.array([ [0, 4, 1, 5, 1, 4], [0, 5, 6, 3, 2, 1], [2, 5, 19, 4, 19, 1]]) data = data + 1j wavelet = pywt.Wavelet('haar') LL, (HL, LH, HH) = pywt.dwt2(data, wavelet) d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH} for mode in pywt.Modes.modes: assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode=mode), pywt.idwtn(d, wavelet, mode=mode), rtol=1e-14, atol=1e-14)
def getwater(imgurl): img = cv2.imread('media/' + imgurl) watermark = cv2.imread('static/markers/marker.png') version = Version.objects.filter(original_picture=imgurl) list = [] for i in version: list.append(i.version_id) print(len(list)) saveurl = 'media/digitalmark/encode' + str(list[0]) + '.png' b, g, r = cv2.split(img) bw, gw, rw = cv2.split(watermark) coeffs_b = getNewCo(b, bw) coeffs_g = getNewCo(g, gw) coeffs_r = getNewCo(r, rw) imgb = pywt.idwt2(coeffs_b, 'Haar') imgr = pywt.idwt2(coeffs_r, 'Haar') imgg = pywt.idwt2(coeffs_g, 'Haar') img = cv2.merge([imgb, imgg, imgr]) cv2.imwrite(saveurl, img) Version.objects.filter(original_picture=imgurl).update( digital_picture=saveurl) return saveurl
def _recreate16(self, subbands, wavelet): """ Recreate the original from the 16 subbands. Parameters ---------- subbands : list of 16 numpy arrays giving the subbands wavelet : string, giving the pywavelets name of the wavelet to use Returns ------- img : numpy array, inverting the effect of _decompose16 """ LL = pywt.idwt2((subbands[0], tuple(subbands[1:4])), wavelet, mode='per') details = [] for i in xrange(1, 4): details.append( pywt.idwt2( (subbands[4 * i], tuple(subbands[4 * i + 1:4 * i + 4])), wavelet, mode='per')) return pywt.idwt2((LL, tuple(details)), wavelet, mode='per')
def applyHaar(data, mask): global encCount lcount = 0 for layer in data: coeffs = pywt.dwt2(layer, 'haar') cA, (cH, cV, cD) = coeffs cdim = cD.shape cdata = cD.ravel() if(cdata.size < mask.size): raise Exception("Data is not big enough to accommodate the mask") counts = numpy.bincount(cdata) # number of elements with a coefficient of 0 or 1, that can be # repurposed to encode the message space = counts[0] + counts[1] if(space < mask.size): print "Layer {0} cannot accommodate the mask. Skipping.".format(lcount) continue numMasks = space / mask.size # grow the mask by tiling it mask = numpy.tile(mask, numMasks) newmask = copy.deepcopy(mask.astype(type(cdata[0]))) # zero-fill the end to match the amount of space in this layer newmask.resize(space) if(cdata.size != newmask.size): raise Exception("Mask is not the same size as the space available") maskInd = 0 for offset in range(0, cdata.size): if(offset == cdata.size): break elif(maskInd == newmask.size): break while(cdata[offset] > 2): offset += 1 cdata[offset] = newmask[maskInd] maskInd += 1 encCount += numMasks cD.shape = (cdim) coeffs = (cA, (cH, cV, cD)) layer = pywt.idwt2(coeffs, 'haar') lcount += 1
def ColorToTexturedImage(img): ycrcb = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) y, cr, cb = cv2.split(ycrcb) ycrcb = cv2.merge((y, cr, cb)) plt.imshow(ycrcb) titles = ['L', ' H'] cfs = pywt.dwt(y, 'haar') CA, CB = cfs fig = plt.figure(figsize=(3, 3)) for i, a in enumerate([CA, CB]): ax = fig.add_subplot(1, 2, i + 1) ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray) ax.set_title(titles[i], fontsize=10) ax.set_xticks([]) ax.set_yticks([]) fig.tight_layout() plt.show() i = pywt.idwt(cb, cr, 'haar') plt.imshow(i) titles = ['LL', ' LH', 'HL', 'HH'] coeffs2 = pywt.dwt2(y, 'haar') LL, (LH, HL, HH) = coeffs2 fig = plt.figure(figsize=(12, 3)) for i, a in enumerate([LL, LH, HL, HH]): ax = fig.add_subplot(2, 2, i + 1) ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray) ax.set_title(titles[i], fontsize=10) ax.set_xticks([]) ax.set_yticks([]) fig.tight_layout() plt.show() newcb = zeros([len(LL), len(LL[0])]) for i in range(len(cb)): for j in range(len(cb[0]), 2): newcb[i][j] = cb[i][j] newcr = zeros([len(LL), len(LL[0])]) for i in range(len(cr)): for j in range(len(cr[0]), 2): newcr[i][j] = cr[i][j] coeffs = (LL, (newcb, newcr, HH)) img = pywt.idwt2(coeffs, 'haar') scipy.misc.imsave('textured.png', img) return img
def image_feature_label_wave(img,dir_name): """ use hog to generate image features Args: img : image name/image path dir_name: boat type folder, use to makde labels Returns: features[0]: feature array dif_name : label name feature[1] : hig image """ img = cv2.imread(img) img = cv2.resize(img, (256, 256)) coeffs = pywt.dwt2(img, 'haar') coeffs = pywt.idwt2(coeffs, 'haar') return coeffs[0], dir_name
def wav_synthesis(W, wavelet, niv): '''Sintesis de los coef W en niv niveles''' n, m = np.array(W.shape) / 2**(niv - 1) imagen = W.copy() for i in xrange(niv): LL = imagen[:n / 2, :m / 2] HL = imagen[:n / 2, m / 2:m] LH = imagen[n / 2:n, :m / 2] HH = imagen[n / 2:n, m / 2:m] imagen[:n, :m] = pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode='per') n *= 2 m *= 2 return imagen
def _embed(self, img, payload, k): cA, (cH, cV, cD) = dwt2(img, self.mother) cH2 = cH.reshape(cH.size) cV2 = cV.reshape(cV.size) assert cH2.shape == cV2.shape chunk_size = cH2.size // (self.total_bits // 2) sequence_of = (self.seq0[:chunk_size], self.seq1[:chunk_size]) for i, bit in enumerate(iterbits(payload)): seq = sequence_of[bit] #chunk = target[i::self.total_bits][:seq.size] target = (cH2, cV2)[i % 2] offset = (i//2) * chunk_size target[offset:offset + seq.size] += k * seq w, h = img.shape return idwt2((cA, (cH2.reshape(cH.shape), cV2.reshape(cV.shape), cD)), self.mother)[:w,:h]
def dwt_compose(dwtimg_list): """ compose the single-channel image from the cA,cH,cV,cD :param dwtimg_list: 4-channel imgs (cA,cH,cV,cD) :return: composed images """ imgs = [] for i in range(len(dwtimg_list)): cA = dwtimg_list[i][:, :, 0] cH = dwtimg_list[i][:, :, 1] cV = dwtimg_list[i][:, :, 2] cD = dwtimg_list[i][:, :, 3] coef = [cA, (cH, cV, cD)] img = pywt.idwt2(coef, 'db1') imgs.append(img) return imgs
def synthesize(LL, H, wavelet=WAVELET): #def synthesize(color_decomposition, wavelet=WAVELET): #print(type(H)) LH, HL, HH = H n_channels = LL.shape[2] #len(LL) _color_frame = [] for c in range(n_channels): frame = pywt.idwt2((LL[:,:,c], (LH[:,:,c], HL[:,:,c], HH[:,:,c])), wavelet=wavelet, mode='per') _color_frame.append(frame) n_rows, n_columns = _color_frame[0].shape #n_rows = _color_frame[0].shape[0] #n_columns = _color_frame[0].shape[1] color_frame = np.ndarray((n_rows, n_columns, n_channels), dtype=np.float64) for c in range(n_channels): color_frame[:,:,c] = _color_frame[c][:,:] return color_frame
def _remove_stripe_fw(level, wname, sigma, pad, istart, iend): tomo = mproc.SHARED_ARRAY dx, dy, dz = tomo.shape nx = dx if pad: nx = dx + dx / 8 xshift = int((nx - dx) / 2.) num_jobs = iend - istart for m in range(istart, iend): sli = np.zeros((nx, dz), dtype='float32') sli[xshift:dx + xshift] = tomo[:, m, :] # Wavelet decomposition. cH = [] cV = [] cD = [] for n in range(level): sli, (cHt, cVt, cDt) = pywt.dwt2(sli, wname) cH.append(cHt) cV.append(cVt) cD.append(cDt) # FFT transform of horizontal frequency bands. for n in range(level): # FFT # fcV = np.fft.fftshift(pyfftw.interfaces.numpy_fft.fft( # cV[n], axis=0, planner_effort=phase._plan_effort(num_jobs))) fcV = np.fft.fftshift(np.fft.fft(cV[n], axis=0)) my, mx = fcV.shape # Damping of ring artifact information. y_hat = (np.arange(-my, my, 2, dtype='float32') + 1) / 2 damp = 1 - np.exp(-np.power(y_hat, 2) / (2 * np.power(sigma, 2))) fcV = np.multiply(fcV, np.transpose(np.tile(damp, (mx, 1)))) # Inverse FFT. # cV[n] = np.real(pyfftw.interfaces.numpy_fft.ifft( # np.fft.ifftshift(fcV), axis=0, # planner_effort=phase._plan_effort(num_jobs))) cV[n] = np.real(np.fft.ifft(np.fft.ifftshift(fcV), axis=0)) # Wavelet reconstruction. for n in range(level)[::-1]: sli = sli[0:cH[n].shape[0], 0:cH[n].shape[1]] sli = pywt.idwt2((sli, (cH[n], cV[n], cD[n])), wname) tomo[:, m, :] = sli[xshift:dx + xshift, 0:dz]
def removeStripesTomoPy(sinogram, level=5, sigma=2.4, wname='db20'): #From tomopy https://github.com/tomopy/tomopy/blob/master/tomopy/preprocess/stripe_removal.py # 24/03/2014 if not hasPyWt: print('PyWavelets not installed, ring removal not available!') return sinogram size = np.max(sinogram.shape) if level == None: level = int(np.ceil(np.log2(size))) dx, dy = sinogram.shape num_x = dx + dx / 8 x_shift = int((num_x - dx) / 2.) sli = np.zeros((num_x, dy), dtype='float32') sli[x_shift:dx + x_shift, :] = sinogram # Wavelet decomposition. cH = [] cV = [] cD = [] for m in range(level): sli, (cHt, cVt, cDt) = pywt.dwt2(sli, wname) cH.append(cHt) cV.append(cVt) cD.append(cDt) # FFT transform of horizontal frequency bands. for m in range(level): # FFT fcV = np.fft.fftshift(np.fft.fft(cV[m], axis=0)) my, mx = fcV.shape # Damping of ring artifact information. y_hat = (np.arange(-my, my, 2, dtype='float') + 1) / 2 damp = 1 - np.exp(-np.power(y_hat, 2) / (2 * np.power(sigma, 2))) fcV = np.multiply(fcV, np.transpose(np.tile(damp, (mx, 1)))) # Inverse FFT. cV[m] = np.real(np.fft.ifft(np.fft.ifftshift(fcV), axis=0)) # Wavelet reconstruction. for m in range(level)[::-1]: sli = sli[0:cH[m].shape[0], 0:cH[m].shape[1]] sli = pywt.idwt2((sli, (cH[m], cV[m], cD[m])), wname) return sli[x_shift:dx + x_shift, 0:dy].astype(np.float32)
def _embed(self, img, payload, k): cA, (cH, cV, cD) = dwt2(img, self.mother) cH2 = cH.reshape(cH.size) cV2 = cV.reshape(cV.size) cD2 = cD.reshape(cD.size) assert cH2.shape == cV2.shape == cD2.shape chunk_size = (cH2.size * 3) // (self.total_bits) sequence_of = (self.seq0[:chunk_size], self.seq1[:chunk_size]) buffers = (cH2, cV2, cD2) for i, bit in enumerate(iterbits(payload)): seq = sequence_of[bit] target = buffers[i % 3] offset = (i//3) * chunk_size target[offset:offset + seq.size] += k * seq w, h = img.shape return idwt2((cA, (cH2.reshape(cH.shape), cV2.reshape(cV.shape), cD2.reshape(cD.shape))), self.mother)[:w,:h]
def wt_change(): img = cv2.imread('./1600/1.jpg') # 对img进行haar小波变换: cA, (cH, cV, cD) = dwt2(img, 'haar') # 小波变换之后,低频分量对应的图像: cv2.imwrite('lena.png', np.uint8(cA / np.max(cA) * 255)) # 小波变换之后,水平方向高频分量对应的图像: cv2.imwrite('lena_h.png', np.uint8(cH / np.max(cH) * 255)) # 小波变换之后,垂直平方向高频分量对应的图像: cv2.imwrite('lena_v.png', np.uint8(cV / np.max(cV) * 255)) # 小波变换之后,对角线方向高频分量对应的图像: cv2.imwrite('lena_d.png', np.uint8(cD / np.max(cD) * 255)) # 根据小波系数重构回去的图像 rimg = idwt2((cA, (cH, cV, cD)), 'haar')
def _embed(self, img, payload, k): cA, (cH, cV, cD) = dwt2(img, self.mother) cH2 = cH.reshape(cH.size) cV2 = cV.reshape(cV.size) assert cH2.shape == cV2.shape chunk_size = cH2.size // (self.total_bits // 2) sequence_of = (self.seq0[:chunk_size], self.seq1[:chunk_size]) for i, bit in enumerate(iterbits(payload)): seq = sequence_of[bit] #chunk = target[i::self.total_bits][:seq.size] target = (cH2, cV2)[i % 2] offset = (i // 2) * chunk_size target[offset:offset + seq.size] += k * seq w, h = img.shape return idwt2((cA, (cH2.reshape(cH.shape), cV2.reshape(cV.shape), cD)), self.mother)[:w, :h]
def dwt2(x, wavelet='haar', inverse=0): if x.shape[0] % 2 != 0 or x.shape[1] % 2 != 0: raise ("Input Error: all input dimensions must be even") if not inverse: cA, (cH, cV, cD) = pywt.dwt2(x, wavelet) cAH = np.concatenate((cA, cH), axis=1) cVD = np.concatenate((cV, cD), axis=1) return np.concatenate((cAH, cVD), axis=0) else: cA = x[:x.shape[0] / 2, :x.shape[1] / 2] cH = x[:x.shape[0] / 2, x.shape[1] / 2:] cV = x[x.shape[0] / 2:, :x.shape[1] / 2] cD = x[x.shape[0] / 2:, x.shape[1] / 2:] coeffs = (cA, (cH, cV, cD)) img = pywt.idwt2(coeffs, wavelet, **kwargs) return img
def idwt2(z, wavelet, levels=1, mode='periodization'): if levels == 0: return z elif levels < 0: raise ValueError('levels must be non-negative') n = z.shape[0] // (2**levels) m = 2 * n cA = z[:n, :n] cH = z[:n, n:m] cV = z[n:m, :n] cD = z[n:m, n:m] z = z.copy() z[:m, :m] = pywt.idwt2((cA, (cV, cH, cD)), wavelet, mode) return idwt2(z, wavelet, levels - 1, mode)
def syntesis(LL, LH, HL, HH, M): """ Воосстанавливает исходный двумерный сигнал по известным составляющим. Возвращает словарь LL, который представляет собой LL составляющую восстанавливаемогосигнала. LL - словарь. Изначально в нем содерживатся среднее значение сигнала. Оно равно np.mean(orig)* 2^M. Gараметр определяет точность восстановления сигнала. LH - словарь. LH - квадрант исходного сигнала. HL - словарь. HL - квадрант исходного сигнала. HH - словарь. HH - квадрант исходного сигнала. M - определяет разрешение декомпозиции. LL[M] будет размера 2^M * 2^M Функция по своей сути является оберткой над библиотекой pywt. """ for k in range(M): LL[k + 1] = pywt.idwt2([LL[k], (LH[k], HL[k], HH[k])], 'haar') return LL
def _remove_stripe_fw(tomo, level, wname, sigma, pad): dx, dy, dz = tomo.shape nx = dx if pad: nx = dx + dx // 8 xshift = int((nx - dx) // 2) num_jobs = tomo.shape[1] for m in range(num_jobs): sli = np.zeros((nx, dz), dtype='float32') sli[xshift:dx + xshift] = tomo[:, m, :] # Wavelet decomposition. cH = [] cV = [] cD = [] for n in range(level): sli, (cHt, cVt, cDt) = pywt.dwt2(sli, wname) cH.append(cHt) cV.append(cVt) cD.append(cDt) # FFT transform of horizontal frequency bands. for n in range(level): # FFT fcV = np.fft.fftshift(pyfftw.interfaces.numpy_fft.fft( cV[n], axis=0, planner_effort=phase._plan_effort(num_jobs))) my, mx = fcV.shape # Damping of ring artifact information. y_hat = (np.arange(-my, my, 2, dtype='float32') + 1) / 2 damp = 1 - np.exp(-np.power(y_hat, 2) / (2 * np.power(sigma, 2))) fcV = np.multiply(fcV, np.transpose(np.tile(damp, (mx, 1)))) # Inverse FFT. cV[n] = np.real(pyfftw.interfaces.numpy_fft.ifft( np.fft.ifftshift(fcV), axis=0, planner_effort=phase._plan_effort(num_jobs))) # Wavelet reconstruction. for n in range(level)[::-1]: sli = sli[0:cH[n].shape[0], 0:cH[n].shape[1]] sli = pywt.idwt2((sli, (cH[n], cV[n], cD[n])), wname) tomo[:, m, :] = sli[xshift:dx + xshift, 0:dz]
def _embed(self, img, payload, k): cA, (cH, cV, cD) = dwt2(img, self.mother) cH2 = cH.reshape(cH.size) cV2 = cV.reshape(cV.size) cD2 = cD.reshape(cD.size) assert cH2.shape == cV2.shape == cD2.shape chunk_size = (cH2.size * 3) // (self.total_bits) sequence_of = (self.seq0[:chunk_size], self.seq1[:chunk_size]) buffers = (cH2, cV2, cD2) for i, bit in enumerate(iterbits(payload)): seq = sequence_of[bit] target = buffers[i % 3] offset = (i // 3) * chunk_size target[offset:offset + seq.size] += k * seq w, h = img.shape return idwt2((cA, (cH2.reshape(cH.shape), cV2.reshape( cV.shape), cD2.reshape(cD.shape))), self.mother)[:w, :h]
def remove_sino_stripes_rings_wf(data_vol, wv_levels, wavelet_name='db5', sigma=2, pad=True): """ Removes horizontal stripes in sinograms (reducing ring artifacts in the reconstructed volume). Implements a combined Wavelet-Fourier filter (wf) as described in: Muench B, Trtrik P, Marone F, and Stampanoni M. 2009. Optics Express, 17(10):8567-8591. Stripe and ring artifact removal with combined wavelet-fourier filtering. 2009. This implementation is heavily based on the implementation from tomopy. This is not parallel at the moment. """ try: import pywt except ImportError as exc: raise ImportError("Could not import the package pywt. Details: {0}".format(exc)) dimx = data_vol.shape[0] n_x = dimx if pad: n_x = dimx + dimx / 8 xshift = int((n_x - dimx) / 2.) for sino_idx in range(0, data_vol.shape[1]): sli = np.zeros((n_x, data_vol.shape[2]), dtype='float32') sli[xshift:dimx + xshift] = data_vol[:, sino_idx, :] # Wavelet decomposition c_H, c_V, c_D = [], [], [] for _ in range(wv_levels): sli, (cHt, cVt, cDt) = pywt.dwt2(sli, wavelet_name) c_H.append(cHt) c_V.append(cVt) c_D.append(cDt) c_V = ft_horizontal_bands(c_V, wv_levels, sigma) # Wavelet reconstruction for nlvl in range(wv_levels)[::-1]: sli = sli[0:c_H[nlvl].shape[0], 0:c_H[nlvl].shape[1]] sli = pywt.idwt2((sli, (c_H[nlvl], c_V[nlvl], c_D[nlvl])), wavelet_name) data_vol[:, sino_idx, :] = sli[xshift:dimx + xshift, 0:data_vol.shape[2]] return data_vol
def embed(self, img, wm, key=10): w, h = img.shape[:2] img = cv2.resize(img, (512, 512)) LL, (HL, LH, HH) = pywt.dwt2(np.array(img), 'haar') #使用红色通道的高频分量保存水印的特征值 iU, iS, iV = np.linalg.svd(np.mat(HH)) wm = cv2.resize(wm, (512, 512)) #水印图像转成 灰度图像 wU, wS, wV = np.linalg.svd(np.mat(wm)) em_HH = iU * np.diag(wS[:256]) * iV #高频的特征值水印,对图像变化不敏感。用来恢复水印使用@ signature = self._gene_signature(np.array(wU), np.array(wV), key) em_LL = self._embed_signature(LL, signature) img = pywt.idwt2((em_LL, (HL, LH, em_HH)), 'haar') return cv2.resize(img, (h, w))
def mops(img, truth, win_size, h, w, r): H, W = img.shape offset = win_size // 2 # Draw line for angle of gradient (for debugging) #length = 150 #h2 = int(h - length * math.cos(math.radians(r))) #w2 = int(w - length * math.sin(math.radians(r))) #cv2.line(img, (w, h), (w2, h2), (0,255,0), 2) # Rotate image s.t. gradient angle of feature is origin M = cv2.getRotationMatrix2D((w, h), -1 * r, 1) img_rot = cv2.warpAffine(img, M, (W, H), flags=cv2.INTER_NEAREST) # Get 40x40 window around feature win = img_rot[h - offset:h + offset, w - offset:w + offset] # Size (s,s) of each sample region s = win_size // 8 # Prefiltering (N,N) -> (N//s, N//s) i = 0 rows = [] while i < win_size: j = 0 cols = [] while j < win_size: # Sample (s,s) region from window sample = win[i:i + s, j:j + s] # Downsample (s,s) region to a single value sample = np.sum(sample) / (s * s) cols.append(sample) j += s rows.append(cols) i += s feature = np.array(rows) # Normalize feature = (feature - np.mean(feature)) / np.std(feature) # Haar wave transform coeffs = pywt.dwt2(feature, 'haar') feature = pywt.idwt2(coeffs, 'haar') #plot([img, img_rot, truth, win, feature]) return feature
def wiener_dwt(pic, index=1): #index 为进行几层分解与重构 pic = np.array(pic, dtype=float) coeffs = pywt.dwt2(pic, 'bior4.4') LL, (LH, HL, HH) = coeffs #LL为低频信号 LH为水平高频 HL为垂直高频 HH为对角线高频信号 #维纳滤波 LH = wiener_filter(LH, HH) HL = wiener_filter(HL, HH) HH = wiener_filter(HH, HH) #重构 if index > 1: LL = wiener_dwt(LL, index - 1) #bior4.4小波重构可能会改变矩阵维数,现统一矩阵维数 row, col = np.shape(LL) d1 = row - np.shape(HH)[0] d2 = col - np.shape(HH)[1] if d1 > 0 or d2 > 0: d1 = row - np.arange(d1) - 1 d2 = col - np.arange(d2) - 1 LL = np.delete(LL, d1, axis=0) LL = np.delete(LL, d2, axis=1) plt.figure() plt.subplot(2, 2, 1) plt.imshow(LL, cmap='gray') plt.title('The ' + str(time - index + 1) + 'th dwt----' + 'LL') plt.subplot(2, 2, 2) plt.imshow(LH, cmap='gray') plt.title('The ' + str(time - index + 1) + 'th dwt----' + 'LH') plt.subplot(2, 2, 3) plt.imshow(HL, cmap='gray') plt.title('The ' + str(time - index + 1) + 'th dwt----' + 'HL') plt.subplot(2, 2, 4) plt.imshow(HH, cmap='gray') plt.title('The ' + str(time - index + 1) + 'th dwt----' + 'HH') plt.show() pic_ans = pywt.idwt2((LL, (LH, HL, HH)), 'bior4.4') # pic_ans = np.where(pic_ans <= 0, 0, pic_ans) # pic_ans = np.where(pic_ans > 255, 255, pic_ans) return pic_ans
def encode(self, bgr): (row, col, channels) = bgr.shape yuv = cv2.cvtColor(bgr, cv2.COLOR_BGR2YUV) for channel in range(2): if self._scales[channel] <= 0: continue ca1, (h1, v1, d1) = pywt.dwt2(yuv[:row // 4 * 4, :col // 4 * 4, channel], 'haar') self.encode_frame(ca1, self._scales[channel]) yuv[:row // 4 * 4, :col // 4 * 4, channel] = pywt.idwt2( (ca1, (v1, h1, d1)), 'haar') bgr_encoded = cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR) return bgr_encoded
def xRemoveStripesVertical(self, ima, decNum, wname, sigma): ''' Code from https://doi.org/10.1364/OE.17.008567 translated in Python Returns ------- Corrected 2D sinogram data (Numpy Array) ''' # allocate cH, cV, cD Ch = [None] * decNum Cv = [None] * decNum Cd = [None] * decNum # wavelets decomposition for i in range(decNum): ima, (Ch[i], Cv[i], Cd[i]) = pywt.dwt2(ima, wname) # FFT transform of horizontal frequency bands for i in range(decNum): # use to axis=0, which correspond to the angles direction fCv = fftshift(fft(Cv[i], axis=0)) my, mx = fCv.shape # damping of vertical stripe information damp = 1 - np.exp(-np.array([ range(-int(np.floor(my / 2)), -int(np.floor(my / 2)) + my) ])**2 / (2 * sigma**2)) fCv *= damp.T # inverse FFT Cv[i] = np.real(ifft(ifftshift(fCv), axis=0)) # wavelet reconstruction nima = ima for i in range(decNum - 1, -1, -1): nima = nima[0:Ch[i].shape[0], 0:Ch[i].shape[1]] nima = pywt.idwt2((nima, (Ch[i], Cv[i], Cd[i])), wname) return nima
def openmultiBn_clicked(self): path, fileExt = QFileDialog.getOpenFileNames( self, "Open file", "", "Images(*.JPG *.jpg *.bmp)") imgList = [] coeffList = [] caList = [] chList = [] cvList = [] cdList = [] for i in range(len(path)): imgList.append(cv2.imread(path[i], 0)) x, y = imgList[0].shape for i in range(len(path)): imgList[i] = cv2.resize(imgList[i], (y, x)) coeffList.append(pywt.dwt2(imgList[i], 'haar')) caList.append(coeffList[i][0]) chList.append(coeffList[i][1][0]) cvList.append(coeffList[i][1][1]) cdList.append(coeffList[i][1][2]) ca = sum(caList) / len(caList) if len(chList) == 2: ch = np.maximum(chList[0], chList[1]) if len(chList) == 3: ch = np.maximum(chList[0], chList[1], chList[2]) if len(cvList) == 2: cv = np.maximum(cvList[0], cvList[1]) if len(cvList) == 3: cv = np.maximum(cvList[0], cvList[1], cvList[2]) if len(cdList) == 2: cd = np.maximum(cdList[0], cdList[1]) if len(cdList) == 3: cd = np.maximum(cdList[0], cdList[1], cdList[2]) coeff = ca, (ch, cv, cd) resultImg = pywt.idwt2(coeff, 'haar').astype(np.uint8) resultImg = np.repeat(resultImg[:, :, np.newaxis], 3, axis=2) for i in range(len(imgList)): plt.subplot(2, len(imgList), i + 1), plt.imshow(imgList[i], cmap='gray') plt.title(f'Input image {i+1}', fontsize=10) plt.subplot(2, 1, 2), plt.imshow(resultImg) plt.title(f'Result', fontsize=10) plt.show()
def _remove_stripe1(level, wname, sigma, pad, istart, iend): tomo = mp.SHARED_ARRAY dx, dy, dz = tomo.shape nx = dx if pad: nx = dx + dx / 8 xshift = int((nx - dx) / 2.) sli = np.zeros((nx, dz), dtype='float32') for m in range(istart, iend): sli[xshift:dx + xshift, :] = tomo[:, m, :] # Wavelet decomposition. cH = [] cV = [] cD = [] for n in range(level): sli, (cHt, cVt, cDt) = pywt.dwt2(sli, wname) cH.append(cHt) cV.append(cVt) cD.append(cDt) # FFT transform of horizontal frequency bands. for n in range(level): # FFT fcV = np.fft.fftshift(np.fft.fft(cV[n], axis=0)) my, mx = fcV.shape # Damping of ring artifact information. y_hat = (np.arange(-my, my, 2, dtype='float') + 1) / 2 damp = 1 - np.exp(-np.power(y_hat, 2) / (2 * np.power(sigma, 2))) fcV = np.multiply(fcV, np.transpose(np.tile(damp, (mx, 1)))) # Inverse FFT. cV[n] = np.real(np.fft.ifft(np.fft.ifftshift(fcV), axis=0)) # Wavelet reconstruction. for n in range(level)[::-1]: sli = sli[0:cH[n].shape[0], 0:cH[n].shape[1]] sli = pywt.idwt2((sli, (cH[n], cV[n], cD[n])), wname) tomo[:, m, :] = sli[xshift:dx + xshift, 0:dz]
def Guan_destripe(input_array): array = minmax_norm(input_array, np.amin(input_array), np.amax(input_array)) # Discrete Wavelet Transform LLY, (LHY, HLY, HHY) = pywt.dwt2(array, 'haar') Y = np.stack((LLY, LHY, HLY, HHY), axis=2) # predict x_test = np.expand_dims(Y, axis=0) y_pred, noise = model.predict(x_test) coeffs_pred = y_pred[0, :, :, 0], (LHY, y_pred[0, :, :, 2], HHY) img_out = pywt.idwt2(coeffs_pred, 'haar') output_array = np.clip(img_out, 0, 1) # necessary? output_array = undo_norm(output_array, np.amin(input_array), np.amax(input_array)) return output_array
def test_idwt2_axes(): data = np.array([[0, 1, 2, 3], [1, 1, 1, 1], [1, 4, 2, 8]]) coefs = pywt.dwt2(data, 'haar', axes=(1, 1)) assert_allclose(pywt.idwt2(coefs, 'haar', axes=(1, 1)), data, atol=1e-14) # too many axes assert_raises(ValueError, pywt.idwt2, coefs, 'haar', axes=(0, 1, 1))
def _embed(self, img, payload, k): cA, (cH, cV, cD) = dwt2(img, self.mother) #assert cH2.shape == cV2.shape == cD2.shape buffer = numpy.zeros(cH.size + cV.size + cD.size) i = 0 for arr in (cH, cV, cD): for row in arr: buffer[i:i+row.size] = row i += row.size chunk_size = buffer.size // self.total_bits sequence_of = (self.seq0[:chunk_size], self.seq1[:chunk_size]) for i, bit in enumerate(iterbits(payload)): seq = sequence_of[bit] buffer[i * chunk_size : i * chunk_size + seq.size] += k * seq detail = (numpy.zeros(cH.shape), numpy.zeros(cV.shape), numpy.zeros(cD.shape)) i = 0 for arr in detail: h, w = arr.shape for r in range(h): arr[r] = buffer[i:i+w] i += w h, w = img.shape return idwt2((cA, detail), self.mother)[:h,:w]
def _embed(self, img, payload, k): cA, (cH, cV, cD) = dwt2(img, self.mother) target = cD.reshape(cD.size) chunk_size = target.size // self.total_bits sequence_of = (self.seq0[:chunk_size], self.seq1[:chunk_size]) for i, bit in enumerate(iterbits(payload)): seq = sequence_of[bit] #chunk = target[i::self.total_bits][:seq.size] chunk = target[i * chunk_size:i * chunk_size + seq.size] chunk += k * seq return idwt2((cA, (cH, cV, target.reshape(cH.shape))), self.mother)[:img.shape[0],:img.shape[1]]
def wavelet_fusion(Im1, Im2): m1 = np.mean(Im1) m2 = np.mean(Im2) s1 = np.std(Im1) s2 = np.std(Im2) g = s2/s1 offset = m2-g*m1 ImH = Im1*g+offset # Wavelet Transform step coeffs1 = pywt.dwt2(ImH, 'db1') coeffs2 = pywt.dwt2(Im2, 'db1') # SELECTION OF COEFFICIENT USING Linear combination BETWEEN both approximations. A = 2*(coeffs1[0]+coeffs2[0])/2 # INVERSE WAVELET TRANSFORM TO GENERATE THE FUSED IMAGE. Xsyn = pywt.idwt2((A,coeffs1[1]), 'db1') return Xsyn
def wavelet(R,G,B,I,P): interped = _interp(R,G,B,I) multiSpec = [] panCoeffs = pywt.dwt2(P, 'haar') for i in range(len(interped)): wave = pywt.dwt2(interped[i], 'haar') coeffs = (wave[0],panCoeffs[1]) multiSpec.append(pywt.idwt2(coeffs, 'haar')) panImg = np.dstack(multiSpec) return _rescale(panImg,panImg.max(),panImg.min())