66

I am wondering if there exists some functions in Python with OpenCV or any other python image processing library that adds Gaussian or salt and pepper noise to an image? For example, in MATLAB there exists straight-forward functions that do the same job.

Or, how to add noise to an image using Python with OpenCV?

4
  • 8
    Have you tried searching? stackoverflow.com/questions/14435632/… for example Apr 8, 2014 at 12:52
  • 1
    @Cyber Yes I know about them, but they are for MATLAB. They are MATLAB functions for adding noise in the image. But, my question is doing the same while using python and opencv.
    – Sanchit
    Apr 8, 2014 at 12:53
  • 1
    @Sanchit, the answer for question mentioned by Cyber is not Matlab but OpenCV Apr 8, 2014 at 13:22
  • @MichaelBurdinov: Sorry I mistakenly looked into another page (they are using MATLAB functions). Yes, I think this concept can be used (for Gaussian noise). I give a try to it.
    – Sanchit
    Apr 8, 2014 at 13:28

3 Answers 3

125

The Function adds gaussian , salt-pepper , poisson and speckle noise in an image

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.


import numpy as np
import os
import cv2
def noisy(noise_typ,image):
   if noise_typ == "gauss":
      row,col,ch= image.shape
      mean = 0
      var = 0.1
      sigma = var**0.5
      gauss = np.random.normal(mean,sigma,(row,col,ch))
      gauss = gauss.reshape(row,col,ch)
      noisy = image + gauss
      return noisy
   elif noise_typ == "s&p":
      row,col,ch = image.shape
      s_vs_p = 0.5
      amount = 0.004
      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[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[coords] = 0
      return out
  elif noise_typ == "poisson":
      vals = len(np.unique(image))
      vals = 2 ** np.ceil(np.log2(vals))
      noisy = np.random.poisson(image * vals) / float(vals)
      return noisy
  elif noise_typ =="speckle":
      row,col,ch = image.shape
      gauss = np.random.randn(row,col,ch)
      gauss = gauss.reshape(row,col,ch)        
      noisy = image + image * gauss
      return noisy
10
  • 2
    ouput image noise_img = sp_noise(image,0.05) cv2.imwrite('sp_noise.jpg', noise_img) size 0 Oct 12, 2016 at 14:06
  • 1
    this 'salt and pepper' method adds to each color channel individually. some examples I have seen show black and white speckles even for a color image.... which is correct or realistic?
    – ng0323
    Jan 24, 2018 at 8:32
  • what is the meaning of s_vs_p and amount?
    – ng0323
    Jan 24, 2018 at 8:45
  • 3
    for color images it probably makes sense to do it in HSV space and then convert to RGV Feb 23, 2018 at 21:03
  • 5
    I guess u should change 1 as salt to 255 if it's RGB
    – klapeyron
    Feb 26, 2019 at 7:39
25

I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.

import numpy as np
import random
import cv2

def sp_noise(image,prob):
    '''
    Add salt and pepper noise to image
    prob: Probability of the noise
    '''
    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob 
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output

image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)
5
  • Good one. That is working well Jan 18, 2017 at 18:36
  • 2
    Simple and to the point. Thanks. I would recommend doing this with vectorized operations for efficiency since you're using NumPy arrays.
    – rayryeng
    Nov 27, 2018 at 6:19
  • I implemented a vectorized version based on this answer here: gist.github.com/lucaswiman/1e877a164a69f78694f845eab45c381a It is indeed much faster. Mar 13, 2020 at 19:22
  • Why you took rdn>thres to add salt noise? May 1, 2020 at 6:46
  • any reason this would change color of the image?
    – mlanier
    Oct 26, 2021 at 16:34
12

just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.

let's play a bit ;) :

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168,  58,   2,   1],  # uninitialized memory counts as random, too ?  fun ;) 
       [  0, 100,   2,   0, 101],
       [  0,   0, 106,   2,   0],
       [131,   2,   0,  90,   3],
       [  0, 100,   1,   0,  83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))         # normal
array([[  0,  76,   0, 129,   0],
       [  0,   0,   0, 188,  27],
       [  0, 152,   0,   0,   0],
       [  0,   0, 134,  79,   0],
       [  0, 181,  36, 128,   0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))         # uniform
array([[19, 53,  2, 86, 82],
       [86, 73, 40, 64, 78],
       [34, 20, 62, 80,  7],
       [24, 92, 37, 60, 72],
       [40, 12, 27, 33, 18]], dtype=uint8)

to apply it to an existing image, just generate noise in the desired range, and add it:

img = ...
noise = ...

image = img + noise
3
  • Executing this cv2.randn(im,(0),(99)) won't return array as shown in the answer. It returns NoneType . Please print im array to check the random values. randn
    – formatkaka
    Jul 27, 2016 at 5:29
  • Maybe you could change dtype=np.int8 as compared to uint8. That way, the noise can also be negative and the overall brightness stays roughly the same. With this solution it is only getting brighter. Feb 17, 2017 at 9:50
  • 4
    I'd suggest cv2.add(img, noise) because img+noise would give undesirable results . This is because opencv hanldles 250+10 as 255 while numpy would handle it as (250+10)%255 = 5 Apr 6, 2020 at 13:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.