简体   繁体   中英

How to add and save a new image with Gaussian noise

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM