问题描述
我正在尝试创建一个 1920x1080
的 matplotlib 动画。下面生成的动画是(1152x648),比例合适但是太小了。我知道我可以在事后使用 ffmpeg 执行此操作,但如果可能,我想避免重新编码。
y = my_data
fig = plt.figure(figsize=(16,9))
def ani(i):
# Animation Code
animator = FuncAnimation(fig,ani,frames=y.shape[0])
# Can't figure out what extra_args to set here
ffmpeg_writer = FFMpegWriter(fps=y.shape[0]/sound.duration_seconds,extra_args=['-scale','1920x1080'])
animator.save('mymovie.mp4',writer=ffmpeg_writer)
print(ffmpeg_writer.frame_size) # prints (1152,648)
ipd.Video('mymovie.mp4')
正如您在上面看到的,我尝试了几个 extra_args
,但是我无法得到任何工作。
解决方法
您可以按照以下 post 中的说明设置 DPI
参数。
您系统的标称 DPI 为 72,因此分辨率为 72*16
x72*9
= 1152
x648
。
我们可以将 DPI 设置为 1920/16 以获得 1920x1080 的分辨率:
fig = plt.figure(figsize=(16,9),dpi=1920/16)
这是一个可执行代码示例(用于测试):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 72 is the nominal DPI that is the reason figsize=(16,9) resolution is (1152,648).
# Set the DPI to 120 for getting resolution is (1920,1080)
fig = plt.figure(figsize=(16,dpi=(1920/16))
ax = plt.gca() # Get current axes
l1,= ax.plot(np.arange(1,10),np.arange(1,**{'marker':'o'})
def init():
l1.set_data([],[])
def ani(i,l1):
l1.set_data(i/5,np.sin(0.5*i)*4+5)
l1.set_markersize(10)
animator = animation.FuncAnimation(fig,ani,fargs=(l1,),init_func=init,frames=50,interval=1,blit=False) # 50 frames,interval=1
ffmpeg_writer = animation.FFMpegWriter(fps=10)
animator.save('mymovie.mp4',writer=ffmpeg_writer)
plt.show() # Show for testing