python生成动画_用Python生成动画GIF

Python,从表示图像的numpy ndarray创建一个.gif:import os

import numpy as np

from moviepy.editor import ImageSequenceClip

#Installation instructions:

# pip install numpy

# pip install moviepy

# Moviepy needs ffmpeg tools on your system

# (I got mine with opencv2 installed with ffmpeg support)

def create_gif(filename, array, fps=10, scale=1.0):

"""creates a gif given a stack of ndarray using moviepy

Parameters

----------

filename : string

The filename of the gif to write to

array : array_like

A numpy array that contains a sequence of images

fps : int

frames per second (default: 10)

scale : float

how much to rescale each image by (default: 1.0)

"""

fname, _ = os.path.splitext(filename) #split the extension by last period

filename = fname + '.gif' #ensure the .gif extension

if array.ndim == 3: #If number of dimensions are 3,

array = array[..., np.newaxis] * np.ones(3) #copy into the color

#dimension if images are

#black and white

clip = ImageSequenceClip(list(array), fps=fps).resize(scale)

clip.write_gif(filename, fps=fps)

return clip

randomimage = np.random.randn(100, 64, 64)

create_gif('test.gif', randomimage) #example 1

myimage = np.ones(shape=(300, 200))

myimage[:] = 25

myimage2 = np.ones(shape=(300, 200))

myimage2[:] = 85

arrayOfNdarray = np.array([myimage, myimage2])

create_gif(filename="grey_then_black.gif", #example 2

array=arrayOfNdarray,

fps=5,

scale=1.3)

印刷品:[MoviePy] Building file test.gif with imageio

100%|██████████████████████████████████████████| 100/100 [00:00<00:00, 905.27it/s]

[MoviePy] Building file grey_then_black.gif with imageio

67%|█████████████████████████▎ | 2/3 [00:00<00:00, 65.65it/s]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值