Skip to content

Instantly share code, notes, and snippets.

@AxelStrem
Created December 13, 2016 10:10
Show Gist options
  • Save AxelStrem/2a7bd2ed9e7f38eb5cf68f239ae7bc97 to your computer and use it in GitHub Desktop.
Save AxelStrem/2a7bd2ed9e7f38eb5cf68f239ae7bc97 to your computer and use it in GitHub Desktop.
Converts a bitmap to specific 8-bit palette with no dithering
import PIL
import numpy as np
def quantizetopalette(silf, palette, dither=False):
"""Convert an RGB or L mode image to use a given P image's palette."""
silf.load()
# use palette from reference image
palette.load()
if palette.mode != "P":
raise ValueError("bad mode for palette image")
if silf.mode != "RGB" and silf.mode != "L":
raise ValueError(
"only RGB or L mode images can be quantized to a palette"
)
im = silf.im.convert("P", 1 if dither else 0, palette.im)
# the 0 above means turn OFF dithering
return silf._makeself(im)
img = PIL.Image.open('in.bmp').convert('RGB')
pal = PIL.Image.open('palette.bmp').convert('P')
img = quantizetopalette(img, pal, dither=False)
img.save('out.bmp')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment