如何解决在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 来做到这一点?
解决方法
真正的问题是 GIF
只能显示 256 colors
(8 位颜色)所以它必须将 24-bits
颜色(RGB)减少到 256 colors
或者它有模拟使用不同颜色的点获得更多颜色 - ditherring。
至于选项:
挖掘源代码我发现它可以得到两个参数quantizer
,palettesize
,可以控制图像/动画质量。 (还有 subrectangles
可以减小文件大小)
但是 GIF
有两个插件使用不同的模块 Pillow
或 FreeImage
并且它们需要不同的 quantizer
值
PIL
需要整数 0
、1
或 2
。
FI
需要字符串 'wu'
或 'nq'
(但稍后将其转换为整数 0
或 1
)
它们还以不同的方式保存这些值,因此如果您想获取当前值或在 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',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.py 和 freeimagemulti.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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。