如何将Matplotlib输出添加到视频

时间:2019-05-08 18:54:14

标签: python matplotlib video-processing

我正在尝试创建一个具有matplotlib注释的视频(当前),该视频的左侧是原始视频,右侧是某些参数的FFT。

使它起作用的唯一方法是为每个帧保存一个.png文件,这似乎很乏味。我希望有人可以指出“正确”的方法。

import cv2
import numpy as np
import matplotlib
import scipy.fftpack
from moviepy.editor import VideoFileClip
from moviepy.editor import AudioFileClip

vid = VideoFileClip('VID.mp4')
aud = AudioFileClip('VID.mp4')
out  = cv2.VideoWriter('1234.avi',cv2.VideoWriter_fourcc('M','J','P','G'), vid.fps, (vid.w*2, vid.h))
audIndex = 0
vidIndex = 0
numberOfSamples = 600
sampleRate = 800;
T = 1.0 / sampleRate;
x = np.linspace(0.0, numberOfSamples*T, numberOfSamples)

for frame in vid.iter_frames():

    # Put the recorded movie on the left side of the video frame
    frame2 = np.zeros((frame.shape[0], 2*frame.shape[1], 3)).astype('uint8')
    frame2[:720, :1280,:] = frame


    # Put, say, a graph of the FFT on the right side of the video frame
    y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
    yf = scipy.fftpack.fft(y)
    xf = np.linspace(0.0, 1.0/(2.0*T), numberOfSamples/2)
    fig, ax = matplotlib.pyplot.subplots()
    ax.plot(xf, 2.0/numberOfSamples * np.abs(yf[:numberOfSamples//2]))
    matFigureForThisFrame = ????????

    # Put the FFT graph on the left side of this video frame
    frame2[720:, 1280:, :] = matFigureForThisFrame

    out.write(frame2)
    vidIndex = vidIndex+1;

out.release()
#cv2.destroyAllWindows() 

1 个答案:

答案 0 :(得分:0)

您可以尝试采用直接写入视频文件的方法,但我不建议这样做(请参阅here)。写入视频文件比更改框架要复杂得多,您需要获取合适的编码器和其他痛苦的问题。就个人而言,我会解决。一些选项:

1)生成png,然后使用ffmpeg

将其连接到视频文件

2)将每个帧保存到缓冲区中,然后直接在.gif中生成python文件(这样就不必运行多个操作)。有关如何操作,请参见this stackoverflow question