简体   繁体   English

如何在保留特定灰度值的同时在python中调整大小和图像?

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

I have a .png image that contains three grayscale values. 我有一个包含三个灰度值的.png图像。 It contains black (0), white (255) and gray (128) blobs. 它包含黑色(0),白色(255)和灰色(128)斑点。 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. 当前,我正在使用scipy.misc.imresize来执行此操作,但是我注意到减小尺寸时,边缘变得模糊,现在包含3个以上的灰度值。

Does anyone know how to do this in python? 有谁知道如何在python中做到这一点?

From the docs for imresize , note the interp keyword argument: 该文档为imresize ,注意interp关键字参数:

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

The default is bilinear filtering; 默认为bilinear过滤。 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. 切换到nearest ,它将使用最接近的现有像素的确切颜色,这将保留您的精确灰度值,而不是尝试在它们之间进行线性插值。

I believe that PIL.Image.resize does exactly what you want. 我相信PIL.Image.resize确实PIL.Image.resize您的需求。 Take a look at the docs . 看一下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 . 事实上,你几乎可以做,与scipy.misc.imresize看看它的文档

The interp parameter is what you need. interp参数正是您所需要的。 If you set it to nearest the image colors won't be affected. 如果将其设置为nearest则图像颜色不会受到影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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