使用Python为索引PNG图像添加颜色

使用Python为索引PNG图像添加颜色,python,image,colors,python-imaging-library,indexed,Python,Image,Colors,Python Imaging Library,Indexed,我使用的程序需要4bpp索引图像,我想用黑色调色板条目填充1bpp和2bpp图像。我将如何使用Python来实现这一点?我看不到使用PIL的方法。我尝试了使用此图像和ImageMagick的一些实验,它包含在大多数Linux发行版中,可用于macOS和Windows 首先是原始图像,然后减少到16色抖动,然后减少到16色不抖动 抖动: convert paddington.png -colors 16 d.png convert paddington.png +dither -colors

我使用的程序需要4bpp索引图像,我想用黑色调色板条目填充1bpp和2bpp图像。我将如何使用Python来实现这一点?我看不到使用PIL的方法。

我尝试了使用此图像和ImageMagick的一些实验,它包含在大多数Linux发行版中,可用于macOS和Windows

首先是原始图像,然后减少到16色抖动,然后减少到16色不抖动

抖动:

convert paddington.png -colors 16 d.png
convert paddington.png +dither -colors 16 e.png
毫不犹豫:

convert paddington.png -colors 16 d.png
convert paddington.png +dither -colors 16 e.png
然后我看了ImageMagick制作的图像,它们都有8bpp!因此,我尝试使用“古老的”NetPBM套件,发现它将创建一个4bpp映像,如下所示:

convert paddington.png +dither -colors 16 ppm:- | pnmtopng > result.png
如果我在上面运行
pngcheck
,它看起来就像一个4bpp的PNG:

pngcheck -vv result.png
输出

File: result.png (4857 bytes)
  chunk IHDR at offset 0x0000c, length 13
    150 x 150 image, 4-bit palette, non-interlaced
  chunk PLTE at offset 0x00025, length 48: 16 palette entries
  chunk IDAT at offset 0x00061, length 4740
    zlib: deflated, 16K window, default compression
    row filters (0 none, 1 sub, 2 up, 3 avg, 4 paeth):
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      (150 out of 150)
  chunk IEND at offset 0x012f1, length 0
No errors detected in result.png (4 chunks, 56.8% compression).

目前,我建议你考虑使用IMAGE和NETPBM进行“脱壳”。一个4BPP PNG是一个相当罕见的动物!你能说说这个节目是什么吗?我认为你在PIL,甚至ImageMagick上不会有什么好运气。您是否有一些1bpp、2bpp和4bpp PNG可供共享-我怀疑正常的Imgur服务是否能正常工作,您可能需要使用二进制共享服务。当前版本的PIL/Pizz似乎只支持8bpp索引图像。它适用于使用16种颜色图像的Sega Mega Drive工具:)@Matt:如果您想从Python脚本更直接地使用ImageMagick的功能,请参阅所有回复,谢谢。有趣的是,我曾通过命令行尝试imagemagick,但问题仍然存在。如果我把一个图像减少到16种颜色,但它不包含16种颜色,那么最终得到的图像调色板比16种颜色小。你可以通过gimp手动添加额外的颜色,然后重新保存,但这很费劲,因为我有500多张图像。我的观点是ImageMagick不能做你想要的。。。这就是为什么我建议使用NetPBM套件中的
pnmtopng
。非常好,我将看看NetPBM在这方面取得了多少成功?