2018-09-03 13:43:38 +02:00
|
|
|
# Convert png image to 256 palette image for Pokitto.
|
|
|
|
#
|
|
|
|
# author: Miloslav Ciz
|
|
|
|
# license: CC0
|
|
|
|
|
|
|
|
import sys
|
|
|
|
from PIL import Image
|
|
|
|
|
2018-09-27 10:30:52 +02:00
|
|
|
# old code, kept just in case :)
|
|
|
|
|
|
|
|
"""
|
2018-09-03 13:43:38 +02:00
|
|
|
def rgbToIndex(r, g, b):
|
|
|
|
return (r & 0b00000111) | ((g & 0b00000111) << 3) | ((b & 0b00000011) << 6)
|
2018-09-27 10:30:52 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
def encodeHSV(hue, saturation, value):
|
|
|
|
result = 0
|
|
|
|
|
|
|
|
if value > 15:
|
|
|
|
if saturation > 85:
|
|
|
|
result = ((saturation / 86 - 1) << 7) | ((hue / 32) << 4) | ((value - 16) / 15)
|
|
|
|
# "normal" color, as 0bSHHHVVVV, VVVV != 0
|
|
|
|
else:
|
|
|
|
result = value / 16
|
|
|
|
# saturation near 0 => gray, as 0bVVVV0000, VVVV != 0
|
|
|
|
|
|
|
|
return result & 0b11111111
|
|
|
|
# value near 0 => black, as 0b00000000
|
|
|
|
|
|
|
|
def findClosest(pixel, palettePixels):
|
|
|
|
result = 0
|
|
|
|
closestDist = 255 * 255 * 255
|
|
|
|
|
|
|
|
for i in range(256):
|
|
|
|
p = palettePixels[i % 16,i / 16]
|
|
|
|
d = abs(p[0] - pixel[0]) + abs(p[1] - pixel[1]) + abs(p[2] - pixel[2])
|
|
|
|
|
|
|
|
if d < closestDist:
|
|
|
|
result = i
|
|
|
|
closestDist = d
|
|
|
|
|
|
|
|
if d == 0:
|
|
|
|
break
|
|
|
|
|
|
|
|
return result
|
2018-09-03 13:43:38 +02:00
|
|
|
|
|
|
|
image = Image.open(sys.argv[1])
|
2018-09-27 10:30:52 +02:00
|
|
|
#image = image.convert("HSV")
|
2018-09-03 13:43:38 +02:00
|
|
|
pixels = image.load()
|
|
|
|
|
2018-09-27 10:30:52 +02:00
|
|
|
pal = Image.open(sys.argv[2])
|
|
|
|
palPixels = pal.load()
|
|
|
|
|
2018-09-03 13:43:38 +02:00
|
|
|
sys.stdout.write("const unsigned char image[] =\n{ ")
|
|
|
|
sys.stdout.write(str(image.size[0]) + ", " + str(image.size[1]) + " // width, height")
|
|
|
|
|
|
|
|
count = 0
|
|
|
|
|
2018-09-05 06:33:11 +02:00
|
|
|
for x in range(image.size[0]):
|
|
|
|
for y in range(image.size[1]):
|
2018-09-03 13:43:38 +02:00
|
|
|
if count % 14 == 0:
|
|
|
|
sys.stdout.write("\n ");
|
|
|
|
|
|
|
|
p = pixels[x,y]
|
|
|
|
|
2018-09-27 10:30:52 +02:00
|
|
|
#sys.stdout.write(",0x{:02x}".format(rgbToIndex(p[0] / 32, p[1] / 32, p[2] / 85)))
|
|
|
|
#sys.stdout.write(",0x{:02x}".format(encodeHSV(p[0],p[1],p[2])))
|
|
|
|
sys.stdout.write(",0x{:02x}".format(findClosest(p,palPixels)))
|
2018-09-03 13:43:38 +02:00
|
|
|
|
|
|
|
count += 1
|
|
|
|
|
|
|
|
print("\n};")
|
|
|
|
|