Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create image from a list of pixel values in Python3?

If I have a list of pixel rows from an image in the following format, how would get the image?

[
   [(54, 54, 54), (232, 23, 93), (71, 71, 71), (168, 167, 167)],
   [(204, 82, 122), (54, 54, 54), (168, 167, 167), (232, 23, 93)],
   [(71, 71, 71), (168, 167, 167), (54, 54, 54), (204, 82, 122)],
   [(168, 167, 167), (204, 82, 122), (232, 23, 93), (54, 54, 54)]
]
like image 366
Gray Avatar asked Oct 25 '17 03:10

Gray


People also ask

Can Python make images?

PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. PIL. Image. new() method creates a new image with the given mode and size.


1 Answers

PIL and numpy are your friends here:

from PIL import Image
import numpy as np


pixels = [
   [(54, 54, 54), (232, 23, 93), (71, 71, 71), (168, 167, 167)],
   [(204, 82, 122), (54, 54, 54), (168, 167, 167), (232, 23, 93)],
   [(71, 71, 71), (168, 167, 167), (54, 54, 54), (204, 82, 122)],
   [(168, 167, 167), (204, 82, 122), (232, 23, 93), (54, 54, 54)]
]

# Convert the pixels into an array using numpy
array = np.array(pixels, dtype=np.uint8)

# Use PIL to create an image from the new array of pixels
new_image = Image.fromarray(array)
new_image.save('new.png')

EDIT:

A little fun with numpy to make an image of random pixels:

from PIL import Image
import numpy as np

def random_img(output, width, height):

    array = np.random.random_integers(0,255, (height,width,3))  

    array = np.array(array, dtype=np.uint8)
    img = Image.fromarray(array)
    img.save(output)


random_img('random.png', 100, 50)
like image 50
Jebby Avatar answered Sep 27 '22 19:09

Jebby