I'm using this code from here to try and pipe multiple matplotlib plots into ffmpeg to write a video file:
import numpy as np
import matplotlib.pyplot as plt
import subprocess
xlist = np.random.randint(100,size=100)
ylist = np.random.randint(100, size=100)
color = np.random.randint(2, size=100)
f = plt.figure(figsize=(5,5), dpi = 300)
canvas_width, canvas_height = f.canvas.get_width_height()
ax = f.add_axes([0,0,1,1])
ax.axis('off')
# Open an ffmpeg process
outf = 'ffmpeg.mp4'
cmdstring = ('ffmpeg',
'-y', '-r', '30', # overwrite, 30fps
'-s', '%dx%d' % (canvas_width, canvas_height), # size of image string
'-pix_fmt', 'argb', # format
'-f', 'rawvideo', '-i', '-', # tell ffmpeg to expect raw video from the pipe
'-vcodec', 'mpeg4', outf) # output encoding
p = subprocess.Popen(cmdstring, stdin=subprocess.PIPE)
# Draw 1000 frames and write to the pipe
for frame in range(10):
print("Working on frame")
# draw the frame
f = plt.figure(figsize=(5,5), dpi=300)
ax = f.add_axes([0,0,1,1])
ax.scatter(xlist, ylist,
c=color, cmap = 'viridis')
f.canvas.draw()
plt.show()
# extract the image as an ARGB string
string = f.canvas.tostring_argb()
# write to pipe
p.stdin.write(string)
# Finish up
p.communicate()
While plt.show()
does show the correct plot (see image below), the video that ffmpeg creates is a bit different than what plt.show()
shows. I am presuming the issue is with f.canvas.draw()
, but I'm not sure how to get a look at what canvas.draw()
actually plots.
ffmpeg video (imgur link)