How to resize and image in python while preserving specific grayscale values?

Question:

I have a .png image that contains three grayscale values. It contains black (0), white (255) and gray (128) blobs. I want to resize this image to a smaller size while preserving only these three grayscale values.

Currently, I am using scipy.misc.imresize to do it but I noticed that when I reduce the size, the edges get blurred and now contains more than 3 grayscale values.

Does anyone know how to do this in python?

Asked By: jlcv

||

Answers:

I believe that PIL.Image.resize does exactly what you want. Take a look at the docs.

Basically what you need is:

from PIL import Image
im = Image.open('old.png')
# The Image.NEAREST is the default, I'm just being explicit
im = im.resize((im.size[0]/2, im.size[1]/2), Image.NEAREST)
im.save('new.png')

Actually you can pretty much do that with the scipy.misc.imresize
Take a look at its docs.

The interp parameter is what you need. If you set it to nearest the image colors won’t be affected.

Answered By: Dmitry Yantsen

From the docs for imresize, note the interp keyword argument:

interp : str, optional
   Interpolation to use for re-sizing
   (‘nearest’, ‘lanczos’, ‘bilinear’, ‘bicubic’ or ‘cubic’).

The default is bilinear filtering; switch to nearest and it will instead use the exact color of the nearest existing pixel, which will preserve your precise grayscale values rather than trying to linearly interpolate between them.

Answered By: Amber