我打算以 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 的一张截图
您的图像没有以理想的方式供 PIL 使用。首先,它们有一个多余的 Alpha 通道,导致 PIL 无法使用合适的量化算法;其次,尽管颜色很少,但它们是 RGB 而不是调色板。因此,您需要“稍微握住 PIL 的手”并引导它到您想去的地方。
所以,最初我会建议这种方法,如果出现其他因素,可以修改该方法:
这比听起来容易,步骤如下:
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)