Demo entry 4038467

Add Noise

   

Submitted by anonymous on Mar 14, 2016 at 14:07
Language: Python. Code size: 2.1 kB.

'''
Parametros
----------
image : ndarray
    Imagem de entrada que sera convertida para float.
mode : str
    Uma das strings abaixo, dependo do tipo de ruido que voce deseja adicionar:

    'gauss'     Ruidos Gaussianos
    'poisson'   Ruidos do tipo Poisson
    's&p'       Ruidos do tipo "sal e pimenta"
    'speckle'   Ruidos multiplicativos usando saida = entrada + n*entrada onde
                n eh ruido uniforme com tipo e variancia predefinida
'''

import numpy as np
import os
import cv2
from matplotlib import pyplot as plt

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 = 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


img = cv2.imread('teste.png',1)

ruido = noisy('s&p',img)

plt.subplot(121),plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('Original'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(cv2.cvtColor(ruido, cv2.COLOR_BGR2RGB))
plt.title('Com ruido'), plt.xticks([]), plt.yticks([])

plt.show()

cv2.imwrite('img-ruido.png',ruido)

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).