如何将存储在numpy数组中的一组图像制作成电影?

4

我正在尝试制作一部电影(或任何能够按顺序显示结果的东西),使用一组被堆叠成第三维的2D numpy数组。

为了说明我的意思,想象一个9x3x3的numpy数组,其中我们有一个由9个不同的3x3数组组成的序列,如下所示:

import numpy as np
#creating an array where a position is occupied by
# 1 and the others are zero
a = [[[0,0,1],[0,0,0],[0,0,0]],[[0,1,0],[0,0,0],[0,0,0]], [[1,0,0],[0,0,0],[0,0,0]], [[0,0,0],[0,0,1],[0,0,0]], [[0,0,0],[0,1,0],[0,0,0]], [[0,0,0],[1,0,0],[0,0,0]], [[0,0,0],[0,0,0],[0,0,1]], [[0,0,0],[0,0,0],[0,1,0]], [[0,0,0],[0,0,0],[1,0,0]]]
a = np.array(a)

这样a[0],... a[n] 将会返回类似如下内容:

In [10]: a[1]
Out[10]: 
array([[0, 1, 0],
       [0, 0, 0],
       [0, 0, 0]])

但是将数字1的位置进行变换,再加上以下几行代码绘制简单的图形:

img = plt.figure(figsize = (8,8))
    plt.imshow(a[0], origin = 'lower')
    plt.colorbar(shrink = 0.5)
    plt.show(img)

将产生以下输出:

Matrix first element

那么,创建电影的最适当方式是什么?显示类似于上面图片的结果,使每个结果在'a'的第一维中堆叠,以便观察每个不同步骤(帧)的变化情况?

感谢您的关注和时间!


1
你的最后一句话不是很清楚,你是想要动画展示图形还是只是将所有帧堆叠在水平或垂直条中进行绘制? - filippo
我想要给它添加动画效果。 - Chicrala
2个回答

2

您可以使用matplotlib动画API

这是一个基于此示例的快速原型。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

a = [[[0,0,1],[0,0,0],[0,0,0]],
     [[0,1,0],[0,0,0],[0,0,0]],
     [[1,0,0],[0,0,0],[0,0,0]],
     [[0,0,0],[0,0,1],[0,0,0]],
     [[0,0,0],[0,1,0],[0,0,0]],
     [[0,0,0],[1,0,0],[0,0,0]],
     [[0,0,0],[0,0,0],[0,0,1]],
     [[0,0,0],[0,0,0],[0,1,0]],
     [[0,0,0],[0,0,0],[1,0,0]]]
a = np.array(a)

fig, ax = plt.subplots(figsize=(4, 4))

frame = 0
im = plt.imshow(a[frame], origin='lower')
plt.colorbar(shrink=0.5)

def update(*args):
    global frame

    im.set_array(a[frame])

    frame += 1
    frame %= len(a)

    return im,

ani = animation.FuncAnimation(fig, update, interval=500)
plt.show()

您也可以使用ImageMagickFileWriter将它们保存为gif格式,只需将最后两行替换为以下内容。
ani = animation.FuncAnimation(fig, update, len(a))
writer = animation.ImageMagickFileWriter(fps=2)
ani.save('movie.gif', writer=writer) 

matplotlib animated gif


1
你可以使用imageio从输出中创建一个gif:
import numpy as np
import matplotlib.pyplot as plt
import imageio

a = [[[0,0,1],[0,0,0],[0,0,0]], 
     [[0,1,0],[0,0,0],[0,0,0]], 
     [[1,0,0],[0,0,0],[0,0,0]], 
     [[0,0,0],[0,0,1],[0,0,0]], 
     [[0,0,0],[0,1,0],[0,0,0]], 
     [[0,0,0],[1,0,0],[0,0,0]], 
     [[0,0,0],[0,0,0],[0,0,1]], 
     [[0,0,0],[0,0,0],[0,1,0]], 
     [[0,0,0],[0,0,0],[1,0,0]]]

a = np.array(a)

images = []

for array_ in a:
    file_path = "C:\file\path\image.png"

    img = plt.figure(figsize = (8,8))
    plt.imshow(array_, origin = 'lower')
    plt.colorbar(shrink = 0.5)

    plt.savefig(file_path) #Saves each figure as an image
    images.append(imageio.imread(file_path)) #Adds images to list
    plt.clf()

plt.close()
imageio.mimsave(file_path + ".gif", images, fps=1) #Creates gif out of list of images

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接