在python中设置imageio压缩级别

时间:2021-07-13 17:26:02

标签: python animated-gif python-imageio

我在 Python 中使用 imageio 读取 jpg 图像并将它们写为 gif,使用类似于下面代码的东西。

import imageio

with imageio.get_writer('mygif.gif', mode='I') as writer:
    for filename in framefiles:    # iterate over names of jpg files I want to turn into gif frames
    frame = imageio.imread(filename)
    writer.append_data(frame)

我注意到我制作的 gif 的图像质量很差;我怀疑这是由于某种形式的压缩。有没有办法告诉 imageio 不要使用任何压缩?或者也许可以用 opencv 来做到这一点?

1 个答案:

答案 0 :(得分:2)

真正的问题是 GIF 只能显示 256 colors(8 位颜色)所以它必须将 24-bits 颜色(RGB)减少到 256 colors 或者它有模拟使用不同颜色的点获得更多颜色 - ditherring


至于选项:

挖掘源代码我发现它可以得到两个参数quantizerpalettesize,可以控制图像/动画质量。 (还有 subrectangles 可以减小文件大小)

但是 GIF 有两个插件使用不同的模块 PillowFreeImage 并且它们需要不同的 quantizer

PIL 需要整数 012

FI 需要字符串 'wu''nq'(但稍后将其转换为整数 01

它们还以不同的方式保存这些值,因此如果您想获取当前值或在 get_writer() 之后更改它,那么您还需要不同的代码。

您可以使用 format='GIF-PIL'format='GIF-FI' 选择模块

with imageio.get_writer('mygif.gif', format='GIF-PIL', mode='I', 
                        quantizer=2, palettesize=32) as writer:
    print(writer)
    #print(dir(writer))
    #print(writer._writer)
    #print(dir(writer._writer))

    print('quantizer:', writer._writer.opt_quantizer)
    print('palette_size:', writer._writer.opt_palette_size)

    #writer._writer.opt_quantizer = 1
    #writer._writer.opt_palette_size = 256
    #print('quantizer:', writer._writer.opt_quantizer)
    #print('palette_size:', writer._writer.opt_palette_size)


with imageio.get_writer('mygif.gif', format='GIF-FI', mode='I', 
                        quantizer='nq', palettesize=32) as writer:
    print(writer)
    #print(dir(writer))

    print('quantizer:', writer._quantizer)
    print('palette_size:', writer._palettesize)

    #writer._quantizer = 1
    #writer._palettesize = 256
    #print('quantizer:', writer._quantizer)
    #print('palette_size:', writer._palettesize)

我尝试使用不同的设置创建动画,但它们看起来并没有好多少。

我在控制台/终端中使用外部程序 ImageMagick 获得了更好的结果

convert image*.jpg mygif.gif

但仍然不如视频或静态图像。

你可以在 Python 中运行它

os.system("convert image*.jpg mygif.gif")

subprocess.run("convert image*.jpg mygif.gif", shell=True)

或者您可以尝试使用模块 Wand 来实现,它是 ImageMagick

的包装器

源代码:pillowmulti.pyfreeimagemulti.py 中的 GifWriter

* wu - Wu, Xiaolin, Efficient Statistical Computations for Optimal Color Quantization
* nq (neuqant) - Dekker A. H., Kohonen neural networks for optimal color quantization

文档:GIF-PIL Static and animated gif (Pillow)GIF-FI Static and animated gif (FreeImage)

相关问题