Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cấu hình ffmpeg cho matplotlib.animation đúng cách

Để bật ffmpeg cho matplotlib.animation:

  • Thiết lập kích thước figure và padding
  • Đặt thư mục ffmpeg
  • Tạo figure mới
  • Thêm ax1, tạo divider cho colorbar
  • Tạo dữ liệu ngẫu nhiên, hiển thị bằng imshow()
  • Tạo colorbar cho ScalarMappable
  • Đặt title theo frame hiện tại
  • Tạo danh sách colormaps
  • Tạo animation bằng FuncAnimation gọi hàm animate lặp lại
  • Lấy instance FFMpegWriter
  • Lưu animation thành file

Ví dụ mã nguồn

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.axes_grid1 import make_axes_locatable

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.rcParams['animation.ffmpeg_path'] = 'ffmpeg'

fig = plt.figure()
ax = fig.add_subplot(111)
div = make_axes_locatable(ax)
cax = div.append_axes('right', '5%', '5%')
data = np.random.rand(5, 5)
im = ax.imshow(data)
cb = fig.colorbar(im, cax=cax)
tx = ax.set_title('Frame 0')
cmap = ["copper", 'RdBu_r', 'Oranges', 'cividis', 'hot', 'plasma']

def animate(i):
    cax.cla()
    data = np.random.rand(5, 5)
    im = ax.imshow(data, cmap=cmap[i%len(cmap)])
    fig.colorbar(im, cax=cax)
    tx.set_text('Frame {0}'.format(i))

ani = animation.FuncAnimation(fig, animate, frames=10)
FFwriter = animation.FFMpegWriter()
ani.save('plot.mp4', writer=FFwriter)

Kết quả

Tạo file plot.mp4 trong thư mục dự án: animation 10 frames, mỗi frame colormap khác nhau, có colorbar và title frame number.

Yêu cầu: Cần cài ffmpeg trên hệ thống (apt install ffmpeg / brew install ffmpeg / choco install ffmpeg) và đảm bảo trong PATH.