首页 > 解决方案 > 如何从堆叠在 numpy 数组中的一组图像中制作电影?

问题描述

我正在尝试从一组堆叠成第三维的 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)

会给出输出:

矩阵第一个元素

那么什么是创建电影的最合适的方法,显示类似于上图的结果,每个结果都堆叠在“a”的第一维中,以便观察每个不同步骤中的变化是如何发生的(框架)?

感谢您的关注和时间!

标签: pythonarrayspython-3.xnumpymatplotlib

解决方案


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

您也可以将它们保存为 gif ImageMagickFileWriter,只需将最后两行替换为

ani = animation.FuncAnimation(fig, update, len(a))
writer = animation.ImageMagickFileWriter(fps=2)
ani.save('movie.gif', writer=writer) 

matplotlib 动画 gif


推荐阅读