Пример #1
1
#!/usr/bin/env python

import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import convolve2d
from skimage import color, data, restoration

if __name__ == '__main__':
    image = color.rgb2gray(data.astronaut())
    point_spread_func = np.ones((5, 5))/25.0
    image = convolve2d(image, point_spread_func, 'same')
    image += 0.1*image.std()*np.random.standard_normal(image.shape)
    denoised, _ = restoration.unsupervised_wiener(image, point_spread_func)
    figure, axes = plt.subplots(nrows=1, ncols=2, sharex=True, sharey=True,
                                subplot_kw={'adjustable': 'box-forced'},
                                figsize=(8,5))
    plt.gray()
    axes[0].imshow(image, vmin=denoised.min(), vmax=denoised.max())
    axes[0].axis('off')
    axes[0].set_title('original')
    axes[1].imshow(denoised)
    axes[1].axis('off')
    axes[1].set_title('restored')
    figure.tight_layout()
    plt.show()
Пример #2
0
def unSupervisedWiener():
    img = color.rgb2gray(data.astronaut())
    imgO = img.copy()

    psf = np.ones((5, 5)) / 25
    img = convolve2d(img, psf, 'same')
    img += 0.1 * img.std() * np.random.standard_normal(img.shape)
    imgN = img.copy()

    restoration.unsupervised_wiener(img, psf)
    imgR = img.copy()

    return [imgO, imgN, imgR]
Пример #3
0
 def wiener_filter(self, const_psf):
     psf = np.ones((const_psf, const_psf)) / (const_psf * const_psf)
     image_norm, delta, low = self.standardize()
     filtered_image = restoration.unsupervised_wiener(image_norm, psf)[0]
     filtered_image = (filtered_image * delta) - low
     filtered_image = filtered_image - filtered_image.mean()
     return filtered_image
Пример #4
0
def question2():
    print("Question 2:")
    psf = np.load("example_psf.npy")
    img = cv2.imread("calibration2.png")
    img = img.astype(np.float32)/255
    psf_img = cv2.filter2D(img,-1,psf)
    psf_img_noise_val = norm(psf_img - img)
    
    noise_img1 = noisy("gauss", psf_img)
    noise_img = noisy("poisson", noise_img1)
    noise2_val = norm(noise_img - img)
    
    psf_estimated =EstimatePSF(img[:,:,0], noise_img[:,:,0])
    filtered_img = np.copy(noise_img)
    for k in range(img.shape[2]):
        # filtered_img[:,:,k] = cv2.filter2D(noise_img[:,:,k],-1,psf_estimated)
        filtered_img[:,:,k], _ = restoration.unsupervised_wiener(noise_img[:,:,k], psf_estimated)
    filtered_noise_val = norm(filtered_img - img)
    
    ax1 = plt.subplot(2,2,1)
    plt.imshow(img)
    plt.subplot(2,2,2, sharex=ax1, sharey=ax1),plt.imshow(psf_estimated)
    plt.subplot(2,2,3, sharex=ax1, sharey=ax1),plt.imshow(noise_img),plt.title(noise2_val)
    plt.subplot(2,2,4, sharex=ax1, sharey=ax1),plt.imshow(filtered_img), plt.title(filtered_noise_val)
    
    plt.show()
Пример #5
0
def  WeinerFilter():
  e1 = cv2.getTickCount()
  astro = color.rgb2gray(data.imread(imagePath))
  psf = np.ones((5, 5)) / 25
  astro = conv2(astro, psf, 'same')
  astro += 0.1 * astro.std() * np.random.standard_normal(astro.shape)

  deconvolved, _ = restoration.unsupervised_wiener(astro, psf)

  fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 5), sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})

  plt.gray()

  ax[0].imshow(astro, vmin=deconvolved.min(), vmax=deconvolved.max())
  ax[0].axis('off')
  ax[0].set_title('Original Picture')

  ax[1].imshow(deconvolved)
  ax[1].axis('off')
  ax[1].set_title('Self tuned restoration')

  fig.subplots_adjust(wspace=0.02, hspace=0.2,
                      top=0.9, bottom=0.05, left=0, right=1)
  e2 = cv2.getTickCount()
  time = (e2 - e1)/ cv2.getTickFrequency() + (numberThreads) + numberThreadsPerCore + numberCores
  msgbox(msg= str(time) +" seconds", title="Execution Time", ok_button="OK")
  plt.show()
Пример #6
0
def test_unsupervised_wiener_deprecated_user_param():
    psf = np.ones((5, 5), dtype=float) / 25
    data = convolve2d(test_img, psf, 'same')
    otf = uft.ir2tf(psf, data.shape, is_real=False)
    _, laplacian = uft.laplacian(2, data.shape)
    with expected_warnings(
        ["`max_iter` is a deprecated key", "`min_iter` is a deprecated key"]):
        restoration.unsupervised_wiener(data,
                                        otf,
                                        reg=laplacian,
                                        is_real=False,
                                        user_params={
                                            "max_iter": 200,
                                            "min_iter": 30
                                        },
                                        random_state=5)
Пример #7
0
def question3():
    print("Question 3:")
    psf = np.load("example_psf.npy")
    print(psf)
    img = cv2.imread("calibration2.png")
    # scale_img = cv2.resize(img,(int(img.shape[1]/4),int(img.shape[0]/4)))
    # cv2.imwrite("calibration2.png", scale_img)
    img = img.astype(np.float32)/255
    psf_img = cv2.filter2D(img,-1,psf)
    psf_img_noise_val = norm(psf_img - img)
    # noise_img1 = psf_img
    # noise_img = noise_img1
    noise_img1 = noisy("gauss", psf_img)
    noise_img = noisy("poisson", noise_img1)
    
    noise1_val = norm(noise_img1 - img)
    noise2_val = norm(noise_img - img)
    
    filtered_img = np.copy(noise_img)
    for k in range(filtered_img.shape[2]):
        # filtered_img[:,:,k] = restoration.richardson_lucy(noise_img[:,:,k], psf, iterations=30)
        filtered_img[:,:,k], _ = restoration.unsupervised_wiener(noise_img[:,:,k], psf)

    filtered_noise_val = norm(filtered_img - img)
    cv2.imwrite("calibration_after_psf.png", psf_img*255)
    cv2.imwrite("calibration_after_noise.png", noise_img*255)
    cv2.imwrite("calibration_after_filter.png", filtered_img*255)
    ax1 = plt.subplot(2,2,1)
    plt.imshow(img), plt.title("Input Image")
    plt.subplot(2,2,2, sharex=ax1, sharey=ax1),plt.imshow(psf_img), plt.title("img after psf: {0}".format(psf_img_noise_val))
    plt.subplot(2,2,3, sharex=ax1, sharey=ax1),plt.imshow(noise_img),plt.title("img with noise : {0}".format(noise2_val))
    plt.subplot(2,2,4, sharex=ax1, sharey=ax1),plt.imshow(filtered_img), plt.title("filtered image : {0}".format(filtered_noise_val))
    plt.show()
Пример #8
0
def main():
    img = io.imread('images/sabiha-gokcen.jpg')
    img = color.rgb2gray(img)

    psf = np.ones((5, 5)) / 25
    img = conv2(img, psf, 'same')
    img += 0.1 * img.std() * np.random.standard_normal(img.shape)

    deconvolved, _ = restoration.unsupervised_wiener(img, psf)

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

    plt.gray()

    ax[0].imshow(img, vmin=deconvolved.min(), vmax=deconvolved.max())
    ax[0].axis('off')
    ax[0].set_title('Data')

    ax[1].imshow(deconvolved)
    ax[1].axis('off')
    ax[1].set_title('Self tuned restoration')

    fig.tight_layout()

    plt.show()
    return True
Пример #9
0
    def deconvolve_psf(self, method='WH'):

        self.full_map.meta['lvl_num'] = 1.4

        if method == 'WH':
            self.full_map.data = restoration.unsupervised_wiener(self.full_map.data.astype('float64'), self.psf.astype('float64'), clip=False)[0]

        if method == 'RL_SSW':
            # should be equivalent to the IDL AIA_DECONVOLVE_RICHARDSONLUCY() routine but it isn't
            # Not working...
            image = self.full_map.data.astype(np.float)
            im_deconv = np.copy(self.full_map.data.astype(np.float))
            psf = self.psf.astype(np.float)
            psf_mirror = psf[::-1, ::-1] # to make the correlation easier
            psfnorm = fftconvolve(psf, np.ones_like(psf), 'same')

            for _ in range(25):
                relative_blur = image / fftconvolve(psf, im_deconv, 'same')
                im_deconv *= fftconvolve(relative_blur, psf_mirror, 'same')/psfnorm

            self.full_map.data=np.abs(im_deconv)

        if method == 'RL':
            # Not working...
            self.full_map.data = restoration.richardson_lucy(self.full_map.data.astype('float64'), self.psf.astype('float64'), iterations=25, clip=False)
Пример #10
0
def weiner(image, **kwargs):
    # doesn't really make sense
    if 'psf' not in kwargs:
        psf = yp.ones((5, 5)) / 25
    else:
        psf = kwargs['psf']
    filtered, _ = unsupervised_wiener(image, psf, is_real=False)
    return _check_validity(image, filtered)
def test_unsupervised_wiener():
    psf = np.ones((5, 5)) / 25
    data = convolve2d(test_img, psf, "same")
    np.random.seed(0)
    data += 0.1 * data.std() * np.random.standard_normal(data.shape)
    deconvolved, _ = restoration.unsupervised_wiener(data, psf)

    path = pjoin(dirname(abspath(__file__)), "camera_unsup.npy")
    np.testing.assert_allclose(deconvolved, np.load(path), rtol=1e-3)

    _, laplacian = uft.laplacian(2, data.shape)
    otf = uft.ir2tf(psf, data.shape, is_real=False)
    np.random.seed(0)
    deconvolved = restoration.unsupervised_wiener(
        data, otf, reg=laplacian, is_real=False, user_params={"callback": lambda x: None}
    )[0]
    path = pjoin(dirname(abspath(__file__)), "camera_unsup2.npy")
    np.testing.assert_allclose(np.real(deconvolved), np.load(path), rtol=1e-3)
Пример #12
0
def weiner_filter(img):
    astro = color.rgb2gray(img)
    from scipy.signal import convolve2d as conv2
    psf = np.ones((5, 5)) / 25
    astro = conv2(astro, psf, 'same')
    astro += 0.1 * astro.std() * np.random.standard_normal(astro.shape)

    deconvolved, _ = restoration.unsupervised_wiener(astro, psf)

    return deconvolved
Пример #13
0
def wh_dec(array,coupling):
	kernal=np.zeros((3,3))
	coupling=coupling*.01
	kernal[0,1]=coupling
	kernal[1,0]=coupling
	kernal[1,2]=coupling
	kernal[2,1]=coupling
	kernal[1,1]=1-4*coupling
	a,_=restoration.unsupervised_wiener(array,np.asarray(kernal),is_real=True,clip=False)
	return a
Пример #14
0
def test_unsupervised_wiener(dtype):
    psf = np.ones((5, 5), dtype=dtype) / 25
    data = convolve2d(test_img, psf, 'same')
    seed = 16829302
    # keep old-style RandomState here for compatibility with previously stored
    # reference data in camera_unsup.npy and camera_unsup2.npy
    rng = np.random.RandomState(seed)
    data += 0.1 * data.std() * rng.standard_normal(data.shape)
    data = data.astype(dtype, copy=False)
    deconvolved, _ = restoration.unsupervised_wiener(data,
                                                     psf,
                                                     random_state=seed)
    float_type = _supported_float_type(dtype)
    assert deconvolved.dtype == float_type

    rtol, atol = _get_rtol_atol(dtype)
    path = fetch('restoration/tests/camera_unsup.npy')
    np.testing.assert_allclose(deconvolved,
                               np.load(path),
                               rtol=rtol,
                               atol=atol)

    _, laplacian = uft.laplacian(2, data.shape)
    otf = uft.ir2tf(psf, data.shape, is_real=False)
    assert otf.real.dtype == _supported_float_type(dtype)
    deconvolved2 = restoration.unsupervised_wiener(data,
                                                   otf,
                                                   reg=laplacian,
                                                   is_real=False,
                                                   user_params={
                                                       "callback":
                                                       lambda x: None,
                                                       "max_num_iter": 200,
                                                       "min_num_iter": 30,
                                                   },
                                                   random_state=seed)[0]
    assert deconvolved2.real.dtype == float_type
    path = fetch('restoration/tests/camera_unsup2.npy')
    np.testing.assert_allclose(np.real(deconvolved2),
                               np.load(path),
                               rtol=rtol,
                               atol=atol)
Пример #15
0
    def deconvolution(self, toShow=False, z=0):

        imgd = self.img
        psf = np.ones((10, 10)) / 100
        for i in range(2):
            img_slice = conv2(self.img[i], psf, 'same')
            img_slice += 0.1 * img_slice.std() * np.random.standard_normal(
                img_slice.shape)
            deconvolved, _ = restoration.unsupervised_wiener(img_slice, psf)
            imgd[i] = deconvolved
        return imgd
Пример #16
0
def test_unsupervised_wiener():
    psf = np.ones((5, 5)) / 25
    data = convolve2d(test_img, psf, 'same')
    np.random.seed(0)
    data += 0.1 * data.std() * np.random.standard_normal(data.shape)
    deconvolved, _ = restoration.unsupervised_wiener(data, psf)

    path = fetch('restoration/tests/camera_unsup.npy')
    np.testing.assert_allclose(deconvolved, np.load(path), rtol=1e-3)

    _, laplacian = uft.laplacian(2, data.shape)
    otf = uft.ir2tf(psf, data.shape, is_real=False)
    np.random.seed(0)
    deconvolved = restoration.unsupervised_wiener(
        data, otf, reg=laplacian, is_real=False,
        user_params={"callback": lambda x: None})[0]
    path = fetch('restoration/tests/camera_unsup2.npy')
    np.testing.assert_allclose(np.real(deconvolved),
                               np.load(path),
                               rtol=1e-3)
Пример #17
0
    def deblur_frame(self, idx):
        img = cv2.imread(self.img_paths[idx], 0)
        img = np.divide(img, np.max(img))
        psf = self.psf2(np.linalg.norm(self.px_rate_per_frame))
        #img2 = restoration.richardson_lucy(img, psf)
        img2, _ = restoration.unsupervised_wiener(img, psf)

        plt.figure()
        plt.imshow(img)
        plt.figure()
        plt.imshow(img2)
        plt.show()
Пример #18
0
def wiener(imagePath, outputPath):
    warnings.filterwarnings("ignore")
    imagePath = "" + imagePath
    color = io.imread(imagePath)
    image = rgb2gray(color)
    #     image = img_as_ubyte(img)
    psf = np.ones((5, 5)) / 25
    image = conv2(image, psf, 'same')
    image += 0.1 * image.std() * np.random.standard_normal(image.shape)
    cleaned, _ = restoration.unsupervised_wiener(image, psf, clip=True)
    cleaned_uint8 = img_as_ubyte(cleaned)
    imsave('' + outputPath, cleaned_uint8)
    cleaned_uint8
def image_processing(dir_of_file_full_path, filename, num_rows, num_cols):
    resized_filename = resize_image.resize_image_ocr(dir_of_file_full_path,
                                                     filename, num_rows,
                                                     num_cols)
    # image_full_path = os.path.join(dir_of_file_full_path, filename)
    im = imread(resized_filename)

    # size_slice_im = im[:,:,0].shape
    # im_adaptive = np.zeros((size_slice_im[0], size_slice_im[1], 3))
    # for i in range(3):
    #     threshold = threshold_isodata(im[:,:,i])
    #     print threshold
    #     im_adaptive_i = im[:,:,i] > threshold
    #     im_adaptive[:,:,i] = im_adaptive_i

    astro = color.rgb2gray(im)
    num_iter = 1
    for i in range(num_iter):
        ax_len = 3
        psf = np.ones((ax_len, ax_len)) / float(ax_len * ax_len)
        astro = conv2(astro, psf, 'same')
        astro += 0.1 * astro.std() * np.random.standard_normal(astro.shape)

        deconvolved, _ = restoration.unsupervised_wiener(astro, psf)

        # fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 5), sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})
        #
        # plt.gray()
        #
        # ax[0].imshow(astro, vmin=deconvolved.min(), vmax=deconvolved.max())
        # ax[0].axis('off')
        # ax[0].set_title('Data')
        #
        # ax[1].imshow(deconvolved)
        # ax[1].axis('off')
        # ax[1].set_title('Self tuned restoration')
        #
        # fig.subplots_adjust(wspace=0.02, hspace=0.2,
        #                     top=0.9, bottom=0.05, left=0, right=1)
        # plt.show()

        astro = deconvolved
    arr = resized_filename.split('.')
    im_adaptive_filename = arr[0] + '_thresholded.' + arr[-1]
    imsave(im_adaptive_filename, deconvolved)
    # image_file = Image.open(im_adaptive_filename)
    # image_file = image_file.convert('1')
    # image_file.save(im_adaptive_filename)
    return im_adaptive_filename
Пример #20
0
def wiener_filter(img,
                  unsupervised=True,
                  wiener_balance=1100,
                  psf_size=5,
                  psf_numerator=25):
    """Wiener filter to sharpen an image

    This filter is used to estimate the desired value of a noisy signal.
    The Wiener filter minimizes the root mean square error between the estimated random process and the desired process.

    Arguments:
        img {array} -- Image array [Non-normalize (0-255)]

    Keyword Arguments:
        unsupervised {bool} -- true for supervised algorithm, false otherwise (default: {True})
        wiener_balance {int} -- Wiener balance parameter (default: {1100})
        psf_size {int} -- PSF kernel size (default: {5})
        psf_numerator {int} -- PSF kernel numerator (default: {25})

    Returns:
        array -- Filtered image [Non-normalize (0-255)]
    """

    img = np.array(img, np.float32)
    img = cv2.normalize(img,
                        None,
                        alpha=0,
                        beta=1,
                        norm_type=cv2.NORM_MINMAX,
                        dtype=cv2.CV_32F)  # Allow to normalize image

    psf = np.ones((psf_size, psf_size)) / psf_numerator
    convolved_img = convolve2d(img, psf, 'same')
    convolved_img += 0.1 * convolved_img.std() * \
        np.random.standard_normal(convolved_img.shape)

    deconvolved = None
    if unsupervised:
        deconvolved, _ = unsupervised_wiener(convolved_img, psf)
    else:
        deconvolved = wiener(convolved_img, psf, wiener_balance)

    cv2.absdiff(deconvolved, deconvolved)

    return deconvolved * 255
def deblur(image):
	pic = color.rgb2gray(image)
	psf = np.ones((5, 5)) / 25
	pic = conv2(pic, psf, 'same')
	pic += 0.1 * pic.std() * np.random.standard_normal(pic.shape)
	deconvolved, _ = restoration.unsupervised_wiener(pic, psf)
	fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 5),
                       sharex=True, sharey=True)
	plt.gray()
	ax[0].imshow(pic, vmin=deconvolved.min(), vmax=deconvolved.max())
	ax[0].axis('off')
	ax[0].set_title('Data')
	ax[1].imshow(deconvolved)
	ax[1].axis('off')
	ax[1].set_title('Self tuned restoration')
	fig.tight_layout()
	plt.show()
	cv2.imwrite("yo.png", deconvolved)
Пример #22
0
def test_image_shape():
    """Test that shape of output image in deconvolution is same as input.

    This addresses issue #1172.
    """
    point = np.zeros((5, 5), np.float)
    point[2, 2] = 1.
    psf = ndi.gaussian_filter(point, sigma=1.)
    # image shape: (45, 45), as reported in #1172
    image = util.img_as_float(camera()[65:165, 215:315])  # just the face
    image_conv = ndi.convolve(image, psf)
    deconv_sup = restoration.wiener(image_conv, psf, 1)
    deconv_un = restoration.unsupervised_wiener(image_conv, psf)[0]
    # test the shape
    np.testing.assert_equal(image.shape, deconv_sup.shape)
    np.testing.assert_equal(image.shape, deconv_un.shape)
    # test the reconstruction error
    sup_relative_error = np.abs(deconv_sup - image) / image
    un_relative_error = np.abs(deconv_un - image) / image
    np.testing.assert_array_less(np.median(sup_relative_error), 0.1)
    np.testing.assert_array_less(np.median(un_relative_error), 0.1)
def test_image_shape():
    """Test that shape of output image in deconvolution is same as input.

    This addresses issue #1172.
    """
    point = np.zeros((5, 5), np.float)
    point[2, 2] = 1.0
    psf = nd.gaussian_filter(point, sigma=1.0)
    # image shape: (45, 45), as reported in #1172
    image = skimage.img_as_float(camera()[110:155, 225:270])  # just the face
    image_conv = nd.convolve(image, psf)
    deconv_sup = restoration.wiener(image_conv, psf, 1)
    deconv_un = restoration.unsupervised_wiener(image_conv, psf)[0]
    # test the shape
    np.testing.assert_equal(image.shape, deconv_sup.shape)
    np.testing.assert_equal(image.shape, deconv_un.shape)
    # test the reconstruction error
    sup_relative_error = np.abs(deconv_sup - image) / image
    un_relative_error = np.abs(deconv_un - image) / image
    np.testing.assert_array_less(np.median(sup_relative_error), 0.1)
    np.testing.assert_array_less(np.median(un_relative_error), 0.1)
Пример #24
0
def process_image(img):
    shp = img.shape
    for i in range(shp[-1]):
        blr = cv2.blur(img[..., i], (3, 3))
        img = np.concatenate(
            (img, (img[..., i] - blr).reshape(shp[0], shp[1], 1)), axis=-1)

        blr = cv2.GaussianBlur(img[..., i].reshape(shp[0], shp[1], 1), (3, 3),
                               0.5)
        img = np.concatenate(
            (img, (img[..., i] - blr).reshape(shp[0], shp[1], 1)), axis=-1)

        blr = cv2.medianBlur(
            img[..., i].reshape(shp[0], shp[1], 1).astype(np.float32), 3)
        img = np.concatenate(
            (img, (img[..., i] - blr).reshape(shp[0], shp[1], 1)), axis=-1)

        psf = np.ones((3, 3)) / 9
        denoise = restoration.unsupervised_wiener(img[..., i], psf)[0]
        img = np.concatenate(
            (img, (img[..., i] - denoise).reshape(shp[0], shp[1], 1)), axis=-1)

        norm = cv2.normalize(img[..., i], 0, 255, cv2.NORM_MINMAX)
        cA, (cH, cV, cD) = pywt.wavedec2(norm, "haar", level=1)
        img = np.concatenate((img, resize(cA).reshape(shp[0], shp[1], 1)),
                             axis=-1)
        img = np.concatenate((img, resize(cH).reshape(shp[0], shp[1], 1)),
                             axis=-1)
        img = np.concatenate((img, resize(cV).reshape(shp[0], shp[1], 1)),
                             axis=-1)
        img = np.concatenate((img, resize(cD).reshape(shp[0], shp[1], 1)),
                             axis=-1)

        edges = cv2.Canny(np.uint8(img[..., i].reshape(shp[0], shp[1], 1)),
                          100, 200)
        img = np.concatenate((img, edges.reshape(shp[0], shp[1], 1)), axis=-1)

    return img
Пример #25
0
def image_processing(dir_of_file_full_path, filename, num_rows, num_cols):
    resized_filename = resize_image.resize_image_ocr(dir_of_file_full_path,
                                                     filename, num_rows,
                                                     num_cols)
    # image_full_path = os.path.join(dir_of_file_full_path, filename)
    im = imread(resized_filename)
    astro = color.rgb2gray(im)
    num_iter = 1
    for i in range(num_iter):
        ax_len = 3
        psf = np.ones((ax_len, ax_len)) / float(ax_len * ax_len)
        astro = conv2(astro, psf, 'same')
        astro += 0.1 * astro.std() * np.random.standard_normal(astro.shape)

        deconvolved, _ = restoration.unsupervised_wiener(astro, psf)
        astro = deconvolved
    arr = resized_filename.split('.')
    im_adaptive_filename = arr[0] + '_thresholded.' + arr[-1]
    imsave(im_adaptive_filename, deconvolved)
    # image_file = Image.open(im_adaptive_filename)
    # image_file = image_file.convert('1')
    # image_file.save(im_adaptive_filename)
    return im_adaptive_filename
Пример #26
0
def WeinerFilter():
    e1 = cv2.getTickCount()
    astro = color.rgb2gray(data.imread(imagePath))
    psf = np.ones((5, 5)) / 25
    astro = conv2(astro, psf, 'same')
    astro += 0.1 * astro.std() * np.random.standard_normal(astro.shape)

    deconvolved, _ = restoration.unsupervised_wiener(astro, psf)

    fig, ax = plt.subplots(nrows=1,
                           ncols=2,
                           figsize=(8, 5),
                           sharex=True,
                           sharey=True,
                           subplot_kw={'adjustable': 'box-forced'})

    plt.gray()

    ax[0].imshow(astro, vmin=deconvolved.min(), vmax=deconvolved.max())
    ax[0].axis('off')
    ax[0].set_title('Original Picture')

    ax[1].imshow(deconvolved)
    ax[1].axis('off')
    ax[1].set_title('Self tuned restoration')

    fig.subplots_adjust(wspace=0.02,
                        hspace=0.2,
                        top=0.9,
                        bottom=0.05,
                        left=0,
                        right=1)
    e2 = cv2.getTickCount()
    time = (e2 - e1) / cv2.getTickFrequency() + (
        numberThreads) + numberThreadsPerCore + numberCores
    msgbox(msg=str(time) + " seconds", title="Execution Time", ok_button="OK")
    plt.show()
sharpen_kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
sharpen = cv.filter2D(blur, -1, sharpen_kernel)

cv.imshow("GAUSSIAN", blur)
cv.imshow("deGauss", sharpen)

#############################################
# creating poisson noise
poisson = random_noise(img, mode="poisson")
# dePoiss = cv.medianBlur(poisson, 8)
cv.imshow("Poisson", poisson)
# cv.imshow("dePoiss", dePoiss)
#############################################
# creating speckle noise
speckleD = random_noise(img, mode="speckle", mean=0.04)
cv.imshow("speckleD", speckleD)

# cv.imshow("desp", desp)
speckle = random_noise(img, mode="speckle")
cv.imshow("speckle", speckle)

##############################################
psf = np.ones((5, 5)) / 25
poisson = convolve2d(poisson, psf, 'same')
poisson += 0.1 * poisson.std() * np.random.standard_normal(poisson.shape)

filtered_img, _ = restoration.unsupervised_wiener(poisson, psf)

cv.imshow("filtered_img", filtered_img)
cv.waitKey(0)
Пример #28
0
        pixels = image_edge_pixels(img)
        print pixels.min(), pixels.mean(), pixels.max()
        pad_value = int(image_edge_pixels(img).mean())
        print pad, type(pad), pad_value, type(pad_value)
        img = np.pad(img, pad, mode='constant', constant_values=pad_value)
        plt.title("padding inserted")
        plt.imshow(img, cmap=cm.Greys_r)
        plt.show()
    if compare_img is not None:
        if compare_img.shape != img.shape:
            compare_img = pad_to_size(compare_img, img.shape)
        img_diff = img.astype(int) - compare_img
        print "sd of diff", img_diff.std()
        plot_images([(img, "Blurred Original"),
                     (img_diff, "Image minus reference"),
                     (compare_img, "Reference")])
    deconv, chain = restoration.unsupervised_wiener(img,
                                                    kern,
                                                    reg=None,
                                                    user_params=None,
                                                    is_real=True,
                                                    clip=False)
    print chain
    plt.title("after unsupervised Wiener restoration")
    plt.imshow(deconv, cmap=cm.Greys_r)
    plt.show()

    if deconv.shape != orig_img.shape:
        orig_img = pad_to_size(orig_img, deconv.shape)
    plot_image(deconv - orig_img, "Image difference")
Пример #29
0
plt.show()

############       Wiener     #####################

# create the motion blur kernel
im = cv2.imread(('../images/lena_gray_512.tif'), 0)
size = 5

# generating the kernel
kernel_motion_blur = np.zeros((size, size))
kernel_motion_blur[int((size - 1) / 2), :] = np.ones(size)
kernel_motion_blur = kernel_motion_blur / size
H_kernel = np.pad(kernel_motion_blur,
                  (((im.shape[0] - size) // 2, (im.shape[0] - size) // 2),
                   ((im.shape[1] - size) // 2, (im.shape[1] - size) // 2)))
output = cv2.filter2D(im, -1, H_kernel)
Degradate_image = random_noise(output, mode='gaussian', seed=None, clip=True)
psf = kernel_motion_blur
deconvolved_img = wiener(Degradate_image, psf, 10)
deconvolvedW, _ = unsupervised_wiener(Degradate_image, psf)

plt.subplot(221), plt.imshow(im, cmap='gray'), plt.title('Origin')
plt.subplot(222), plt.imshow(Degradate_image,
                             cmap='gray'), plt.title('G_image')
plt.subplot(223), plt.imshow(deconvolved_img, cmap='gray'), plt.title('Wiener')
plt.subplot(224), plt.imshow(deconvolvedW,
                             cmap='gray'), plt.title('unsupervised_wiener')

plt.show()

######
Image._show(ImageChops.subtract(im, im9), title="im-ImageFilter.RankFilter")

# In[10]:

img = np.float32(io.imread(img_name, as_gray=True))
# img = color.rgb2gray(io.imread('image.jpg'))
img = color.rgb2gray(img)

psf = np.ones((7, 7)) / 49
# img = convolve2d(img, psf, 'same')

# Add noise
# img += 0.01 * img.std() * np.random.standard_normal(img.shape)

deconv_img = restoration.wiener(img, psf, 1100)
deconv_img2, _ = restoration.unsupervised_wiener(img, psf)

# ImageViewer(img).show()
# ImageViewer(deconv_img).show()
# ImageViewer(deconv_img2).show()

cv2.imshow("Input Image", img)
cv2.imshow("Deconv1 Image", deconv_img)
cv2.imshow("Deconv2 Image", deconv_img2)
cv2.waitKey(0)
cv2.destroyAllWindows()

# In[11]:


def arithmetic_mean(img, m, n):
Пример #31
0
       Rodet, "Bayesian estimation of regularization and point
       spread function parameters for Wiener-Hunt deconvolution",
       J. Opt. Soc. Am. A 27, 1593-1607 (2010)
"""
import numpy as np
import matplotlib.pyplot as plt

from skimage import color, data, restoration

astro = color.rgb2gray(data.astronaut())
from scipy.signal import convolve2d as conv2
psf = np.ones((5, 5)) / 25
astro = conv2(astro, psf, 'same')
astro += 0.1 * astro.std() * np.random.standard_normal(astro.shape)

deconvolved, _ = restoration.unsupervised_wiener(astro, psf)

fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 5),
                       sharex=True, sharey=True,
                       subplot_kw={'adjustable': 'box-forced'})

plt.gray()

ax[0].imshow(astro, vmin=deconvolved.min(), vmax=deconvolved.max())
ax[0].axis('off')
ax[0].set_title('Data')

ax[1].imshow(deconvolved)
ax[1].axis('off')
ax[1].set_title('Self tuned restoration')
Пример #32
0
    plt.show()


from PIL import Image
im = np.array(Image.open('Bridge.jpg'))
my_imshow(im)

data = color.rgb2gray(im)
my_imshow(data)

#Low pass filter kernel.
ker = make_gaussian_kernel(lpf=1)
my_imshow(ker)

#Convolution of LPF kernel and image.
blurred_img = (convolution_filter(data, ker))
my_imshow(blurred_img)


#Applying wiener filter.
import skimage
import scipy
from skimage import color, data, restoration
from scipy import signal
WF2 = scipy.signal.wiener(blurred_img, mysize=None, noise=5) 
#my_imshow(WF2)

#Deconvolution for restoration of convoluted image.
deconvolved_img_out, _ = restoration.unsupervised_wiener(blurred_img, ker)
my_imshow(deconvolved_img_out)
Пример #33
0
def generateBeamFromApMeas(beamApMeasXFilename, beamApMeasYFilename, beamPostProcessingType, apDiameter, apStep,
                          fitConvolvedGaussian, deconvole, deblurBeam):
    """Create a beam array from aperture scan measurements

    INPUTS:
        beamApMeasXFilename     -string with the location of the aperture scan measurements in the horizontal (x)
                                    direction.
        beamApMeasYFilename     -string with the location of the aperture scan measurements in the vertical (y)
                                    direction.
        beamPostProcessingType  -string giving the type of processing that should be carried out on the beam
                                    array once the deconvolution has taken place.
        apertureDiameter        -The diameter of the aperture in microns
        apertureStep            -The incremental position at which consecutive i_pin readings
                                    are taken (in microns).

    OUTPUTS:
        beamArray               -A 2D numpy array of integer values as a spatially resolved representation
                                    of relative intensities. The values should be between 0 and 255 to be
                                    compatible with the .pgm file format.
    """
    #load the .dat file and store aperture data in a 2D numpy array.
    #Then split the 2D array into two 1D arrays, one to store the i_pin readings.
    #and one to store the aperture positions.
    #Do this for both the vertical and horizontal directions.
    apertureX = np.loadtxt(beamApMeasXFilename,skiprows=7)
    apertureXPosition = apertureX[:,0]
    apertureXMeasurement = apertureX[:,1]

    apertureY = np.loadtxt(beamApMeasYFilename,skiprows=7)
    apertureYPosition = apertureY[:,0]
    apertureYMeasurement = apertureY[:,1]

    #Get maximum i_pin reading
    maxIpin = max(apertureXMeasurement.max(), apertureYMeasurement.max())

    #If Gaussian fit is selected then fit a Gaussian profile to the beam.
    if "gaussfitconv" in fitConvolvedGaussian:
        #Fit Gaussian to the x direction data
        meanGuessX = (apertureXPosition[-1] + apertureXPosition[0])/2.0
        sigmaGuessX = 1
        gaussFitXparams, pcovariance = curve_fit(gauss,apertureXPosition,apertureXMeasurement,
                                           p0=[apertureXMeasurement.max(), meanGuessX, sigmaGuessX])

        #Fit Gaussian to the y direction data
        meanGuessY = (apertureYPosition[-1] + apertureYPosition[0])/2.0
        sigmaGuessY = 1
        gaussFitYparams, pcovariance = curve_fit(gauss,apertureYPosition,apertureYMeasurement,
                                           p0=[apertureYMeasurement.max(), meanGuessY, sigmaGuessY])

        #Create a 2d Gaussian
        X, Y = np.meshgrid(apertureXPosition, apertureYPosition)
        muX = gaussFitXparams[1]
        muY = gaussFitYparams[1]
        sigmaX = gaussFitXparams[2]
        sigmaY = gaussFitYparams[2]
        convolvedBeamArray = maxIpin * exp(-((X-muX)**2 / (2 * sigmaX**2) + (Y-muY)**2 / (2 * sigmaY**2)))

    #If the Gaussian fit wasn't selected then generate the beam by averaging the data.
    else:
        #Create temporary 2D beam arrays using both row and column wise scaling
        tempBeamArrayX = beamScalingRowWise(apertureYMeasurement,apertureXMeasurement)
        tempBeamArrayY = beamScalingColWise(apertureYMeasurement,apertureXMeasurement)

        #Take an average of the two temporary beam arrays to get a single convolved beam array
        convolvedBeamArray = (tempBeamArrayX + tempBeamArrayY) / 2

    ##############################################################
    # Create plot
    ##############################################################
#     rowNum = math.floor(convolvedBeamArray.shape[0]/2.0)
#     colNum = round(convolvedBeamArray.shape[1]/2.0)
#     fig = plt.figure()
#     plt.subplot(211)
#     plt.plot(apertureXPosition, convolvedBeamArray[rowNum,0:], 'b-', apertureXPosition, apertureXMeasurement, 'ro')

#     plt.subplot(212)
#     plt.plot(apertureYPosition, convolvedBeamArray[0:,colNum], 'b-', apertureYPosition, apertureYMeasurement, 'ro')
#     plt.show()

    if deconvole:
        #Create the aperture Point Spread Function.
        aperturePSF = createAperturePSF(apDiameter,apStep)

        #Deconvolve the beam image
        blurredBeamTuple = restoration.unsupervised_wiener(convolvedBeamArray, aperturePSF)
        blurredBeamArray = blurredBeamTuple[0]     #Get beam array

        if "smoothweiner" in deblurBeam:
            #Deblur beam with a Weiner filter
            initialBeamNoiseGuess = 1
            res = minimize(lambda beamNoise: deblurBeamObjectiveFunction(beamNoise,blurredBeamArray,aperturePSF,
                                                                        apertureXMeasurement,apertureYMeasurement),
                           initialBeamNoiseGuess, method='nelder-mead', options={'xtol': 1e-8, 'disp': True})

            #Deblur the image
            deconvolvedBeamArray = signal.wiener(blurredBeamArray,aperturePSF.shape,res.x[0])
            deblurredBeamArray = deconvolvedBeamArray
        elif "smoothgauss" in deblurBeam:
            #Fit gaussian to the blurred beam array
            params = fitgaussian(blurredBeamArray)
            fit = gauss2d(*params)
            deblurredBeamArray = fit(*np.indices(blurredBeamArray.shape))
        else:
            deblurredBeamArray = blurredBeamArray

        resultingBeamArray = deblurredBeamArray #Assign deblurred beam to another variable.
    else:
        resultingBeamArray = convolvedBeamArray

    #Apply post processing on the beam array
    processedBeamArray = beamPostProcessManip(resultingBeamArray,beamPostProcessingType)

    #Scale the beam array
    beamArray = scaleArray(processedBeamArray)

    ##############################################################
    # Create plot
    ##############################################################
#     rowNum = math.floor(beamArray.shape[0]/2.0)
#     colNum = round(beamArray.shape[1]/2.0)
#     fig = plt.figure()
#     plt.subplot(131)
#     plt.imshow(beamArray)

#     plt.subplot(132)
#     plt.plot(apertureXPosition[0:len(beamArray[rowNum,0:])], beamArray[rowNum,0:], 'b-')

#     plt.subplot(133)
#     plt.plot(apertureYPosition, beamArray[0:,colNum], 'b-')
#     plt.show()

    return beamArray
Пример #34
0

# we have to normalize the image & kernel to use skimage tools
sd_min = singledish_im.min()
sd_range = (singledish_im.max() - sd_min)
singledish_scaled = (singledish_im - sd_min) / sd_range
norm_kernel = singledish_kernel.array/singledish_kernel.array.max()

# note that for skimage, it is critical that clip=False be specified!

# Wiener deconvolution is some sort of strange Bayesian approach.  It works
# great on "real" photos of people, but doesn't work at all on our data
wienered_singledish,chain = unsupervised_wiener(image=singledish_scaled,
                                                psf=norm_kernel,
                                                clip=False,
                                                user_params=dict(max_iter=1000,
                                                                 burnin=100,
                                                                 min_iter=100,
                                                                 threshold=1e-5),)

pl.clf()
pl.imshow(wienered_singledish*sd_range+sd_min, cmap='viridis')
pl.colorbar()
pl.title("Deconvolved Single Dish (Wiener) pl=1.5 image")
pl.savefig("wienerdeconvolve_singledish_image_pl1.5.png")


# Lucy-Richardson/Richardson-Lucy is an iterative, fourier-based approach.  I
# don't understand why, but it is *very* slow.  It looks like it works fine,
# except that it saturates the brightest pixels.  This is probably an issue of
# skimage assuming everything is normalized in the range [0,1]
Пример #35
0
"""

import numpy as np
import matplotlib.pyplot as plt

from scipy.signal import convolve2d as conv2

from skimage import color, data, restoration, io

image = io.imread('bimage2.bmp')
image = color.rgb2gray(image)
psf = np.ones((8, 8)) / 81
image = conv2(image, psf, 'same')
image += 0.1 * image.std() * 0

deconvolved, _ = restoration.unsupervised_wiener(image, psf)

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

plt.gray()

ax[0].imshow(image, vmin=deconvolved.min(), vmax=deconvolved.max())
ax[0].axis('off')
ax[0].set_title('Data')

ax[1].imshow(deconvolved)
ax[1].axis('off')
Пример #36
0
       Rodet, "Bayesian estimation of regularization and point
       spread function parameters for Wiener-Hunt deconvolution",
       J. Opt. Soc. Am. A 27, 1593-1607 (2010)
"""
import numpy as np
import matplotlib.pyplot as plt

from skimage import color, data, restoration

lena = color.rgb2gray(data.lena())
from scipy.signal import convolve2d as conv2
psf = np.ones((5, 5)) / 25
lena = conv2(lena, psf, 'same')
lena += 0.1 * lena.std() * np.random.standard_normal(lena.shape)

deconvolved, _ = restoration.unsupervised_wiener(lena, psf)

fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 5))

plt.gray()

ax[0].imshow(lena, vmin=deconvolved.min(), vmax=deconvolved.max())
ax[0].axis('off')
ax[0].set_title('Data')

ax[1].imshow(deconvolved)
ax[1].axis('off')
ax[1].set_title('Self tuned restoration')

fig.subplots_adjust(wspace=0.02, hspace=0.2,
                    top=0.9, bottom=0.05, left=0, right=1)
Пример #37
0
import matplotlib.pyplot as plt
from skimage import color, data, restoration
from scipy.signal import convolve2d as conv2

# image sample
astro = color.rgb2gray(data.astronaut())
plt.title('Original image')
plt.imshow(astro, cmap='gray')
plt.show()

# define PSF as an array
# psf = np.ones((5, 5)) / 25
psf = np.array([[1, 2, 4, 2, 1], [2, 4, 8, 4, 2], [4, 8, 16, 8, 4],
                [2, 4, 8, 4, 2], [1, 2, 4, 2, 1]])
psf = psf / 25
print(psf)
plt.title('Point Spread Function')
plt.imshow(psf, cmap='gray')
plt.show()

# convolution of an original image and the PSF
astro_PSF = conv2(astro, psf, 'same')
plt.title('Imaged blurred with PSF')
plt.imshow(astro_PSF, cmap='gray')
plt.show()

# deconvolution of blurred image with Wiener filter
astro_deconvolved, noise = restoration.unsupervised_wiener(astro_PSF, psf)
plt.title('Blurred imaged recovered using \n inverse function (Wiener filter)')
plt.imshow(astro_deconvolved, cmap='gray')
plt.show()
Пример #38
0
    print "img.shape", img.shape, "kern.shape", kern.shape
    if min(img.shape) < min(kern.shape):
        pad = max(kern.shape) - min(img.shape)
        #img = np.pad(img, pad, mode='reflect')
        #img = np.pad(img, pad, mode='edge')
        pixels = image_edge_pixels(img)
        print pixels.min(), pixels.mean(), pixels.max()
        pad_value = int(image_edge_pixels(img).mean())
        print pad, type(pad), pad_value, type(pad_value)
        img = np.pad(img, pad, mode='constant', constant_values=pad_value)
        plt.title("padding inserted")
        plt.imshow(img, cmap = cm.Greys_r)
        plt.show()
    if compare_img is not None:
        if compare_img.shape != img.shape:
            compare_img = pad_to_size(compare_img, img.shape)
        img_diff = img.astype(int)-compare_img
        print "sd of diff", img_diff.std()
        plot_images([(img, "Blurred Original"), (img_diff, "Image minus reference"), (compare_img, "Reference")])
    deconv, chain = restoration.unsupervised_wiener(img, kern, reg=None, user_params=None, is_real=True, clip=False)
    print chain
    plt.title("after unsupervised Wiener restoration")
    plt.imshow(deconv, cmap = cm.Greys_r)
    plt.show()


    if deconv.shape != orig_img.shape:
        orig_img = pad_to_size(orig_img, deconv.shape)
    plot_image(deconv-orig_img, "Image difference")