【问题标题】:Displaying Numpy Matrix as Video将 Numpy 矩阵显示为视频
【发布时间】:2022-05-18 18:06:15
【问题描述】:

我有一个 numpy 矩阵,其中每一行都是一张图片。我可以用 matplotlib.pyplot 重塑行并显示图像。问题是:我不想单独显示图像,我想像视频一样依次显示它们。

这在 python 中怎么可能?

【问题讨论】:

  • 你试过什么?也许用time pause 遍历矩阵并不断改变你的显示
  • 当我想要将它保存在带有 pyfits 的 fit 文件中时,我所做的,而不仅仅是用 DS9 显示它,在那里您可以分别遍历每一帧等-(在我的情况下,我hade 一个 3D 数组,我只是将它保存为 3 个不同的文件,并交换了轴,以便能够“遍历它”,每个文件一个轴,但如果 time.pause 有效,则无需使其更困难我的解决方案确实允许您保存它们并稍后再做,而无需模拟您想在 3D 矩阵中看到的任何内容

标签: python numpy


【解决方案1】:

好吧,我不知道这是否是最好的方法,但我使用 matplotlib.pyplot 来解决我的问题。将其导入为“plt”并执行以下操作:

matrix=numpy.genfromtxt(path,delimiter=',') # Read the numpy matrix with images in the rows
c=matrix[0]
c=c.reshape(120, 165) # this is the size of my pictures
im=plt.imshow(c)
for row in matrix:
    row=row.reshape(120, 165) # this is the size of my pictures
    im.set_data(row)
    plt.pause(0.02)
plt.show()

【讨论】:

  • 解决方案有点hacky,但是如果您只想调试某事,那么我认为这完全没问题,但是,我会对更复杂的版本感兴趣,您可以将视频保存到文件。
  • 不幸的是,这不适用于 jupyter 笔记本。
【解决方案2】:

您好,我使用 matplotlib 动画的解决方案:

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

video # my numpy matrix of shape (frames, channel, w, h)

# initializing a figure in 
# which the graph will be plotted
fig = plt.figure(figsize=(10,10)) 

# create an axis
ax = plt.axes() 

# initializing a line variable
img = ax.imshow(np.ndarray(shape=video.shape[2:])
   
def animate(i):
    img.set_data(i)
    return img,
   
anim = FuncAnimation(fig, animate, frames=video, interval=20, blit=True)
  
anim.save(filename, writer='ffmpeg', fps=5, bitrate=2000)

请注意,如果您在 jupyter notebook 中,您可以使用临时文件和 ipywidgets 来显示视频而不保存它。

from tempfile import NamedTemporaryFile
f = NamedTemporaryFile(mode='w+', suffix='.mp4')

#...previous code

anim.save(f.name, writer='ffmpeg', fps=5, bitrate=2000)
from ipywidgets import Video
Video.from_file(f.name)

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2017-07-08
  • 2017-05-07
  • 2016-07-23
  • 2013-10-16
  • 2021-10-05
  • 2016-08-25
  • 2018-07-18
  • 2021-09-14
  • 1970-01-01
相关资源
最近更新 更多