如果使用Python Pillow制作gif,颜色会消失

问题描述 投票:0回答:1

我打算以 1 度为间隔制作总共 360 张灯泡气压图片,并将其制作为 gif。 然而,如果你用gif制作并查看结果,颜色就消失了。 原图肯定有颜色

我觉得 Pillow 很奇怪,所以我尝试使用 imageio,但出现了同样的问题

我不知道如何解决这个问题

# image code
import matplotlib.pyplot as plt
import os
import numpy as np
import imageio
from PIL import Image
import matplotlib.image as mpimg

file_list = os.listdir("./")
file_png = [file for file in file_list if file.endswith(".png")]
 
path = [f"./{i}" for i in file_png]
 
paths = [Image.open(i) for i in path]
 
imageio.mimsave('./simul2.gif', paths, fps = 60)

# pillow code
import numpy as np
from PIL import Image
 
al = []

for i in np.arange(0, 360, 1):
  st = "{}.png".format(i)
  al.append(st)

frames = []
for j in al:
  new_frame = Image.open(j)
  frames.append(new_frame)
 
frames[0].save('simul1.gif', format = 'GIF',
               append_images = frames[1:],
               save_all = True,
               duration = 1,
               loop = 0)
 

~

这是我的原始图像和结果 gif 的一张截图

python python-imaging-library
1个回答
1
投票

您的图像没有以理想的方式供 PIL 使用。首先,它们有一个多余的 Alpha 通道,导致 PIL 无法使用合适的量化算法;其次,尽管颜色很少,但它们是 RGB 而不是调色板。因此,您需要“稍微握住 PIL 的手”并引导它到您想去的地方。

所以,最初我会建议这种方法,如果出现其他因素,可以修改该方法:

  • 加载第一个图像 - 只要颜色代表整个序列,如果不加载多个图像并加入到更大的图像中以获得所有颜色,
  • 抛弃 Alpha 通道,
  • 转换为调色板模式,使用“中值剪切”量化
  • 提取调色板并将其放在一侧,以便在输出 GIF 的所有帧中使用
  • 加载其他图像,同时放弃 Alpha 通道
  • 保存所有图像,就像您已经在做的那样,但强制使用通用调色板

这比听起来容易,步骤如下:

from PIL import Image

frames = []
# Load first image, ditch alpha channel, quantise and extract palette
im = Image.open('first.png').convert('RGB').quantize(method=Image.Quantize.MEDIANCUT, dither=False)
frames.append(im)

# Extract palette and put aside
palette = im.getpalette()

# Load other images, ditch alpha and append to list
for i in otherImages:
    im = Image.open(i).convert('RGB')
    frames.append(im)

# Save all frames with common palette
frames[0].save('simul1.gif', format = 'GIF',
           append_images = frames[1:],
           save_all = True,
           duration = 1,
           loop = 0,
           palette=palette)
© www.soinside.com 2019 - 2024. All rights reserved.