Denoising different types of noises in an image is done with the following steps:
- Define the plt_hist() function to plot the histogram of the noise added to the image:
def plt_hist(noise, bins=None):
plt.grid()
plt.hist(np.ravel(noise), bins=bins, alpha=0.5, color='green')
plt.tick_params(labelsize=15)
plt.title('Noise Historgram', size=25)
- Next, define the plt_images() function to plot all the images, that is, the original, noisy and denoised images, using the mean/median filters, and plot the noise histogram by calling the plt_hist() function defined previously. Also, compare the quality of the images denoised using the filters with the PSNR:
def plt_images(im, im_noisy, noise, noise_type, i):
im_denoised_mean = uniform_filter(im_noisy, 5)
im_denoised_median = median_filter(im_noisy, 5)
plt.subplot(7,4,i), plt.imshow(im_noisy), \
plt.title('Noisy ({}), PSNR={}'.format(noise_type, \
np.round(compare_psnr(im, im_noisy),3)), size=25), \
plt.axis('off')
plt.subplot(7,4,i+1), plt.imshow(im_denoised_mean), \
plt.title('Denoised (mean), PSNR={}'.format(np.round\
(compare_psnr(im, im_denoised_mean),3)), size=25), \
plt.axis('off')
plt.subplot(7,4,i+2), plt.imshow(im_denoised_median), \
plt.title('Denoised (median), PSNR={}'.format(np.round\
(compare_psnr(im, im_denoised_median),3)), size=25), \
plt.axis('off')
plt.subplot(7,4,i+3), plt_hist(noise)
- Load the original Lena RGB color image and convert it to a grayscale image:
im = rgb2gray(imread('images/lena.png'))
- Now, add random noise to the original image by drawing samples from different distributions, along with appropriate parameters—one for each of the noise distributions. After this, call the plt_images() function defined earlier to plot the images and the noise distributions:
im1 = random_noise(im, 'gaussian', var=0.15**2)
plt_images(im, im1, im1-im, 'Gaussian', 1)
im1 = random_noise(im, 's&p', amount=0.15)
plt_images(im, im1, im1[((im1==0)|(im1==1))&((im!=0)&(im!=1))], 'Impulse', 5)
noise = np.random.poisson(lam=int(np.mean(255*im)), size=im.shape)/255 - np.mean(im)
im1 = np.clip(im + noise, 0, 1)
plt_images(im, im1, noise, 'Poisson', 9)
im1 = random_noise(im, 'speckle', var=0.15**2)
plt_images(im, im1, im1-im, 'Speckle', 13)
noise = np.random.rayleigh(scale=0.15, size=im.shape) - 0.15
im1 = np.clip(im + noise, 0, 1)
plt_images(im, im1, noise, 'Rayleigh', 17)
noise = np.random.exponential(scale=0.15, size=im.shape) - 0.15
im1 = np.clip(im + noise, 0, 1)
plt_images(im, im1, noise, 'Exponential', 21)
noise = np.random.uniform(0, 0.5, size=im.shape) - 0.25
im1 = np.clip(im + noise, 0, 1)
plt_images(im, im1, noise, 'Uniform', 25)