import sys from PIL import Image def rgbTo565(rgb): return ((rgb[0] >> 3) << 11) | ((rgb[1] >> 2) << 5) | ((rgb[2] >> 3)) def colorDist(c1,c2): return abs((c1 & 0x1f) - (c2 & 0x1f)) + abs(((c1 >> 5) & 0x3f) - ((c2 >> 5) & 0x3f)) + abs((c1 >> 11) - (c2 >> 11)) FILENAME = sys.argv[1] image = Image.open(FILENAME).convert("RGB") IMG_SIZE = image.size[0] pixels = image.load() outArray = [] if IMG_SIZE == 64: # normal texture for y in range(IMG_SIZE): for x in range(IMG_SIZE): outArray.append(rgbTo565(pixels[(x,y)])) else: # sky texture hist = [0 for i in range(65536)] for y in range(IMG_SIZE): for x in range(IMG_SIZE): hist[rgbTo565(pixels[(x,y)])] += 1 for i in range(256): # make the palette from 256 most common colors histMaxIndex = 0 for j in range(65536): if hist[j] > hist[histMaxIndex]: histMaxIndex = j outArray.append(histMaxIndex) hist[histMaxIndex] = -1 odd = True for y in range(IMG_SIZE): for x in range(IMG_SIZE): pixel = rgbTo565(pixels[(x,y)]) closestIndex = 0 closestDist = 1000 for i in range(256): dist = colorDist(pixel,outArray[i]) if dist < closestDist: closestDist = dist closestIndex = i if closestDist == 0: break if odd: outArray.append(closestIndex) odd = False else: outArray[-1] = outArray[-1] | (closestIndex << 8) odd = True outStr = "" for i in range(len(outArray)): if i % 16 == 0: outStr += "\n " outStr += "{0:#0{1}x}".format(outArray[i],6) if i != len(outArray) - 1: outStr += "," print(outStr)