使用Python-Matplotlib制作动画

在可视化一些数据的时候,我们希望能够通过动态演示的方式来展示数据随时间的演化。通常,我们可以用python一帧一帧绘制并储存图片,然后转换成视频。但是如果帧数非常大,那么就不可能手动一张一张生成、保存了。除了批量生成、存储以外,我们期望能够在计算的同时可视化,那么python代码中就要加入动态演示的代码了。

Python动态更新Matplotlib绘制的图片

代码结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import matplotlib.pyplot as plt

## some definition and initialization

# create an interactive canvas
plt.ion()
plt.show()

# setting up the figure as you like
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)

for step in range(Nsteps):
## some computation
## setting up the ax (labels, ticks, xylims)
## some plot action, as a normal simple ax.plot(...)

# update the canvas immediately
fig.canvas.draw()
fig.canvas.flush_events()

# save frames if you want
#plt.savefig("%4d.png"%step)

其中,for循环中就按照最基本的画图方法设置横纵轴、画图就可以,比如ax.plt(x,y,'.-')这样的。

如果开启保存,那么一边动态更新canvas的时候就一边产生png图片。

参考
https://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib

Linux下将png图片转化为mp4视频

首先确保自己安装了ffmpeg。Debian/Ubuntu用户可以执行

1
$ sudo apt install ffmpeg

Shell下进入保存了编号的图片的文件夹,执行

1
$ ffmpeg -framerate 30 -i %04d.png -c:v libx264 -pix_fmt yuv420p out.mp4

其中30是帧频,即每秒帧数;%04d.png是输入图片文件的格式;lib264是视频编码格式,yuv420p是颜色编码方案,一般就采用这两种;out.mp4是输出视频文件名。

参考
https://stackoverflow.com/questions/24961127/how-to-create-a-video-from-images-with-ffmpeg

Linux下将mp4视频转化为微信可播放格式

如果需要将产生的视频发送到朋友圈分享的话,那么可能会出现问题“不支持这种尺寸”。(微信要求的视频格式H.264上文已经满足。)这里可以继续利用ffmpeg添加白边调整尺寸到16:9。

假设我们要将产生的视频out.mp4文件转化成432x768适合手机屏幕的视频,就在shell下执行

1
$ ffmpeg -i out.mp4 -vf "scale=w=432:h=768:force_original_aspect_ratio=1,pad=432:768:(ow-iw)/2:(oh-ih)/2:white" out1.mp4

生成了out1.mp4文件就可以发送到手机相册,从微信朋友圈小视频分享了。如果你想要补黑边的话,就把white改成black或者连最后一个冒号一起删掉就好。

参考:
https://blog.csdn.net/zzcchunter/article/details/78017184
https://superuser.com/questions/991371/ffmpeg-scale-and-pad