I am trying to use PIL to display an image from an array. The array is a long list of elements which are pixel values of an image. How do I display these pixel values as an image ?
1 Answer
You don't specify what kind of data is in your list, so I assume it is an array with 25 elements (grouped in 5 groups of 5), which will be converted to a 5 by 5 black & white image.
from PIL import Image
import random
data = [
[1,0,0,1,0],
[1,1,1,0,0],
[1,1,0,1,0],
[1,0,1,1,0],
[0,1,1,0,1],
]
img = Image.new("1", (5, 5))
pixels = img.load()
for i in range(img.size[0]):
for j in range(img.size[1]):
pixels[i, j] = data[i][j]
img.show()
img.save("img.png")
This is similar to this question: How can I write a binary array as an image in Python?