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 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 _2D_DWT(image): '''2D DWT of a color image. Arguments --------- image : [:,:,:]. A color frame. Returns ------- (L,H) where L=[:,:,:] and H=(LH,HL,HH), where LH,HL,HH=[:,:,:]. A color pyramid. ''' y = math.ceil(image.shape[0] / 2) x = math.ceil(image.shape[1] / 2) LL = np.ndarray((y, x, 3), np.float64) LH = np.ndarray((y, x, 3), np.float64) HL = np.ndarray((y, x, 3), np.float64) HH = np.ndarray((y, x, 3), np.float64) for c in range(3): (LL[:, :, c], (LH[:, :, c], HL[:, :, c], HH[:, :, c])) = pywt.dwt2(image[:, :, c], 'db5', mode='per') return (LL, (LH, HL, HH))
def _extract(self, img): 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 buffers = (cH2, cV2, cD2) chunk_size = (cH2.size * 3) // (self.total_bits) seq0 = self.seq0[:chunk_size] seq1 = self.seq1[:chunk_size] byte = 0 output = bytearray() for i in range(self.total_bits): target = buffers[i % 3] offset = (i//3) * chunk_size chunk = target[offset : offset + seq0.size] corr0, _ = pearsonr(chunk, seq0) corr1, _ = pearsonr(chunk, seq1) bit = int(corr1 > corr0) byte = (byte << 1) | bit if i % 8 == 7: output.append(byte) byte = 0 #print repr(output) return output
def _decompose(self, img): """ Decompose an image into the WSQ subband pattern. Parameters ---------- img : numpy array holding the image to be decomposed Returns ------- subbands : list of 64 numpy arrays containing the WSQ subbands in order """ wavelet = 'coif1' subbands = [] # first decompose image into 16 subbands temp1 = self._decompose16(img, wavelet) # next, decompose top left three subbands again into 16 temp2 = [] for i in xrange(3): temp2.append(self._decompose16(temp1[i], wavelet)) # finally, decompose top left subband again into 4 ll, hvd = pywt.dwt2(temp2[0][0], wavelet, mode='per') # insert subbands into list in correct order subbands.append(ll) subbands.extend(hvd) subbands.extend(temp2[0][1:]) subbands.extend(temp2[1]) subbands.extend(temp2[2]) subbands.extend(temp1[3:]) return subbands
def remove_blob_sino_wavelet(sinogram, sigma): # define the wavelet type wl = 'haar' # First order wavelet decomposition coeffs = pywt.dwt2(sinogram, wl) # Extract coefficients cA, (cH, cV, cD) = coeffs # Median filter the coefficients of the decomposition cAm = median_filter(cA, size=sigma) cHm = median_filter(cH, size=int(2 * sigma)) cVm = median_filter(cV, size=int(2 * sigma)) cDm = median_filter(cD, size=int(2 * sigma)) # Filter the coefficients. For points in the mask replace the value with the value obtained # from the median filtered versions of the same arrays xt = 3 cA[std_mask(cA, x=2) == 1] = cAm[std_mask(cA, x=2) == 1] cH[std_mask(cH, x=xt) == 1] = cHm[std_mask(cH, x=xt) == 1] cV[std_mask(cV, x=xt) == 1] = cVm[std_mask(cV, x=xt) == 1] cD[std_mask(cD, x=xt) == 1] = cDm[std_mask(cD, x=xt) == 1] # Inverse wavelet decomposition. Return the sinogram after filtering # the wavelet coefficients sinow = pywt.idwt2(coeffs, wl) if sinogram.shape[1] / 2.0 != sinogram.shape[1] // 2: sinow = sinow[:, :-1] #sinow = imresize(sinow, (sinogram.shape[0], sinogram.shape[1]), interp='bilinear') return sinow.astype('float32')
def wavedec2(arr): try: r = pywt.dwt2(arr, 'db9') return r[1] except Exception as e: print "wavedec2 error" raise e
def prediction_generator(h5_path, batch_size, idxs): f = h5.File(h5_path, 'r') batch_count = get_batch_count(idxs, batch_size) for b in range(batch_count): batch_idxs = idxs[b*batch_size:(b+1)*batch_size] batch_idxs = sorted(batch_idxs) X = [] batch = f['S2'][batch_idxs, :,:,:] for bb in range(len(batch)): patch = batch[bb,:,:,:] # dwt2 for each chan cA0, (cD0, cV0, cH0) = pywt.dwt2(batch[bb, :,:,0], 'haar') cA1, (cD1, cV1, cH1) = pywt.dwt2(batch[bb, :,:,1], 'haar') cA2, (cD2, cV2, cH2) = pywt.dwt2(batch[bb, :,:,2], 'haar') cA3, (cD3, cV3, cH3) = pywt.dwt2(batch[bb, :,:,3], 'haar') dwt2 = np.zeros((16,16,4)) dwt2[:,:,0] = np.concatenate((np.concatenate((cA0, cD0), axis=1), np.concatenate((cV0, cH0), axis=1)), axis=0) dwt2[:,:,1] = np.concatenate((np.concatenate((cA1, cD1), axis=1), np.concatenate((cV1, cH1), axis=1)), axis=0) dwt2[:,:,2] = np.concatenate((np.concatenate((cA2, cD2), axis=1), np.concatenate((cV2, cH2), axis=1)), axis=0) dwt2[:,:,3] = np.concatenate((np.concatenate((cA3, cD3), axis=1), np.concatenate((cV3, cH3), axis=1)), axis=0) fft2 = np.zeros((16,16,4)) fft2[:,:,0] = np.real(np.fft.fft2(batch[bb, :,:,0])) fft2[:,:,1] = np.real(np.fft.fft2(batch[bb, :,:,1])) fft2[:,:,2] = np.real(np.fft.fft2(batch[bb, :,:,2])) fft2[:,:,3] = np.real(np.fft.fft2(batch[bb, :,:,3])) tmp1 = np.zeros((16,16,12)) tmp1[:,:,0] = patch[:,:,0] tmp1[:,:,1] = patch[:,:,1] tmp1[:,:,2] = patch[:,:,2] tmp1[:,:,3] = patch[:,:,3] tmp1[:,:,4] = dwt2[:,:,0] tmp1[:,:,5] = dwt2[:,:,1] tmp1[:,:,6] = dwt2[:,:,2] tmp1[:,:,7] = dwt2[:,:,3] tmp1[:,:,8] = fft2[:,:,0] tmp1[:,:,9] = fft2[:,:,1] tmp1[:,:,10] = fft2[:,:,2] tmp1[:,:,11] = fft2[:,:,3] X.append(tmp1) yield np.array(X)
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 collect(S, wavelet, mode, level): ''' Returns the full quad tree of wavelet packets. @param S: Input signal. Both single and double precision floating-point data types are supported and the output type depends on the input type. If the input data is not in one of these types it will be converted to the default double precision data format before performing computations. @param wavelet: Wavelet to use in the transform. This must be a name of the wavelet from the wavelist() list. @param mode: Signal extension mode to deal with the border distortion problem. @param level: Number of decomposition steps to perform. If the level is None, then the full decomposition up to the level computed with dwt_max_level() function for the given data and wavelet lengths is performed. @return: The full quad tree of wavelet packets. ''' Nodes = [[] for i in range(level)] (CA, (CH, CV, CD)) = pywt.dwt2(S, wavelet=wavelet, mode=mode) Nodes[0] = [node.Node(CA, 0, 0), node.Node(CH, 0, 1), node.Node(CV, 0, 2), node.Node(CD, 0, 3)] for l in range(0, level-1): Parents = Nodes[l] Childs = [] for p in range(len(Parents)): (CA, (CH, CV, CD)) = pywt.dwt2(Parents[p].C, wavelet=wavelet, mode=mode) Childs.append(node.Node(CA, l+1, 4*p)) Childs.append(node.Node(CH, l+1, 4*p+1)) Childs.append(node.Node(CV, l+1, 4*p+2)) Childs.append(node.Node(CD, l+1, 4*p+3)) Nodes[l+1] = Childs return Nodes
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 _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 waveletTransformFunction(img1, img2): # whole of the wavelet families: ['haar', 'db', 'sym', 'coif', 'bior', 'rbio', 'dmey'] imgVl = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY) wImgV= pywt.dwt2(imgVl,'haar') cAv, (cHv, cVv, cDv) = wImgV print (imgVl.shape) imgIr = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY) wImgIr = pywt.dwt2(imgNir, 'haar') cAi, (cHi, cVi, cDi) = wImgIr # cv2.imwrite('temporal.png', cAv) # cv2.imshow('cAv', cAv) # cv2.imshow('cHv', cHv) # cv2.imshow('cVv', cVv) # cv2.imshow('cDv', cDv) # cv2.imshow('imgVl', imgVl) # cAv1 = np.int16(cAv) # cHv1 = np.int16(cHv) # cVv1 = np.int16(cVv) # cDv1 = np.int16(cDv) # np.savetxt('texcAv.txt', cAv1) # np.savetxt('texcHv.txt', cHv) # print (cHv1[16:20][:18]) # a short code for pyramid imgVlPy = [] imgVlPy = cv2.pyrDown(imgVl,) #print (imgVlPy[16:20][:18]) cv2.imshow('pyramid image', imgVlPy) cv2.waitKey(0) cv2.destroyAllWindows() a = imgVlPy[0:19][0:17] print (a) print a.shape
def getGeneralStatistics(self, hara=False, zern=False, tamura=False, only1D=None): generalStatistics = [] if self.rows == 1 and self.columns == 1: for index in range(3): generalStatistics.append(self.image[0, 0, index]) return generalStatistics if not only1D is None: im = only1D generalStatistics.extend(self._calculateStatistics(im, haralick=hara, zernike=zern)) fourierTransform = np.abs(fftpack.fft2(im)) # fourierTransform generalStatistics.extend(self._calculateStatistics(fourierTransform)) waveletTransform = pywt.dwt2(im, "sym5")[0] generalStatistics.extend(self._calculateStatistics(waveletTransform)) waveletFourierTransform = pywt.dwt2(fourierTransform, "sym5")[0] generalStatistics.extend(self._calculateStatistics(waveletFourierTransform)) if tamura: generalStatistics.extend(self.get3Dstatistics(tamura=True)) return generalStatistics for index in range(3): im = self.image[:, :, index] generalStatistics.extend(self._calculateStatistics(im, haralick=hara, zernike=zern)) fourierTransform = np.abs(fftpack.fft2(im)) # fourierTransform generalStatistics.extend(self._calculateStatistics(fourierTransform)) waveletTransform = pywt.dwt2(im, "sym5")[0] generalStatistics.extend(self._calculateStatistics(waveletTransform)) waveletFourierTransform = pywt.dwt2(fourierTransform, "sym5")[0] generalStatistics.extend(self._calculateStatistics(waveletFourierTransform)) if tamura: generalStatistics.extend(self.get3Dstatistics(tamura=True)) return generalStatistics
def get_dwt_images(img_list, img_size=8, wavelet='db1'): """ use wavelet to decomposite images :param img_list: images :param img_size: size of decomposed wavelet images :return the dwt images with channels, which are cA, cH, cV and cD ------------------- | | | | cA(LL) | cH(LH) | | | | (cA, (cH, cV, cD)) <---> ------------------- | | | | cV(HL) | cD(HH) | | | | ------------------- (DWT 2D output and interpretation) """ dwt_imgs = [] # output the imgs for img in img_list: #list for the leaf items on the dwt h, _, channel = np.shape(img) leaf_imgs = [] for i in range(channel): cA, (cH, cV, cD) = pywt.dwt2(img[:, :, i], wavelet) dwt_list = [cD, cV, cH, cA] while len(dwt_list) > 0: dwt_img = dwt_list.pop() height, _ = np.shape(dwt_img) if height > img_size: #large than leaf item, continue decomposing cA, (cH, cV, cD) = pywt.dwt2(dwt_img, wavelet) #print_mean_var(cA, cH, cV, cD) dwt_list.extend([cD, cV, cH, cA]) else: leaf_imgs.append(dwt_img) #merge all leaf images dwt_img = np.transpose(leaf_imgs, [1, 2, 0]) # normalize coef _, _, channels = np.shape(dwt_img) level = math.log(channels / channel, 4) step = math.pow(2, level - 1) #dwt_img = (dwt_img + step) / (3 * step) #dwt_img = dwt_img + step dwt_imgs.append(dwt_img) return dwt_imgs
def applyTwoDDWTUsingLibrary(self, blockList): '''2D DWT using the pywt library.''' coeffs = pywt.dwt2(blockRef.getValue(), 'haar') cA, (cH, cV, cD) = coeffs print cA print cV print coeffs
def run_DWT(signal, wav, flag_print=0, mode='zero'): """ Serial implementation of the 2D DWT that also returns the runtime of the program :param: signal: input signal to perform 2D DWT :param: wav: pywavelet object defined before :param: flag_print: whether to print the coefficients or not :param: mode: the padding scheme applied to the input (only supports zero-padding) :return: cA, cH, cV, cD: 2D DWT coefficients :return: time_diff: runtime for the serial program """ # Call the pywavelets 2D DWT function using the pywavelets function tic = time.time() coeffs = pywt.dwt2(signal, wav, mode) toc = time.time() cA, (cH, cV, cD) = coeffs cA = cA.astype(np.float32) cH = cH.astype(np.float32) cV = cV.astype(np.float32) cD = cD.astype(np.float32) time_diff = toc - tic if flag_print: print("approx: {} \n detail: {} \n{}\n{}\n".format(cA, cH, cV, cD)) return cA, cH, cV, cD, time_diff
def _extract(self, img): 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) seq0 = self.seq0[:chunk_size] seq1 = self.seq1[:chunk_size] byte = 0 output = bytearray() for i in range(self.total_bits): target = (cH2, cV2)[i % 2] offset = (i//2) * chunk_size chunk = target[offset : offset + seq0.size] #chunk = target[i::self.total_bits][:seq0.size] #if not all(chunk[i] == chunk[i+1] for i in range(chunk.size-1)): corr0, _ = pearsonr(chunk, seq0) corr1, _ = pearsonr(chunk, seq1) bit = int(corr1 > corr0) #else: # bit = 0 byte = (byte << 1) | bit if i % 8 == 7: output.append(byte) byte = 0 print repr(output) return output
def _decompose(self, img): """ Decompose an image into the WSQ subband pattern. Parameters ---------- img : numpy array holding the image to be decomposed Returns ------- subbands : list of 64 numpy arrays containing the WSQ subbands in order """ wavelet='coif1' subbands = [] # first decompose image into 16 subbands temp1 = self._decompose16(img, wavelet) # next, decompose top left three subbands again into 16 temp2 = [] for i in xrange(3): temp2.append(self._decompose16(temp1[i], wavelet)) # finally, decompose top left subband again into 4 ll, hvd = pywt.dwt2(temp2[0][0], wavelet, mode='per') # insert subbands into list in correct order subbands.append(ll) subbands.extend(hvd) subbands.extend(temp2[0][1:]) subbands.extend(temp2[1]) subbands.extend(temp2[2]) subbands.extend(temp1[3:]) return subbands
def kernel_2d(self, kernel, sx, sy, float_type=np.float32): ran = np.random.rand(5, sx, sy).astype(float_type) # choose appropriate padding for Pywavelets to have same size as wavetf if (kernel == 'haar'): padmode = 'antireflect' else: padmode = 'periodization' # mywavelet ten = tf.convert_to_tensor(ran) ten = tf.transpose(ten, perm=[1, 2, 0]) ten = tf.reshape(ten, (1, ) + tuple(ten.shape)) w = WaveTFFactory.build(kernel) tfw = w.call(ten)[0] tfw = tf.transpose(tfw, perm=[2, 0, 1]) # pywavelets pyw = pywt.dwt2(ran, kernel, mode=padmode) pyw = np.concatenate((pyw[0], ) + pyw[1]) # comparison diff = (tfw - pyw).numpy() if (kernel == 'haar'): maxd = abs(diff).max() else: maxd = abs(diff[:, 1:-1, 1:-1]).max() # ignore different border handling return maxd
def dwt(cls, cover_image_path, watermark_path): image = cv2.imread(cover_image_path, 0) watermark = cv2.imread(watermark_path, 0) image = cv2.resize(image, (400, 400)) watermark = cv2.resize(watermark, (100, 100)) watermark = arnold(watermark, SCRAMBLING_KEY) # 对图片三级小波分解 image = np.float32(image) image /= 255 [cA3, (cH3, cV3, cD3), (cH2, cV2, cD2), (cH1, cV1, cD1)] = pywt.wavedec2(image, 'haar', level=3) # 对水印一级小波分解 watermark = np.float32(watermark) watermark /= 255 cA, (cH, cV, cD) = pywt.dwt2(watermark, 'haar') # 水印嵌入 a1, a2, a3, a4 = COEFFICIENTS cA3 += a1 * cA cH3 += a2 * cH cV3 += a3 * cV cD3 += a4 * cD # 重构原图 cA2 = pywt.idwt2((cA3, (cH3, cV3, cD3)), 'haar') cA1 = pywt.idwt2((cA2, (cH2, cV2, cD2)), 'haar') watermarkedImage = pywt.idwt2((cA1, (cH1, cV1, cD1)), 'haar') watermarkedImage *= 255 watermarkedImage = np.uint8(watermarkedImage) return cls.save_image(watermarkedImage, 'easyw_dwt_result[%s].bmp' % time.time())
def pyramid(image, nLevs): outArr = [] cA = image for iLvl in range(nLevs): cA, (cH, cV, cD) = pywt.dwt2(cA, 'haar') outArr.append(np.absolute(cA)) return outArr
def read_img(self, filename): # 读入图片->YUV化->加白边使像素变偶数->四维分块 self.img = cv2.imread(filename).astype(np.float32) self.img_shape = self.img.shape[:2] # 如果不是偶数,那么补上白边 self.img_YUV = cv2.copyMakeBorder(cv2.cvtColor(self.img, cv2.COLOR_BGR2YUV), 0, self.img.shape[0] % 2, 0, self.img.shape[1] % 2, cv2.BORDER_CONSTANT, value=(0, 0, 0)) self.ca_shape = [(i + 1) // 2 for i in self.img_shape] self.ca_block_shape = (self.ca_shape[0] // self.block_shape[0], self.ca_shape[1] // self.block_shape[1], self.block_shape[0], self.block_shape[1]) strides = 4 * np.array([ self.ca_shape[1] * self.block_shape[0], self.block_shape[1], self.ca_shape[1], 1 ]) for channel in range(3): self.ca[channel], self.hvd[channel] = dwt2( self.img_YUV[:, :, channel], 'haar') # 转为4维度 self.ca_block[channel] = np.lib.stride_tricks.as_strided( self.ca[channel].astype(np.float32), self.ca_block_shape, strides)
def myWavelet(img, wavelet): #wavelet = 'haar' #decompose to 2nd level coefficients [cA, (cH, cV, cD)] = pywt.dwt2(img, wavelet=wavelet) maxval = cA.max() cA = cA * (img.max() / maxval) return cA
def _extract(self, img): 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 buffers = (cH2, cV2, cD2) chunk_size = (cH2.size * 3) // (self.total_bits) seq0 = self.seq0[:chunk_size] seq1 = self.seq1[:chunk_size] byte = 0 output = bytearray() for i in range(self.total_bits): target = buffers[i % 3] offset = (i // 3) * chunk_size chunk = target[offset:offset + seq0.size] corr0, _ = pearsonr(chunk, seq0) corr1, _ = pearsonr(chunk, seq1) bit = int(corr1 > corr0) byte = (byte << 1) | bit if i % 8 == 7: output.append(byte) byte = 0 #print repr(output) return output
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 DWT_DCT_SVD(coverImage, watermarkImage): coverImage = cv2.resize(coverImage, (512, 512)) cv2.imshow('Cover Image', coverImage) watermarkImage = cv2.resize(watermarkImage, (256, 256)) cv2.imshow('Watermark Image', watermarkImage) coverImage = np.float32(coverImage) coverImage /= 255 coeff = pywt.dwt2(coverImage, 'haar') cA, (cH, cV, cD) = coeff watermarkImage = np.float32(watermarkImage) watermarkImage_dct = cv2.dct(watermarkImage) cA_dct = cv2.dct(cA) ua, sa, va = np.linalg.svd(cA_dct, full_matrices=1, compute_uv=1) uw, sw, vw = np.linalg.svd(watermarkImage, full_matrices=1, compute_uv=1) #Embedding alpha = 10 sA = np.zeros((256, 256), np.uint8) sA[:256, :256] = np.diag(sa) sW = np.zeros((256, 256), np.uint8) sW[:256, :256] = np.diag(sW) W = sA + alpha * sW u1, w1, v1 = np.linalg.svd(W, full_matrices=1, compute_uv=1) ww = np.zeros((256, 256), np.uint8) ww[:256, :256] = np.diag(w1) Wmodi = np.matmul(ua, np.matmul(ww, va)) widct = cv2.idct(Wmodi) watermarkedImage = pywt.idwt2((widct, (cH, cV, cD)), 'haar') cv2.imshow('watermarkedImage', watermarkedImage)
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 post(self): file = request.files['image'].read() filename = str(time.time_ns()) + '.png' with open(filename, 'wb') as f: f.write(file) imgObj = Image.open(filename) img = np.array(imgObj) res_pywt = pywt.dwt2(img, "haar") file_pi = open('filename_pi.obj', 'wb') pickle.dump(res_pywt, file_pi) enc.encrypt_file('filename_pi.obj') with open('filename_pi.obj' + '.enc', 'rb') as f: encrypted_image = f.read() passcode = request.form['passcode'] crypto_steganography = CryptoSteganography(passcode) # Save the encrypted file inside the image crypto_steganography.hide('img.jpg', 'output_image_file.png', encrypted_image) with open('output_image_file.png', "rb") as output: message = output.read() os.remove('output_image_file.png') img_base64 = base64.b64encode(message) return jsonify({'status': str(img_base64)[2:-1]})
def details(img): imArray = cv2.imread(img) # Datatype conversions # convert to grayscale imArray = cv2.cvtColor(imArray, cv2.COLOR_BGR2GRAY) # convert to float imArray = np.float32(imArray) # normalize imArray /= 255 # Wavelet transform of image, and plot approximation and details titles = [ 'Approximation', ' Horizontal detail', 'Vertical detail', 'Diagonal detail' ] coeffs2 = pywt.dwt2(imArray, 'bior1.3') LL, (LH, HL, HH) = coeffs2 fig = plt.figure(figsize=(12, 3)) for i, a in enumerate([LL, LH, HL, HH]): ax = fig.add_subplot(1, 4, 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()
def multiscale_wd(loader, device, size): """ Description: Input: Output: """ numparr = loader.data.cpu().numpy() LL_array = np.zeros((len(loader), 1, size, size), dtype=float) wavelet_img = np.zeros((len(loader), 4, size, size), dtype=float) for i in range(len(loader)): coeffs = pywt.dwt2(numparr[i], 'db1') LL, (LH, HL, HH) = coeffs LL_array[i, :, :, :] = LL wavelet_img[i, 0, :, :] = LL wavelet_img[i, 0, :, :] = LH wavelet_img[i, 1, :, :] = HL wavelet_img[i, 2, :, :] = HH data = np.asarray(wavelet_img) data = torch.from_numpy(data) data = data.type(torch.FloatTensor) data = data.to(device) LL_array = np.asarray(LL_array) LL_array = torch.from_numpy(LL_array) LL_array = LL_array.type(torch.FloatTensor) LL_array = LL_array.to(device) return LL_array, data
def singlelvl_wd(loader, device, size): """ Description: Single Level Wavelet Decomposition for Wavelet Layer in NN Architecture Input: (1) Loader - images loaded to GPU/device (2) device - location of memory (GPU/CPU) (3) size - Size of images that will be generated Half of input image Output: (1) data - Images to be sent to network """ numparr = loader.data.cpu().numpy() wavelet_img = np.zeros((len(loader), 4, size, size), dtype=float) for i in range(len(loader)): coeffs = pywt.dwt2(numparr[i], 'db1') LL, (LH, HL, HH) = coeffs wavelet_img[i, 0, :, :] = LL wavelet_img[i, 1, :, :] = LH wavelet_img[i, 2, :, :] = HL wavelet_img[i, 3, :, :] = HH data = np.asarray(wavelet_img) data = torch.from_numpy(data) data = data.type(torch.FloatTensor) data = data.to(device) return data
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 wavelet(image, scale = 1): # This thresholds the data based on db1 wavelet. coeffs2 = pywt.dwt2(image[:, :, 0], 'db1') # This assigns the directionality thresholded arrays to variables. LL, (LH, HL, HH) = coeffs2 # This line helps eliminate the cloud but... coeffs2 = LL * 0, (LH * 1, HL * 1, HH * 1) # Reconstruct the image based on our removal of the LL (low frequency) component. new_img = pywt.idwt2(coeffs2, 'db1') # Print statements for evaluation purposes. print("Reconstructed image parameters") print("Standard Deviations: ", np.std(new_img)) print("Means: ", np.mean(new_img)) print("Maxima: ", np.amax(new_img)) # Thresholding based on the mean and std of the image.. thresholded_image = pywt.threshold(new_img, np.mean(new_img) + scale * np.std(new_img), substitute=0, mode='greater') # For image viewing purposes. # plt.subplot(131) # plt.imshow(image[:, :, 0], cmap=plt.cm.gray) # plt.title("Original") # plt.subplot(132) # plt.imshow(new_img, cmap=plt.cm.gray) # plt.title("After") # plt.subplot(133) # plt.imshow(thresholded_image, cmap=plt.cm.gray) # plt.title("Thresholded") # plt.show() return thresholded_image
def test_2d_haar_lvl1(): """Test a 2d-Haar wavelet conv-fwt.""" # ------------------------- 2d haar wavelet tests ----------------------- face = np.transpose(scipy.misc.face()[128:(512 + 128), 256:(512 + 256)], [2, 0, 1]).astype(np.float64) wavelet = pywt.Wavelet("haar") # single level haar - 2d coeff2d_pywt = pywt.dwt2(face, wavelet, mode="zero") coeff2d = wavedec2(torch.from_numpy(face), wavelet, level=1, mode="constant") flat_list_pywt = np.concatenate(flatten_2d_coeff_lst(coeff2d_pywt), -1) flat_list_ptwt = torch.cat(flatten_2d_coeff_lst(coeff2d), -1) cerr = np.mean(np.abs(flat_list_pywt - flat_list_ptwt.numpy())) print("haar 2d coeff err,", cerr, ["ok" if cerr < 1e-4 else "failed!"]) assert np.allclose(flat_list_pywt, flat_list_ptwt.numpy()) # plt.plot(flat_list_pywt, 'o') # plt.plot(flat_list_ptwt.numpy(), '.') # plt.show() rec = waverec2(coeff2d, wavelet).numpy().squeeze() err_img = np.abs(face - rec) err = np.mean(err_img) # err2 = np.mean(np.abs(face-ptwt_rec)) print("haar 2d rec err", err, ["ok" if err < 1e-4 else "failed!"]) assert np.allclose(rec, face)
def dwt2(self, img, wavelet='db1'): coeffs = pywt.dwt2(img, wavelet) cA, (cH, cV, cD) = coeffs # Return cA for next wavelet transform return DWTSubTree(cA, level=self.level, maxLevel=self.maxLevel), cH, cV, cD
def calc2D(data,npoints=1000,interp='linear'): from surfacePlots import setGrid [xi,yi,zi] = setGrid(data,npoints,interp) grid = [xi,yi,zi] coef = wt.dwt2(zi,'db1') return coef,grid
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 dwtHH(temp): x = len(temp) coeffs2 = pywt.dwt2(temp, 'bior1.1') LL, (LH, HL, HH) = coeffs2 a = HH mn = np.min(a) mx = np.max(a) temp = np.float64((a - mn)*255/(mx - mn)) temp = resize(temp, (x, x)) return temp
def prob3(image="swanlake_polluted.jpg"): #the True flag ensures the image will be grayscale img = imread(image, True) lw = pywt.dwt2(img,'db4', mode='per') plt.subplot(221) plt.imshow(lw[0], cmap='gray') for n in xrange(1,4): plt.subplot(2,2,n+1) plt.imshow(lw[1][n-1], cmap='gray') plt.show()
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 decompose(image, prefix, levels, suffix, wtype, cur=0): print prefix+str(cur)+suffix piio.write(prefix+str(cur)+suffix, image) print image.shape if levels==1: return ret, _ = pywt.dwt2(image,wtype,axes=(0,1)) decompose(ret/2.0,prefix,levels-1,suffix, wtype, cur+1)
def dwt(space): assert space.ndim == 2 cA, (cH, cV, cD) = dwt2(space, 'db1') secret_space = SecretSpace(cH.astype(int)) def revert(secret_space): return space.revert( idwt2((cA, (secret_space[:], cV, cD)), 'db1').astype(int)) secret_space.revert = revert return secret_space
def _dwtHH(self, batch): for i in range(len(batch)): temp = batch[i] temp = temp[ :, :, 0] x = len(temp[0]) coeffs2 = pywt.dwt2(temp, 'bior1.3') LL, (LH, HL, HH) = coeffs2 mn = np.min(HH) mx = np.max(HH) HH = np.float32((HH - mn)*255/(mx - mn)) a = cv2.resize(HH, dsize=(x, x), interpolation=cv2.INTER_CUBIC) batch[i] = a.reshape([x, x, 1]) return batch
def image_diff_dwt(lhs_image, rhs_image) -> int: _, (lhs_LH, lhs_HL, lhs_HH) = pywt.dwt2(lhs_image, 'haar') _, (rhs_LH, rhs_HL, rhs_HH) = pywt.dwt2(rhs_image, 'haar') d1 = cv2.absdiff(lhs_LH, rhs_LH).sum() d2 = cv2.absdiff(lhs_HL, rhs_HL).sum() d3 = cv2.absdiff(lhs_HH, rhs_HH).sum() return d1 + d2 + d3
def decompose3ch(original, filter): # Wavelet transform of image, and plot approximation and details coeffs0 = pywt.dwt2(original[:, :, 0], filter) # bior1.3 LL0, (LH0, HL0, HH0) = coeffs0 coeffs1 = pywt.dwt2(original[:, :, 1], filter) LL1, (LH1, HL1, HH1) = coeffs1 coeffs2 = pywt.dwt2(original[:, :, 2], filter) LL2, (LH2, HL2, HH2) = coeffs2 LL = np.stack((LL0, LL1, LL2), axis=2) LH = np.stack((LH0, LH1, LH2), axis=2) HL = np.stack((HL0, HL1, HL2), axis=2) HH = np.stack((HH0, HH1, HH2), axis=2) return (LL, LH, HL, HH)
def generator_histogram(h5_path, batch_size, idxs): f = h5.File(h5_path, 'r') while True : idxs = shuffle_idx(idxs) batch_count = get_batch_count(idxs, batch_size) for b in range(batch_count): batch_idxs = idxs[b*batch_size:(b+1)*batch_size] batch_idxs = sorted(batch_idxs) X = [] Y = f['TOP_LANDCOVER'][batch_idxs, :] batch = f['S2'][batch_idxs, :,:,:] for bb in range(len(batch)): patch = batch[bb,:,:,:] # dwt2 for each chan cA0, (cD0, cV0, cH0) = pywt.dwt2(batch[bb,:,:,0], 'haar') cA1, (cD1, cV1, cH1) = pywt.dwt2(batch[bb,:,:,1], 'haar') cA2, (cD2, cV2, cH2) = pywt.dwt2(batch[bb,:,:,2], 'haar') cA3, (cD3, cV3, cH3) = pywt.dwt2(batch[bb,:,:,3], 'haar') dwt2 = np.zeros((16,16,4)) dwt2[:,:,0] = np.concatenate((np.concatenate((cA0, cD0), axis=1), np.concatenate((cV0, cH0), axis=1)), axis=0) dwt2[:,:,1] = np.concatenate((np.concatenate((cA1, cD1), axis=1), np.concatenate((cV1, cH1), axis=1)), axis=0) dwt2[:,:,2] = np.concatenate((np.concatenate((cA2, cD2), axis=1), np.concatenate((cV2, cH2), axis=1)), axis=0) dwt2[:,:,3] = np.concatenate((np.concatenate((cA3, cD3), axis=1), np.concatenate((cV3, cH3), axis=1)), axis=0) fft2 = np.zeros((16,16,4)) fft2[:,:,0] = np.real(np.fft.fft2(batch[bb,:,:,0])) fft2[:,:,1] = np.real(np.fft.fft2(batch[bb,:,:,1])) fft2[:,:,2] = np.real(np.fft.fft2(batch[bb,:,:,2])) fft2[:,:,3] = np.real(np.fft.fft2(batch[bb,:,:,3])) tmp1 = np.zeros((16,16,12)) tmp1[:,:,0] = patch[:,:,0] tmp1[:,:,1] = patch[:,:,1] tmp1[:,:,2] = patch[:,:,2] tmp1[:,:,3] = patch[:,:,3] tmp1[:,:,4] = dwt2[:,:,0] tmp1[:,:,5] = dwt2[:,:,1] tmp1[:,:,6] = dwt2[:,:,2] tmp1[:,:,7] = dwt2[:,:,3] tmp1[:,:,8] = fft2[:,:,0] tmp1[:,:,9] = fft2[:,:,1] tmp1[:,:,10] = fft2[:,:,2] tmp1[:,:,11] = fft2[:,:,3] X.append(tmp1) yield np.array(X), keras.utils.np_utils.to_categorical(np.array(Y), 23)
def main(): img = cv2.imread('Lenna.jpg', 3) img = tr.RGB2YCBCR(img) Y, Cr, Cb = cv2.split(img) print(Y.shape) pathlib.Path('./FirstAttempt').mkdir(parents=True, exist_ok=True) cv2.imwrite("./FirstAttempt/OldY.jpg", Y) cv2.waitKey(0) cv2.destroyAllWindows() (Sl, (Sh, Sv, Sd)) = pywt.dwt2(Y, 'haar') ReducedCb = downscale_local_mean(Cb, (2, 2)) ReducedCr = downscale_local_mean(Cr, (2, 2)) # Sh = ReducedCb # Sv = ReducedCr NewY = pywt.idwt2((Sl, (ReducedCb, ReducedCr, Sd)), 'haar') cv2.imwrite("./FirstAttempt/NewYFirstTry.jpg", NewY) cv2.waitKey(0) cv2.destroyAllWindows() h = hf.Halftone('./FirstAttempt/NewYFirstTry.jpg') h.make(angles=[0, 15, 30, 45], antialias=True, percentage=10, sample=1, scale=2, style='grayscale')
def WaveletTransform(image, wavelet): coeffs = pywt.dwt2(image, wavelet) cA, (cH, cV, cD) = coeffs #####------For db2 trimming down the image to maintain size consistancy------##### if wavelet=='db2': cA=cA[1:len(cA),1:len(cA)] cH=cH[1:len(cH),1:len(cH)] cV=cV[1:len(cV),1:len(cV)] cD=cD[1:len(cD),1:len(cD)] print 'len(cA) '+str(len(cA)) print 'len(cH) '+str(len(cH)) print 'len(cV) '+str(len(cV)) print 'len(cD) '+str(len(cD)) #####------Scaling the transformed image by 2------##### cA=cv2.pyrUp(cA) cH=cv2.pyrUp(cH) cV=cv2.pyrUp(cV) cD=cv2.pyrUp(cD) print 'len(cA)up '+str(len(cA)) print 'len(cH)up '+str(len(cH)) print 'len(cV)up '+str(len(cV)) print 'len(cD)up '+str(len(cD)) return cA,cH,cV,cD
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 CutImage(path, variable_size_block, maskpath): img = cv2.imread(path, 0) print(img.shape) h, w = img.shape if h < 300 and w < 300: BLOCK = variable_size_block elif h > 1000 or w > 1000: BLOCK = variable_size_block else: BLOCK = variable_size_block print("WIDTH:", w, "HEIGHT:", h) coeffs2 = pywt.dwt2(img, 'db8') LL, (LH, HL, HH) = coeffs2 HH = HH[0:int(np.floor(HH.shape[0] / BLOCK)) * BLOCK, 0:int(np.floor(HH.shape[1] / BLOCK)) * BLOCK] blockMatrix = [] for i in range(0, HH.shape[0], BLOCK): for j in range(0, HH.shape[1], BLOCK): blockWindow = HH[i:i + BLOCK, j:j + BLOCK] blockMatrix.append(blockWindow) label = [i for i in range(len(blockMatrix))] blockMatrix = np.array(blockMatrix) label = np.array(label) label_idx = list(label.copy()) dicts = { "blk": blockMatrix, "label": label, "label_id": label_idx, "HH": HH, "img": img, "BLOCK": BLOCK } return dicts
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 _extract(self): container = EmbeddingMethodStack.rgb_2_ycbcr(self.container) stego = EmbeddingMethodStack.rgb_2_ycbcr(self.stego) 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]) w1a, (w1h, w1v, w1d) = pywt.dwt2(stego[:, :, 0], self.aux[ElahianMethodConfig.AUX_WAVELET]) w2a, (w2h, w2v, w2d) = pywt.dwt2(w1a, self.aux[ElahianMethodConfig.AUX_WAVELET]) w3a, (w3h, w3v, w3d) = pywt.dwt2(w2a, self.aux[ElahianMethodConfig.AUX_WAVELET]) x = self.aux[ElahianMethodConfig.AUX_POSITION][:, 1] # coordinates for stegodata embedding (abscissa) y = self.aux[ElahianMethodConfig.AUX_POSITION][:, 0] # coordinates for stegodata embedding (ordinate) bit_ammount = self.aux[ElahianMethodConfig.AUX_STEGO_SIZE][0] * \ self.aux[ElahianMethodConfig.AUX_STEGO_SIZE][1] * 8 watermark_bitstream = numpy.zeros((1, bit_ammount), dtype=numpy.uint8) for k in range(bit_ammount): if w3a[y[k], x[k]] > c3a[y[k], x[k]]: watermark_bitstream[0][k] = 1 w3a[y[k], x[k]] = w3a[y[k], x[k]] - self.aux[ElahianMethodConfig.AUX_G] else: watermark_bitstream[0][k] = 0 # print watermark_bitstream.size, self.aux[ElahianMethodConfig.AUX_STEGO_SIZE] self.watermark = EmbeddingMethodStack.bitstream_2_matrix( watermark_bitstream, self.aux[ElahianMethodConfig.AUX_STEGO_SIZE]) super(ElahianExtractor, self)._extract() return self.watermark
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())