如何将matplotlib输出添加到vid

2024-05-08 14:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个带有由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() 

Tags: oftheimportfftputmatplotlibonnp
1条回答
网友
1楼 · 发布于 2024-05-08 14:26:31

您可以尝试直接写入视频文件,但我不建议这样做(请参见here为什么)。写入视频文件比仅仅改变帧更复杂,你需要找到合适的编码器和其他痛苦的问题。就我个人而言,我会解决的。一些选项:

1)生成png,然后使用ffmpeg将它们连接到视频文件

2)将每个帧保存到缓冲区,然后直接在python中生成.gif文件(这样就不必运行多个操作)。请参阅this stackoverflow question了解如何做到这一点。你知道吗

相关问题 更多 >