Reputation: 2244
I want to create synthetic noise within an image. How will I degrade the black and white image with errors, with an independent probability of error at each point. How will I do that in Python (e.g. Error probability = 0.0011)?
Upvotes: 2
Views: 682
Reputation: 46600
Here's a vectorized approach using OpenCV + skimage.util.random_noise
. You can experiment with noise modes such as localvar
, pepper
, s&p
, and speckle
to obtain the desired result. You can set the proportion of noise with the amount
parameter. Here's an example using s&p
with amount=0.011
:
import cv2
import numpy as np
from skimage.util import random_noise
# Load the image
image = cv2.imread('1.png', 0)
# Add salt-and-pepper noise to the image
noise = random_noise(image, mode='s&p', amount=0.011)
# The above function returns a floating-point image in the range [0, 1]
# so need to change it to 'uint8' with range [0,255]
noise = np.array(255 * noise, dtype=np.uint8)
cv2.imshow('noise',noise)
cv2.imwrite('noise.png',noise)
cv2.waitKey()
Upvotes: 2
Reputation: 8395
Here's an example program simply replacing the "degraded" pixels with black, using the Pillow library
from PIL import Image
import random
img = Image.open('text.png')
pixels = img.load()
for x in range(img.size[0]):
for y in range(img.size[1]):
if random.random() < 0.011:
pixels[x,y] = 0 # only 1 number given since the image is grayscale
img.save('text_degraded.png')
I've increased the probability to 0.011 to make it more noticeable, here's the output
Upvotes: 1