We can use the putpixel() function to change a pixel value in an image. Next, let us discuss a popular application of adding noise to an image using the function.
Adding salt and pepper noise to an image
We can add some salt-and-pepper noise to an image by selecting a few pixels from the image randomly and then setting about half of those pixel values to black and the other half to white. The next code snippet shows how to add the noise:
# choose 5000 random locations inside imageim1 = im.copy() # keep the original image, create a copy n = 5000x, y = np.random.randint(0, im.width, n), np.random.randint(0, im.height, n)for (x,y) in zip(x,y): im1.putpixel((x, y), ((0,0,0) if np.random.rand() < 0.5 else (255,255,255))) ...