我正在尝试从一组堆叠成第三维的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'的第一个维度中,以便观察每个结果发生的变化不同的步骤(框架)?
感谢您的关注和时间!
答案 0 :(得分:1)
您可以使用matplotlib animation api。
这是基于this example
的快速原型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)
答案 1 :(得分:1)
您可以使用imageio
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