python - 如何用堆叠在 numpy 数组中的一组图像制作电影?

标签 python arrays python-3.x numpy matplotlib

我正在尝试用一组堆叠到第 3 维的 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'的第一个维度中,以便观察每个结果如何发生变化不同的步骤(框架)?

感谢您的关注和时间!

最佳答案

您可以使用 matplotlib animation api .

这是一个基于 this example 的快速原型(prototype)

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

关于python - 如何用堆叠在 numpy 数组中的一组图像制作电影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50704472/

相关文章:

python - 在Python中并行读取多个文件

python - virtualenvwrapper:virtualenv信息存储在哪里?

java - 在 toString 类中使用 for 循环返回多个数组

linux - 在 Pycharm 中修改我的 Python 代码后,如何将更改部署到我的 Portainer?

python - 如何修复属性错误: 'HTMLParserTreeBuilder' object has no attribute 'initialize_soup'

python - 朴素贝叶斯 : Imbalanced Test Dataset

python - 反转交替正则表达式

arrays - 数组上不确定函数的异步映射

Python 在数组/列表中查找数据索引,但有约束

python - 在 Python 3.6 XOR 中获取简单错误