I have an image that I want to perform quantization on it. I want to use PIL and Numpy libraries and the original image is:
and I expect the output for 2-level quantization to be like this:
but the output is like this:
What am I doing wrong?
from PIL import Image
import PIL
# creating an image object (main image)
im1 = Image.open(r'File Address').convert('L')
# quantize a image
im1 = im1.quantize(2)
# to show a specified image
im1.show()
You can quantize to another image with a specific palette, so you just need to make such an image first and then quantize to it:
#!/usr/bin/env python3
from PIL import Image
# Make tiny palette Image, one black pixel
palIm = Image.new('P', (1,1))
# Make your desired B&W palette containing only 1 pure white and 255 pure black entries
palette = [255, 255, 255 ] + [0, 0 ,0] * 255
# Push in our lovely B&W palette and save just for debug purposes
palIm.putpalette(palette)
palIm.save('DEBUG-palette.png')
# Load actual image
actual = Image.open('95KIY.png').convert('RGB')
# Quantize actual image to palette
actual = actual.quantize(palette=palIm, dither=Image.Dither.NONE)
actual.save('result.png')
So if you want to quantize to orange and navy blue, just change the palette to:
palette = [255, 128, 0 ] + [0, 0 ,128] * 255
And you get this:
And if you remove the dither
parameter, you get a dithered version: