如何从 2D 模型或数据集创建动画?

计算科学 可视化
2021-11-27 23:22:12

我在物理堆栈交换中找到了以下线程,在那里我看到了名为 output 的视频附加到主帖子视频可以在这里找到。

我将如何制作这样的动画?

4个回答

我假设您知道如何在电影中输出您想要的所有帧。然后是一个简单的免费工具,可以将它们作为Imagemagick 的 convert 转换为电影。如果您在 Linux 系统上,您可能已经拥有它,或者可以通过包管理器轻松获得它。根据您要制作的电影格式,您还需要一个合适的编码器(例如ffmpeg)。如果你有一堆文件

frame001.png
frame002.png
...

然后你只需

convert *.png movie.mpg

您可以使用许多选项来更改帧速率和其他内容;请参阅上面链接的转换文档。

如果您对生成单个帧感兴趣,这里有一个 Python 小示例:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt   # For plotting graphs.
import numpy as np
import subprocess                 # For issuing commands to the OS.
import os
import sys                        # For determining the Python version.
import glob

fileList = glob.glob(os.path.join("LEMtrace*.dat"))

style = {0: '--',
         1: '-',
         2: '-.',
         3: ':'}
color = {0: 'k',
         1: 'r',
         2: 'g',
         3: 'b'}
n = 0
for f in fileList:
    n = n + 1
    plt.figure()
    data = np.loadtxt(f)
    ax = plt.subplot(111)
    ax.plot(data[:,0],data[:,1],label='YO2',c=color[0],ls=style[0])
    ax.plot(data[:,0],data[:,2],label='YH2',c=color[1],ls=style[1])
    ax.plot(data[:,0],data[:,3],label='YOH',c=color[2],ls=style[2])
    ax.plot(data[:,0],data[:,8]/2000.,label='T/2000',c=color[3],ls=style[3])
    ax.set_xlabel('LEM cell')
    ax.set_ylabel('Mass fraction or T / 2000 K')
    ax.set_ylim((0.0,2.0))
    str = 'Time {0:.5f} ms'.format(n * 5.8e-5)
    plt.title(str)
    leg = ax.legend(loc='best', shadow=True, fancybox=True)
    fig = "frame_%04d"%(n)
    plt.savefig(fig+'.png',format='png')
    plt.clf()

command = ('mencoder',
           'mf://*png',
           '-mf',
           'type=png:w=800:h=600:fps=5',
           '-ovc',
           'lavc',
           '-lavcopts',
           'vcodec=mpeg4',
           '-oac',
           'copy',
           '-o',
           'profile_LEM.avi')
print "\n\nabout to execute:\n%s\n\n" % ' '.join(command)
subprocess.check_call(command)
command = ('convert',
           'frame*png',
           '+dither',
           '-layers',
           'Optimize',
           '-colors',
           '256',
           '-depth',
           '8',
           'profile_LEM.gif')

subprocess.check_call(command)
print "\n\n The movie was written to 'output.avi'"

假设您在LEMtrace*.dat文件中存储了一些一维数据,该程序使用numpy.loadtxt(非常适合文本文件)为每个文件加载数据,使用漂亮的小时间计数器绘制一个简单的图形matplotlib并为每个文件输出 1 帧。然后它使用mencoderorconvert来生成aviorgif动画。希望这可以帮助 !

PS:一个不太漂亮(因为数据)的输出示例:GIF 样本

我经常使用 Mathematica 来做这类事情......动画可以很容易地制作:

Manipulate[
  Plot[Sin[x + t] + Cos[0.3 x + t], {x, 0, 20},PlotRange -> {All, {-2, 2}}],
  {t, 1, 10}
]

这为您提供了一个交互式绘图,其中包含用于拖动 t 的滑块。

要将动画另存为电影,只需将其导出:

Export["movie.mov",
  Table[Plot[Sin[x + t] + Cos[0.3 x + t], {x, 0, 20}, PlotRange -> {All, {-2, 2}}], 
    {t, 1, 10, 0.1}
  ]
]

例子:

移动波

还有一个免费软件程序ffmpeg可免费使用。如果您更喜欢使用 GUI 来执行此操作,您可能还需要考虑使用ImageJ