使用PyCharm软件,然后pip install imageio
之后代码如下
import imageio.v2 as imageio
# 合成 gif 方法
def compose_gif():
img_path = ["D:\\picture\\R-CA.jpg", "D:\\picture\\R-C.jpg","D:\\picture\\R-C.jpg", "D:\\picture\\R-C.jpg"]
gif_images = []
first_shape = None
for path in img_path:
try:
img = imageio.imread(path)
if first_shape is None:
first_shape = img.shape
elif img.shape!= first_shape:
print(f"图像 {path} 的形状与第一张图像不同,将被跳过")
continue
gif_images.append(img)
except Exception as e:
print(f"读取文件 {path} 时出错: {e}")
# 在循环结束后保存 GIF
if gif_images:
imageio.mimsave("test.gif", gif_images, fps=1)
# 调用合成方法
compose_gif()
使用带透明度的图片生成gif图片
import warnings
import imageio.v2 as imageio
from PIL import Image
# 忽略特定的警告
warnings.filterwarnings('ignore',
message='Palette images with Transparency expressed in bytes should be converted to RGBA images')
def compose_gif():
img_path = ["output_image_part_0.png", "output_image_part_1.png", "output_image_part_2.png", "output_image_part_3.png"]
gif_images = []
first_shape = None
for path in img_path:
try:
img = imageio.imread(path)
# 如果需要,将图像转换为RGBA模式(这里可能不是必需的)
# img = Image.fromarray(img).convert("RGBA") # 如果img是numpy数组,则需要先转换为PIL图像
# 但由于imageio已经处理了读取,我们可能不需要这一步,除非有特定需求
# 注意:上面的转换代码可能不适用于直接从imageio读取的numpy数组,
# 所以这里我们省略转换步骤,除非确实需要处理PIL Image对象。
if first_shape is None:
first_shape = img.shape
elif img.shape != first_shape:
print(f"图像 {path} 的形状与第一张图像不同,将被跳过")
continue
gif_images.append(img)
except Exception as e:
print(f"读取文件 {path} 时出错: {e}")
if gif_images:
imageio.mimsave("test.gif", gif_images, fps=1)
compose_gif()