1

I have a list of length 9 million which contains tuples representing RGB value. Example: A = [(255, 255, 255), (0, 0, 0) .......... , (0, 0, 0)]

I have to create an image in python (size: 3000*3000) where every tuple in the list represents one pixel. The image should contain some black and white pixels.

#However, using the code below I got an image with all pixels black. 

img = Image.new('1', (3000,3000))
img.putdata(A)
img.show()

Why does not the image not reflect white pixels? Appreciate any help. Thank you!

Sonal Borkar
  • 531
  • 1
  • 6
  • 12
Kalamazoo
  • 111
  • 1
  • 10
  • Possible duplicate of [How to create image from a list of pixel values in Python3?](https://stackoverflow.com/questions/46923244/how-to-create-image-from-a-list-of-pixel-values-in-python3) – Sonal Borkar Dec 01 '18 at 03:54
  • Maybe try re-slicing the array with `[A[3000ii:3000*(ii+1)] for ii in range(3000)]`? I don't recall if putdata() is smart enough to automatically 2d-ify arrays for you. – Jakob Lovern Dec 01 '18 at 05:28

1 Answers1

0

there are many ways to accomplish what you are looking for. The problem in your code is that you are giving a one-dimensional array as input. To solve the problem just convert it in a bidimensional array.

from PIL import Image
import numpy as np

long_list = [(255, 255, 255), (0, 0, 0) .......... , (0, 0, 0)]
img_size = 3000
array = np.array([long_list[img_size*i:img_size*(i+1)] for i in range(img_size)], dtype=np.uint8)

img = Image.fromarray(array)

img.save('output.png')

another way is to work with the single pixel value using two for loops like this:

from PIL import Image

long_list = [(255, 255, 255), (0, 0, 0) .......... , (0, 0, 0)]

img_size = 3000 #int(sqrt(len(long_list)))

img = Image.new("RGB", (img_size,img_size))

pixels = img.load()

for x in range(img_size):
    for y in range(img_size):
        pixels[x,y] = long_list[img_size*x+y]


img.save("new.png")
Liam
  • 6,009
  • 4
  • 39
  • 53