Skip to main content

High quality quantization for Pillow images.

Project description

hquant

High quality quantization for Pillow images.

Pillow uses Euclidean distance for color matching during quantization, which yields poor results when using RGB due to the nonlinearity of color perception. YCbCr is a better fit for Euclidean distance, but Pillow does not natively support quantization of such images.

This module improves the quantization by converting the images to YCbCr, and then tricking Pillow into thinking it's an RGB image so quantization works.

Samples

The following samples dither the original image to the classic 16 colors supported in all terminals, using RGB (as Pillow quantize method would normally use), CIELAB and YCbCr.

Original RGB CIELAB YCbCr
Original Lena Lena using RGB Lena using CIELAB Lena using YCbCr
Original Kobold Kobold using RGB Kobold using CIELAB Kobold using YCbCr

Usage example

from PIL import Image
import hquant

terminal_palette = bytes([
	# Primary 3-bit (8 colors). Unique representation!
	0x00, 0x00, 0x00,
	0x80, 0x00, 0x00,
	0x00, 0x80, 0x00,
	0x80, 0x80, 0x00,
	0x00, 0x00, 0x80,
	0x80, 0x00, 0x80,
	0x00, 0x80, 0x80,
	0xc0, 0xc0, 0xc0,

	# Equivalent "bright" versions of original 8 colors.
	0x80, 0x80, 0x80,
	0xff, 0x00, 0x00,
	0x00, 0xff, 0x00,
	0xff, 0xff, 0x00,
	0x00, 0x00, 0xff,
	0xff, 0x00, 0xff,
	0x00, 0xff, 0xff,
	0xff, 0xff, 0xff,
])

original = Image.open('lena.png')
dithered = hquant.quantize(original, terminal_palette)
dithered.save('dithered.png')

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

hquant-0.1.0.tar.gz (347.9 kB view hashes)

Uploaded Source

Built Distribution

hquant-0.1.0-py3-none-any.whl (3.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page