Mayank Thapliyal
Mayank Thapliyal

Reputation: 39

How to downsize image while preserving same no. of colors used?

I have an image that is composed of 25 colors. Its resolution is 720x1280 & I want to downsize it to 144x256 (it is in ratio with the original one). I use PIL in python to achieve the same

Here is my code:-

o=PIL.Image.open('original25.png')
o=o.resize((144,256),resample=PIL.Image.LANCZOS)
o.save('3_.png')

The issue is that the new image has lots of colors (around 15000) whereas the original image had only 25 colors.

How to downsize the image without gain in number of colors?

Note:-I experimented a little bit from my side & I played with the "resample" filter. Using NEAREST option, there were only 25 colors in the final result which I wanted. But unfortunately, the quality of the image became super trashy & was filled with white pixels (practically unusable). And by using BILINEAR /BICUBIC /LANCZOS, the number of colors were getting increased

Edit:- Example of an image https://drive.google.com/file/d/1tBjnU1NkN0x72tHTuCQOBZUxTfxNxq9w/view?usp=sharing

Upvotes: 0

Views: 239

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207485

Use "Nearest Neighbour" resampling instead of Lanczos to preserve original colours.

Or, if it is ok to use 25 new colours after resizing, you could use Lanczos to resize, then use Image.quantize() to revert to 25 colours afterwards - preferably using LIBIMAGEQUANT method.

This is what ImageMagick makes of it with Nearest Neighbour resampling - you don't show your "super trashy" result:

enter image description here

Upvotes: 1

Related Questions