1
votes

What I want to do is a code which creates an image from a list of pixels. Here is the code.

from PIL import Image
data=open("data")
data2=data.read()
dat=print (data2)
img = Image.new('RGB', (10000,10000))
img.putdata([data2])
img.save("prova_v2.jpg")

And the error that output is:

Traceback (most recent call last):
  File "C:\Users\cicles\Desktop\img - copia.py", line 5, in <module>
    img.putdata([data2])
  File "C:\Users\cicles\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\Image.py", line 1671, in putdata
    self.im.putdata(data, scale, offset)
TypeError: color must be int or tuple

The data file that contains every RGB valour for every pixel inside an image. the format is [(R,G,B), (R,G,B), (R,G,B)] So a 2-line image with Red, Green and Blue pixels in the top row and Black, Grey and White pixels in the bottom row is like this:

[(255,0,0), (0,255,0), (0,0,255), (255,255,255), (128,128,128), (0,0,0)]
1
Could you add the information about the error that occurred and provide the content in data? You can check the type of data2 to make sure the content can be put into img. - Hao Li
As Hao Li mentiones above, we really need more information to exactly say what's going wrong. One suspicious thing I see is that you put data2 in an additional array in the line img.putdata([data2]). That is probably not what you want. - physicalattraction
@HaoLi I did all the changes mentioned so it is now understandable. - user14565116
@physicalattraction I did all the changes mentioned so it is now understandable. - user14565116
Please show a data file that would correspond to a 3 pixel wide by 2 pixel high image, with for example the top row Red, Green, Blue pixels and the bottom row Black, Grey and White pixels. Thank you. - Mark Setchell

1 Answers

1
votes

Your file format is a very poor choice, so you will have to spend ages parsing the data out, removing the parentheses and commas something like this mess:

#!/usr/bin/env python3

import re
import numpy as np
from PIL import Image

# Open image file, slurp the lot
with open('file.rgb') as f:
   s = f.read()

# Make a list of anything that looks like numbers using a regex - this is ugly and slow
l = re.findall(r'[0-9]+', s)

# Now make list of strings into Numpy array of uint8 and reshape
na = np.array(l, dtype=np.uint8).reshape(2,3,3)

# Now make the Numpy array into a PIL Image
im = Image.fromarray(na)

# Save
im.save("prova_v2.png")

enter image description here