Pokitto-Raycasting/convert_png.py

70 lines
1.7 KiB
Python
Raw Permalink Normal View History

2018-10-01 17:04:57 +02:00
# Convert png image to 256 palette image for Pokitto. Usage:
#
# python convert_png.py input_image.png palette_16x16_image.png
#
# The script will read the input PNG image (must be in RGB format, NOT
# indexed), match each pixel to the closest color in the palette and output
# the image to stdout as an array of bytes, by columns. It's best if the image
# is made only of color of the palette as the closest match can sometimes look
# different from what you imagined.
#
# The script will also create an image (out.png) of the converted image, so
# that you can check how it looks.
2018-09-03 13:43:38 +02:00
#
# author: Miloslav Ciz
# license: CC0
import sys
from PIL import Image
2018-09-27 10:30:52 +02:00
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])
pixels = image.load()
2018-09-27 10:30:52 +02:00
pal = Image.open(sys.argv[2])
palPixels = pal.load()
2018-09-27 15:25:20 +02:00
outImage = Image.new("RGB",(image.size[0],image.size[1]),"white")
outPixels = outImage.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 15:25:20 +02:00
closest = findClosest(p,palPixels)
sys.stdout.write(",0x{:02x}".format(closest))
outPixels[x,y] = palPixels[closest % 16,closest / 16]
2018-09-03 13:43:38 +02:00
count += 1
print("\n};")
2018-09-27 15:25:20 +02:00
outImage.save("out.png")