Ejemplo n.º 1
0
def test_swt2_axes():
    atol = 1e-14
    current_wavelet = pywt.Wavelet('db2')
    input_length_power = int(
        np.ceil(np.log2(max(current_wavelet.dec_len,
                            current_wavelet.rec_len))))
    input_length = 2**(input_length_power)
    X = np.arange(input_length**2).reshape(input_length, input_length)
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', FutureWarning)
        (cA1, (cH1, cV1, cD1)) = pywt.swt2(X, current_wavelet, level=1)[0]
        # opposite order
        (cA2, (cH2, cV2, cD2)) = pywt.swt2(X,
                                           current_wavelet,
                                           level=1,
                                           axes=(1, 0))[0]
        assert_allclose(cA1, cA2, atol=atol)
        assert_allclose(cH1, cV2, atol=atol)
        assert_allclose(cV1, cH2, atol=atol)
        assert_allclose(cD1, cD2, atol=atol)

        # duplicate axes not allowed
        assert_raises(ValueError,
                      pywt.swt2,
                      X,
                      current_wavelet,
                      1,
                      axes=(0, 0))
        # too few axes
        assert_raises(ValueError, pywt.swt2, X, current_wavelet, 1, axes=(0, ))
Ejemplo n.º 2
0
def get_swt(shape, wname, levels):
    """ returns stationary wavelet transforms for a given image shape
	"""
    # get slices for pywt array <--> coeff conversion
    coeffs = pywt.swt2(np.zeros(shape), wname, levels, trim_approx=True)
    _, swt_slices = coeffs_to_array(coeffs)
    # stationary/undecimated wavelet transform
    iswt = lambda x: pywt.iswt2(array_to_coeffs(x, swt_slices, 'wavedec2'),
                                wname)
    swt = lambda x: coeffs_to_array(
        pywt.swt2(x, wname, levels, trim_approx=True))[0]
    return swt, iswt
Ejemplo n.º 3
0
def swt2d(img, wavelet='bior2.2', level=2):
    if img.ndim == 2:
        img = np.expand_dims(img, axis=2)

    nc = img.shape[2]
    coeffs = [
        pywt.swt2(img[:, :, c], wavelet=wavelet, level=level)
        for c in range(nc)
    ]
    # print("len(coeffs):", len(coeffs))

    approx_list = []
    detail_list = []

    for c in range(nc):
        detail_list.append(coeffs[c][0][0])

    for coeff in zip(*coeffs):
        # print("len(coeff):", len(coeff))

        for c in range(nc):
            # print("len(coeff[{}]: {}".format(c, len(coeff[c])))
            approx_list.append(coeff[c][0])

        for d in zip(*[coeff[i][1] for i in range(nc)]):
            for di in range(nc):
                detail_list.append(d[di])

    # print("len(approx_list):", len(approx_list))
    # print("len(detail_list):", len(detail_list))
    return approx_list, detail_list
 def _transform(self, image, channel=['r']):
     new_image = self._pad(image)
     wave = pywt.Wavelet(self._wavelet)
     cA_1, (cH_1, cV_1, cD_1) = pywt.swt2(new_image,
                                          wave,
                                          level=1,
                                          start_level=1)[0]
     if self._mode == 'rebuild':
         cA = np.zeros_like(cA_1)
         coeffs = ((cA, (cH_1, cV_1, cD_1)), )
         reb_image = pywt.iswt2(coeffs, wave)
         channels = (channel, 'high_pass')
         return channels, (image, self._unpad(reb_image))
     elif self._mode == 'features':
         channels = (channel, 'cH', 'cV', 'cD')
         return channels, (image, self._unpad(cH_1), self._unpad(cV_1),
                           self._unpad(cD_1))
     elif self._mode == 'features-all':
         channels = (channel, 'cA', 'cH', 'cV', 'cD')
         return channels, (image, self._unpad(cA_1), self._unpad(cH_1),
                           self._unpad(cV_1), self._unpad(cD_1))
     elif self._mode == 'features-only':
         channels = ('cA', 'cH', 'cV', 'cD')
         return channels, (self._unpad(cA_1), self._unpad(cH_1),
                           self._unpad(cV_1), self._unpad(cD_1))
Ejemplo n.º 5
0
def test_iswt2_mixed_dtypes():
    # Mixed precision inputs give double precision output
    rstate = np.random.RandomState(0)
    x_real = rstate.randn(8, 8)
    x_complex = x_real + 1j*x_real
    wav = 'sym2'
    for dtype1, dtype2 in [(np.float64, np.float32),
                           (np.float32, np.float64),
                           (np.float16, np.float64),
                           (np.complex128, np.complex64),
                           (np.complex64, np.complex128)]:

        if dtype1 in [np.complex64, np.complex128]:
            x = x_complex
            output_dtype = np.complex128
        else:
            x = x_real
            output_dtype = np.float64

        coeffs = pywt.swt2(x, wav, 2)
        # different precision for the approximation coefficients
        coeffs[0] = [coeffs[0][0].astype(dtype1),
                     tuple([c.astype(dtype2) for c in coeffs[0][1]])]
        y = pywt.iswt2(coeffs, wav)
        assert_equal(output_dtype, y.dtype)
        assert_allclose(y, x, rtol=1e-3, atol=1e-3)
Ejemplo n.º 6
0
def test_per_axis_wavelets():
    # tests seperate wavelet for each axis.
    rstate = np.random.RandomState(1234)
    data = rstate.randn(16, 16, 16)
    level = 3

    # wavelet can be a string or wavelet object
    wavelets = (pywt.Wavelet('haar'), 'sym2', 'db4')

    coefs = pywt.swtn(data, wavelets, level=level)
    assert_allclose(pywt.iswtn(coefs, wavelets), data, atol=1e-14)

    # 1-tuple also okay
    coefs = pywt.swtn(data, wavelets[:1], level=level)
    assert_allclose(pywt.iswtn(coefs, wavelets[:1]), data, atol=1e-14)

    # length of wavelets doesn't match the length of axes
    assert_raises(ValueError, pywt.swtn, data, wavelets[:2], level)
    assert_raises(ValueError, pywt.iswtn, coefs, wavelets[:2])

    with warnings.catch_warnings():
        warnings.simplefilter('ignore', FutureWarning)
        # swt2/iswt2 also support per-axis wavelets/modes
        data2 = data[..., 0]
        coefs2 = pywt.swt2(data2, wavelets[:2], level)
        assert_allclose(pywt.iswt2(coefs2, wavelets[:2]), data2, atol=1e-14)
Ejemplo n.º 7
0
def test_iswt2_2d_only():
    # iswt2 is not currently compatible with data that is not 2D
    x_3d = np.ones((4, 4, 4))
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', FutureWarning)
        c = pywt.swt2(x_3d, 'haar', level=1)
        assert_raises(ValueError, pywt.iswt2, c, 'haar')
Ejemplo n.º 8
0
    def get_swt_coeffs(self, img, wavelet='db1', downsample="True"):

        p = self.get_image(img, gray=True)

        # downsampling
        if downsample:
            p = pywt.dwt2(p, wavelet)[0]

        # calculate maximum decomposition level
        l_max = pywt.swt_max_level(min(np.shape(p)))
        self.max_level = l_max

        # Multilevel 2D stationary wavelet transform with wavelet filters.
        coefs = pywt.swt2(p,
                          wavelet,
                          l_max,
                          start_level=0,
                          trim_approx=True,
                          norm=True)

        # converting from float64 to uint8 to save memory
        coefs[0] = coefs[0].astype(np.uint8)
        for level in range(1, l_max):
            coefs[level] = list(coefs[level])
            for band in range(3):
                picture = np.asarray(coefs[level][band])
                picture -= np.min(picture)
                picture *= 255 / np.max(picture)
                picture = picture.astype(np.uint8)
                coefs[level][band] = picture
        return coefs
Ejemplo n.º 9
0
def calculateChannelCoefficients(C, channel, num, lock):
    # Pad the image so that there is a border large enough so that edge artifacts don't occur
    padding = 2**(Sharpen.LEVEL)
    C = cv2.copyMakeBorder(C, padding, padding, padding, padding, cv2.BORDER_REFLECT)
    
    # Pad so that dimensions are multiples of 2**level
    h, w = C.shape[:2]
    
    hR = (h % 2**Sharpen.LEVEL)
    wR = (w % 2**Sharpen.LEVEL)

    C = cv2.copyMakeBorder(C, 0, (2**Sharpen.LEVEL - hR), 0, (2**Sharpen.LEVEL - wR), cv2.BORDER_REFLECT)
    
    C =  np.float32(C)
    C /= 255

    # Compute coefficients
    g.coeffs = list(swt2(C, 'haar', level=Sharpen.LEVEL, trim_approx=True))
    g.channel = channel
    
    # Make sure that the other processes have completed as well
    with lock:
        num.value += 1
    while(num.value < 3):
        sleep(0.01)
Ejemplo n.º 10
0
def test_swt2_iswt2_integration():
    # This function performs a round-trip swt2/iswt2 transform test on
    # all available types of wavelets in PyWavelets - except the
    # 'dmey' wavelet. The latter has been excluded because it does not
    # produce very precise results. This is likely due to the fact
    # that the 'dmey' wavelet is a discrete approximation of a
    # continuous wavelet. All wavelets are tested up to 3 levels. The
    # test validates neither swt2 or iswt2 as such, but it does ensure
    # that they are each other's inverse.

    max_level = 3
    wavelets = pywt.wavelist()
    if 'dmey' in wavelets:
        # The 'dmey' wavelet seems to be a bit special - disregard it for now
        wavelets.remove('dmey')
    for current_wavelet_str in wavelets:
        current_wavelet = pywt.Wavelet(current_wavelet_str)
        input_length_power = int(np.ceil(np.log2(max(
            current_wavelet.dec_len,
            current_wavelet.rec_len))))
        input_length = 2**(input_length_power + max_level - 1)
        X = np.arange(input_length**2).reshape(input_length, input_length)
        coeffs = pywt.swt2(X, current_wavelet, max_level)
        Y = pywt.iswt2(coeffs, current_wavelet)
        assert_allclose(Y, X, rtol=1e-5, atol=1e-5)
def w2d(img, mode='bior5.5', level=1):
    # show wavelet decomp for fits images

    imArray = fits.getdata(img)
    # DataPrep conversions
    imArray[imArray < 0.1] = 0.1
    imArray = np.float32(np.sqrt(imArray))
    imArray /= imArray.max();

    # compute coefficients
    lw = pywt.swt2(imArray, mode, level=level)[0]

    plt.subplot(221)
    plt.imshow(lw[0], cmap='gray')
    plt.axis('off')
    plt.subplot(222)

    plt.imshow(np.abs(lw[1][0]), cmap='gray')
    plt.axis('off')
    plt.subplot(223)
    plt.imshow(np.abs(lw[1][1]), cmap='gray')
    plt.axis('off')
    plt.subplot(224)
    plt.imshow(np.abs(lw[1][2]), cmap='gray')
    plt.axis('off')
    plt.subplots_adjust(wspace=0, hspace=0)
Ejemplo n.º 12
0
 def setup(self, n, wavelet):
     try:
         from pywt import iswt2
     except ImportError:
         raise NotImplementedError("iswt2 not available")
     super(Iswt2TimeSuite, self).setup(n, wavelet)
     self.data = pywt.swt2(self.data, wavelet, self.level)
Ejemplo n.º 13
0
def swt_lv2_dict(img, wavelet='bior2.2'):
    """
    2019.11.29
    It seems that trim_approx option behaves differently from the document.
    If trim_approx is False, approximation is shown in every level.
    Approximation should be included to recover original image from wavelet transform coefficients

    For 1D stationary wavelet transform, the document is writtne correctly
    """
    coeffs = pywt.swt2(img,
                       wavelet=wavelet,
                       level=2,
                       start_level=0,
                       axes=(-2, -1),
                       trim_approx=True)
    LL2, LL, HH = coeffs
    LH2, HL2, HH2 = LL
    LH1, HL1, HH1 = HH

    coeffs_dict = {}
    coeffs_dict['LL2'] = LL2
    coeffs_dict['LH2'] = LH2
    coeffs_dict['HL2'] = HL2
    coeffs_dict['HH2'] = HH2
    coeffs_dict['LH1'] = LH1
    coeffs_dict['HL1'] = HL1
    coeffs_dict['HH1'] = HH1

    return coeffs_dict
Ejemplo n.º 14
0
def procChanSWT(img, wavelet, nLevels):
    wt = pywt.swt2(img, wavelet=wavelet, level=nLevels)
    fv = []
    for l in xrange(1, nLevels):
        for x in wt[l][1]:
            fv.append(np.std(x))
            fv.append(np.mean(x))
    return fv
Ejemplo n.º 15
0
    def apply_wavelet(self,img):
        ################ADDED undecimated isotropic wavelet transform####################
        import pywt
        #Interested in the Stationary Wavelet Transformation or a Trous or starlet (swt2)
        
        #get a median filter for wavelet transformation
        from scipy.signal import medfilt
        
        #Use skimage to create the background gaussian filter
        from scipy.ndimage.filters import gaussian_filter



        #check to see if image is a list if not make it one for convience
        unlist = False
        if not isinstance(img,list):
            img = [img]
            unlist = True

        #processed image list
        nimg = []
        for j,i in enumerate(img):
            #Add wavelet transformation
            wav_img = i.data

            #degrade image for faster comp
            wav_img_low = self.shrink(wav_img,1024,1024)/16.
            d_size = 15
            #get median filter
            n_back = medfilt(wav_img_low,kernel_size=d_size)

            #expand the median filter back to normal size
            n_back = np.repeat(n_back,4,axis=1)
            n_back = np.repeat(n_back,4,axis=0)
            n_back = gaussian_filter(n_back,2)

            #subtract median filter
            img_sub = wav_img-n_back

            #Use Biorthogonal Wavelet
            wavelet = 'bior2.6'

            #use 6 levels
            n_lev = 6
            o_wav = pywt.swt2(img_sub, wavelet, level=n_lev )
            #only use the first 4 (Will need to switch order sometime)
            f_img = pywt.iswt2(o_wav[0:4],wavelet)
            #Add  wavelet back into image
            f_img = f_img+wav_img

            #store the new image and return
            nimg.append(sunpy.map.Map(f_img,i.meta))
        
        #if it was only one file remove list attribute 
        if unlist:
            nimg = nimg[0]

        return nimg
Ejemplo n.º 16
0
def test_swt2_iswt2_non_square(wavelets=None):
    for nrows in [8, 16, 48]:
        X = np.arange(nrows*32).reshape(nrows, 32)
        current_wavelet = 'db1'
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', FutureWarning)
            coeffs = pywt.swt2(X, current_wavelet, level=2)
            Y = pywt.iswt2(coeffs, current_wavelet)
        assert_allclose(Y, X, rtol=tol_single, atol=tol_single)
def edges(path):
    im = Image.open(path).convert('L')
    arr = numpy.fromstring(im.tostring(), numpy.uint8)
    arr.shape = (im.size[1], im.size[0])

    data = pywt.swt2(arr, 'haar', level=3, start_level=0)
    LL, (LH, HL, HH) = data[2]
    pylab.imshow(LH, interpolation='nearest', cmap=pylab.cm.gray)
    pylab.show()
Ejemplo n.º 18
0
def performDywt2(input_image):
    a = pywt.swt2(input_image, 'haar', level=1, start_level=0)
    LL, (LH, HL, HH) = a[0]
    LL = LL / 255
    return {
        'LL': LL,
        'LH': LH,
        'HL': HL,
        'HH': HH
    }
Ejemplo n.º 19
0
def swt2d_c(img, wavelet='bior2.2', level=2):
    coeffs = pywt.swt2(img, wavelet, level=level)

    approx_list = []
    detail_list = []
    detail_list.append(coeffs[0][0])
    for a, d in coeffs:
        approx_list.append(a)
        detail_list.extend(d)

    return approx_list, detail_list
Ejemplo n.º 20
0
def swt_lv2(img, wavelet='bior2.2'):
    coeffs = pywt.swt2(img,
                       wavelet=wavelet,
                       level=2,
                       start_level=0,
                       axes=(-2, -1),
                       trim_approx=True)
    LL2, LL, HH = coeffs
    LH2, HL2, HH2 = LL
    LH1, HL1, HH1 = HH

    return (LL2, LH2, HL2, HH2, LH1, HL1, HH1)
Ejemplo n.º 21
0
def _swt_norm(x, wavelet, level, p=2):
    """Computes the p-norm of the SWT detail coefficients of the input and its gradient."""
    div = 2**math.ceil(math.log2(max(x.shape[1:])))
    pw = pad_width(x.shape, (1, div, div))
    x_pad = np.pad(x, pw, 'symmetric')
    inv = []
    for ch in x_pad:
        coeffs = pywt.swt2(ch, wavelet, level)
        for a, _ in coeffs:
            a[...] = 0
        inv.append(pywt.iswt2(coeffs, wavelet)[pw[1][0]:pw[1][0] + x.shape[1],
                                               pw[2][0]:pw[2][0] + x.shape[2]])
    return p_norm(np.stack(inv), p)
Ejemplo n.º 22
0
 def initialize_wl_operators(self):
     if self.use_decimated:
         H = lambda x: pywt.wavedecn(x, wavelet=self.wl_type, axes=self.axes, level=self.decomp_lvl)
         Ht = lambda x: pywt.waverecn(x, wavelet=self.wl_type, axes=self.axes)
     else:
         if use_swtn:
             H = lambda x: pywt.swtn(x, wavelet=self.wl_type, axes=self.axes, level=self.decomp_lvl)
             Ht = lambda x: pywt.iswtn(x, wavelet=self.wl_type, axes=self.axes)
         else:
             H = lambda x: pywt.swt2(np.squeeze(x), wavelet=self.wl_type, axes=self.axes, level=self.decomp_lvl)
             #                Ht = lambda x : pywt.iswt2(x, wavelet=self.wl_type)
             Ht = lambda x: pywt.iswt2(x, wavelet=self.wl_type)[np.newaxis, ...]
     return (H, Ht)
Ejemplo n.º 23
0
def _swt_norm(x, wavelet, level, p=2):
    """Computes the p-norm of the SWT detail coefficients of the input and its gradient."""
    div = 2**math.ceil(math.log2(max(x.shape[1:])))
    pw = pad_width(x.shape, (1, div, div))
    x_pad = np.pad(x, pw, 'symmetric')
    inv = []
    for ch in x_pad:
        coeffs = pywt.swt2(ch, wavelet, level)
        for a, _ in coeffs:
            a[:] = 0
        inv.append(
            pywt.iswt2(coeffs, wavelet)[pw[1][0]:pw[1][0] + x.shape[1],
                                        pw[2][0]:pw[2][0] + x.shape[2]])
    return p_norm(np.stack(inv), p)
Ejemplo n.º 24
0
def test_swt2_axes():
    atol = 1e-14
    current_wavelet = pywt.Wavelet('db2')
    input_length_power = int(np.ceil(np.log2(max(
        current_wavelet.dec_len,
        current_wavelet.rec_len))))
    input_length = 2**(input_length_power)
    X = np.arange(input_length**2).reshape(input_length, input_length)

    (cA1, (cH1, cV1, cD1)) = pywt.swt2(X, current_wavelet, level=1)[0]
    # opposite order
    (cA2, (cH2, cV2, cD2)) = pywt.swt2(X, current_wavelet, level=1,
                                       axes=(1, 0))[0]
    assert_allclose(cA1, cA2, atol=atol)
    assert_allclose(cH1, cV2, atol=atol)
    assert_allclose(cV1, cH2, atol=atol)
    assert_allclose(cD1, cD2, atol=atol)

    # duplicate axes not allowed
    assert_raises(ValueError, pywt.swt2, X, current_wavelet, 1,
                  axes=(0, 0))
    # too few axes
    assert_raises(ValueError, pywt.swt2, X, current_wavelet, 1, axes=(0, ))
Ejemplo n.º 25
0
def swt2d_rgb(img, wavelet='bior2.2', level=2):
    coeffs_b = pywt.swt2(img[:, :, 0], wavelet, level=level)
    coeffs_g = pywt.swt2(img[:, :, 1], wavelet, level=level)
    coeffs_r = pywt.swt2(img[:, :, 2], wavelet, level=level)

    approx_list = []
    detail_list = []
    detail_list.append(coeffs_b[0][0])
    detail_list.append(coeffs_g[0][0])
    detail_list.append(coeffs_r[0][0])
    for (a_b, d_b), (a_g, d_g), (a_r, d_r) in zip(coeffs_b, coeffs_g,
                                                  coeffs_r):
        approx_list.append(a_b)
        approx_list.append(a_g)
        approx_list.append(a_r)
        # detail_list.extend(d_b)
        # detail_list.extend(d_g)
        # detail_list.extend(d_r)
        for (b, g, r) in zip(d_b, d_g, d_r):
            detail_list.append(b)
            detail_list.append(g)
            detail_list.append(r)
    return approx_list, detail_list
Ejemplo n.º 26
0
def main():
    noise_sigma = 2
    wavelet = 'bior1.3'

    images = list(io.load_fits_images_in_folder('./resources'))
    with PdfPages('multipage.pdf') as pdf:
        for i, (calibrated_image, npe_truth) in tqdm(enumerate(images)):

            fig = plt.figure()
            plt.text(1, 1, 'Event Number: {}'.format(i))
            plt.xlim(0, 2)
            plt.ylim(0, 2)
            plt.axis('off')
            pdf.savefig(fig)
            plt.close()

            # transform the image
            level = pywt.swt_max_level(len(calibrated_image))
            # print('maximum level of decomposition: {}'.format(level))

            coeff_list = pywt.swt2(calibrated_image, wavelet, level)

            fig = plot.coefficients(coeff_list)
            pdf.savefig(figure=fig)
            plt.close()

            levels = [0.889, 0.7, 0.586]
            coeff_list = denoise.thresholding(coeff_list,
                                              sigma_d=noise_sigma,
                                              kind='hard',
                                              sigma_levels=levels)

            # coeff_list = denoise.wiener(coeff_list)
            reconstructed_image = pywt.iswt2(coeff_list, wavelet)

            fig = plot.results(calibrated_image, reconstructed_image,
                               npe_truth)
            pdf.savefig(figure=fig)
            plt.close()

            fig = plot.pixel_histogram(
                reconstructed_image,
                calibrated_image,
                npe_truth,
                labels=['reconstructed', 'calibrated', 'npe mc truth'],
                bins=60)

            pdf.savefig(figure=fig)
            plt.close()
Ejemplo n.º 27
0
def batch_Swt(batch, level=1):
    '''
    Args:
        batch: Input batch RGB image [batch_size, img_h, img_w, 3]
    Returns:
        dwt_batch: Batch  DWT result [batch_size, img_h, img_w, 12]
    '''
    # print(len(batch.shape))
    assert (len(batch.shape) == 4), "Input batch Shape error"
    assert (batch.shape[3] == 3), "Color channel error"

    Swt_batch = np.zeros(
        [batch.shape[0], batch.shape[1], batch.shape[2], 12 * level])

    for i in range(batch.shape[0]):
        coeffs_R = pywt.swt2(batch[i, :, :, 0], 'haar', level=level)
        coeffs_G = pywt.swt2(batch[i, :, :, 1], 'haar', level=level)
        coeffs_B = pywt.swt2(batch[i, :, :, 2], 'haar', level=level)

        for k in range(level):
            # print((level-k)-1)
            (LL_r, (LH_r, HL_r, HH_r)) = coeffs_R[level - k - 1]
            (LL_g, (LH_g, HL_g, HH_g)) = coeffs_G[level - k - 1]
            (LL_b, (LH_b, HL_b, HH_b)) = coeffs_B[level - k - 1]

            coeffs_stack_R = np.stack([LL_r, LH_r, HL_r, HH_r], axis=-1)
            coeffs_stack_G = np.stack([LL_g, LH_g, HL_g, HH_g], axis=-1)
            coeffs_stack_B = np.stack([LL_b, LH_b, HL_b, HH_b], axis=-1)

            # print(coeffs_stack_R.shape)
            coeffs = np.concatenate(
                [coeffs_stack_R, coeffs_stack_G, coeffs_stack_B], axis=-1)

            Swt_batch[i, :, :, 12 * k:12 * (k + 1)] = coeffs

    return Swt_batch
Ejemplo n.º 28
0
def test_swt_dtypes():
    wavelet = pywt.Wavelet('haar')
    for dt_in, dt_out in zip(dtypes_in, dtypes_out):
        errmsg = "wrong dtype returned for {0} input".format(dt_in)

        # swt
        x = np.ones(8, dtype=dt_in)
        (cA2, cD2), (cA1, cD1) = pywt.swt(x, wavelet, level=2)
        assert_(cA2.dtype == cD2.dtype == cA1.dtype == cD1.dtype == dt_out,
                "swt: " + errmsg)

        # swt2
        x = np.ones((8, 8), dtype=dt_in)
        cA, (cH, cV, cD) = pywt.swt2(x, wavelet, level=1)[0]
        assert_(cA.dtype == cH.dtype == cV.dtype == cD.dtype == dt_out,
                "swt2: " + errmsg)
Ejemplo n.º 29
0
def test_swt_roundtrip_dtypes():
    # verify perfect reconstruction for all dtypes
    rstate = np.random.RandomState(5)
    wavelet = pywt.Wavelet('haar')
    for dt_in, dt_out in zip(dtypes_in, dtypes_out):
        # swt, iswt
        x = rstate.standard_normal((8, )).astype(dt_in)
        c = pywt.swt(x, wavelet, level=2)
        xr = pywt.iswt(c, wavelet)
        assert_allclose(x, xr, rtol=1e-6, atol=1e-7)

        # swt2, iswt2
        x = rstate.standard_normal((8, 8)).astype(dt_in)
        c = pywt.swt2(x, wavelet, level=2)
        xr = pywt.iswt2(c, wavelet)
        assert_allclose(x, xr, rtol=1e-6, atol=1e-7)
Ejemplo n.º 30
0
def swt_decomp(Filt, ShapeOrig, ypad, xpad, dcomLvl):
    ims = []
    # noinspection PyUnusedLocal
    for cA, (cH, cV, cD) in pywt.swt2(Filt, 'bior5.5', dcomLvl):
        ims.append(cA)
    wvFilt = np.stack(ims, axis=2)
    del ims

    # via Niyi's method
    wvFilt[:, :, dcomLvl - 1] = Filt.copy()
    del Filt

    # remove zero-padding, if needed
    if ShapeOrig[0] != ShapeOrig[1] or ShapeOrig[0] != int(2**np.ceil(
            np.log2(ShapeOrig[0]))):
        wvFilt = remove_padding(wvFilt, ShapeOrig, ypad, xpad)

    return wvFilt
Ejemplo n.º 31
0
    def swt2(self):
        """
        Test pypwt against pywt for SWT2.
        """
        W = self.W
        levels = self.levels
        wname = self.wname

        # Forward SWT2 with pypwt
        logging.info("computing Wavelets from pypwt")
        t0 = time()
        W.forward()
        logging.info("Wavelets.forward took %.3f ms" % elapsed_ms(t0))

        # Forward SWT2 with pywt
        logging.info("computing wavedec2 from pywt")
        Wpy = pywt.swt2(self.data, self.wname, level=levels)
        logging.info("pywt took %.3f ms" % elapsed_ms(t0))

        # Compare results
        # FIXME: Error increases when levels increase, since output is scaled.
        tol = self.tol * 2**levels

        W_coeffs = W.coeffs
        if (levels != W.levels):
            err_msg = str("compare_coeffs(): pypwt instance has %d levels while pywt instance has %d levels" % (W.levels, levels))
            logging.error(err_msg)
            raise ValueError(err_msg)

        # For now pypwt only returns the last appcoeff
        A = Wpy[levels-1][0]
        maxerr = _calc_errors(A, W_coeffs[0], "[app]")
        self.assertTrue(maxerr < tol, msg="[%s] something wrong with the approximation coefficients (%d levels) (errmax = %e)" % (wname, levels, maxerr))
        for i in range(levels): # wavedec2 format. TODO: pywavelets > 0.5 will use another order
            tol = self.tol * 2**(i+1)
            A, D1, D2, D3 = Wpy[i][0], Wpy[i][1][0], Wpy[i][1][1], Wpy[i][1][2]
            logging.info("%s Level %d %s" % ("-"*5, i+1, "-"*5))
            maxerr = _calc_errors(D1, W_coeffs[i+1][0], "[det.H]")
            self.assertTrue(maxerr < tol, msg="[%s] something wrong with the detail coefficients 1 at level %d (errmax = %e)" % (wname, i+1, maxerr))
            maxerr = _calc_errors(D2, W_coeffs[i+1][1], "[det.V]")
            self.assertTrue(maxerr < tol, msg="[%s] something wrong with the detail coefficients 2 at level %d (errmax = %e)" % (wname, i+1, maxerr))
            maxerr = _calc_errors(D3, W_coeffs[i+1][2], "[det.D]")
            self.assertTrue(maxerr < tol, msg="[%s] something wrong with the detail coefficients 3 at level %d (errmax = %e)" % (wname, i+1, maxerr))
Ejemplo n.º 32
0
    def iswt2(self):
        """
        Test pypwt for DWT2 reconstruction (iswt2).
        """

        W = self.W
        # 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.swt2(self.data, self.wname, level=self.levels)
            logging.info("computing iswt2 from pywt")
            _ = pywt.iswt2(Wpy, self.wname)
            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))
Ejemplo n.º 33
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pylab
import numpy
import Image  # PIL

import pywt

im = Image.open("data/aero.png").convert('L')
arr = numpy.fromstring(im.tostring(), numpy.uint8)
arr.shape = (im.size[1], im.size[0])

pylab.imshow(arr, interpolation="nearest", cmap=pylab.cm.gray)

for LL, (LH, HL, HH) in pywt.swt2(arr, 'bior1.3', level=3, start_level=0):
    pylab.figure()
    for i, a in enumerate([LL, LH, HL, HH]):
        pylab.subplot(2, 2, i + 1)
        pylab.imshow(a, origin='image', interpolation="nearest",
            cmap=pylab.cm.gray)

pylab.show()
Ejemplo n.º 34
0
def test_iswt2_2d_only():
    # iswt2 is not currently compatible with data that is not 2D
    x_3d = np.ones((4, 4, 4))
    c = pywt.swt2(x_3d, 'haar', level=1)
    assert_raises(ValueError, pywt.iswt2, c, 'haar')
Ejemplo n.º 35
0
 def time_swt2(self, n, wavelet):
     pywt.swt2(self.data, wavelet, self.level)