Search code examples
image-processingpython-imaging-libraryquantization

Quantize Image using PIL and numpy


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:

enter image description here

and I expect the output for 2-level quantization to be like this:

enter image description here

but the output is like this:

enter image description here

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()

Solution

  • 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')
    

    enter image description here


    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:

    enter image description here

    And if you remove the dither parameter, you get a dithered version:

    enter image description here