Skip to content

Instantly share code, notes, and snippets.

@Cosmologist
Created February 7, 2014 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cosmologist/8858729 to your computer and use it in GitHub Desktop.
Save Cosmologist/8858729 to your computer and use it in GitHub Desktop.
Image quantize - http://pickbox.ru/e/330
import quantize
image.open('test.png')
# Quantize image with 8 colors (3-bit)
image = quantize.quantize(image, quantize.PALETTE_8_COLORS)e
image.save('test_quantize.png')
from PIL import Image
PALETTE_8_COLORS = (
(0, 0, 0), (0, 0, 255), (0, 255, 0), (0, 255, 255), (255, 0, 0), (255, 0, 255), (255, 255, 0), (255, 255, 255))
def quantize(im, use_colors=None):
"""
Quantize image
:param image: Image for quantize
:param use_colors: The list of colors, all other colors are converted into their
Each color must be presented as a tuple (red, green, blue)
"""
# if use_colors is None and depth is None:
# return im
palette = []
# Generate palette from use_colors params
if use_colors is not None:
for color in use_colors:
palette += color
# The palette sequence must contain 768 integer values
palette += [0, ] * (768 - len(palette))
# a palette image to use for quantize
palette_image = Image.new("P", (1, 1), 0)
palette_image.putpalette(palette)
# quantize it using our palette image
return im.quantize(palette=palette_image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment