I have a file 'map.jpg' which is composed of black and white pixels (16x16 img) and I would like to convert in a text file a white pixel to a 0 and a black pixel to a 1. I have this:
from PIL import Image
import os
mapImg = Image.open('map.png')
with open('map.txt', 'a+') as map:
for y in range(16):
for x in range(16):
pix = mapImg.getpixel((x, y))
if x == 15:
map.write('\n')
else:
if pix == (255, 255, 255):
map.write('0')
else:
map.write('1')
But I don't know why the result is this in my txt file:
000000000
0011000000
0111110000
0100000110
0010011100
0101010
0111100
000010101000
001110000
00011000000
0000100000
0011000
0000010000
00000000
000000000
000000000
which is not what the 'map.jpg' file looks like.
Edit: Thanks to Random Davis, problem solved! Just needed to change the image format because jpeg compressed the img to much or something, thanks!
If your image is a jpg
, then it's lossily compressed, meaning that all the pixels won't necessarily be fully black or white. You need a lossless source that truly has only those two colors, otherwise pixels will be miscategorized.