18

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)]
]
Gray
  • 373
  • 1
  • 3
  • 10

2 Answers2

23

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)
Jebby
  • 1,845
  • 1
  • 12
  • 25
  • 2
    Great! Editing my post for a little list comprehension fun to make an image with random pixel values. – Jebby Oct 25 '17 at 05:20
  • Great answer but for a big resolution it takes quite a bit of time ( the random pixels one) and so I though I should try to optimize it (Never done it before). The only modification I made is that instead of list comprehension and calling the function width*height*3 times I just called it once. array = np.random.random_integers(0,255, (width,height,3)) . Have a great day :) –  Jan 06 '18 at 07:06
  • 1
    Well noted. I will update my answer for anyone else that comes across this. – Jebby Jan 06 '18 at 07:08
1

Haven't used PIL myself, but the best way of finding out is to open an actual image file using PIL. Then explore the API and objects involved with opening said image and look at how the pixel values are stored within the specific object pertaining to the API.

You can then construct a valid PIL image object using your extracted RGB values.

Edit: See the following post: How do I create an image in PIL using a list of RGB tuples?

Additional, accessing pixel values in PIL: https://pillow.readthedocs.io/en/4.3.x/reference/PixelAccess.html

silent
  • 2,836
  • 10
  • 47
  • 73
  • Thanks, but I've already looked at those posts before, but I still don't understand how to create an image from the values that I have. I know that you can extract pixel values from an image using getdata(), but how would you create a new image from only a list of pixel values? – Gray Oct 25 '17 at 03:52