简体   繁体   中英

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

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM