Skip to content

Instantly share code, notes, and snippets.

@lucaswiman
Created March 13, 2020 19:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lucaswiman/1e877a164a69f78694f845eab45c381a to your computer and use it in GitHub Desktop.
Save lucaswiman/1e877a164a69f78694f845eab45c381a to your computer and use it in GitHub Desktop.
import numpy as np
import cv2
def sp_noise(image, prob):
'''
Add salt and pepper noise to image
prob: Probability of the noise
'''
output = image.copy()
if len(image.shape) == 2:
black = 0
white = 255
else:
colorspace = image.shape[2]
if colorspace == 3: # RGB
black = np.array([0, 0, 0], dtype='uint8')
white = np.array([255, 255, 255], dtype='uint8')
else: # RGBA
black = np.array([0, 0, 0, 255], dtype='uint8')
white = np.array([255, 255, 255, 255], dtype='uint8')
probs = np.random.random(image.shape[:2])
image[probs < (prob / 2)] = black
image[probs > 1 - (prob / 2)] = white
return image
@youngsoul
Copy link

Works great - thanks!

@VladUsatii
Copy link

Fast implementation! Thank you 😄

@ghltshubh
Copy link

Shouldn't it be image = image.copy() instead?

@gutierrezps
Copy link

Shouldn't it be image = image.copy() instead?

Fixed on my fork: https://gist.github.com/gutierrezps/f4ddad3bbd2ad5a9b96e3c06378e28b4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment