Search code examples
pythonpython-3.ximageimage-processingnoise

How to add synthetic noise in an image with specified error probability


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)?

enter image description here


Solution

  • 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 enter image description here