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 test_dwtn_input(): # Array-like must be accepted pywt.dwtn([1, 2, 3, 4], 'haar') # Others must not data = dict() assert_raises(TypeError, pywt.dwtn, data, 'haar') # Must be at least 1D assert_raises(ValueError, pywt.dwtn, 2, 'haar')
def test_negative_axes(): data = np.array([[0, 1, 2, 3], [1, 1, 1, 1], [1, 4, 2, 8]]) coefs1 = pywt.dwtn(data, 'haar', axes=(1, 1)) coefs2 = pywt.dwtn(data, 'haar', axes=(-1, -1)) assert_equal(coefs1, coefs2) rec1 = pywt.idwtn(coefs1, 'haar', axes=(1, 1)) rec2 = pywt.idwtn(coefs1, 'haar', axes=(-1, -1)) assert_equal(rec1, rec2)
def test_byte_offset(): wavelet = pywt.Wavelet("haar") for dtype in ("float32", "float64"): data = np.array([[0, 4, 1, 5, 1, 4], [0, 5, 6, 3, 2, 1], [2, 5, 19, 4, 19, 1]], dtype=dtype) for mode in pywt.Modes.modes: expected = pywt.dwtn(data, wavelet) padded = np.ones((3, 6), dtype=np.dtype([("data", data.dtype), ("pad", "byte")])) padded[:] = data padded_dwtn = pywt.dwtn(padded["data"], wavelet) for key in expected.keys(): assert_allclose(padded_dwtn[key], expected[key])
def test_stride(): wavelet = pywt.Wavelet("haar") for dtype in ("float32", "float64"): data = np.array([[0, 4, 1, 5, 1, 4], [0, 5, 6, 3, 2, 1], [2, 5, 19, 4, 19, 1]], dtype=dtype) for mode in pywt.Modes.modes: expected = pywt.dwtn(data, wavelet) strided = np.ones((3, 12), dtype=data.dtype) strided[::-1, ::2] = data strided_dwtn = pywt.dwtn(strided[::-1, ::2], wavelet) for key in expected.keys(): assert_allclose(strided_dwtn[key], expected[key])
def test_byte_offset(): wavelet = pywt.Wavelet('haar') for dtype in ('float32', 'float64'): data = np.array([[0, 4, 1, 5, 1, 4], [0, 5, 6, 3, 2, 1], [2, 5, 19, 4, 19, 1]], dtype=dtype) for mode in pywt.Modes.modes: expected = pywt.dwtn(data, wavelet) padded = np.ones((3, 6), dtype=np.dtype([('data', data.dtype), ('pad', 'byte')])) padded[:] = data padded_dwtn = pywt.dwtn(padded['data'], wavelet) for key in expected.keys(): assert_allclose(padded_dwtn[key], expected[key])
def test_wavelet_decomposition3d_and_reconstruction3d(): # Test 3D wavelet decomposition and reconstruction and verify that # they perform as expected x = np.random.rand(16, 16, 16) mode = 'sym' wbasis = pywt.Wavelet('db5') nscales = 1 wavelet_coeffs = wavelet_decomposition3d(x, wbasis, mode, nscales) aaa = wavelet_coeffs[0] reference = pywt.dwtn(x, wbasis, mode) aaa_reference = reference['aaa'] assert all_almost_equal(aaa, aaa_reference) reconstruction = wavelet_reconstruction3d(wavelet_coeffs, wbasis, mode, nscales) reconstruction_reference = pywt.idwtn(reference, wbasis, mode) assert all_almost_equal(reconstruction, reconstruction_reference) assert all_almost_equal(reconstruction, x) assert all_almost_equal(reconstruction_reference, x) wbasis = pywt.Wavelet('db1') nscales = 3 wavelet_coeffs = wavelet_decomposition3d(x, wbasis, mode, nscales) shape_true = (nscales + 1, ) assert all_equal(np.shape(wavelet_coeffs), shape_true) reconstruction = wavelet_reconstruction3d(wavelet_coeffs, wbasis, mode, nscales) assert all_almost_equal(reconstruction, x)
def test_dwtn_axes(): data = np.array([[0, 1, 2, 3], [1, 1, 1, 1], [1, 4, 2, 8]]) data = data + 1j*data # test with complex data coefs = pywt.dwtn(data, 'haar', axes=(1,)) expected_a = list(map(lambda x: pywt.dwt(x, 'haar')[0], data)) assert_equal(coefs['a'], expected_a) expected_d = list(map(lambda x: pywt.dwt(x, 'haar')[1], data)) assert_equal(coefs['d'], expected_d) coefs = pywt.dwtn(data, 'haar', axes=(1, 1)) expected_aa = list(map(lambda x: pywt.dwt(x, 'haar')[0], expected_a)) assert_equal(coefs['aa'], expected_aa) expected_ad = list(map(lambda x: pywt.dwt(x, 'haar')[1], expected_a)) assert_equal(coefs['ad'], expected_ad)
def test_idwtn_axes(): data = np.array([[0, 1, 2, 3], [1, 1, 1, 1], [1, 4, 2, 8]]) data = data + 1j*data # test with complex data coefs = pywt.dwtn(data, 'haar', axes=(1, 1)) assert_allclose(pywt.idwtn(coefs, 'haar', axes=(1, 1)), data, atol=1e-14)
def estimate_sigma(image, average_sigmas=False, multichannel=False): """ Robust wavelet-based estimator of the (Gaussian) noise standard deviation. Parameters ---------- image : ndarray Image for which to estimate the noise standard deviation. average_sigmas : bool, optional If true, average the channel estimates of `sigma`. Otherwise return a list of sigmas corresponding to each channel. multichannel : bool Estimate sigma separately for each channel. Returns ------- sigma : float or list Estimated noise standard deviation(s). If `multichannel` is True and `average_sigmas` is False, a separate noise estimate for each channel is returned. Otherwise, the average of the individual channel estimates is returned. Notes ----- This function assumes the noise follows a Gaussian distribution. The estimation algorithm is based on the median absolute deviation of the wavelet detail coefficients as described in section 4.2 of [1]_. References ---------- .. [1] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. DOI:10.1093/biomet/81.3.425 Examples -------- >>> import skimage.data >>> from skimage import img_as_float >>> img = img_as_float(skimage.data.camera()) >>> sigma = 0.1 >>> img = img + sigma * np.random.standard_normal(img.shape) >>> sigma_hat = estimate_sigma(img, multichannel=False) """ if multichannel: nchannels = image.shape[-1] sigmas = [estimate_sigma( image[..., c], multichannel=False) for c in range(nchannels)] if average_sigmas: sigmas = np.mean(sigmas) return sigmas elif image.shape[-1] <= 4: msg = ("image is size {0} on the last axis, but multichannel is " "False. If this is a color image, please set multichannel " "to True for proper noise estimation.") warn(msg.format(image.shape[-1])) coeffs = pywt.dwtn(image, wavelet='db2') detail_coeffs = coeffs['d' * image.ndim] return _sigma_est_dwt(detail_coeffs, distribution='Gaussian')
def estimate_sigma(im, average_sigmas=False, multichannel=False): """ Robust wavelet-based estimator of the (Gaussian) noise standard deviation. Parameters ---------- im : ndarray Image for which to estimate the noise standard deviation. average_sigmas : bool, optional If true, average the channel estimates of `sigma`. Otherwise return a list of sigmas corresponding to each channel. multichannel : bool Estimate sigma separately for each channel. Returns ------- sigma : float or list Estimated noise standard deviation(s). If `multichannel` is True and `average_sigmas` is False, a separate noise estimate for each channel is returned. Otherwise, the average of the individual channel estimates is returned. Notes ----- This function assumes the noise follows a Gaussian distribution. The estimation algorithm is based on the median absolute deviation of the wavelet detail coefficients as described in section 4.2 of [1]_. References ---------- .. [1] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. DOI:10.1093/biomet/81.3.425 Examples -------- >>> import skimage.data >>> from skimage import img_as_float >>> img = img_as_float(skimage.data.camera()) >>> sigma = 0.1 >>> img = img + sigma * np.random.standard_normal(img.shape) >>> sigma_hat = estimate_sigma(img, multichannel=False) """ if multichannel: nchannels = im.shape[-1] sigmas = [estimate_sigma( im[..., c], multichannel=False) for c in range(nchannels)] if average_sigmas: sigmas = np.mean(sigmas) return sigmas elif im.shape[-1] <= 4: msg = ("image is size {0} on the last axis, but multichannel is " "False. If this is a color image, please set multichannel " "to True for proper noise estimation.") warn(msg.format(im.shape[-1])) coeffs = pywt.dwtn(im, wavelet='db2') detail_coeffs = coeffs['d' * im.ndim] return _sigma_est_dwt(detail_coeffs, distribution='Gaussian')
def wave_process(input): if input.shape[2] == 3: ciffes = pywt.dwtn(input, 'haar') else: ciffes = pywt.dwt2(input, 'haar') for i in range(len(ciffes)): cv2.imshow(ciffes[i][:, :, 0]) cv2.waitkey(0) return len(ciffes)
def test_idwtn_take(): data = np.array([ [[1, 4, 1, 5, 1, 4], [0, 5, 6, 3, 2, 1], [2, 5, 19, 4, 19, 1]], [[1, 5, 1, 2, 3, 4], [7, 12, 6, 52, 7, 8], [5, 2, 6, 78, 12, 2]]]) wavelet = pywt.Wavelet('haar') d = pywt.dwtn(data, wavelet) assert_(data.shape != pywt.idwtn(d, wavelet).shape) assert_allclose(data, pywt.idwtn(d, wavelet, take=data.shape), atol=1e-15) # Check shape for take not equal to data.shape data = np.random.randn(51, 17, 68) d = pywt.dwtn(data, wavelet) assert_equal((2, 2, 2), pywt.idwtn(d, wavelet, take=2).shape) assert_equal((52, 18, 68), pywt.idwtn(d, wavelet, take=0).shape)
def test_byte_offset(): wavelet = pywt.Wavelet('haar') for dtype in ('float32', 'float64'): data = np.array( [[0, 4, 1, 5, 1, 4], [0, 5, 6, 3, 2, 1], [2, 5, 19, 4, 19, 1]], dtype=dtype) for mode in pywt.Modes.modes: expected = pywt.dwtn(data, wavelet) padded = np.ones((3, 6), dtype=np.dtype( { 'data': (data.dtype, 0), 'pad': ('byte', data.dtype.itemsize) }, align=True)) padded[:] = data padded_dwtn = pywt.dwtn(padded['data'], wavelet) for key in expected.keys(): assert_allclose(padded_dwtn[key], expected[key])
def test_dwtn_idwtn_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) coeffs = pywt.dwtn(x, wavelet) for k, v in coeffs.items(): assert_(v.dtype == dt_out, "dwtn: " + errmsg) x_roundtrip = pywt.idwtn(coeffs, wavelet) assert_(x_roundtrip.dtype == dt_out, "idwtn: " + errmsg)
def wavelet1(image_arr): print("开始小波变换") # Load image original = image_arr # Wavelet transform of image, and plot approximation and details titles = [ 'Approximation', ' Horizontal detail', 'Vertical detail', 'Diagonal detail' ] coeffs2 = pywt.dwt2(original, 'bior1.3') LL, (LH, HL, HH) = coeffs2 fig = plt.figure() for i, a in enumerate([LL, LH, HL, HH]): ax = fig.add_subplot(2, 2, i + 1) ax.imshow(a, origin='image', interpolation="nearest", cmap=plt.cm.gray) ax.set_title(titles[i], fontsize=12) fig.suptitle("dwt2 coefficients", fontsize=14) # Now reconstruct and plot the original image reconstructed = pywt.idwt2(coeffs2, 'bior1.3') fig = plt.figure() plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray) # Check that reconstructed image is close to the original np.testing.assert_allclose(original, reconstructed, atol=1e-13, rtol=1e-13) # Now do the same with dwtn/idwtn, to show the difference in their signatures coeffsn = pywt.dwtn(original, 'bior1.3') fig = plt.figure() for i, key in enumerate(['aa', 'ad', 'da', 'dd']): ax = fig.add_subplot(2, 2, i + 1) ax.imshow(coeffsn[key], origin='image', interpolation="nearest", cmap=plt.cm.gray) ax.set_title(titles[i], fontsize=12) fig.suptitle("dwtn coefficients", fontsize=14) # Now reconstruct and plot the original image reconstructed = pywt.idwtn(coeffsn, 'bior1.3') fig = plt.figure() plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray) # Check that reconstructed image is close to the original np.testing.assert_allclose(original, reconstructed, atol=1e-13, rtol=1e-13) plt.show()
def test_3D_reconstruct(): data = np.array( [ [[0, 4, 1, 5, 1, 4], [0, 5, 26, 3, 2, 1], [5, 8, 2, 33, 4, 9], [2, 5, 19, 4, 19, 1]], [[1, 5, 1, 2, 3, 4], [7, 12, 6, 52, 7, 8], [2, 12, 3, 52, 6, 8], [5, 2, 6, 78, 12, 2]], ] ) wavelet = pywt.Wavelet("haar") for mode in pywt.Modes.modes: d = pywt.dwtn(data, wavelet, mode=mode) assert_allclose(data, pywt.idwtn(d, wavelet, mode=mode), rtol=1e-13, atol=1e-13)
def __compute_coeffs(im, wavelet): """ Compute the wavelet coefficients for an image (called theta_uij in the paper). Returns a stack of values where the last index is which set of coefficients starting at fully detail down to fully approximate. """ from numpy import stack from pywt import dwtn theta = dwtn(im, wavelet) return stack( [theta[''.join(axes)] for axes in product('da', repeat=im.ndim)], axis=-1)
def test_dwdtn_idwtn_allwavelets(): rstate = np.random.RandomState(1234) r = rstate.randn(16, 16) # test 2D case only for all wavelet types wavelist = pywt.wavelist() if 'dmey' in wavelist: wavelist.remove('dmey') for wavelet in wavelist: for mode in pywt.Modes.modes: coeffs = pywt.dwtn(r, wavelet, mode=mode) assert_allclose(pywt.idwtn(coeffs, wavelet, mode=mode), r, rtol=1e-7, atol=1e-7)
def multi_compress(data, iterations=3): stds = [] for image in data: stds.append(std(image, axis=(0, 1))) order = [] itdata = data for it in range(iterations): r = dwtn(itdata, 'db1') aaa = r['aaa'] aad = r['aad'] ada = r['ada'] add = r['add'] daa = r['daa'] dad = r['dad'] dda = r['dda'] ddd = r['ddd'] itdata = aaa order += [ddd, dda, dad, daa, add, ada, aad] if it == iterations - 1: order.append(aaa) for block in order: for m, _std in zip(block, stds): rows = len(m) cols = len(m[0]) for r in range(rows): for c in range(cols): if abs(m[r][c]) < _std: m[r][c] = 0 itll = order.pop() for it in range(iterations): aad = order.pop() ada = order.pop() add = order.pop() daa = order.pop() dad = order.pop() dda = order.pop() ddd = order.pop() r = { 'aaa': itll, 'aad': aad, 'ada': ada, 'add': add, 'daa': daa, 'dad': dad, 'dda': dda, 'ddd': ddd, } itll = idwtn(r, 'db1') return itll
def test_3D_reconstruct(): data = np.array([[[0, 4, 1, 5, 1, 4], [0, 5, 26, 3, 2, 1], [5, 8, 2, 33, 4, 9], [2, 5, 19, 4, 19, 1]], [[1, 5, 1, 2, 3, 4], [7, 12, 6, 52, 7, 8], [2, 12, 3, 52, 6, 8], [5, 2, 6, 78, 12, 2]]]) wavelet = pywt.Wavelet('haar') for mode in pywt.Modes.modes: d = pywt.dwtn(data, wavelet, mode=mode) assert_allclose(data, pywt.idwtn(d, wavelet, mode=mode), rtol=1e-13, atol=1e-13)
def test_idwtn_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 coefs = pywt.dwtn(data, 'haar', axes=(1, 1)) # verify setting coefficients to None is the same as zeroing them coefs['dd'] = np.zeros_like(coefs['dd']) result_zeros = pywt.idwtn(coefs, 'haar', axes=(1, 1)) coefs['dd'] = None result_none = pywt.idwtn(coefs, 'haar', axes=(1, 1)) assert_equal(result_zeros, result_none)
def pyramid_data(self): # data normalization ref_data = ((self.ref_data - np.ndarray.mean(self.ref_data, axis=0)) / np.ndarray.std(self.ref_data, axis=0)) img_data = ((self.img_data - np.ndarray.mean(self.img_data, axis=0)) / np.ndarray.std(self.img_data, axis=0)) ref_pyramid = [] img_pyramid = [] prColor( 'obtain pyramid image with pyramid level: {}'.format( self.pyramid_level), 'green') ref_pyramid.append(ref_data) img_pyramid.append(img_data) for kk in range(self.pyramid_level): ref_pyramid.append( pywt.dwtn(ref_pyramid[kk], 'db3', mode='zero', axes=(-2, -1))['aa']) img_pyramid.append( pywt.dwtn(img_pyramid[kk], 'db3', mode='zero', axes=(-2, -1))['aa']) return ref_pyramid, img_pyramid
def test_idwtn_mixed_complex_dtype(): rstate = np.random.RandomState(0) x = rstate.randn(8, 8, 8) x = x + 1j * x coeffs = pywt.dwtn(x, 'db2') x_roundtrip = pywt.idwtn(coeffs, 'db2') assert_allclose(x_roundtrip, x, rtol=1e-10) # mismatched dtypes OK coeffs['a' * x.ndim] = coeffs['a' * x.ndim].astype(np.complex64) x_roundtrip2 = pywt.idwtn(coeffs, 'db2') assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7) assert_(x_roundtrip2.dtype == np.complex128)
def test_idwtn_mixed_complex_dtype(): rstate = np.random.RandomState(0) x = rstate.randn(8, 8, 8) x = x + 1j*x coeffs = pywt.dwtn(x, 'db2') x_roundtrip = pywt.idwtn(coeffs, 'db2') assert_allclose(x_roundtrip, x, rtol=1e-10) # mismatched dtypes OK coeffs['a' * x.ndim] = coeffs['a' * x.ndim].astype(np.complex64) x_roundtrip2 = pywt.idwtn(coeffs, 'db2') assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7) assert_(x_roundtrip2.dtype == np.complex128)
def test_idwtn_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 coefs = pywt.dwtn(data, 'haar', axes=(1, 1)) # verify setting coefficients to None is the same as zeroing them coefs['dd'] = np.zeros_like(coefs['dd']) result_zeros = pywt.idwtn(coefs, 'haar', axes=(1, 1)) coefs['dd'] = None result_none = pywt.idwtn(coefs, 'haar', axes=(1, 1)) assert_equal(result_zeros, result_none)
def test_3D_reconstruct(): # All dimensions even length so `take` does not need to be specified data = np.array([[[0, 4, 1, 5, 1, 4], [0, 5, 26, 3, 2, 1], [5, 8, 2, 33, 4, 9], [2, 5, 19, 4, 19, 1]], [[1, 5, 1, 2, 3, 4], [7, 12, 6, 52, 7, 8], [2, 12, 3, 52, 6, 8], [5, 2, 6, 78, 12, 2]]]) wavelet = pywt.Wavelet('haar') d = pywt.dwtn(data, wavelet) # idwtn creates even-length shapes (2x dwtn size) original_shape = [slice(None, s) for s in data.shape] assert_allclose(data, pywt.idwtn(d, wavelet)[original_shape], rtol=1e-13, atol=1e-13)
def test_3D_reconstruct_complex(): # All dimensions even length so `take` does not need to be specified data = np.array( [ [[0, 4, 1, 5, 1, 4], [0, 5, 26, 3, 2, 1], [5, 8, 2, 33, 4, 9], [2, 5, 19, 4, 19, 1]], [[1, 5, 1, 2, 3, 4], [7, 12, 6, 52, 7, 8], [2, 12, 3, 52, 6, 8], [5, 2, 6, 78, 12, 2]], ] ) data = data + 1j wavelet = pywt.Wavelet("haar") d = pywt.dwtn(data, wavelet) # idwtn creates even-length shapes (2x dwtn size) original_shape = [slice(None, s) for s in data.shape] assert_allclose(data, pywt.idwtn(d, wavelet)[original_shape], rtol=1e-13, atol=1e-13)
def test_dwdtn_idwtn_allwavelets(): rstate = np.random.RandomState(1234) r = rstate.randn(16, 16) # test 2D case only for all wavelet types wavelist = pywt.wavelist() if 'dmey' in wavelist: wavelist.remove('dmey') for wavelet in wavelist: if wavelet in ['cmor', 'shan', 'fbsp']: # skip these CWT families to avoid warnings continue if isinstance(pywt.DiscreteContinuousWavelet(wavelet), pywt.Wavelet): for mode in pywt.Modes.modes: coeffs = pywt.dwtn(r, wavelet, mode=mode) assert_allclose(pywt.idwtn(coeffs, wavelet, mode=mode), r, rtol=1e-7, atol=1e-7)
def estimate_noise_sigma_dwt(arr, wavelet='dmey', mode='symmetric', axes=None, estimator=lambda d: np.std(d), correction=lambda s, x: s - s / np.std(x)): """ Estimate of the noise standard deviation with discrete wavelet transform. This is computed from the single-level discrete wavelete transform (DWT) details coefficients. Default values are for Gaussian distribution. Other distribution may require tweaking. Args: arr (np.ndarray): The input array. wavelet (str|pw.Wavelet): The wavelet to use. See `pw.dwtn()` and `pw.wavelist()` for more info. mode (str): Signal extension mode. See `pw.dwtn()` and `pw.Modes()` for more info. axes (Iterable[int]|None): Axes over which to perform the DWT. See `pw.dwtn()` for more info. estimator (callable): The estimator to use. Must accept an `np.ndarray` as its first argument. Sensible options may be: - `np.std` - `lambda x: np.median(np.abs(x)) / sp.stats.norm.ppf(0.75)` - `lambda x: np.std(x) / np.mean(np.abs(x)) - 1 correction (callable|None): Correct for signal bias. Returns: sigma (float): The estimate of the noise standard deviation. """ coeffs = pw.dwtn(arr, wavelet=wavelet, mode=mode, axes=axes) # select details coefficients in all dimensions d_coeffs = coeffs['d' * arr.ndim] # d_coeffs = d_coeffs[np.nonzero(d_coeffs)] sigma = estimator(d_coeffs) if correction: sigma = correction(sigma, arr) return sigma
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") coefs = pywt.dwtn(data, wavelet) # No point removing zero, or all for num_missing in range(1, len(coefs)): for missing in combinations(coefs.keys(), num_missing): missing_coefs = coefs.copy() for key in missing: del missing_coefs[key] LL = missing_coefs.get("aa", None) HL = missing_coefs.get("da", None) LH = missing_coefs.get("ad", None) HH = missing_coefs.get("dd", None) assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet), pywt.idwtn(missing_coefs, "haar"), 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') coefs = pywt.dwtn(data, wavelet) # No point removing zero, or all for num_missing in range(1, len(coefs)): for missing in combinations(coefs.keys(), num_missing): missing_coefs = coefs.copy() for key in missing: del missing_coefs[key] LL = missing_coefs.get('aa', None) HL = missing_coefs.get('da', None) LH = missing_coefs.get('ad', None) HH = missing_coefs.get('dd', None) assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet), pywt.idwtn(missing_coefs, 'haar'), atol=1e-15)
def estimate_sigma(image, average_sigmas=False, multichannel=False): """ Robust wavelet-based estimator of the (Gaussian) noise standard deviation. Parameters ---------- image : ndarray Image for which to estimate the noise standard deviation. average_sigmas : bool, optional If true, average the channel estimates of `sigma`. Otherwise return a list of sigmas corresponding to each channel. multichannel : bool Estimate sigma separately for each channel. Returns ------- sigma : float or list Estimated noise standard deviation(s). If `multichannel` is True and `average_sigmas` is False, a separate noise estimate for each channel is returned. Otherwise, the average of the individual channel estimates is returned. """ if multichannel: nchannels = image.shape[-1] sigmas = [ estimate_sigma(image[..., c], multichannel=False) for c in range(nchannels) ] if average_sigmas: sigmas = np.mean(sigmas) return sigmas elif image.shape[-1] <= 4: msg = ("image is size {0} on the last axis, but multichannel is " "False. If this is a color image, please set multichannel " "to True for proper noise estimation.") warn(msg.format(image.shape[-1])) coeffs = pywt.dwtn(image, wavelet='db2') detail_coeffs = coeffs['d' * image.ndim] return _sigma_est_dwt(detail_coeffs, distribution='Gaussian')
def setup(self, D, n, wavelet): super(IdwtnTimeSuite, self).setup(D, n, wavelet) self.data = pywt.dwtn(self.data, wavelet)
def time_dwtn(self, D, n, wavelet): pywt.dwtn(self.data, wavelet)
#!/usr/bin/env python import pprint import numpy import pywt data = numpy.ones((4, 4, 4, 4)) # 4D array result = pywt.dwtn(data , 'db1') # sixteen 4D coefficient arrays pprint.pprint(result)
""" https://pywavelets.readthedocs.io/en/latest/ref/nd-dwt-and-idwt.html """ import pywt import numpy as np # nD Single level data = np.ones((4, 4, 4, 4), dtype=np.float64) print(data) coeffs = pywt.dwtn( data, 'haar' ) # decomposition: Single-level n-dimensional Discrete Wavelet Transform. for key in coeffs.keys(): print(coeffs[key]) rec = pywt.idwtn( coeffs, 'haar' ) # reconstruction: Single-level n-dimensional Inverse Discrete Wavelet Transform. print(rec) print() # nD Multi level coeffs = pywt.wavedecn(np.ones((4, 4, 4, 4)), 'db1') # decomposition print(len(coeffs) - 1) for i in range(len(coeffs)): v = coeffs[i] if isinstance(v, np.ndarray): print(v) else: for key in v.keys(): print(v[key])
def apply_wavelet(img_arr): coeffs2 = pywt.dwtn(img_arr, 'sym4') return coeffs2
def test_idwtn_axes_subsets(): data = np.array(np.random.standard_normal((4, 4, 4, 4))) # test all combinations of 3 out of 4 axes transformed for axes in combinations((0, 1, 2, 3), 3): coefs = pywt.dwtn(data, 'haar', axes=axes) assert_allclose(pywt.idwtn(coefs, 'haar', axes=axes), data, atol=1e-14)
# ax = fig.add_subplot(2, 2, i + 1) # ax.imshow(a, origin='image', interpolation="nearest", cmap=plt.cm.gray) # ax.set_title(titles[i], fontsize=12) #fig.suptitle("dwt2 coefficients", fontsize=14) # Now reconstruct and plot the original image reconstructed = pywt.idwt2(coeffs2, 'bior1.3') fig = plt.figure() plt.imshow(reconstructed, interpolation="nearest") # Check that reconstructed image is close to the original # Now do the same with dwtn/idwtn, to show the difference in their signatures coeffsn = pywt.dwtn(original, 'bior1.3') fig = plt.figure() #for i, key in enumerate(['aa', 'ad', 'da', 'dd']): # ax = fig.add_subplot(2, 2, i + 1) # ax.imshow(coeffsn[key], origin='image', interpolation="nearest", # cmap=plt.cm.gray) # ax.set_title(titles[i], fontsize=12) #fig.suptitle("dwtn coefficients", fontsize=14) # Now reconstruct and plot the original image reconstructed = pywt.idwtn(coeffsn, 'bior1.3') fig = plt.figure() plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray) # Check that reconstructed image is close to the original
counter += 1 f.close() a = numpy.array(data_list) # conversion of input data into array d = numpy.shape(a) # Dimension of input data array t = numpy.size(a) # total no. of elements in input data array w = pywt.Wavelet('db20') # wavelet object with handle max_ld = pywt.dwt_max_level(t,w) # maximum useful decomposition level of given input data length(total elements) and wavelet object results = pywt.dwtn(a, w, max_ld) # N-Dimensional DWT on huggies data pprint.pprint(results) # print results t2 = numpy.size(results) # total no. of elements in results lpd = w.dec_lo # decomposition filter coefficients of LPF for the defined wavelet hpd = w.dec_hi # decomposition filter coefficients of HPF for the defined wavelet lpr = w.rec_lo # reconstruction filter coefficients of LPF for the defined wavelet hpr = w.rec_hi # reconstruction filter coefficients of HPF for the defined wavelet dl = int(w.dec_len) # Decomposition filter length for the defined wavelet
def estimate_sigma(image, average_sigmas=False, multichannel=False, *, channel_axis=None): """ Robust wavelet-based estimator of the (Gaussian) noise standard deviation. Parameters ---------- image : ndarray Image for which to estimate the noise standard deviation. average_sigmas : bool, optional If true, average the channel estimates of `sigma`. Otherwise return a list of sigmas corresponding to each channel. multichannel : bool Estimate sigma separately for each channel. This argument is deprecated: specify `channel_axis` instead. channel_axis : int or None, optional If None, the image is assumed to be a grayscale (single channel) image. Otherwise, this parameter indicates which axis of the array corresponds to channels. .. versionadded:: 0.19 ``channel_axis`` was added in 0.19. Returns ------- sigma : float or list Estimated noise standard deviation(s). If `multichannel` is True and `average_sigmas` is False, a separate noise estimate for each channel is returned. Otherwise, the average of the individual channel estimates is returned. Notes ----- This function assumes the noise follows a Gaussian distribution. The estimation algorithm is based on the median absolute deviation of the wavelet detail coefficients as described in section 4.2 of [1]_. References ---------- .. [1] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. :DOI:`10.1093/biomet/81.3.425` Examples -------- >>> import skimage.data >>> from skimage import img_as_float >>> img = img_as_float(skimage.data.camera()) >>> sigma = 0.1 >>> rng = np.random.default_rng() >>> img = img + sigma * rng.standard_normal(img.shape) >>> sigma_hat = estimate_sigma(img, channel_axis=None) """ if channel_axis is not None: channel_axis = channel_axis % image.ndim _at = functools.partial(utils.slice_at_axis, axis=channel_axis) nchannels = image.shape[channel_axis] sigmas = [ estimate_sigma(image[_at(c)], channel_axis=None) for c in range(nchannels) ] if average_sigmas: sigmas = np.mean(sigmas) return sigmas elif image.shape[-1] <= 4: msg = f'image is size {image.shape[-1]} on the last axis, '\ f'but channel_axis is None. If this is a color image, '\ f'please set channel_axis=-1 for proper noise estimation.' warn(msg) coeffs = pywt.dwtn(image, wavelet='db2') detail_coeffs = coeffs['d' * image.ndim] return _sigma_est_dwt(detail_coeffs, distribution='Gaussian')
def wavelet_decomposition3d(x, wbasis, mode, nscales): """Discrete 3D multiresolution wavelet decomposition. Compute the discrete 3D multiresolution wavelet decomposition at the given level (nscales) for a given 3D image. Utilizes a `n-dimensional PyWavelet <http://www.pybytes.com/pywavelets/ref/other-functions.html>`_ function ``pywt.dwtn``. Parameters ---------- x : `DiscreteLpVector` wbasis : ``pywt.Wavelet`` Selected wavelet basis. For more information see the `PyWavelets documentation on wavelet bases <http://www.pybytes.com/pywavelets/ref/wavelets.html>`_. mode : `str` Signal extention mode. For possible extensions see the `Pywavelets documentation on signal extenstion modes <http://www.pybytes.com/pywavelets/ref/\ signal-extension-modes.html>`_. nscales : `int` Number of scales in the coefficient list. Returns ------- coeff_list : `list` A list of coefficient organized in the following way ```[aaaN, (aadN, adaN, addN, daaN, dadN, ddaN, dddN), ... (aad1, ada1, add1, daa1, dad1, dda1, ddd1)]``` . The abbreviations refer to ``aaa`` = approx. on 1st dim, approx. on 2nd dim, approx. on 3rd dim, ``aad`` = approx. on 1st dim, approx. on 2nd dim, detail on 3rd dim, ``ada`` = approx. on 1st dim, detail on 3nd dim, approx. on 3rd dim, ``add`` = approx. on 1st dim, detail on 3nd dim, detail on 3rd dim, ``daa`` = detail on 1st dim, approx. on 2nd dim, approx. on 3rd dim, ``dad`` = detail on 1st dim, approx. on 2nd dim, detail on 3rd dim, ``dda`` = detail on 1st dim, detail on 2nd dim, approx. on 3rd dim, ``ddd`` = detail on 1st dim, detail on 2nd dim, detail on 3rd dim, ``N`` = the number of scaling levels """ wcoeffs = pywt.dwtn(x, wbasis, mode) aaa = wcoeffs['aaa'] aad = wcoeffs['aad'] ada = wcoeffs['ada'] add = wcoeffs['add'] daa = wcoeffs['daa'] dad = wcoeffs['dad'] dda = wcoeffs['dda'] ddd = wcoeffs['ddd'] details = (aad, ada, add, daa, dad, dda, ddd) coeff_list = [] coeff_list.append(details) for _ in range(1, nscales): wcoeffs = pywt.dwtn(aaa, wbasis, mode) aaa = wcoeffs['aaa'] aad = wcoeffs['aad'] ada = wcoeffs['ada'] add = wcoeffs['add'] daa = wcoeffs['daa'] dad = wcoeffs['dad'] dda = wcoeffs['dda'] ddd = wcoeffs['ddd'] details = (aad, ada, add, daa, dad, dda, ddd) coeff_list.append(details) coeff_list.append(aaa) coeff_list.reverse() return coeff_list
def wavelet_transform(image): return pywt.dwtn(image, 'coif1')
def pywt_single_level_decomp(arr, wavelet, mode): """Return single level wavelet decomposition coefficients from ``arr``. Parameters ---------- arr : `array-like` Input array to the wavelet decomposition. wavelet : string or `pywt.Wavelet` Specification of the wavelet to be used in the transform. If a string is given, it is converted to a `pywt.Wavelet`. Use `pywt.wavelist` to get a list of available wavelets. mode : string, optional PyWavelets style signal extension mode. See `signal extension modes`_ for available options. Returns ------- approx : `numpy.ndarray` Approximation coefficients, a single array. details : tuple of `numpy.ndarray`'s Detail coefficients, ``2 ** ndim - 1`` arrays, where ``ndim`` is the number of dimensions of ``arr``. See Also -------- pywt_single_level_recon : Single-level reconstruction, i.e. the inverse of this function. pywt_multi_level_decomp : Multi-level version of the decompostion. Examples -------- Decomposition of a small two-dimensional array using a Haar wavelet and zero padding: >>> arr = [[1, 1, 1], ... [1, 0, 0], ... [0, 1, 1]] >>> coeffs = pywt_single_level_decomp(arr, wavelet='haar', mode='zero') >>> approx, details = coeffs >>> print(approx) [[ 1.5 0.5] [ 0.5 0.5]] >>> for detail in details: ... print(detail) [[ 0.5 0.5] [-0.5 0.5]] [[ 0.5 0.5] [ 0.5 0.5]] [[-0.5 0.5] [-0.5 0.5]] References ---------- .. _signal extension modes: https://pywavelets.readthedocs.io/en/latest/ref/signal-extension-\ modes.html """ # Handle input arr = np.asarray(arr) wavelet = pywt_wavelet(wavelet) mode, mode_in = str(mode).lower(), mode if mode not in PYWT_SUPPORTED_MODES: raise ValueError("mode '{}' not understood".format(mode_in)) # Compute single level DWT using pywt.dwtn and pick the approximation # and detail coefficients from the dictionary coeff_dict = pywt.dwtn(arr, wavelet, mode) dict_keys = pywt_dict_keys(arr.ndim) approx = coeff_dict[dict_keys[0]] details = tuple(coeff_dict[k] for k in dict_keys[1:]) return approx, details
#!/usr/bin/env python import pprint import numpy import pywt data = numpy.ones((4, 4, 4, 4)) # 4D array result = pywt.dwtn(data, 'db1') # sixteen 4D coefficient arrays pprint.pprint(result)
def test_idwtn_axes(): data = np.array([[0, 1, 2, 3], [1, 1, 1, 1], [1, 4, 2, 8]]) data = data + 1j * data # test with complex data coefs = pywt.dwtn(data, 'haar', axes=(1, 1)) assert_allclose(pywt.idwtn(coefs, 'haar', axes=(1, 1)), data, atol=1e-14)
ax.set_title(titles[i], fontsize=12) fig.suptitle("dwt2 coefficients", fontsize=14) # Now reconstruct and plot the original image reconstructed = pywt.idwt2(coeffs2, 'bior1.3') fig = plt.figure() plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray) # Check that reconstructed image is close to the original np.testing.assert_allclose(original, reconstructed, atol=1e-13, rtol=1e-13) # Now do the same with dwtn/idwtn, to show the difference in their signatures coeffsn = pywt.dwtn(original, 'bior1.3') fig = plt.figure() for i, key in enumerate(['aa', 'ad', 'da', 'dd']): ax = fig.add_subplot(2, 2, i + 1) ax.imshow(coeffsn[key], origin='image', interpolation="nearest", cmap=plt.cm.gray) ax.set_title(titles[i], fontsize=12) fig.suptitle("dwtn coefficients", fontsize=14) # Now reconstruct and plot the original image reconstructed = pywt.idwtn(coeffsn, 'bior1.3') fig = plt.figure() plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray) # Check that reconstructed image is close to the original