python - 如何从堆叠在 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”的第一维中,以便观察每个不同步骤中的变化是如何发生的(框架)?
感谢您的关注和时间!
解决方案
您可以使用 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)
推荐阅读
- php - GMail SMTP 服务器和 PHPMailer:发送成功但未收到
- node.js - 如何使用指定参数存根对象的方法?
- php - 如何使用中间表设置 Laravel 多对多关系,中间表不仅是数据透视表,而且代表模型
- airflow - Airflow 网络服务器也启动了 worker
- java - Java调整嵌套的Hashmap值
- magento2 - magento api 2 create product error
- javascript - 如何设置网站标题的文本方向?
- angular - 预期未定义是真实的 - Jasmine/Karma
- c++ - (C++) 字符串文字与参数列表不匹配
- ios - iOS -weak_library 和 -bitcode_bundle(Xcode 设置 ENABLE_BITCODE=YES)不能一起使用