How can I create a PNG image file from a list of pixel values in Python? -


i can generate list of pixel values existing image file using procedure following:

from pil import image image = image.open("test.png") pixels = list(image.getdata()) width, height = image.size pixels = [pixels[i * width:(i + 1) * width] in xrange(height)] 

how convert list of pixel values image file?

quick fix

first, need have pixel tuples in single un-nested list:

pixels_out = [] row in pixels:     tup in row:         pixels_out.append(tup) 

next, make new image object, using properties of input image, , put data it:

image_out = image.new(image.mode,image.size) image_out.putdata(pixels_out) 

finally, save it:

image_out.save('test_out.png') 

fundamental issue

your list comprehension generates list of lists, latter being generated slicing (i*width:(i+1)*width). comprehension can easier: pixels = [pixel pixel in pixels]. outputs same list, pixels, can use idea perform operation on pixels, e.g. pixels = [operation(pixel) pixel in pixels].

really, overthought it. don't have manage image dimensions. getting pixels in list, , putting them equal-sized image putdata keeps in order because linearized same way pil.

in short, original snippet should have been:

from pil import image image = image.open("test.png") image_out = image.new(image.mode,image.size)  pixels = list(image.getdata()) image_out.putdata(pixels) image_out.save('test_out.png') 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -