Python: reverse of transferring image into list of pixels?

Viewed 342
im = Image.open('segmentace_zkusebni_pi.jpg')
pixel = list(im.getdata())

gets me a list of RGB of every pixel in the image. For my thesis (not programming, math) I need also to reverse this process, after I do some calculations with RGB values of the pixels. So I need to get the list of 3-elemental vectors (variable pixel) transfer into image. Is there any way? Thank you very much

2 Answers
import numpy as np

im = Image.open('segmentace_zkusebni_pi.jpg')
n = np.asarray(im)
shape = n.shape

pixel = list(im.getdata())
# pixel = n.reshape((shape[0]*shape[1], shape[2])).tolist()

# do your work, but make sure the image dimension is kept same
# preferably you should work with numpy array itself
..
..

im2 = Image.fromarray((np.array(pixel, dtype='uint8')).reshape(shape))
im2.show()

You can create a new instance of Image class, store your new pixels there by using putdata and then save the new image using save method. The following is an example:

from PIL import Image

im = Image.open('segmentace_zkusebni_pi.jpg')
pixel = list(im.getdata())

# Pixel modification code
newPixel = modify(pixel)

newImg = Image.new('RGB', (im.size[0], im.size[1]))
newImg.putdata(newPixel)
newImg.save('segmentace_zkusebni_pi_new.jpg')

You can check Pillow's Image docs.

Related