我有以下代码,使用 Python 3.11.10 中的 Pillow 创建了 60 帧,我想用它来创建一个 GIF(无限循环),每帧持续时间为 0.1 秒。前 4 帧应该显示一个红色方块,其余时间(大约 6 秒)应该基本为黑色。但是,创建的 GIF 似乎只包含 2 帧,一帧包含红色方块,一帧不包含。如何正确创建 GIF?
from PIL import Image, ImageDraw
import imageio
import numpy as np
# Colors
red = (255, 0, 0)
black = (0, 0, 0)
grey = (30, 30, 30)
frames = []
framerate = 10
frame_count = 60
for i in range(frame_count):
# Create an image with black background
img = Image.new('RGB', (55, 50), black)
draw = ImageDraw.Draw(img)
# Draw rectangle
draw.rectangle((10, 20, 45, 30), fill=red if i<5 else grey)
# Append frame to the list
frames.append(np.array(img))
# Save frames as a GIF
imageio.mimsave("test.gif", frames, duration=1./framerate, loop=0, plugin='pillow')
这是创建的 gif:
预期行为:0.4 秒显示红色方块,然后 5.6 秒显示基本黑色。
根据 Grismar 的建议: