วิธีเปิดใช้งาน ffmpeg สำหรับ matplotlib.animation เราสามารถทำตามขั้นตอนต่อไปนี้ -
-
กำหนดขนาดรูปและปรับช่องว่างภายในระหว่างและรอบๆ แผนผังย่อย
-
ตั้งค่า ffmpeg ไดเรกทอรี
-
สร้างตัวเลขใหม่หรือเปิดใช้งานตัวเลขที่มีอยู่โดยใช้ figure() วิธีการ
-
เพิ่ม 'ax1' ไปที่ร่างซึ่งเป็นส่วนหนึ่งของการจัดโครงเรื่องย่อย
-
พล็อตตัวแบ่งตามแกนที่มีอยู่แล้ว
-
สร้างข้อมูลแบบสุ่มเพื่อวางแผน เพื่อแสดงข้อมูลเป็นรูปภาพ เช่น บนแรสเตอร์ปกติ 2 มิติ
-
สร้างแถบสีสำหรับ ScalarMappable ตัวอย่าง cb .
-
ตั้งชื่อเป็นเฟรมปัจจุบัน
-
ทำรายการแผนที่สี
-
สร้างแอนิเมชั่นด้วยการเรียกฟังก์ชัน เคลื่อนไหวซ้ำๆ ฟังก์ชันสร้างข้อมูลสุ่มใหม่ จากนั้นใช้ imshow() วิธีการแสดงข้อมูลเป็นภาพ
-
รับอินสแตนซ์ของ ffmpeg . แบบไพพ์ นักเขียน
-
บันทึกภาพเคลื่อนไหวปัจจุบัน
ตัวอย่าง
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) ผลลัพธ์
เมื่อเรารันโค้ด มันจะสร้างไฟล์ mp4 ที่มีชื่อ 'plot.mp4' และบันทึกไว้ใน Project Directory