Python/Blurring/noise.py

"""
Parameters
----------
image : ndarray
    Input image data. Will be converted to float.
mode : str
    One of the following strings, selecting the type of noise to add:

    'gauss'     Gaussian-distributed additive noise.
    'poisson'   Poisson-distributed noise generated from the data.
    's&p'       Replaces random pixels with 0 or 1.
    'speckle'   Multiplicative noise using out = image + n*image,where
                n is uniform noise with specified mean & variance.

Taken from https://stackoverflow.com/questions/22937589/how-to-add-noise-gaussian-salt-and-pepper-etc-to-image-in-python-with-opencv
"""


import numpy as np
import os
import cv2 as cv

def toIntImage(frame):
    frame *= 255
    return frame.astype(np.uint8)

def normaliseImage(frame):
    """
    Convert to greyscale, and to 64bit floating point.
    Normalise pixel values to [0,1] range.
    It assumes an 8bit integer image as input and does
    no error checking.
    """
    grey = cv.cvtColor(frame, cv.COLOR_BGR2GRAY).astype(np.float64)
    grey /= 255
    return grey

def addGaussNoise(image,var=0.02):
      row,col = image.shape
      mean = 0
      sigma = var**0.5
      gauss = np.random.normal(mean,sigma,(row,col))
      gauss = gauss.reshape(row,col)
      noisy = image + gauss
      return noisy

def addSaltPepperNoise(image,amount=0.01):
      row,col = image.shape
      s_vs_p = 0.5
      out = np.copy(image)
      # Salt mode
      num_salt = np.ceil(amount * image.size * s_vs_p)
      coords = [np.random.randint(0, i - 1, int(num_salt))
              for i in image.shape]
      out[tuple(coords)] = 1

      # Pepper mode
      num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
      coords = [np.random.randint(0, i - 1, int(num_pepper))
              for i in image.shape]
      out[tuple(coords)] = 0
      return out

def addPoissonNoise(image):
      "Not reviewed"
      vals = len(np.unique(image))
      vals = 2 ** np.ceil(np.log2(vals))
      noisy = np.random.poisson(image * vals) / float(vals)
      return noisy
def addSpeckleNoise(image):
      "Not reviewed"
      row,col = image.shape
      gauss = np.random.randn(row,col)
      gauss = gauss.reshape(row,col)        
      noisy = image + image * gauss
      return noisy