我正在尝试使用枕头库(Python图像库,PIL)将PNG格式的RGB图像转换为使用特定的索引调色板。但我想用“舍入到最接近的颜色”的方法来转换,而不是抖动,因为图像是像素艺术,抖动会扭曲区域的轮廓,并给打算平坦的区域添加噪声。
我试过Image.Image.paste()
,它使用了四种指定的颜色,但它生成了一个抖动的图像:
from PIL import Image
oldimage = Image.open("oldimage.png")
palettedata = [0, 0, 0, 102, 102, 102, 176, 176, 176, 255, 255, 255]
newimage = Image.new('P', oldimage.size)
newimage.putpalette(palettedata * 64)
newimage.paste(oldimage, (0, 0) + oldimage.size)
newimage.show()
我试过pictu's answer to a similar question中提到的Image.Image.quantize()
,但也产生了抖动:
from PIL import Image
palettedata = [0, 0, 0, 102, 102, 102, 176, 176, 176, 255, 255, 255]
palimage = Image.new('P', (16, 16))
palimage.putpalette(palettedata * 64)
oldimage = Image.open("School_scrollable1.png")
newimage = oldimage.quantize(palette=palimage)
newimage.show()
我试过Image.Image.convert()
,它没有抖动就转换了图像,但它包含了指定颜色以外的其他颜色,可能是因为它使用了web调色板或自适应调色板
from PIL import Image
oldimage = Image.open("oldimage.png")
palettedata = [0, 0, 0, 102, 102, 102, 176, 176, 176, 255, 255, 255]
expanded_palettedata = palettedata * 64
newimage = oldimage.convert('P', dither=Image.NONE, palette=palettedata)
newimage.show()
如何在不抖动的情况下自动将图像转换为特定调色板?我想避免使用Python处理每个像素的解决方案,如John La Rooy's answer及其注释中所建议的,因为我以前的解决方案涉及Python编写的内部循环,对于大型图像来说,速度明显较慢。
在C中实现的PIL部分位于
PIL._imaging
模块中,在您from PIL import Image
之后也可以作为Image.core
使用。 当前版本的枕头给每个PIL.Image.Image
实例一个名为im
的成员,它是ImagingCore
的实例,一个在PIL._imaging
中定义的类。 您可以用help(oldimage.im)
列出它的方法,但是这些方法本身在Python中没有文档。ImagingCore
对象的convert
方法在^{ImagingCore
对象(在_imaging.c
内称为Imaging_Type
)。mode
(必需):模式字符串(例如"P"
)dither
(可选,默认为0):PIL传递0或1paletteimage
(可选):带有调色板的ImagingCore
我面临的问题是
dist-packages/PIL/Image.py
中的quantize()
将dither
参数强制为1。 所以我取出了quantize()
方法的一个副本并更改了它。 这在枕头的未来版本中可能不起作用,但如果不起作用,它们很可能实现quantize()
中的注释承诺的“以后版本中的扩展量化器接口”。我把所有这些都记下来,使它更快,并添加了一些注释,以便您理解,并将其转换为枕头而不是pil。基本上。
相关问题 更多 >
编程相关推荐