Reputation: 119
I'm trying to create an image from list of 1s and 0s in Python.
from PIL import Image
img1 = Image.open('Image1.gif') #the image is strictly black and white
img1_size = img1.size
img1_k = []
for i in range(img1_size[0]):
for j in range(img1_size[1]):
tmp_pix = img1.getpixel((i,j))
if (tmp_pix>127):
img1_k.append(1)
else:
img1_k.append(0)
img = Image.new('RGB', (img1_size[1],img1_size[0]), "white")
cmap = {1: (255,255,255),
0: (0,0,0)}
data = [cmap[i] for i in img1_k]
img.putdata(data)
img.show()
img.save('Image2.png')
However, instead of original image:
The code produces rotated and inverted image:
I'm guessing that the format of putdata() differs from the way I acquired pixels for the list. How can I get the picture right?
Upvotes: 4
Views: 4341
Reputation: 368894
getpixel
, putpixel
is based on x-y coordinates while getdata
, putdata
is based on row-column based.
First, you need to make the img_k
row-column based:
for j in range(img1_size[1]): # row (y)
for i in range(img1_size[0]): # column (x)
tmp_pix = img1.getpixel((i,j))
if tmp_pix > 127:
img1_k.append(1)
else:
img1_k.append(0)
Second, you need to create x*y sized image:
img = Image.new('RGB', (img1_size[0], img1_size[1]), "white") # <--
# OR Image.new('RGB', img1.size, "white")
cmap = {1: (255,255,255),
0: (0,0,0)}
data = [cmap[i] for i in img1_k]
img.putdata(data)
img.show()
img.save('Image2.png')
BTW, instead of mixing getpixel
and putdata
, by using getdata
and putdata
the code can be simpler:
from PIL import Image
img1 = Image.open('Image1.gif')
data = [(255, 255, 255) if pixel > 127 else (0, 0, 0) for pixel in img1.getdata()]
img = Image.new('RGB', img1.size, "white")
img.putdata(data)
img.show()
img.save('Image2.png')
Upvotes: 2