使用python生成gif图

使用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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值