def blend_images(base, texture, level=4, mode='sp1', base_gain=None, texture_gain=None): base_data = image2array(base) texture_data = image2array(texture) output_data = [] for base_band, texture_band in zip(base_data, texture_data): base_band_coeffs = pywt.wavedec2(base_band, 'db2', mode, level) texture_band_coeffs = pywt.wavedec2(texture_band, 'db2', mode, level) output_band_coeffs = [base_band_coeffs[0]] del base_band_coeffs[0], texture_band_coeffs[0] for n, (base_band_details, texture_band_details) in enumerate( zip(base_band_coeffs, texture_band_coeffs)): blended_details = [] for (base_detail, texture_detail) in zip(base_band_details, texture_band_details): if base_gain is not None: base_detail *= base_gain if texture_gain is not None: texture_detail *= texture_gain blended = numpy.where(abs(base_detail) > abs(texture_detail), base_detail, texture_detail) blended_details.append(blended) base_band_coeffs[n] = texture_band_coeffs[n] = None output_band_coeffs.append(blended_details) new_band = pywt.waverec2(output_band_coeffs, 'db2', mode) output_data.append(new_band) del new_band, base_band_coeffs, texture_band_coeffs del base_data, texture_data output_data = numpy.array(output_data) return array2image(output_data, base.mode)
def imageWT(image, scaleLevel): r = pywt.wavedec2(image[0], 'Haar', level=scaleLevel)[0] g = pywt.wavedec2(image[1], 'Haar', level=scaleLevel)[0] b = pywt.wavedec2(image[2], 'Haar', level=scaleLevel)[0] x = np.sqrt(image.shape[1]*image.shape[2]/(r.shape[0]*r.shape[1])) waveImg = np.array([r,g,b]/x).astype(int) return waveImg
def dwt2(image, wavelet, mode, level): signal = np.asarray(image) if signal.ndim == 2: r = pack_wave_coeff(pywt.wavedec2(signal, wavelet, mode, level)) return r elif signal.ndim == 3: r, g, b = wv.splitRGB(image) rw = pack_wave_coeff(pywt.wavedec2(r, wavelet, mode, level)) gw = pack_wave_coeff(pywt.wavedec2(g, wavelet, mode, level)) bw = pack_wave_coeff(pywt.wavedec2(b, wavelet, mode, level)) return (rw, gw, bw)
def multiwavelet_from_rgb(rgb): from scipy.fftpack import dct from pywt import wavedec2 r = rgb[:, :, 0].astype(np.float) g = rgb[:, :, 1].astype(np.float) dctr = dct(r, norm='ortho').ravel() dctg = dct(g, norm='ortho').ravel() daubr = _unpack(wavedec2(r, 'db4')) daubg = _unpack(wavedec2(g, 'db4')) return np.hstack([dctr, dctg, daubr, daubg])
def ReduceDimension(X = np.zeros([2,2])): r, c = X.shape image = X[0,:].reshape([385,576]) coeffs = pywt.wavedec2(image,'db1', level=4) cA4, (cH4, cV4, cD4), (cH3, cV3, cD3),(cH2, cV2, cD2),(cH1, cV1, cD1) = coeffs nr,nc = cA4.shape rX = np.zeros([r,nc*nr], dtype=np.float32) for i in range(r): image = X[i,:].reshape([385,576]) coeffs = pywt.wavedec2(image,'db1', level=4) cA4, (cH4, cV4, cD4), (cH3, cV3, cD3),(cH2, cV2, cD2),(cH1, cV1, cD1) = coeffs rX[i,:] = cV4.flatten() return rX
def func(dframe): frame1, frame2 = dframe[0], dframe[1] frame1 = np.array(frame1) frame2 = np.array(frame2) C = pywt.wavedec2(frame1, 'db4', level=level) S = pywt.wavedec2(frame2, 'db4', level=level) tA2 = (C[0] + S[0])/2 coeffs = fuse(tA2, C[1:], S[1:]) fuse_img = pywt.waverec2(coeffs, 'db4') if frame1.dtype == np.uint16: fuse_img = fuse_img.clip(0,65535).astype(np.uint16) elif frame1.dtype == np.uint8: fuse_img = fuse_img.clip(0,255).astype(np.uint8) return np.squeeze(fuse_img)
def idwt2(self): """ Test pypwt for DWT reconstruction (waverec2). """ W = self.W levels = self.levels # inverse DWT with pypwt W.forward() logging.info("computing Wavelets.inverse from pypwt") t0 = time() W.inverse() logging.info("Wavelets.inverse took %.3f ms" % elapsed_ms(t0)) if self.do_pywt: # inverse DWT with pywt Wpy = pywt.wavedec2(self.data, self.wname, mode=per_kw, level=levels) logging.info("computing waverec2 from pywt") _ = pywt.waverec2(Wpy, self.wname, mode=per_kw) logging.info("pywt took %.3f ms" % elapsed_ms(t0)) # Check reconstruction W_image = W.image maxerr = _calc_errors(self.data, W_image, "[rec]") self.assertTrue(maxerr < self.tol, msg="[%s] something wrong with the reconstruction (errmax = %e)" % (self.wname, maxerr))
def test_equal_double(wave, J, mode): with set_double_precision(): x = torch.randn(5, 4, 64, 64).to(dev) assert x.dtype == torch.float64 dwt = DWTForward(J=J, wave=wave, mode=mode).to(dev) iwt = DWTInverse(wave=wave, mode=mode).to(dev) yl, yh = dwt(x) x2 = iwt((yl, yh)) # Test the forward and inverse worked np.testing.assert_array_almost_equal(x.cpu(), x2.detach().cpu(), decimal=PREC_DBL) coeffs = pywt.wavedec2(x.cpu().numpy(), wave, level=J, axes=(-2, -1), mode=mode) np.testing.assert_array_almost_equal(yl.cpu(), coeffs[0], decimal=7) for j in range(J): for b in range(3): np.testing.assert_array_almost_equal(coeffs[J - j][b], yh[j][:, :, b].cpu(), decimal=PREC_DBL)
def wave(image,lev): matrix = image.shape transform = pywt.wavedec2(image,'db1',level=lev) data = transform[0] scale = int(np.ceil(float(matrix[0])/(2**lev))*np.ceil(float(matrix[1])/(2**lev))) vector = list(data.reshape(1,scale)[0]) return vector
def init_image(self, winName): self.winName = winName # initialise switches self.switchWavelet = createSwitch(self.optionsWavelet) # initialise window and trackbars self.waveletType = self.optionsWavelet[0][1] cv2.namedWindow(self.winName) cv2.createTrackbar('levels', self.winName, 0, self.maxLevel, self.update) if len(self.optionsWavelet) > 1: cv2.createTrackbar(self.switchWavelet, self.winName, 0, len(self.optionsWavelet) - 1, self.update) # load input image self.inputImage = toPyWt((cv2.imread(self.inputImagePath, 0))) # initialise image self.levels = 0 self.coefficients = pywt.wavedec2(self.inputImage, self.waveletType, level=self.levels) self.outputImage = dwtPlot(self.coefficients) if len(self.outputImagePath) != 0: cv2.imwrite(self.outputImagePath, self.outputImage) cv2.imshow(self.winName, self.outputImage)
def remove_stripes(image, decomp_level, wavelet, sigma): """Removes stripes from `image` with a combined wavelet/FFT approach. Params ------ image : 2d array containing the stripy image decomp_level : int Decomposition level of DWT (TODO: could be automatically calculated?) wavelet : str name of wavelet to use for DWT sigma : int sigma of Gaussian that is used to smooth FFT coefficients """ coeffs = pywt.wavedec2(image, wavelet=wavelet, level=decomp_level, mode='symmetric') damped_coeffs = [coeffs[0]] for ii in range(1, len(coeffs)): ch, cv, cd = coeffs[ii] cv = damp_coefficient(cv, sigma) ch = damp_coefficient(ch, sigma) damped_coeffs.append((ch, cv, cd)) rec_image = pywt.waverec2(damped_coeffs, wavelet=wavelet, mode='symmetric') return rec_image
def loadImageSet(folder=u'E:\data_faces', sampleCount=5): #加载图像集,随机选择sampleCount张图片用于训练 trainData = []; testData = [];yTrain2=[];yTest2=[] #print(yTest) for k in range(40): yTrain1 = np.zeros(40) yTest1 = np.zeros(40) folder2 = os.path.join(folder, 's%d' % (k+1)) """ a=glob.glob(os.path.join(folder2, '*.pgm')) for d in a: #print(d) img=cv2.imread(d)#imread读取图像返回的是三维数组,返回值是3个数组:I( : , : ,1) I( : , : ,2) I( : , : ,3) 这3个数组中应该存放的是RGB的值 #print(img)#112*92*3 cv2.imshow('image', img) """ #data 每次10*112*92 data = [ cv2.imread(d,0) for d in glob.glob(os.path.join(folder2, '*.pgm'))]#cv2.imread()第二个参数为0的时候读入为灰度图,即使原图是彩色图也会转成灰度图#glob.glob匹配所有的符合条件的文件,并将其以list的形式返回 data_pwt=[] """ ###多尺度二维离散小波分解wavedec2 ###c为各层分解系数,s为各层分解系数长度 pywt.wavedec2(data, wavelet, mode=’symmetric’, level=None, axes=(-2, -1)) data: 输入的数据 wavelet:小波基 level: 尺度(要变换多少层) return: 返回的值要注意,每一层的高频都是包含在一个tuple中,例如三层的话返回为 [cA3, (cH3, cV3, cD3), (cH2, cV2, cD2), (cH1, cV1, cD1)] ###保留低频部分,(高频部分为噪声部分) """ for i in range(10): #subplot(numRows, numCols, plotNum)图表的整个绘图区域被分成 numRows 行和 numCols 列,然后按照从左到右,从上到下的顺序对每个子区域进行编号,左上的子区域的编号为1 #plt.subplot(1,2,1) #plt.imshow(data[0],cmap="gray") xTrain_pwt = pywt.wavedec2(data[i], 'db2', mode='symmetric', level=3, axes=(-2, -1)) #plt.subplot(1, 2, 2) #plt.imshow(xTrain_pwt[0],cmap="gray") #plt.show() data_pwt.append(xTrain_pwt[0]) #print(xTrain_pwt) sampleCount=5 #sample = random.sample(range(10), sampleCount)#random.sample()可以从指定的序列中,随机的截取指定长度的片断,不作原地修改 #print(sample) #print(data) sample=[1,3,5,7,9] #print(data_pwt) trainData.extend([data_pwt[i].ravel() for i in range(10) if i in sample])#ravel将多维数组降位一维####40*5*112*92 testData.extend([data_pwt[i].ravel() for i in range(10) if i not in sample])#40*5*112*92 yTrain1[k]=1 yTest1[k]=1 #yTest.extend([]* (10-sampleCount)) #yTrain.extend([k]* sampleCount) yTrain = np.matrix(yTrain1) yTrain= np.tile(yTrain1,5)# np.tile(a,(2,1))就是把a先沿x轴(就这样称呼吧)复制1倍,即没有复制,仍然是 [0,1,2]。 再把结果沿y方向复制2倍 yTest=np.tile(yTest1,5)#沿着x轴复制5倍,增加列数 yTrain2.extend(yTrain) yTest2.extend(yTest) return np.array(trainData), np.array(yTrain2), np.array(testData), np.array(yTest2)
def __init__(self, nrow=256, ncol=256, wavelet='db4', level=3, fwd_mode='recon'): # Initialize the base class LinTrans.__init__(self) # Save parameters self.wavelet = wavelet self.level = level self.shape0 = (nrow, ncol) self.shape1 = (nrow, ncol) # 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 denoise(): wave = 'db4' sig = 20 tau1 = 3 * sig tau2 = 3 * sig / 2 noisyLena = lena + np.random.normal(scale=sig, size=lena.shape) lw = pywt.wavedec2(noisyLena, wave, level=4) lwt1 = hardThresh(lw, tau1) lwt2 = softThresh(lw, tau2) rlena1 = pywt.waverec2(lwt1, wave) rlena2 = pywt.waverec2(lwt2, wave) plt.subplot(131) plt.imshow(noisyLena, cmap=plt.cm.Greys_r) plt.axis('off') plt.subplot(132) plt.imshow(rlena1, cmap=plt.cm.Greys_r) plt.axis('off') plt.subplot(133) plt.imshow(rlena2, cmap=plt.cm.Greys_r) plt.axis('off') plt.savefig('denoise.pdf') plt.clf()
def denoise(): wave = 'db4' sig = 20 tau1 = 3*sig tau2 = 3*sig/2 noisyLena = lena + np.random.normal(scale = sig, size=lena.shape) lw = pywt.wavedec2(noisyLena, wave, level=4) lwt1 = hardThresh(lw, tau1) lwt2 = softThresh(lw, tau2) rlena1 = pywt.waverec2(lwt1, wave) rlena2 = pywt.waverec2(lwt2, wave) plt.subplot(131) plt.imshow(noisyLena, cmap=plt.cm.Greys_r) plt.axis('off') plt.subplot(132) plt.imshow(rlena1, cmap=plt.cm.Greys_r) plt.axis('off') plt.subplot(133) plt.imshow(rlena2, cmap=plt.cm.Greys_r) plt.axis('off') plt.savefig('denoise.pdf') plt.clf()
def _get_haar_feature(filename): data = misc.imread(filename) data = misc.imresize(data, (64, 64)) #data.resize(64, 64) feature_layers = np.zeros((32, 32, 3), dtype=np.float32) additional = np.empty(4) for index in range(3): layer = data[:, :, index] layer = np.float32(layer) additional[index] = layer.mean() #layer /= 255.0 #print(layer.min(), layer.max(), layer.mean()) #print(layer[:1]) haar = pywt.wavedec2(data=layer, wavelet='haar', level=1) cA = haar[0] feature_layers[:, :, index] = cA height, width, _ = data.shape aspect = float(width)/(width+height) additional[-1] = aspect features = np.concatenate((feature_layers.reshape(32*32*3), additional)) return features
def _call(self, x): """Compute the discrete wavelet transform. Parameters ---------- x : `DiscreteLpVector` Returns ------- arr : `numpy.ndarray` Flattened and concatenated coefficient array The length of the array depends on the size of input image to be transformed and on the chosen wavelet basis. """ if x.space.ndim == 1: coeff_list = pywt.wavedec(x, self.wbasis, self.mode, self.nscales) coeff_arr = pywt_coeff_to_array(coeff_list, self.size_list) return self.range.element(coeff_arr) if x.space.ndim == 2: coeff_list = pywt.wavedec2(x, self.wbasis, self.mode, self.nscales) coeff_arr = pywt_coeff_to_array(coeff_list, self.size_list) return self.range.element(coeff_arr) if x.space.ndim == 3: coeff_dict = wavelet_decomposition3d(x, self.wbasis, self.mode, self.nscales) coeff_arr = pywt_coeff_to_array(coeff_dict, self.size_list) return self.range.element(coeff_arr)
def matvec(x): xnd = x.reshape(shapein) yl = pywt.wavedec2(xnd, wavelet, mode=mode, level=level) y = yl[0].flatten() for el in yl[1:]: y = np.concatenate((y, np.concatenate(el).flatten())) return y
def __init__(self, M, N, start_thres, wavelet): img = np.zeros((M, N)) self.wavelet = wavelet self.coeffs = pywt.wavedec2(img, wavelet) self.trees = CoefficientTree.build_trees(self.coeffs) self.T = start_thres self.processed = []
def create_haar_dictionary(p=8): import pywt c = pywt.wavedec2(np.zeros((p, p)), 'haar') D = [] for k in range(1, len(c)): for i in range(3): ck = c[k][i] l = ck.shape[0] for j in range(l): for m in range(l): ck[j, m] = 1 D += [pywt.waverec2(c, 'haar')] ck[j, m] = 0 ck = c[0] l = ck.shape[0] for j in range(l): for m in range(l): ck[j, m] = 1 D += [pywt.waverec2(c, 'haar')] ck[j, m] = 0 D = np.array(D).reshape(-1, p*p) Dn = [] for i in range(15): Dn += _translate(D[i].reshape((p, p))) Dn = np.array(Dn).reshape((-1, p*p)) i0 = np.sum(abs(Dn), axis=1) != 0 return Dn[i0]
def munchetal_filter(im, wlevel, sigma, wname='db15'): # Wavelet decomposition: coeffs = pywt.wavedec2(im.astype(np.float32), wname, level=wlevel) coeffsFlt = [coeffs[0]] # FFT transform of horizontal frequency bands: for i in range(1, wlevel + 1): # FFT: fcV = np.fft.fftshift(np.fft.fft(coeffs[i][1], axis=0)) my, mx = fcV.shape # Damping of vertical stripes: damp = 1 - np.exp(-(np.arange(-np.floor(my / 2.), -np.floor(my / 2.) + my) ** 2) / (2 * (sigma ** 2))) dampprime = np.kron(np.ones((1, mx)), damp.reshape((damp.shape[0], 1))) fcV = fcV * dampprime # Inverse FFT: fcVflt = np.real(np.fft.ifft(np.fft.ifftshift(fcV), axis=0)) cVHDtup = (coeffs[i][0], fcVflt, coeffs[i][2]) coeffsFlt.append(cVHDtup) # Get wavelet reconstruction: im_f = np.real(pywt.waverec2(coeffsFlt, wname)) # Return image according to input type: if (im.dtype == 'uint16'): # Check extrema for uint16 images: im_f[im_f < np.iinfo(np.uint16).min] = np.iinfo(np.uint16).min im_f[im_f > np.iinfo(np.uint16).max] = np.iinfo(np.uint16).max # Return filtered image (an additional row and/or column might be present): return im_f[0:im.shape[0], 0:im.shape[1]].astype(np.uint16) else: return im_f[0:im.shape[0], 0:im.shape[1]]
def blur_feature_tong_etal(img, thresh=35, MinZero=0.05): img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = resize_borders_to_multiple_of(img, 8) w = pywt.wavedec2(img, 'haar', level=3) emap = [np.sqrt(w[i][0]**2 + w[i][1]**2 + w[i][2]**2) for i in range(1, len(w))] window_size_map = [2, 4, 8] emax = [np.zeros((e.shape[0]/s, e.shape[1]/s)) for e, s in zip(emap, window_size_map)] for e, s, m in zip(emap, window_size_map, emax): for y in range(0, e.shape[0]/s): for x in range(0, e.shape[1]/s): ep = e[y*s:y*s+s,x*s:x*s+s] m[y,x] = np.amax(ep) r1 = edge_point = np.logical_or(emax[0] > thresh, np.logical_or(emax[1] > thresh, emax[2] > thresh)) r2 = ds_or_as = np.logical_and(edge_point, np.logical_and(emax[0] > emax[1], emax[1] > emax[2])) r3 = rs_or_gs = np.logical_and(edge_point, np.logical_and(emax[0] < emax[1], emax[1] < emax[2])) r4 = rs = np.logical_and(edge_point, np.logical_and(emax[1] > emax[0], emax[1] > emax[2])) r5 = more_likely = np.logical_and(np.logical_or(rs_or_gs, rs), emax[0] < thresh) N_edge = np.count_nonzero(r1) N_da = np.count_nonzero(r2) N_rg = np.count_nonzero(np.logical_or(r3, r4)) N_brg = np.count_nonzero(r5) Per = float(N_da)/float(N_edge) unblured = Per > MinZero # if N_rg is 0 then the image must be really blurry if N_rg == 0: BlurExtent = 1 else: BlurExtent = float(N_brg)/float(N_rg) return BlurExtent
def w2d(img, mode='haar', level=1): imArray = cv2.imread(img) #Datatype conversions #convert to grayscale imArray = cv2.cvtColor( imArray,cv2.COLOR_RGB2GRAY ) #convert to float imArray = np.float32(imArray) imArray /= 255.; # compute coefficients coeffs=pywt.wavedec2(imArray, mode, level=level) #print len(coeffs) #Process Coefficients coeffs_H=list(coeffs[1][0]) coeffs_H *= 0 coeffs[1][0] = coeffs_H # reconstruction imArray_H=pywt.waverec2(coeffs, mode); imArray_H *= 255.; imArray_H = np.uint8(imArray_H) #Display result cv2.imshow('image',imArray_H) cv2.waitKey(0) cv2.destroyAllWindows()
def whash(image, hash_size = 8, image_scale = None, mode = 'haar', remove_max_haar_ll = True): """ Wavelet Hash computation. based on https://www.kaggle.com/c/avito-duplicate-ads-detection/ @image must be a PIL instance. @hash_size must be a power of 2 and less than @image_scale. @image_scale must be power of 2 and less than image size. By default is equal to max power of 2 for an input image. @mode (see modes in pywt library): 'haar' - Haar wavelets, by default 'db4' - Daubechies wavelets @remove_max_haar_ll - remove the lowest low level (LL) frequency using Haar wavelet. """ import pywt if image_scale is not None: assert image_scale & (image_scale - 1) == 0, "image_scale is not power of 2" else: image_natural_scale = 2**int(numpy.log2(min(image.size))) image_scale = max(image_natural_scale, hash_size) ll_max_level = int(numpy.log2(image_scale)) level = int(numpy.log2(hash_size)) assert hash_size & (hash_size-1) == 0, "hash_size is not power of 2" assert level <= ll_max_level, "hash_size in a wrong range" dwt_level = ll_max_level - level image = image.convert("L").resize((image_scale, image_scale), Image.ANTIALIAS) pixels = numpy.asarray(image) / 255. # Remove low level frequency LL(max_ll) if @remove_max_haar_ll using haar filter if remove_max_haar_ll: coeffs = pywt.wavedec2(pixels, 'haar', level = ll_max_level) coeffs = list(coeffs) coeffs[0] *= 0 pixels = pywt.waverec2(coeffs, 'haar') # Use LL(K) as freq, where K is log2(@hash_size) coeffs = pywt.wavedec2(pixels, mode, level = dwt_level) dwt_low = coeffs[0] # Substract median and compute hash med = numpy.median(dwt_low) diff = dwt_low > med return ImageHash(diff)
def denoise(self, img, d=3): # channel first img = img.transpose(2, 0, 1) # --- wavelet transform coeffs = pywt.wavedec2(img, wavelet=self.wavelet_type, level=self.wavelet_levels) LP = coeffs[0] dcoeffs = coeffs[1:] if self.sigma is None: # Estimate the noise via the method in [2]_ detail_coeffs = dcoeffs[-1][-1] self.sigma = _sigma_est_dwt(detail_coeffs, distribution='Gaussian') var = self.sigma**2 for l in range(self.wavelet_levels): # --- denoise LP with bilateral LP_filter = np.zeros_like(LP) for i in range(LP.shape[0]): s = 2 * estimate_noise_fast(LP[i]) # GF = GrayGuidedFilter(LP[i], radius=d, eps=1e-6) # GF = GrayGuidedFilter(LP[i], radius=d, eps=1e-4) # LP_filter[i] = GF.filter(LP[i]) im, imin, imax = flt2norm(LP[i]) im_out = guided(im, im, d=d, sigmaColor=(s**2) * 255 * 255, color_space='RGB') # im_out = guided(im, im, d=d, sigmaColor=1e-6*255*255, color_space = 'RGB') LP_filter[i] = norm2flt(im_out, imin, imax) # # --- denoise HP with thresholding level = dcoeffs[l] if self.threshold_type == "BayesShrink": threshold = [_bayes_thresh(channel, var) for channel in level] denoised_detail = [pywt.threshold(channel, value=thres, mode=self.mode) \ for thres, channel in zip(threshold,level)] # TODO: add VisuShrink #elif self.threshold_type == "VisuShrink": else: denoised_detail = level coeffs_rec = [LP_filter] + [denoised_detail] LP = pywt.waverec2(coeffs_rec, self.wavelet_type) # channel last img_out = LP.transpose(1, 2, 0) # sigmaColor = estimate_noise_fast(img_out) im, imin, imax = flt2norm(img_out) im_out = guided(im, im, d=d, sigmaColor=2500, color_space='RGB') # im_out = guided(im, im, d=d, sigmaColor=1e-5*255*255, color_space = 'RGB') img_out = norm2flt(im_out, imin, imax) # GF = MultiDimGuidedFilter(img_out, radius=d, eps=1e-5) # GF = MultiDimGuidedFilter(img_out, radius=d, eps=2500/255/255) # img_out = GF.filter(img_out) return img_out
def blend_images(base, texture, wavelet, level, mode='smooth', base_gain=None, texture_gain=None): """Blend loaded images at `level` of granularity using `wavelet`""" base_data = image2array(base) texture_data = image2array(texture) output_data = [] # process color bands for base_band, texture_band in zip(base_data, texture_data): # multilevel dwt base_band_coeffs = pywt.wavedec2(base_band, wavelet, mode, level) texture_band_coeffs = pywt.wavedec2(texture_band, wavelet, mode, level) # average coefficients of base image output_band_coeffs = [base_band_coeffs[0]] # cA del base_band_coeffs[0], texture_band_coeffs[0] # blend details coefficients for n, (base_band_details, texture_band_details) in enumerate( zip(base_band_coeffs, texture_band_coeffs)): blended_details = [] for (base_detail, texture_detail) in zip(base_band_details, texture_band_details): if base_gain is not None: base_detail *= base_gain if texture_gain is not None: texture_detail *= texture_gain # select coeffs with greater energy blended = numpy.where(abs(base_detail) > abs(texture_detail), base_detail, texture_detail) blended_details.append(blended) base_band_coeffs[n] = texture_band_coeffs[n] = None output_band_coeffs.append(blended_details) # multilevel idwt new_band = pywt.waverec2(output_band_coeffs, wavelet, mode) output_data.append(new_band) del new_band, base_band_coeffs, texture_band_coeffs del base_data, texture_data output_data = numpy.array(output_data) return array2image(output_data, base.mode)
def updateImage(waveletType): self.levels = cv2.getTrackbarPos('levels', self.winName) coefficients = pywt.wavedec2(self.inputImage, waveletType, level=self.levels) self.outputImage = dwtPlot(coefficients) #self.outputImage = toOpCv(self.outputImage) cv2.imshow(self.winName, self.outputImage)
def waveletDenoise(u,noiseSigma): wavelet = pywt.Wavelet('bior6.8') levels = int( np.log2(u.shape[0]) ) waveletCoeffs = pywt.wavedec2( u, wavelet, level=levels) threshold=noiseSigma*np.sqrt(2*np.log2(u.size)) NWC = [pywt.thresholding.soft(x,threshold) for x in waveletCoeffs] u = pywt.waverec2( NWC, wavelet)[:u.shape[0],:u.shape[1]] return u
def wavelet2(image_data): db1 = pywt.Wavelet('db1') # 多尺度小波变化,返回值分别为[低频分量,(水平高频,垂直高频,对角线高频)] [cA2, (cH2, cV2, cD2), (cH1, cV1, cD1)] = pywt.wavedec2(image_data, db1, mode='symmetric', level=2) return cA2
def dwt(img, mode='haar', dst=None): cc = pywt.wavedec2(data=img, wavelet=mode, level=3) rec = pywt.waverec2(coeffs=cc, wavelet=mode) diff = img - rec if dst: cv2.imwrite(dst % (mode + '_rec'), rec) cv2.imwrite(dst % (mode + '_diff'), diff) return rec, diff
def dwt2(): mandrill = imread("baboon.png") mandrill = mandrill.mean(axis=-1) lw = pywt.wavedec2(mandrill, 'db4',mode='per', level=2) plt.imsave("mandrill1.png",lw[0], cmap=plt.cm.Greys_r) plt.imsave("mandrill2.png",np.abs(lw[1][0]), cmap=plt.cm.Greys_r) plt.imsave("mandrill3.png",np.abs(lw[1][1]), cmap=plt.cm.Greys_r) plt.imsave("mandrill4.png",np.abs(lw[1][2]), cmap=plt.cm.Greys_r)
def dwt(data, wav, dl=1): """Runs DWT one the give image with the provided wavelet and optional levels""" if _args.verbose: print('DWT ...', end='') d = pywt.wavedec2(data, wavelet=wav, level=dl) if _args.verbose: print(' done.') return d
def denoise(noisy_img, mode, level, noiseSigma): coeffs = pywt.wavedec2(noisy_img, mode, level=level) # Thresholding the detail (i.e. high frequency) coefficiens # using a Donoho-Johnstone universal threshold threshold = noiseSigma * np.sqrt(2 * np.log2(noisy_img.size)) rec_coeffs = coeffs rec_coeffs[1:] = (pywt.threshold(i, value=threshold, mode="soft") for i in rec_coeffs[1:]) return rec_coeffs
def whash(image, hash_size = 8, image_scale = None, mode = 'haar', remove_max_haar_ll = True): """ Wavelet Hash computation. based on https://www.kaggle.com/c/avito-duplicate-ads-detection/ @image must be a PIL instance. @hash_size must be a power of 2 and less than @image_scale. @image_scale must be power of 2 and less than image size. By default is equal to max power of 2 for an input image. @mode (see modes in pywt library): 'haar' - Haar wavelets, by default 'db4' - Daubechies wavelets @remove_max_haar_ll - remove the lowest low level (LL) frequency using Haar wavelet. """ import pywt if image_scale is not None: assert image_scale & (image_scale - 1) == 0, "image_scale is not power of 2" else: image_scale = 2**int(numpy.log2(min(image.size))) ll_max_level = int(numpy.log2(image_scale)) level = int(numpy.log2(hash_size)) assert hash_size & (hash_size-1) == 0, "hash_size is not power of 2" assert level <= ll_max_level, "hash_size in a wrong range" dwt_level = ll_max_level - level image = image.convert("L").resize((image_scale, image_scale), Image.ANTIALIAS) pixels = numpy.array(image.getdata(), dtype=numpy.float).reshape((image_scale, image_scale)) pixels /= 255 # Remove low level frequency LL(max_ll) if @remove_max_haar_ll using haar filter if remove_max_haar_ll: coeffs = pywt.wavedec2(pixels, 'haar', level = ll_max_level) coeffs = list(coeffs) coeffs[0] *= 0 pixels = pywt.waverec2(coeffs, 'haar') # Use LL(K) as freq, where K is log2(@hash_size) coeffs = pywt.wavedec2(pixels, mode, level = dwt_level) dwt_low = coeffs[0] # Substract median and compute hash med = numpy.median(dwt_low) diff = dwt_low > med return ImageHash(diff)
def test_waverec2_axes_subsets(): rstate = np.random.RandomState(0) data = rstate.standard_normal((8, 8, 8)) # test all combinations of 2 out of 3 axes transformed for axes in combinations((0, 1, 2), 2): coefs = pywt.wavedec2(data, 'haar', axes=axes) rec = pywt.waverec2(coefs, 'haar', axes=axes) assert_allclose(rec, data, atol=1e-14)
def spectral_images_to_wavelet(self, spectral_images, wavelet = wt.Wavelet('db1')): if (int(self.new_d1)!=self.d1) or (int(self.new_d2)!=self.d2): spectral_images = self._resize_spectral_images(spectral_images, self.new_d1, self.new_d2) haar_images = np.zeros([self.nwindows,self.new_d1,self.new_d2]) for i in range(self.nwindows): coeffs = wt.wavedec2(spectral_images[i,:,:], wavelet) haar_images[i,:,:] = self._unwrap_wavelet_coeffs(coeffs) return haar_images
def haar(img): coefs = pywt.wavedec2(img, 'haar', level=2) coefs[1] = pywt.threshold(coefs[1], 5, 'soft', 0) coefs[2] = pywt.threshold(coefs[2], 5, 'soft', 0) print(coefs[1], coefs[2]) con_img = pywt.waverec2(coefs, 'haar') con_img = con_img.astype(np.uint8) # 进行类型转换 return con_img
def getContrast(img): lowFreq, highFreq = pywt.wavedec2(img, 'haar', level=1) row, col = img.shape ctr = np.zeros((row, col)) size = len(highFreq) for array in highFreq: ctr += (array / lowFreq)**2 / size return ctr.sum() * 100 / (row * col)
def analysis(self,z0): """ Analysis: image -> coefficients """ coeffs = pywt.wavedec2(z0, wavelet=self.wavelet, level=self.level, \ mode=self.mode) z1, _ = pywt.coeffs_to_array(coeffs) return z1
def wavelet_transform_for_image(src_image, level, M_WAVELET="db1", mode="sym"): """ coeffs: リスト型、0番目の要素はndarray、それ以降の要素はタプル、タプル内には3つの要素がありすべてndarray [array([]),(array([]),array([]),array([])), ... ,(array([]),array([]),array([]))] """ data = src_image.astype(np.float64) coeffs = pywt.wavedec2(data, M_WAVELET, level=level, mode=mode) return coeffs
def generate_wavlet_slices(x_shape, y_shape, level): sample_image = np.random.normal(size=(x_shape, y_shape)) sample_coeff = pywt.wavedec2(sample_image, 'db2', mode='periodization', level=level) slices_instructions = pywt.coeffs_to_array(sample_coeff)[1] return slices_instructions
def prereq_f16_f17_f18(i): global S1, S2, S3, LL, HL, HH coeffs = wavedec2(IV[i], 'db1', level=3) LL, LH, HL, HH = coeffs S1 = sum(sum(abs(LH[0]))) + sum(sum(abs(HL[0]))) + sum(sum(abs(HH[0]))) S2 = sum(sum(abs(LH[1]))) + sum(sum(abs(HL[1]))) + sum(sum(abs(HH[1]))) S3 = sum(sum(abs(LH[2]))) + sum(sum(abs(HL[2]))) + sum(sum(abs(HH[2]))) check_zero()
def wavedec_arr(img, delta, delta_step, level=None, threshold_factor=3, print_max=False): coeffs = pywt.wavedec2(img, 'db4', level=level) r, c = coeffs[0].shape sizes = [] max_int = 128 # approximation coefficient max_val = max(abs(coeffs[0].ravel())) # scale = int(next_power_of_2(max_val)) # scale = max(int(delta),int(delta * np.ceil(max_val / (max_int * delta)))) scale = int(delta) sizes.append([r, c, scale]) if print_max: print('wavelet', max_val, scale) count = r * c delta = int(scale / delta_step) # rest of detail coefficients for i, coeff in enumerate(coeffs[1:]): size = [] for cd in coeff: max_val = max(abs(cd.ravel())) # scale = min(int(delta),int(delta * np.ceil(max_val / (max_int * delta)))) # scale = int(next_power_of_2(int(delta * np.ceil(max_val / (max_int * delta))))) scale = delta if print_max: print('wavelet', max_val, scale) r, c = cd.shape size.append([r, c, scale]) count += r * c # delta = int(scale / delta_step) sizes.append(size) # approximation coefficient arr = np.zeros(count, dtype=np.int8) r, c = coeffs[0].shape idx = r * c s_idx = 0 scale = sizes[s_idx][2] arr[:idx] = quantize(coeffs[0], scale, threshold_factor, print_max).ravel() assert np.max(abs(arr[:idx])) < 127, np.max(abs(arr[:idx])) # rest of detail coefficients for coeff in coeffs[1:]: s_idx += 1 for i, cd in enumerate(coeff): r, c = cd.shape scale = sizes[s_idx][i][2] arr[idx:idx + r * c] = quantize(cd, scale, threshold_factor, print_max).ravel() idx += r * c return arr, sizes
def recognize_card(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Gaussian Blur and Threshold blurred_image = cv2.GaussianBlur(gray, (FILTER_SIZE, FILTER_SIZE), 6) thresh, binary = cv2.threshold(blurred_image, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) # Wavelet decomposition # Assume periodic signal (such that the artifacts at the boundaries can be minimized, for our purpose) coefs = pywt.wavedec2(binary, WAV, level=COMPRESSION_LEVEL, mode='per') # Retain only the first-level approximation # And zero all remaining coefficients coefs2 = copy.copy(coefs) for i in range(1, len(coefs)): cH, cV, cD = (np.zeros(coefs[i][0].shape), np.zeros(coefs[i][1].shape), np.zeros(coefs[i][2].shape)) coefs2[i] = (cH, cV, cD) # Start with no guess guess = None max_corr = -1 # Handle rotations (4 times, 90 degrees each) for rotation in range(0, 4): for (card, coef) in zip(possible_cards, possible_card_coefs): corr = np.corrcoef(coefs[0].reshape(-1), coef.reshape(-1)) corr = corr[0, 1] # Update guess if better if guess is None or corr > max_corr: guess = card max_corr = corr if rotation < 3: binary = np.rot90(binary) coefs = pywt.wavedec2(binary, WAV, level=COMPRESSION_LEVEL, mode='per') return guess
def image_fusion(img1, img2, window): p1 = mean_ration_img(img1, img2, window) p2 = log_ration_img(img1, img2) #wavelet w1 = list(pywt.wavedec2(p1, 'haar', level=2)) w2 = list(pywt.wavedec2(p2, 'haar', level=2)) #fusion w_fusion = [] w_fusion.append((w1[0] + w2[0]) / 2) #LL w = [] for n in range(len(w1) - 1): for i in range(3): #lh,hk,hh w.append(fustion_rule(w1[n + 1][i], w2[n + 1][i], window)) w_fusion.append(w) w = [] #rebiuld img = pywt.waverec2(w_fusion, 'haar') return (img)
def prereq_f13_f14_f15(i): global S1, S2, S3, LL, HL, HH HL = LH = HH = [0]*3 coeffs = wavedec2(IS[i], 'db1', level = 3) LL, (HL[2], HL[2], HH[2]), (HL[1], HL[1], HH[1]), (HL[0], HL[0], HH[0]) = coeffs S1 = sum(sum(abs(LH[0]))) + sum(sum(abs(HL[0]))) + sum(sum(abs(HH[0]))) S2 = sum(sum(abs(LH[1]))) + sum(sum(abs(HL[1]))) + sum(sum(abs(HH[1]))) S3 = sum(sum(abs(LH[2]))) + sum(sum(abs(HL[2]))) + sum(sum(abs(HH[2]))) check_zero()
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 trans(imArray, mode='haar', level=1): coeffs = pywt.wavedec2(imArray, mode, level=level) coeffs_H = list(coeffs) coeffs_H[0] = np.zeros(coeffs_H[0].shape) imArray_H = pywt.waverec2(coeffs_H, mode) #return imArray #print "img1", imArray[0] #print "img2", imArray_H[0] return imArray_H
def test_waverec2_axes_errors(): data = np.ones((4, 4)) c = pywt.wavedec2(data, 'haar') # integer axes not allowed assert_raises(TypeError, pywt.waverec2, c, 'haar', axes=1) # non-unique axes not allowed assert_raises(ValueError, pywt.waverec2, c, 'haar', axes=(0, 0)) # out of range axis not allowed assert_raises(ValueError, pywt.waverec2, c, 'haar', axes=(0, 2))
def test_waverec2_coeff_shape_mismatch(): x = np.ones((8, 8)) coeffs = pywt.wavedec2(x, 'db1') # introduce a shape mismatch in the coefficients coeffs = list(coeffs) coeffs[1] = list(coeffs[1]) coeffs[1][1] = np.zeros((16, 1)) assert_raises(ValueError, pywt.waverec2, coeffs, 'db1')
def test_waverec2_all_wavelets_modes(): # test 2D case using all wavelets and modes rstate = np.random.RandomState(1234) r = rstate.randn(80, 96) for wavelet in wavelist: for mode in pywt.Modes.modes: coeffs = pywt.wavedec2(r, wavelet, mode=mode) assert_allclose(pywt.waverec2(coeffs, wavelet, mode=mode), r, rtol=tol_single, atol=tol_single)
def wavelet(img): coeffs = pywt.wavedec2(img, wavelet='haar', level=3) cA3, (cH3, cV3, cD3), (cH2, cV2, cD2), (cH1, cV1, cD1) = coeffs feature = [] for mat in [cH3, cV3, cD3, cH2, cV2, cD2, cH1, cV1, cD1]: feature.append(mat.mean()) feature.append(mat.std()) return np.array(feature)
def get_wavelet_features(input_image): feature_array = [] coefficients = wt.wavedec2(input_image, "haar", level=4) for level in reversed(coefficients[1:]): for details in level: feature_array.append((np.sum(details ** 2)) / np.size(input_image)) return feature_array
def describe_texture(self, img): # converting the given image to grayscale and normalizing it gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) imArray = np.float32(gray_img) imArray /= 255 # initializing arrays to store mean, variance and final features imMean, imVar, feats = [], [], [] # calculating the dimensions of the regions, for which mean and variance are to be calculated # we split the image into 8X8 separate regions (h, w) = gray_img.shape[:2] (cX, cY) = (int(w * 0.125), int(h * 0.125)) # iterating over all of the 64 separate regions for r in range(8): imRMean, imRVar = [], [] for c in range(8): tMean, tVar = [], [] # perforimg wavelet decomposition of the region using db1 mode at level 1 coeffs = pywt.wavedec2( imArray[r * cY:r * cY + cY, c * cX:c * cX + cX], 'db1', 1) # finding the mean and variance of 4 arrays that resulted from decomposition # coeffs[0] will be a low res copy of image region # coeffs[1][0..2] will be 3 band passed filter results in horizontal, # vertical and diagonal directions respectively for i in range(4): # appending the mean and variance values of a region into two vectors if i == 0: tMean.append(np.mean(coeffs[i])) tVar.append(np.var(coeffs[i])) else: tMean.append(np.mean(coeffs[1][i - 1])) tVar.append(np.var(coeffs[1][i - 1])) # appending the mean and variance vectors of all regions along the row imRMean.append(tMean) imRVar.append(tVar) # appending the mean and variance vectors of all rows imMean.append(imRMean) imVar.append(imRVar) # appending mean and variance vectors into one features vector feats.append(imMean) feats.append(imVar) # flattening the features vector feats = np.asarray(feats) feats = cv2.normalize(feats, feats) feats = feats.flatten() # returning the features vector / histogram return feats
def describe_texture(self, img): # converting the given image to grayscale and normalizing it gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) imArray = np.float32(gray_img) imArray /= 255; # initializing arrays to store mean, variance and final features imMean, imVar, feats = [], [], [] # calculating the dimensions of the regions, for which mean and variance are to be calculated # we split the image into 8X8 separate regions (h, w) = gray_img.shape[:2] (cX, cY) = (int(w * 0.125), int(h * 0.125)) # iterating over all of the 64 separate regions for r in range(8): imRMean, imRVar = [],[] for c in range(8): tMean, tVar = [],[] # perforimg wavelet decomposition of the region using db1 mode at level 1 coeffs=pywt.wavedec2(imArray[r*cY:r*cY+cY,c*cX:c*cX+cX], 'db1', 1) # finding the mean and variance of 4 arrays that resulted from decomposition # coeffs[0] will be a low res copy of image region # coeffs[1][0..2] will be 3 band passed filter results in horizontal, # vertical and diagonal directions respectively for i in range(4): # appending the mean and variance values of a region into two vectors if i == 0: tMean.append(np.mean(coeffs[i])) tVar.append(np.var(coeffs[i])) else: tMean.append(np.mean(coeffs[1][i-1])) tVar.append(np.var(coeffs[1][i-1])) # appending the mean and variance vectors of all regions along the row imRMean.append(tMean) imRVar.append(tVar) # appending the mean and variance vectors of all rows imMean.append(imRMean) imVar.append(imRVar) # appending mean and variance vectors into one features vector feats.append(imMean) feats.append(imVar) # flattening the features vector feats = np.asarray(feats) feats = cv2.normalize(feats,feats) feats = feats.flatten() # returning the features vector / histogram return feats
def two(): global P eps = 1 Pw = deepcopy(P) for i,n in enumerate(xrange(1,4)): X = pywt.wavedec2(Pw, 'sym5', level=n) Pw = X[1][0] #Pw[abs(Pw) < eps] = 0 #Pw[abs(Pw) >= eps] = 1 pylab.matshow(Pw)
def test_waverec2_accuracies(): rstate = np.random.RandomState(1234) x0 = rstate.randn(4, 4) for dt, tol in dtypes_and_tolerances: x = x0.astype(dt) if np.iscomplexobj(x): x += 1j*rstate.randn(4, 4).astype(x.real.dtype) coeffs = pywt.wavedec2(x, 'db1') assert_(len(coeffs) == 3) assert_allclose(pywt.waverec2(coeffs, 'db1'), x, atol=tol, rtol=tol)