Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเปิดใช้งาน FFmpeg สำหรับ Matplotlib Animation อย่างถูกต้อง

ตั้งค่า plt.rcParams['animation.ffmpeg_path'] และใช้ FFMpegWriter บันทึก Animation เป็น MP4

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. ตั้งค่า FFmpeg Path
  3. สร้าง Figure, Axes, Colorbar
  4. สร้าง Animation Function
  5. สร้าง FuncAnimation
  6. บันทึกด้วย FFMpegWriter

ตัวอย่างโค้ด


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

# ตั้งค่า FFmpeg Path (ต้องติดตั้ง FFmpeg ในระบบ)
plt.rcParams['animation.ffmpeg_path'] = 'ffmpeg'

fig = plt.figure()
ax = fig.add_subplot(111)

# สร้าง Colorbar แยก
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)

# บันทึกเป็น MP4
FFwriter = animation.FFMpegWriter()
ani.save('plot.mp4', writer=FFwriter)

ข้อกำหนดเบื้องต้น

  • ติดตั้ง FFmpeg ในระบบ: sudo apt install ffmpeg (Ubuntu) หรือ brew install ffmpeg (macOS)
  • Windows: ดาวน์โหลดจาก ffmpeg.org และเพิ่มใน PATH

Writer อื่นๆ


# GIF (ต้อง Pillow)
ani.save('plot.gif', writer='pillow', fps=10)

# HTML5 Video (สำหรับ Jupyter)
from IPython.display import HTML
HTML(ani.to_jshtml())

ผลลัพธ์

สร้างไฟล์ plot.mp4 ใน Project Directory เป็น Animation 10 เฟรม สลับ Colormap