Home > Software design >  How to add and save a new image with Gaussian noise
How to add and save a new image with Gaussian noise

Time:07-07

In this bit of code, I am trying to add Gaussian noise to a PIL image and write it to an image file:

import os, skimage
from PIL import Image

images = os.listdir('/home/onur/Downloads/datasets/LFW-a/lfw2/')

for img in images:
    image = Image.open('/home/onur/Downloads/datasets/LFW-a/lfw2/'   img)
    image = skimage.util.random_noise(image, mode='gaussian', seed=None, clip=True)

I can't do image.save() because it is an skimage.util.random_noise() object. How can I write this to a new image file?

CodePudding user response:

I had some trouble recreating your issue so I ended up using io from skimage to open the file. Assuming you want the result saved as an image in PIL format, try this.

import os, skimage
from PIL import Image

images = os.listdir('/home/onur/Downloads/datasets/LFW-a/lfw2/')
import numpy as np
from skimage import io

for img in images:
    image = io.imread('/home/onur/Downloads/datasets/LFW-a/lfw2/'   img)    
    image = skimage.util.random_noise(image, mode='gaussian', seed=None, clip=True)
    noise_img = np.array(255*image, dtype = 'uint8')
    pil_image=Image.fromarray(np.array(noise_img))
    pil_image.save('/Users/eric/Desktop/goproject4/test.jpg')

That being said, if you want to skip a few of these steps, you can open the file in a different way, or save it before converting the output to PIL

  • Related