Пример #1
0
def Wavelet_proj(S, lambda_this):
    """
    This function does the Wavelet projection
    """
    S1 = np.reshape(S[0, :], image_size)
    S2 = np.reshape(S[1, :], image_size)
    # Wavelet denoising
    S1 = denoise_wavelet(S1,
                         sigma=lambda_this,
                         multichannel=False,
                         convert2ycbcr=False,
                         method='BayesShrink',
                         mode='soft',
                         rescale_sigma=True)
    S2 = denoise_wavelet(S2,
                         sigma=lambda_this,
                         multichannel=False,
                         convert2ycbcr=False,
                         method='BayesShrink',
                         mode='soft',
                         rescale_sigma=False)

    S[0, :] = np.reshape(S1, (1, image_size[0] * image_size[1]))
    S[1, :] = np.reshape(S2, (1, image_size[0] * image_size[1]))

    return S
Пример #2
0
 def denoise(im, ctx,props={}):
     trange = ctx["noise_trange"]
     perc = ctx["last_frame_stats"]["percentiles_509599"][-1]
     pseudo_ent = ctx["last_frame_stats"]["pseudo_ent"]   
     noise = ctx["last_frame_stats"]["noise"]     
     if ctx.is_frame_degenerate:return im
         
     if trange != None:
         if noise > 0.085:
             ctx.log("estimated noise standard deviation of {:.4f} exceeds 0.085. Thresholding aggressively, smoothing and skipping denoise!".format(noise, trange[1],perc))
             im/=im.max()
             im[im<0.5] = 0
             im/=im.max()
             #smooth a little - these are usually very messy data with a few bright spots here and there
             #I have thinned out and smoothed as a weak attempt to detect signals that can be picked up by pinpoint
             im = preprocessing.smoothing(im,ctx,props={"sigma":1})
             return im
         elif noise > trange[1]:#excessive
             ctx.log("estimated noise standard deviation of {:.4f} exceeds [*,{}]. Thresholding @ 99 percentile {} before denoise...".format(noise, trange[1],perc))
             im[im<perc] = 0
             im/=im.max()
             return denoise_wavelet(im, multichannel=False,  mode='soft')
         elif pseudo_ent < 0.1:#low entropy - i tried this on .2 but .1 seems more sensible looking at plot
             ctx.log("estimated pseudo entropy {:.4f} less than 0.2. Thresholding @ 99 percentile {} before denoise...".format(pseudo_ent, perc))
             im[im<perc] = 0
             im/=im.max()
             return denoise_wavelet(im, multichannel=False,  mode='soft')
         elif noise> trange[0] and noise < trange[1]: #no point denoising if its too noisy perhaps??
             ctx.log("estimated noise standard deviation of {:.4f} is in range of [{},{}]. Applying denoise...".format(noise, *trange))
             return denoise_wavelet(im, multichannel=False,  mode='soft')
         return im
     return denoise_wavelet(im, multichannel=False,  mode='soft')
Пример #3
0
def extract_noise_frame(frame, color=False):
    cropped_frame = cropCenter(frame, CROP_X, CROP_Y)
    if cropped_frame is None:
        print("Less than", CROP_X, "x", CROP_Y)
        return None
    if color:
        noise_b = cropped_frame[:, :, 0] - 255 * denoise_wavelet(
            cropped_frame[:, :, 0],
            wavelet='db8',
            mode='soft',
            wavelet_levels=4,
            multichannel=False)
        noise_g = cropped_frame[:, :, 1] - 255 * denoise_wavelet(
            cropped_frame[:, :, 1],
            wavelet='db8',
            mode='soft',
            wavelet_levels=4,
            multichannel=False)
        noise_r = cropped_frame[:, :, 2] - 255 * denoise_wavelet(
            cropped_frame[:, :, 2],
            wavelet='db8',
            mode='soft',
            wavelet_levels=4,
            multichannel=False)
        noise = noise_r * 0.2989 + noise_g * 0.5870 + noise_b * 0.1140
    else:
        cropped_frame = cv2.cvtColor(cropped_frame, cv2.COLOR_BGR2GRAY)
        noise = cropped_frame - 255 * denoise_wavelet(cropped_frame,
                                                      wavelet='db8',
                                                      mode='soft',
                                                      wavelet_levels=4,
                                                      multichannel=False)
    return noise
Пример #4
0
def test_wavelet_denoising_args(rescale_sigma):
    """
    Some of the functions inside wavelet denoising throw an error the wrong
    arguments are passed. This protects against that and verifies that all
    arguments can be passed.
    """
    img = astro
    noisy = img.copy() + 0.1 * np.random.randn(*(img.shape))

    for convert2ycbcr in [True, False]:
        for multichannel in [True, False]:
            if convert2ycbcr and not multichannel:
                with testing.raises(ValueError):
                    restoration.denoise_wavelet(noisy,
                                                convert2ycbcr=convert2ycbcr,
                                                multichannel=multichannel,
                                                rescale_sigma=rescale_sigma)
                continue
            anticipated_warnings = (PYWAVELET_ND_INDEXING_WARNING
                                    if multichannel else None)
            for sigma in [0.1, [0.1, 0.1, 0.1], None]:
                if (not multichannel and not convert2ycbcr) or \
                        (isinstance(sigma, list) and not multichannel):
                    continue
                with expected_warnings([anticipated_warnings]):
                    restoration.denoise_wavelet(noisy,
                                                sigma=sigma,
                                                convert2ycbcr=convert2ycbcr,
                                                multichannel=multichannel,
                                                rescale_sigma=rescale_sigma)
Пример #5
0
def wavelet_denoising(data):
    '''
    Wavelet Denoising using scikit-image
    NOTE: Wavelet denoising is an effective method for SNR improvement in environments with
              wide range of noise types competing for the same subspace.
    '''
    sigma_est = estimate_sigma(data, multichannel=True, average_sigmas=True)
    im_bayes = denoise_wavelet(data,
                               multichannel=False,
                               convert2ycbcr=True,
                               method='BayesShrink',
                               mode='soft')
    im_visushrink = denoise_wavelet(data,
                                    multichannel=False,
                                    convert2ycbcr=True,
                                    method='VisuShrink',
                                    mode='soft')

    # VisuShrink is designed to eliminate noise with high probability, but this
    # results in a visually over-smooth appearance. Here, we specify a reduction
    # in the threshold by factors of 2 and 4.
    im_visushrink2 = denoise_wavelet(data,
                                     multichannel=False,
                                     convert2ycbcr=True,
                                     method='VisuShrink',
                                     mode='soft',
                                     sigma=sigma_est / 2)
    im_visushrink4 = denoise_wavelet(data,
                                     multichannel=False,
                                     convert2ycbcr=True,
                                     method='VisuShrink',
                                     mode='soft',
                                     sigma=sigma_est / 4)
    return im_bayes
Пример #6
0
def test_wavelet_denoising_args(rescale_sigma):
    """
    Some of the functions inside wavelet denoising throw an error the wrong
    arguments are passed. This protects against that and verifies that all
    arguments can be passed.
    """
    img = astro
    noisy = img.copy() + 0.1 * np.random.randn(*(img.shape))

    for convert2ycbcr in [True, False]:
        for multichannel in [True, False]:
            channel_axis = -1 if multichannel else None
            if convert2ycbcr and not multichannel:
                with testing.raises(ValueError):
                    restoration.denoise_wavelet(noisy,
                                                convert2ycbcr=convert2ycbcr,
                                                channel_axis=channel_axis,
                                                rescale_sigma=rescale_sigma)
                continue
            for sigma in [0.1, [0.1, 0.1, 0.1], None]:
                if (not multichannel and not convert2ycbcr) or \
                        (isinstance(sigma, list) and not multichannel):
                    continue
                restoration.denoise_wavelet(noisy,
                                            sigma=sigma,
                                            convert2ycbcr=convert2ycbcr,
                                            channel_axis=channel_axis,
                                            rescale_sigma=rescale_sigma)
Пример #7
0
def test_wavelet_denoising_deprecated():
    rstate = np.random.RandomState(1234)
    sigma = 0.1
    img = astro_odd
    noisy = img + sigma * rstate.randn(*(img.shape))
    noisy = np.clip(noisy, 0, 1)

    with expected_warnings(["`multichannel` is a deprecated argument"]):
        # Verify that SNR is improved when true sigma is used
        denoised = restoration.denoise_wavelet(noisy,
                                               sigma=sigma,
                                               multichannel=True,
                                               rescale_sigma=True)
    psnr_noisy = peak_signal_noise_ratio(img, noisy)
    psnr_denoised = peak_signal_noise_ratio(img, denoised)
    assert_(psnr_denoised > psnr_noisy)

    # providing multichannel argument positionally also warns
    with expected_warnings(["Providing the `multichannel` argument"]):
        restoration.denoise_wavelet(noisy,
                                    sigma,
                                    'db1',
                                    'soft',
                                    None,
                                    True,
                                    rescale_sigma=True)
Пример #8
0
def test_wavelet_denoising_levels():
    rstate = np.random.RandomState(1234)
    ndim = 2
    N = 256
    wavelet = 'db1'
    # Generate a very simple test image
    img = 0.2*np.ones((N, )*ndim)
    img[[slice(5, 13), ] * ndim] = 0.8

    sigma = 0.1
    noisy = img + sigma * rstate.randn(*(img.shape))
    noisy = np.clip(noisy, 0, 1)

    denoised = restoration.denoise_wavelet(noisy, wavelet=wavelet)
    denoised_1 = restoration.denoise_wavelet(noisy, wavelet=wavelet,
                                             wavelet_levels=1)
    psnr_noisy = compare_psnr(img, noisy)
    psnr_denoised = compare_psnr(img, denoised)
    psnr_denoised_1 = compare_psnr(img, denoised_1)

    # multi-level case should outperform single level case
    assert_(psnr_denoised > psnr_denoised_1 > psnr_noisy)

    # invalid number of wavelet levels results in a ValueError
    max_level = pywt.dwt_max_level(np.min(img.shape),
                                   pywt.Wavelet(wavelet).dec_len)
    assert_raises(ValueError, restoration.denoise_wavelet, noisy,
                  wavelet=wavelet, wavelet_levels=max_level+1)
    assert_raises(ValueError, restoration.denoise_wavelet, noisy,
                  wavelet=wavelet, wavelet_levels=-1)
Пример #9
0
def test_wavelet_denoising_levels():
    rstate = np.random.RandomState(1234)
    ndim = 2
    N = 256
    wavelet = 'db1'
    # Generate a very simple test image
    img = 0.2*np.ones((N, )*ndim)
    img[[slice(5, 13), ] * ndim] = 0.8

    sigma = 0.1
    noisy = img + sigma * rstate.randn(*(img.shape))
    noisy = np.clip(noisy, 0, 1)

    denoised = restoration.denoise_wavelet(noisy, wavelet=wavelet)
    denoised_1 = restoration.denoise_wavelet(noisy, wavelet=wavelet,
                                             wavelet_levels=1)
    psnr_noisy = compare_psnr(img, noisy)
    psnr_denoised = compare_psnr(img, denoised)
    psnr_denoised_1 = compare_psnr(img, denoised_1)

    # multi-level case should outperform single level case
    assert_(psnr_denoised > psnr_denoised_1 > psnr_noisy)

    # invalid number of wavelet levels results in a ValueError
    max_level = pywt.dwt_max_level(np.min(img.shape),
                                   pywt.Wavelet(wavelet).dec_len)
    assert_raises(ValueError, restoration.denoise_wavelet, noisy,
                  wavelet=wavelet, wavelet_levels=max_level+1)
    assert_raises(ValueError, restoration.denoise_wavelet, noisy,
                  wavelet=wavelet, wavelet_levels=-1)
Пример #10
0
def test_wavelet_denoising():
    for img, multichannel in [(astro_gray, False), (astro, True)]:
        sigma = 0.1
        noisy = img + sigma * np.random.randn(*(img.shape))
        noisy = np.clip(noisy, 0, 1)

        # Verify that SNR is improved when true sigma is used
        denoised = restoration.denoise_wavelet(noisy, sigma=sigma,
                                               multichannel=multichannel)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert psnr_denoised > psnr_noisy

        # Verify that SNR is improved with internally estimated sigma
        denoised = restoration.denoise_wavelet(noisy,
                                               multichannel=multichannel)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert psnr_denoised > psnr_noisy

        # Test changing noise_std (higher threshold, so less energy in signal)
        res1 = restoration.denoise_wavelet(noisy, sigma=2*sigma,
                                           multichannel=multichannel)
        res2 = restoration.denoise_wavelet(noisy, sigma=sigma,
                                           multichannel=multichannel)
        assert (res1.sum()**2 <= res2.sum()**2)
Пример #11
0
def denoise_img(file_name):
    if file_name is not None:
        image = cv2.imread(file_name)
        original = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        noisy = original
    else:
        original = img_as_float(data.chelsea()[100:250, 50:300])
        sigma = 0.155
        noisy = random_noise(original, var=sigma**2)
    print("img shape", np.shape(noisy))
    fig, ax = plt.subplots(nrows=2,
                           ncols=4,
                           figsize=(8, 5),
                           sharex=True,
                           sharey=True)
    plt.gray()
    # Estimate the average noise standard deviation across color channels.
    sigma_est = estimate_sigma(noisy, multichannel=True, average_sigmas=True)
    # Due to clipping in random_noise, the estimate will be a bit smaller than the
    # specified sigma.
    print("Estimated Gaussian noise standard deviation = {}".format(sigma_est))
    ax[0, 0].imshow(noisy)
    ax[0, 0].axis('off')
    ax[0, 0].set_title('Noisy')
    ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True))
    ax[0, 1].axis('off')
    ax[0, 1].set_title('TV')
    ax[0, 2].imshow(
        denoise_bilateral(noisy,
                          sigma_color=0.05,
                          sigma_spatial=15,
                          multichannel=True))
    ax[0, 2].axis('off')
    ax[0, 2].set_title('Bilateral')
    ax[0, 3].imshow(denoise_wavelet(noisy, multichannel=True))
    ax[0, 3].axis('off')
    ax[0, 3].set_title('Wavelet denoising')

    ax[1, 1].imshow(denoise_tv_chambolle(noisy, weight=0.02,
                                         multichannel=True))
    ax[1, 1].axis('off')
    ax[1, 1].set_title('(more) TV')
    ax[1, 2].imshow(
        denoise_bilateral(noisy,
                          sigma_color=0.001,
                          sigma_spatial=3,
                          multichannel=True))
    ax[1, 2].axis('off')
    ax[1, 2].set_title('(more) Bilateral')
    ax[1,
       3].imshow(denoise_wavelet(noisy, multichannel=True, convert2ycbcr=True))
    ax[1, 3].axis('off')
    ax[1, 3].set_title('Wavelet denoising\nin YCbCr colorspace')
    ax[1, 0].imshow(original)
    ax[1, 0].axis('off')
    ax[1, 0].set_title('Original')

    fig.tight_layout()

    plt.show()
Пример #12
0
def test_wavelet_denoising():
    for img, multichannel in [(astro_gray, False), (astro, True)]:
        sigma = 0.1
        noisy = img + sigma * np.random.randn(*(img.shape))
        noisy = np.clip(noisy, 0, 1)

        # Verify that SNR is improved when true sigma is used
        denoised = restoration.denoise_wavelet(noisy,
                                               sigma=sigma,
                                               multichannel=multichannel)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert psnr_denoised > psnr_noisy

        # Verify that SNR is improved with internally estimated sigma
        denoised = restoration.denoise_wavelet(noisy,
                                               multichannel=multichannel)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert psnr_denoised > psnr_noisy

        # Test changing noise_std (higher threshold, so less energy in signal)
        res1 = restoration.denoise_wavelet(noisy,
                                           sigma=2 * sigma,
                                           multichannel=multichannel)
        res2 = restoration.denoise_wavelet(noisy,
                                           sigma=sigma,
                                           multichannel=multichannel)
        assert (res1.sum()**2 <= res2.sum()**2)
Пример #13
0
def wavelet(img, method=' ', sigma=None):
    '''
    :param img: noisy input image
    :param method: 'visu' or 'bayes'
                    standard is visu
    :param sigma:
    :return: denoise output image
    '''

    if sigma == None:
        sigma = est_sigma(img)

    if method == 'bayes':
        dumb = denoise_wavelet(img,
                               multichannel=True,
                               convert2ycbcr=True,
                               method='BayesShrink',
                               mode='soft',
                               rescale_sigma=True)

    else:
        dumb = denoise_wavelet(img,
                               multichannel=True,
                               convert2ycbcr=True,
                               method='VisuShrink',
                               mode='soft',
                               sigma=sigma,
                               rescale_sigma=True)

    return dumb
Пример #14
0
def Noise(img):
    img = img

    sigma = 0.155
    noisy = random_noise(img, var=sigma**2)

    fig, ax = plt.subplots(nrows=2,
                           ncols=4,
                           figsize=(8, 5),
                           sharex=True,
                           sharey=True)

    plt.gray()

    # Estimate the average noise standard deviation across color channels.
    sigma_est = estimate_sigma(noisy, multichannel=True, average_sigmas=True)
    # Due to clipping in random_noise, the estimate will be a bit smaller than the
    # specified sigma.
    print(f"Estimated Gaussian noise standard deviation = {sigma_est}")

    ax[0, 0].imshow(noisy)
    ax[0, 0].axis('off')
    ax[0, 0].set_title('Noisy')
    ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True))
    ax[0, 1].axis('off')
    ax[0, 1].set_title('TV')
    ax[0, 2].imshow(
        denoise_bilateral(noisy,
                          sigma_color=0.05,
                          sigma_spatial=15,
                          multichannel=True))
    ax[0, 2].axis('off')
    ax[0, 2].set_title('Bilateral')
    ax[0, 3].imshow(denoise_wavelet(noisy, multichannel=True))
    ax[0, 3].axis('off')
    ax[0, 3].set_title('Wavelet denoising')

    ax[1, 1].imshow(denoise_tv_chambolle(noisy, weight=0.2, multichannel=True))
    ax[1, 1].axis('off')
    ax[1, 1].set_title('(more) TV')
    ax[1, 2].imshow(
        denoise_bilateral(noisy,
                          sigma_color=0.1,
                          sigma_spatial=15,
                          multichannel=True))
    ax[1, 2].axis('off')
    ax[1, 2].set_title('(more) Bilateral')
    ax[1,
       3].imshow(denoise_wavelet(noisy, multichannel=True, convert2ycbcr=True))
    ax[1, 3].axis('off')
    ax[1, 3].set_title('Wavelet denoising\nin YCbCr colorspace')
    ax[1, 0].imshow(img)
    ax[1, 0].axis('off')
    ax[1, 0].set_title('Original')

    fig.tight_layout()

    plt.show()
Пример #15
0
def denoise_batch(source_path, dest_path):
    if not os.path.exists(dest_path):
        os.makedirs(dest_path)
    noise = []
    dirlist = os.listdir(img_path)
    dirlist = sorted(dirlist)
    if DEBUG:
        print(dirlist)
    for f in dirlist:
        if f.split('.')[-1].upper() in ['TIF', 'TIFF', 'JPG', 'PNG']:
            if COLOR:
                img = cv2.imread(source_path + '/' + f, 1)
            else:
                img = cv2.imread(source_path + '/' + f, 0)
            img = cropCenter(img, 1024, 1024)
            if img is None:
                print("Image", f, "less than 1024x1024")
                continue
            if DEBUG:
                print(f)
            if COLOR:
                n0 = img[:, :, 0] - 255 * denoise_wavelet(img[:, :, 0],
                                                          wavelet='db8',
                                                          mode='soft',
                                                          wavelet_levels=4,
                                                          multichannel=False)
                n1 = img[:, :, 1] - 255 * denoise_wavelet(img[:, :, 1],
                                                          wavelet='db8',
                                                          mode='soft',
                                                          wavelet_levels=4,
                                                          multichannel=False)
                n2 = img[:, :, 2] - 255 * denoise_wavelet(img[:, :, 2],
                                                          wavelet='db8',
                                                          mode='soft',
                                                          wavelet_levels=4,
                                                          multichannel=False)
                #cv2 creates image in BGR order
                #n = n0 * 0.2989 + n1 * 0.5870 + n2 * 0.1140
                n = n2 * 0.2989 + n1 * 0.5870 + n0 * 0.1140
            else:
                # Noise
                # Wavelets
                n = img - 255 * denoise_wavelet(img,
                                                wavelet='db8',
                                                mode='soft',
                                                wavelet_levels=4,
                                                multichannel=False)
            # Total Variation
            # n = img -  denoise_tv_chambolle(img.astype(float), weight=10, multichannel=False)
            # Zero-mean
            #n = zero_mean(n)
            # Wiener
            #n = wiener_filter(n)
            # print(noise_path + '/' + f[:-4])
            np.save(dest_path + '/' + f[:-4], n)
Пример #16
0
def test_wavelet_denoising():
    for img in [astro_gray, astro]:
        noisy = img.copy() + 0.1 * np.random.randn(*(img.shape))
        noisy = np.clip(noisy, 0, 1)
        # less energy in signal
        denoised = restoration.denoise_wavelet(noisy, sigma=0.3)
        assert denoised.sum()**2 <= img.sum()**2

        # test changing noise_std (higher threshold, so less energy in signal)
        assert (restoration.denoise_wavelet(noisy, sigma=0.2).sum()**2 <=
                restoration.denoise_wavelet(noisy, sigma=0.1).sum()**2)
Пример #17
0
def test_wavelet_denoising():
    rstate = np.random.RandomState(1234)

    # version with one odd-sized dimension
    astro_gray_odd = astro_gray[:, :-1]
    astro_odd = astro[:, :-1]

    for img, multichannel, convert2ycbcr in [(astro_gray, False, False),
                                             (astro_gray_odd, False, False),
                                             (astro_odd, True, False),
                                             (astro_odd, True, True)]:
        sigma = 0.1
        noisy = img + sigma * rstate.randn(*(img.shape))
        noisy = np.clip(noisy, 0, 1)

        # Verify that SNR is improved when true sigma is used
        with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
            denoised = restoration.denoise_wavelet(noisy,
                                                   sigma=sigma,
                                                   multichannel=multichannel,
                                                   convert2ycbcr=convert2ycbcr)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert_(psnr_denoised > psnr_noisy)

        # Verify that SNR is improved with internally estimated sigma
        with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
            denoised = restoration.denoise_wavelet(noisy,
                                                   multichannel=multichannel,
                                                   convert2ycbcr=convert2ycbcr)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert_(psnr_denoised > psnr_noisy)

        # SNR is improved less with 1 wavelet level than with the default.
        denoised_1 = restoration.denoise_wavelet(noisy,
                                                 multichannel=multichannel,
                                                 wavelet_levels=1,
                                                 convert2ycbcr=convert2ycbcr)
        psnr_denoised_1 = compare_psnr(img, denoised_1)
        assert_(psnr_denoised > psnr_denoised_1)
        assert_(psnr_denoised_1 > psnr_noisy)

        # Test changing noise_std (higher threshold, so less energy in signal)
        with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
            res1 = restoration.denoise_wavelet(noisy,
                                               sigma=2 * sigma,
                                               multichannel=multichannel)
        with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
            res2 = restoration.denoise_wavelet(noisy,
                                               sigma=sigma,
                                               multichannel=multichannel)
        assert_(np.sum(res1**2) <= np.sum(res2**2))
def denoising_BayesShrinkAndVIsuShrink(Nom_image):
    image=su.PullFromSlicer(NomDeLImage)
    NumpyImage=sitk.GetArrayFromImage(image)
    # Estimate the average noise standard deviation across color channels.
    sigma_est = estimate_sigma(NumpyImage, multichannel=True, average_sigmas=True)
    # Due to clipping in random_noise, the estimate will be a bit smaller than the
    # specified sigma.
    print(f"Estimated Gaussian noise standard deviation = {sigma_est}")
    im_bayes = denoise_wavelet(NumpyImage, multichannel=True, convert2ycbcr=True, method='BayesShrink', mode='soft',rescale_sigma=True)
    im_visushrink = denoise_wavelet(NumpyImage, multichannel=True, convert2ycbcr=True, method='VisuShrink', mode='soft',sigma=sigma_est, rescale_sigma=True)
    su.PushToSlicer(im_bayes,'image_DenoisWave_level0-'+str(Nlevel))
    su.PushToSlicer(im_visushrink,'image_DenoisWave_level0-'+str(Nlevel))
Пример #19
0
def test_wavelet_denoising():
    rstate = np.random.RandomState(1234)

    # version with one odd-sized dimension
    astro_gray_odd = astro_gray[:, :-1]
    astro_odd = astro[:, :-1]

    for img, multichannel, convert2ycbcr in [(astro_gray, False, False),
                                             (astro_gray_odd, False, False),
                                             (astro_odd, True, False),
                                             (astro_odd, True, True)]:
        sigma = 0.1
        noisy = img + sigma * rstate.randn(*(img.shape))
        noisy = np.clip(noisy, 0, 1)

        # Verify that SNR is improved when true sigma is used
        with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
            denoised = restoration.denoise_wavelet(noisy, sigma=sigma,
                                                   multichannel=multichannel,
                                                   convert2ycbcr=convert2ycbcr)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert_(psnr_denoised > psnr_noisy)

        # Verify that SNR is improved with internally estimated sigma
        with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
            denoised = restoration.denoise_wavelet(noisy,
                                                   multichannel=multichannel,
                                                   convert2ycbcr=convert2ycbcr)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert_(psnr_denoised > psnr_noisy)

        # SNR is improved less with 1 wavelet level than with the default.
        denoised_1 = restoration.denoise_wavelet(noisy,
                                                 multichannel=multichannel,
                                                 wavelet_levels=1,
                                                 convert2ycbcr=convert2ycbcr)
        psnr_denoised_1 = compare_psnr(img, denoised_1)
        assert_(psnr_denoised > psnr_denoised_1)
        assert_(psnr_denoised_1 > psnr_noisy)

        # Test changing noise_std (higher threshold, so less energy in signal)
        with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
            res1 = restoration.denoise_wavelet(noisy, sigma=2 * sigma,
                                               multichannel=multichannel)
        with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
            res2 = restoration.denoise_wavelet(noisy, sigma=sigma,
                                               multichannel=multichannel)
        assert_(np.sum(res1**2) <= np.sum(res2**2))
Пример #20
0
def test_wavelet_denoising(img, multichannel, convert2ycbcr):
    rstate = np.random.RandomState(1234)
    sigma = 0.1
    noisy = img + sigma * rstate.randn(*(img.shape))
    noisy = np.clip(noisy, 0, 1)

    # Verify that SNR is improved when true sigma is used
    with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
        denoised = restoration.denoise_wavelet(noisy,
                                               sigma=sigma,
                                               multichannel=multichannel,
                                               convert2ycbcr=convert2ycbcr,
                                               rescale_sigma=True)
    psnr_noisy = peak_signal_noise_ratio(img, noisy)
    psnr_denoised = peak_signal_noise_ratio(img, denoised)
    assert_(psnr_denoised > psnr_noisy)

    # Verify that SNR is improved with internally estimated sigma
    with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
        denoised = restoration.denoise_wavelet(noisy,
                                               multichannel=multichannel,
                                               convert2ycbcr=convert2ycbcr,
                                               rescale_sigma=True)
    psnr_noisy = peak_signal_noise_ratio(img, noisy)
    psnr_denoised = peak_signal_noise_ratio(img, denoised)
    assert_(psnr_denoised > psnr_noisy)

    # SNR is improved less with 1 wavelet level than with the default.
    with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
        denoised_1 = restoration.denoise_wavelet(noisy,
                                                 multichannel=multichannel,
                                                 wavelet_levels=1,
                                                 convert2ycbcr=convert2ycbcr,
                                                 rescale_sigma=True)
    psnr_denoised_1 = peak_signal_noise_ratio(img, denoised_1)
    assert_(psnr_denoised > psnr_denoised_1)
    assert_(psnr_denoised_1 > psnr_noisy)

    # Test changing noise_std (higher threshold, so less energy in signal)
    with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
        res1 = restoration.denoise_wavelet(noisy,
                                           sigma=2 * sigma,
                                           multichannel=multichannel,
                                           rescale_sigma=True)
    with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
        res2 = restoration.denoise_wavelet(noisy,
                                           sigma=sigma,
                                           multichannel=multichannel,
                                           rescale_sigma=True)
    assert_(np.sum(res1**2) <= np.sum(res2**2))
Пример #21
0
def check_with_ski(path):
    names_x, names_y = get_training_set_names(path)

    mean_err = 0
    min_err = maxsize
    max_err = 0

    count = len(names_x)

    for i, (name_x, name_y) in \
        enumerate(zip(names_x, names_y)):
        with Image.open(open(name_x, 'rb')) as x, \
                Image.open(open(name_y, 'rb')) as y:

            noisy = image_to_array(x)
            clean = image_to_array(y)

            processed = denoise_wavelet(noisy,
                                        multichannel=True,
                                        convert2ycbcr=True)

            mse = compare_images(clean, processed)
            print('%d/%d %s' % (i, count, str(mse)))

            if mse < min_err:
                min_err = mse
            if mse > max_err:
                max_err = mse

            mean_err += mse

    if len(names_x):
        mean_err /= len(names_x)

    return (mean_err, min_err, max_err)
Пример #22
0
def test_wavelet_denoising_nd(rescale_sigma, method, ndim):
    rstate = np.random.default_rng(1234)
    # Generate a very simple test image
    if ndim < 3:
        img = 0.2*np.ones((128, )*ndim)
    else:
        img = 0.2*np.ones((16, )*ndim)
    img[(slice(5, 13), ) * ndim] = 0.8

    sigma = 0.1
    noisy = img + sigma * rstate.standard_normal(img.shape)
    noisy = np.clip(noisy, 0, 1)

    # Mark H. 2018.08:
    #   The issue arises because when ndim in [1, 2]
    #   ``waverecn`` calls ``_match_coeff_dims``
    #   Which includes a numpy 1.15 deprecation.
    #   for larger number of dimensions _match_coeff_dims isn't called
    #   for some reason.
    # Verify that SNR is improved with internally estimated sigma
    denoised = restoration.denoise_wavelet(
        noisy, method=method,
        rescale_sigma=rescale_sigma)
    psnr_noisy = peak_signal_noise_ratio(img, noisy)
    psnr_denoised = peak_signal_noise_ratio(img, denoised)
    assert psnr_denoised > psnr_noisy
Пример #23
0
def wavelet_denoising(spectrogram):
    """In this step, we would apply Wavelet-denoising.

    Wavelet denoising is an effective method for SNR improvement
    in environments with a wide range of noise types competing for the
    same subspace.

    Wavelet denoising relies on the wavelet representation of
    the image. Gaussian noise tends to be represented by small values in the
    wavelet domain and can be removed by setting coefficients below
    a given threshold to zero (hard thresholding) or
    shrinking all coefficients toward zero by a given
    amount (soft thresholding).

    Args:
        data: Spectrogram data in the form of NumPy array.

    Returns:
        Denoised spectrogram data in the form of numpy array.
    """
    im_bayes = denoise_wavelet(spectrogram,
                               multichannel=False,
                               convert2ycbcr=False,
                               method="BayesShrink",
                               mode="soft")
    return im_bayes
def image_correction(image):
    path = lowlight(image)

    img = cv2.imread(path)
    out = simplest_cb(img, 5)
    correct_path = os.path.splitext(path)[0] + "_correct.jpg"
    cv2.imwrite(correct_path, out)
    print("Correct written")

    img = cv2.imread(correct_path)
    img2 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255

    denoise_img_wavelet = np.uint8(
        denoise_wavelet(img2, multichannel=True, rescale_sigma=True) * 255)
    denoise_path_wavelet = os.path.splitext(
        path)[0] + "_correct_denoise_wavelet.jpg"
    cv2.imwrite(denoise_path_wavelet,
                cv2.cvtColor(denoise_img_wavelet, cv2.COLOR_RGB2BGR))
    print("Denoise wavelet written")

    dst = cv2.fastNlMeansDenoisingColored(img, None, 5, 5, 3, 15)
    denoise_path_opencv = os.path.splitext(
        path)[0] + "_correct_denoise_opencv.jpg"
    cv2.imwrite(denoise_path_opencv, dst)
    print("Denoise opencv written")
Пример #25
0
def denoiser(denoiser_name, img, sigma):
    '''
    :param denoiser_name: str| 'wavelet' or 'TVM' or 'bilateral' or 'deconv' or 'NLM'
    :param img: (H,W,C) | np.array | [0,1]
    :param sigma:  for wavelet
    :return:(H,W,C) | np.array | [0,1]
    '''
    from skimage.restoration import (denoise_tv_chambolle, denoise_bilateral,
                                     denoise_wavelet, denoise_nl_means, wiener)
    if denoiser_name == 'wavelet':
        return denoise_wavelet(img,
                               sigma=sigma,
                               mode='soft',
                               multichannel=True,
                               convert2ycbcr=True,
                               method='BayesShrink')
    elif denoiser_name == 'TVM':
        return denoise_tv_chambolle(img, multichannel=True)
    elif denoiser_name == 'bilateral':
        return denoise_bilateral(img, bins=1000, multichannel=True)
    elif denoiser_name == 'deconv':
        return wiener(img)
    elif denoiser_name == 'NLM':
        return denoise_nl_means(img, multichannel=True)
    else:
        raise Exception(
            'Incorrect denoiser mentioned. Options: wavelet, TVM, bilateral, deconv, NLM'
        )
Пример #26
0
def optDenoise_v2(x):
    x = np.array(x)
    #original_mean = np.mean(x)

    #In the paper they used zero-mean normalization, which means the series is just shifted vertically downwards by its mean.
    #x = x - np.mean(x) #equivalently, standardise(x, 0, np.std(x))

    #grid search best parameters for denoising function.
    #maximise SNR-RMSE, as they recommended in the paper.
    params = gridSearch_v2(x, 1)

    #See https://www.youtube.com/watch?v=HSG-gVALa84
    y = denoise_wavelet(x,
                        wavelet=params[0],
                        wavelet_levels=params[1],
                        mode=params[2],
                        method=params[3],
                        rescale_sigma=True)
    #y = denoise_wavelet(x, wavelet='coif3', wavelet_levels=3, mode='hard', method='BayesShrink', rescale_sigma=True) #paramters used in paper
    '''
    method: 'BayesShrink' or 'VisuShrink'
    Most of the time, the denoised series is basically identical to the original
    #  VisuShrink doesn't capture price peaks, and these obviously can't be noise.
    '''
    #y = y + original_mean

    return y
Пример #27
0
def filterNoiseAndSaveImage(imageWithNoise):
    try:
        processedImage = denoise_wavelet(imageWithNoise, multichannel=True, rescale_sigma=True)
        imsave(processedImageName, img_as_ubyte(processedImage))
        logging.info('Image without noise was saved into file: \'' + processedImageName + '\'')
    except Exception:
        logging.error('Something went wrong during image with noise processing.')
Пример #28
0
def silly_gen(denoise=False):
    # creating base label space
    spacial_data = np.zeros((50, 50))

    # creating base image
    data = np.zeros((240, 50, 50))
    data = random_noise(data)

    # creating label space
    rr, cc = ellipse(14, 19, 12, 18, (27, 39))
    rr1, cc1 = ellipse(15, 20, 5, 8, (27, 39))
    rr2, cc2 = ellipse(12, 13, 3, 3, (27, 39))
    rr3, cc3 = ellipse(18, 23, 3, 3, (27, 39))

    #prr, pcc = ellipse_perimeter(14, 19, 12, 18, shape=(27, 39))
    # prr2, pcc2 = ellipse_perimeter(14, 19, 11, 17, shape=(27, 39))

    # assigning labels to label space
    spacial_data[rr, cc] += 1
    spacial_data[rr1, cc1] *= 2
    spacial_data[rr2, cc2] *= 3
    spacial_data[rr3, cc3] *= 5
    # spacial_data[rr3, cc3] *= 7
    #spacial_data[prr, pcc] = 11
    # spacial_data[prr2,pcc2] = 11

    # create ellipse for spectral values at depth
    ell = ellipsoid(120, 12, 18, levelset=True)

    # making more similar to real data
    ell *= -500
    ell += 2500
    # ell1 *= -250
    # ell1 += 1000
    # adding ellipse to base image
    data[0:240, rr, cc] += ell[0:240, rr, cc]
    data[0:240, rr1, cc1] += ell[0:240, rr1, cc1]
    ell1 = ell * 0.25
    data[25:37, rr2, cc2] -= ell1[25:37, rr2, cc2]
    data[50:63, rr3, cc3] += ell[50:63, rr3, cc3]

    if denoise:
        data = denoise_wavelet(data, mode='soft', multichannel=True)
    # Reshaping image for label classification
    data_n = data.swapaxes(0, 2)
    # data_n = data_n.swapaxes(0, 1)
    # Reshape to 2D in form samples*lines,bands
    # data_pix = data_n.transpose(2, 0, 1).reshape(40000, -1)
    d1, d2, d3 = data_n.shape
    data_pix = data_n.transpose(2, 0, 1).reshape(d1 * d2, -1)

    spacial_pix = spacial_data.reshape(d1 * d2, -1).ravel()

    # Reshaping label space for classification
    # print(spacial_data.shape)
    # sd1, sd2, sd3 = spacial_data.shape
    # spacial_pix = spacial_data.swapaxes(0, 2).transpose(2, 0, 1).reshape(sd2*sd3, -1)
    # print(spacial_pix.shape)
    # split train and test data
    return data_pix, spacial_pix, data, spacial_data
def denoise_wavelet_filter(
    folder
):  # iterate through folders, assembling feature, label, and classname data objects
    class_id = 0
    features = []
    labels = np.array([])
    classnames = []
    for root, dirs, filenames in os.walk(folder):
        for d in sorted(dirs):
            #print("Reading data from", d)
            classnames.append(
                d)  # use the folder name as the class name for this label
            files = os.listdir(os.path.join(root, d))
            for f in files:
                imgFile = os.path.join(root, d, f)  # Load the image file
                img = plt.imread(imgFile)
                img = cv2.resize(
                    img,
                    (128,
                     128))  # Resizing all the images to insure proper reading

                denoise_wavelet_filt = denoise_wavelet(img,
                                                       multichannel=True,
                                                       rescale_sigma=True)

                features.append(denoise_wavelet_filt.ravel())
                labels = np.append(
                    labels, class_id)  # Add it to the numpy array of labels
            class_id += 1

    features = np.array(
        features)  # Convert the list of features into a numpy array
    return features, labels, classnames
Пример #30
0
def denoise2d(image, sigma, wavelet='db1'):
    """
    Denoise input `image` using wavelet filtering filtering

    Parameters
    ----------
    image : ndarray
        Input 2D image
    sigma : float
        Noise standard deviation
    wavelet : str
        Wavelet to use in DWT. Default, 'db1'.

    Returns
    -------
    output : ndarray
        Denoised 2D image

    """
    # sigma_estimate = estimate_sigma(image, average_sigmas=True)

    output = denoise_wavelet(image, sigma, wavelet=wavelet)
    # output = (output - output.min()) / (output.max() - output.min())  # Scale to [0, 1]
    # output = output * (image.max() - image.min()) + image.min()  # Scale to original range

    # Old PyBM3D code
    # output = bm3d(image, sigma, patch_size=patch_size, tau_2D_hard='BIOR', tau_2D_wien='BIOR')
    # # Default useSD_h=True, useSD_w=True are used
    # # Not sure why DCT-based filters are not working and giving severe block artifacts
    # # Using bidirectional wavelets seems to be more stable
    return output.astype(image.dtype)
Пример #31
0
def test_wavelet_denoising_nd(rescale_sigma, method, ndim):
    rstate = np.random.RandomState(1234)
    # Generate a very simple test image
    if ndim < 3:
        img = 0.2 * np.ones((128, ) * ndim)
    else:
        img = 0.2 * np.ones((16, ) * ndim)
    img[(slice(5, 13), ) * ndim] = 0.8

    sigma = 0.1
    noisy = img + sigma * rstate.randn(*(img.shape))
    noisy = np.clip(noisy, 0, 1)

    # Mark H. 2018.08:
    #   The issue arises because when ndim in [1, 2]
    #   ``waverecn`` calls ``_match_coeff_dims``
    #   Which includes a numpy 1.15 deprecation.
    #   for larger number of dimensions _match_coeff_dims isn't called
    #   for some reason.
    anticipated_warnings = (PYWAVELET_ND_INDEXING_WARNING
                            if ndim < 3 else None)
    with expected_warnings([anticipated_warnings]):
        # Verify that SNR is improved with internally estimated sigma
        denoised = restoration.denoise_wavelet(noisy,
                                               method=method,
                                               rescale_sigma=rescale_sigma)
    psnr_noisy = peak_signal_noise_ratio(img, noisy)
    psnr_denoised = peak_signal_noise_ratio(img, denoised)
    assert_(psnr_denoised > psnr_noisy)
Пример #32
0
def test_wavelet_denoising_nd():
    rstate = np.random.RandomState(1234)
    for method in ['VisuShrink', 'BayesShrink']:
        for ndim in range(1, 5):
            # Generate a very simple test image
            if ndim < 3:
                img = 0.2*np.ones((128, )*ndim)
            else:
                img = 0.2*np.ones((16, )*ndim)
            img[(slice(5, 13), ) * ndim] = 0.8

            sigma = 0.1
            noisy = img + sigma * rstate.randn(*(img.shape))
            noisy = np.clip(noisy, 0, 1)

            # Mark H. 2018.08:
            #   The issue arises because when ndim in [1, 2]
            #   ``waverecn`` calls ``_match_coeff_dims``
            #   Which includes a numpy 1.15 deprecation.
            #   for larger number of dimensions _match_coeff_dims isn't called
            #   for some reason.
            anticipated_warnings = (PYWAVELET_ND_INDEXING_WARNING
                                    if ndim < 3 else None)
            with expected_warnings([anticipated_warnings]):
                # Verify that SNR is improved with internally estimated sigma
                denoised = restoration.denoise_wavelet(noisy, method=method)
            psnr_noisy = compare_psnr(img, noisy)
            psnr_denoised = compare_psnr(img, denoised)
            assert_(psnr_denoised > psnr_noisy)
Пример #33
0
def test_wavelet_denoising(img, multichannel, convert2ycbcr):
    rstate = np.random.RandomState(1234)
    sigma = 0.1
    noisy = img + sigma * rstate.randn(*(img.shape))
    noisy = np.clip(noisy, 0, 1)

    channel_axis = -1 if multichannel else None

    # Verify that SNR is improved when true sigma is used
    denoised = restoration.denoise_wavelet(noisy,
                                           sigma=sigma,
                                           channel_axis=channel_axis,
                                           convert2ycbcr=convert2ycbcr,
                                           rescale_sigma=True)
    psnr_noisy = peak_signal_noise_ratio(img, noisy)
    psnr_denoised = peak_signal_noise_ratio(img, denoised)
    assert_(psnr_denoised > psnr_noisy)

    # Verify that SNR is improved with internally estimated sigma
    denoised = restoration.denoise_wavelet(noisy,
                                           channel_axis=channel_axis,
                                           convert2ycbcr=convert2ycbcr,
                                           rescale_sigma=True)
    psnr_noisy = peak_signal_noise_ratio(img, noisy)
    psnr_denoised = peak_signal_noise_ratio(img, denoised)
    assert_(psnr_denoised > psnr_noisy)

    # SNR is improved less with 1 wavelet level than with the default.
    denoised_1 = restoration.denoise_wavelet(noisy,
                                             channel_axis=channel_axis,
                                             wavelet_levels=1,
                                             convert2ycbcr=convert2ycbcr,
                                             rescale_sigma=True)
    psnr_denoised_1 = peak_signal_noise_ratio(img, denoised_1)
    assert_(psnr_denoised > psnr_denoised_1)
    assert_(psnr_denoised_1 > psnr_noisy)

    # Test changing noise_std (higher threshold, so less energy in signal)
    res1 = restoration.denoise_wavelet(noisy,
                                       sigma=2 * sigma,
                                       channel_axis=channel_axis,
                                       rescale_sigma=True)
    res2 = restoration.denoise_wavelet(noisy,
                                       sigma=sigma,
                                       channel_axis=channel_axis,
                                       rescale_sigma=True)
    assert_(np.sum(res1**2) <= np.sum(res2**2))
Пример #34
0
def dwtcoefftoarray(myim, wavelet, level, denoise, partial=False):
    ''' 
    This function collects all the coefficients of the DWT and converts them
    in a flat array which can be passed to the Deep Neural Network.
    
    Parameters:
        - myim = image opened with PIL.Image
        - wavelet = which wavelet to use
        - level = level of the wavelet decomposition
        - denoise = wheter to prior denoise the image or not, denoise should be set to "yes" or "no"
        - partial = True or False <-- let's you choose wheter to take only the second and third levels coeffiecients if level is 3, or the second, third and fourth levels coefficients if level is 4
    '''
    if denoise == 'yes':
        myimfl = img_as_float(myim)
        myim = denoise_wavelet(myimfl,
                               method='BayesShrink',
                               mode='soft',
                               rescale_sigma='True')
    elif denoise == 'no':
        pass

    coeffs = pywt.wavedec2(myim, wavelet, level=level)

    infocoeffs = pywt.ravel_coeffs(coeffs)

    if partial == False:
        ''' 
        If partial is False I want to take all the coefficients obtained from the wavedec2 decomposition 
        '''
        coeffsarray = infocoeffs[0]

    if partial == True:
        ''' 
        If partial is True AND level is 3 I want to take the coefficients of 2nd and 3rd levels without the 1st level ones
        and without those related to the approximated image.
        If partial is True AND level is 4 I want to take the coefficients of 2nd, 3rd and 4th levels without the 1st level ones
        and without those related to the approximated image.
        '''
        secondlevelcoeffs = np.concatenate(
            (infocoeffs[0][infocoeffs[1][-2]['da']],
             infocoeffs[0][infocoeffs[1][-2]['ad']],
             infocoeffs[0][infocoeffs[1][-2]['dd']]))
        thirdlevelcoeffs = np.concatenate(
            (infocoeffs[0][infocoeffs[1][-3]['da']],
             infocoeffs[0][infocoeffs[1][-3]['ad']],
             infocoeffs[0][infocoeffs[1][-3]['dd']]))
        if level == 3:
            coeffsarray = np.concatenate((secondlevelcoeffs, thirdlevelcoeffs))
        elif level == 4:
            fourthlevelcoeffs = np.concatenate(
                (infocoeffs[0][infocoeffs[1][-4]['da']],
                 infocoeffs[0][infocoeffs[1][-4]['ad']],
                 infocoeffs[0][infocoeffs[1][-4]['dd']]))
            coeffsarray = np.concatenate(
                (secondlevelcoeffs, thirdlevelcoeffs, fourthlevelcoeffs))
        else:
            pass

    return coeffsarray
Пример #35
0
def test_wavelet_denoising_args():
    """
    Some of the functions inside wavelet denoising throw an error the wrong
    arguments are passed. This protects against that and verifies that all
    arguments can be passed.
    """
    img = astro
    noisy = img.copy() + 0.1 * np.random.randn(*(img.shape))

    for convert2ycbcr in [True, False]:
        for multichannel in [True, False]:
            for sigma in [0.1, [0.1, 0.1, 0.1], None]:
                if (not multichannel and not convert2ycbcr) or \
                        (isinstance(sigma, list) and not multichannel):
                    continue
                restoration.denoise_wavelet(noisy, sigma=sigma,
                                            convert2ycbcr=convert2ycbcr,
                                            multichannel=multichannel)
Пример #36
0
def test_wavelet_denoising_nd():
    for ndim in range(1, 5):
        # Generate a very simple test image
        img = 0.2*np.ones((16, )*ndim)
        img[[slice(5, 13), ] * ndim] = 0.8

        sigma = 0.1
        noisy = img + sigma * np.random.randn(*(img.shape))
        noisy = np.clip(noisy, 0, 1)

        # Verify that SNR is improved with internally estimated sigma
        denoised = restoration.denoise_wavelet(noisy)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert psnr_denoised > psnr_noisy
Пример #37
0
def test_wavelet_denoising_levels():
    rstate = np.random.RandomState(1234)
    ndim = 2
    N = 256
    wavelet = 'db1'
    # Generate a very simple test image
    img = 0.2*np.ones((N, )*ndim)
    img[(slice(5, 13), ) * ndim] = 0.8

    sigma = 0.1
    noisy = img + sigma * rstate.randn(*(img.shape))
    noisy = np.clip(noisy, 0, 1)

    with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
        denoised = restoration.denoise_wavelet(noisy, wavelet=wavelet)
    denoised_1 = restoration.denoise_wavelet(noisy, wavelet=wavelet,
                                             wavelet_levels=1)
    psnr_noisy = compare_psnr(img, noisy)
    psnr_denoised = compare_psnr(img, denoised)
    psnr_denoised_1 = compare_psnr(img, denoised_1)

    # multi-level case should outperform single level case
    assert_(psnr_denoised > psnr_denoised_1 > psnr_noisy)

    # invalid number of wavelet levels results in a ValueError or UserWarning
    max_level = pywt.dwt_max_level(np.min(img.shape),
                                   pywt.Wavelet(wavelet).dec_len)
    if Version(pywt.__version__) < '1.0.0':
        # exceeding max_level raises a ValueError in PyWavelets 0.4-0.5.2
        with testing.raises(ValueError):
            with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
                restoration.denoise_wavelet(
                    noisy, wavelet=wavelet, wavelet_levels=max_level + 1)
    else:
        # exceeding max_level raises a UserWarning in PyWavelets >= 1.0.0
        with expected_warnings([
                'all coefficients will experience boundary effects']):
            restoration.denoise_wavelet(
                noisy, wavelet=wavelet, wavelet_levels=max_level + 1)

    with testing.raises(ValueError):
        with expected_warnings([PYWAVELET_ND_INDEXING_WARNING]):
            restoration.denoise_wavelet(
                noisy,
                wavelet=wavelet, wavelet_levels=-1)
Пример #38
0
def test_wavelet_denoising_nd():
    rstate = np.random.RandomState(1234)
    for method in ['VisuShrink', 'BayesShrink']:
        for ndim in range(1, 5):
            # Generate a very simple test image
            if ndim < 3:
                img = 0.2*np.ones((128, )*ndim)
            else:
                img = 0.2*np.ones((16, )*ndim)
            img[[slice(5, 13), ] * ndim] = 0.8

            sigma = 0.1
            noisy = img + sigma * rstate.randn(*(img.shape))
            noisy = np.clip(noisy, 0, 1)

            # Verify that SNR is improved with internally estimated sigma
            denoised = restoration.denoise_wavelet(noisy, method=method)
            psnr_noisy = compare_psnr(img, noisy)
            psnr_denoised = compare_psnr(img, denoised)
            assert_(psnr_denoised > psnr_noisy)
Пример #39
0
# Estimate the average noise standard deviation across color channels.
sigma_est = estimate_sigma(noisy, multichannel=True, average_sigmas=True)
# Due to clipping in random_noise, the estimate will be a bit smaller than the
# specified sigma.
print("Estimated Gaussian noise standard deviation = {}".format(sigma_est))

ax[0, 0].imshow(noisy)
ax[0, 0].axis('off')
ax[0, 0].set_title('noisy')
ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True))
ax[0, 1].axis('off')
ax[0, 1].set_title('TV')
ax[0, 2].imshow(denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15))
ax[0, 2].axis('off')
ax[0, 2].set_title('Bilateral')
ax[0, 3].imshow(denoise_wavelet(noisy, sigma=0.85*sigma_est,
                                multichannel=True))
ax[0, 3].axis('off')
ax[0, 3].set_title('Wavelet')

ax[1, 1].imshow(denoise_tv_chambolle(noisy, weight=0.2, multichannel=True))
ax[1, 1].axis('off')
ax[1, 1].set_title('(more) TV')
ax[1, 2].imshow(denoise_bilateral(noisy, sigma_color=0.1, sigma_spatial=15))
ax[1, 2].axis('off')
ax[1, 2].set_title('(more) Bilateral')
ax[1, 3].imshow(denoise_wavelet(noisy, sigma=1.25*sigma_est,
                                multichannel=True))
ax[1, 3].axis('off')
ax[1, 3].set_title('(more) Wavelet')
ax[1, 0].imshow(astro)
ax[1, 0].axis('off')
Пример #40
0
def test_wavelet_invalid_method():
    with testing.raises(ValueError):
        restoration.denoise_wavelet(np.ones(16), method='Unimplemented')
Пример #41
0
sigma_est = estimate_sigma(noisy, multichannel=True, average_sigmas=True)
# Due to clipping in random_noise, the estimate will be a bit smaller than the
# specified sigma.
print("Estimated Gaussian noise standard deviation = {}".format(sigma_est))

ax[0, 0].imshow(noisy)
ax[0, 0].axis('off')
ax[0, 0].set_title('Noisy')
ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=False))
ax[0, 1].axis('off')
ax[0, 1].set_title('TV')
ax[0, 2].imshow(denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15,
                                  multichannel=False))
ax[0, 2].axis('off')
ax[0, 2].set_title('Bilateral')
ax[0, 3].imshow(denoise_wavelet(noisy, multichannel=False))
ax[0, 3].axis('off')
ax[0, 3].set_title('Wavelet denoising')

ax[1, 1].imshow(denoise_tv_chambolle(noisy, weight=0.2, multichannel=False))
ax[1, 1].axis('off')
ax[1, 1].set_title('(more) TV')
ax[1, 2].imshow(denoise_bilateral(noisy, sigma_color=0.1, sigma_spatial=15,
                                  multichannel=False))
ax[1, 2].axis('off')
ax[1, 2].set_title('(more) Bilateral')
ax[1, 3].imshow(denoise_wavelet(noisy, multichannel=False, convert2ycbcr=True))
ax[1, 3].axis('off')
ax[1, 3].set_title('Wavelet denoising\nin YCbCr colorspace')
ax[1, 0].imshow(original)
ax[1, 0].axis('off')
Пример #42
0
sigma = 0.12
noisy = random_noise(original, var=sigma**2)

fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(8, 5),
                       sharex=True, sharey=True)

plt.gray()

# Estimate the average noise standard deviation across color channels.
sigma_est = estimate_sigma(noisy, multichannel=True, average_sigmas=True)
# Due to clipping in random_noise, the estimate will be a bit smaller than the
# specified sigma.
print("Estimated Gaussian noise standard deviation = {}".format(sigma_est))

im_bayes = denoise_wavelet(noisy, multichannel=True, convert2ycbcr=True,
                           method='BayesShrink', mode='soft')
im_visushrink = denoise_wavelet(noisy, multichannel=True, convert2ycbcr=True,
                                method='VisuShrink', mode='soft',
                                sigma=sigma_est)

# VisuShrink is designed to eliminate noise with high probability, but this
# results in a visually over-smooth appearance.  Repeat, specifying a reduction
# in the threshold by factors of 2 and 4.
im_visushrink2 = denoise_wavelet(noisy, multichannel=True, convert2ycbcr=True,
                                 method='VisuShrink', mode='soft',
                                 sigma=sigma_est/2)
im_visushrink4 = denoise_wavelet(noisy, multichannel=True, convert2ycbcr=True,
                                 method='VisuShrink', mode='soft',
                                 sigma=sigma_est/4)

# Compute PSNR as an indication of image quality
Пример #43
0
fig, ax = plt.subplots(nrows=2, ncols=4, figsize=(8, 5), sharex=True,
                       sharey=True, subplot_kw={'adjustable': 'box-forced'})

plt.gray()

ax[0, 0].imshow(noisy)
ax[0, 0].axis('off')
ax[0, 0].set_title('noisy')
ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True))
ax[0, 1].axis('off')
ax[0, 1].set_title('TV')
ax[0, 2].imshow(denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15))
ax[0, 2].axis('off')
ax[0, 2].set_title('Bilateral')
ax[0, 3].imshow(denoise_wavelet(noisy, sigma=0.4*astro.std()))
ax[0, 3].axis('off')
ax[0, 3].set_title('Wavelet')

ax[1, 1].imshow(denoise_tv_chambolle(noisy, weight=0.2, multichannel=True))
ax[1, 1].axis('off')
ax[1, 1].set_title('(more) TV')
ax[1, 2].imshow(denoise_bilateral(noisy, sigma_color=0.1, sigma_spatial=15))
ax[1, 2].axis('off')
ax[1, 2].set_title('(more) Bilateral')
ax[1, 3].imshow(denoise_wavelet(noisy, sigma=0.6*astro.std()))
ax[1, 3].axis('off')
ax[1, 3].set_title('(more) Wavelet')
ax[1, 0].imshow(astro)
ax[1, 0].axis('off')
ax[1, 0].set_title('original')
Пример #44
0
fig, ax = plt.subplots(nrows=2, ncols=4, figsize=(8, 5), sharex=True,
                       sharey=True, subplot_kw={'adjustable': 'box-forced'})

plt.gray()

ax[0, 0].imshow(noisy)
ax[0, 0].axis('off')
ax[0, 0].set_title('noisy')
ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True))
ax[0, 1].axis('off')
ax[0, 1].set_title('TV')
ax[0, 2].imshow(denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15))
ax[0, 2].axis('off')
ax[0, 2].set_title('Bilateral')
ax[0, 3].imshow(denoise_wavelet(noisy, sigma=0.4*astro.std(),
                                multichannel=True))
ax[0, 3].axis('off')
ax[0, 3].set_title('Wavelet')

ax[1, 1].imshow(denoise_tv_chambolle(noisy, weight=0.2, multichannel=True))
ax[1, 1].axis('off')
ax[1, 1].set_title('(more) TV')
ax[1, 2].imshow(denoise_bilateral(noisy, sigma_color=0.1, sigma_spatial=15))
ax[1, 2].axis('off')
ax[1, 2].set_title('(more) Bilateral')
ax[1, 3].imshow(denoise_wavelet(noisy, sigma=0.6*astro.std(),
                                multichannel=True))
ax[1, 3].axis('off')
ax[1, 3].set_title('(more) Wavelet')
ax[1, 0].imshow(astro)
ax[1, 0].axis('off')
Пример #45
-1
def test_wavelet_denoising():
    rstate = np.random.RandomState(1234)

    # version with one odd-sized dimension
    astro_gray_odd = astro_gray[:, :-1]
    astro_odd = astro[:, :-1]

    for img, multichannel in [(astro_gray, False), (astro_gray_odd, False),
                              (astro_odd, True)]:
        sigma = 0.1
        noisy = img + sigma * rstate.randn(*(img.shape))
        noisy = np.clip(noisy, 0, 1)

        # Verify that SNR is improved when true sigma is used
        denoised = restoration.denoise_wavelet(noisy, sigma=sigma,
                                               multichannel=multichannel)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert_(psnr_denoised > psnr_noisy)

        # Verify that SNR is improved with internally estimated sigma
        denoised = restoration.denoise_wavelet(noisy,
                                               multichannel=multichannel)
        psnr_noisy = compare_psnr(img, noisy)
        psnr_denoised = compare_psnr(img, denoised)
        assert_(psnr_denoised > psnr_noisy)

        # Test changing noise_std (higher threshold, so less energy in signal)
        res1 = restoration.denoise_wavelet(noisy, sigma=2*sigma,
                                           multichannel=multichannel)
        res2 = restoration.denoise_wavelet(noisy, sigma=sigma,
                                           multichannel=multichannel)
        assert_(np.sum(res1**2) <= np.sum(res2**2))