Denoising images

Noise is a common phenomenon in data and also in images. Of course, noise is undesirable, as it does not add any value to our analysis. We typically assume that noise is normally distributed around zero. We consider a pixel value to be the sum of the true value and noise (if any). We also assume that the noise values are independent, that is, the noise value of one pixel is independent of another pixel.

One simple idea is to average pixels in a small window, since we suppose the expected value of noise to be zero. This is the general idea behind blurring. We can take this idea a step further and define multiple windows around a pixel, and we can then average similar patches.

OpenCV has several denoising functions and usually we need to specify the strength of the filter, the size of the search window, and the size of the template window for similarity checks. You should be careful not to set the filter strength too high because that may make the image not only cleaner, but also a bit blurred.

Getting ready

Follow the instructions in the Setting up OpenCV recipe.

How to do it...

  1. The imports are as follows:
    import cv2
    import matplotlib.pyplot as plt
    from sklearn.datasets import load_sample_image
    import numpy as np
    import dautil as dl
  2. Plot the original image as follows:
    img = load_sample_image('china.jpg')
    dl.plotting.img_show(plt.gca(), img) 
    plt.title('Original')
    Z = img.reshape((-1, 3))
  3. Add noise to the image and plot the noisy image:
    np.random.seed(59)
    noise = np.random.random(Z.shape) < 0.99
    
    noisy = (Z * noise).reshape((img.shape))
    
    plt.figure()
    plt.title('Noisy')
    dl.plotting.img_show(plt.gca(), noisy)
  4. Clean the image and display it:
    cleaned = cv2.fastNlMeansDenoisingColored(noisy, None, 10, 10, 7, 21)
    plt.figure()
    plt.title('Cleaned')
    dl.plotting.img_show(plt.gca(), cleaned)

Refer to the following screenshot for the end result:

How to do it...

The code is in the denoising_images.ipynb file in this book's code bundle.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.161.225