cv2.VideoWriter 在 RPi3 中比实际更快

cv2.VideoWriter in RPi3 is faster than actual

我正在尝试录制罗技网络摄像头视频。摄像头能够录制它,但 40 秒的视频仅以 nX 速度录制 6 秒。我参考了以下 link 的解决方案,但它无法解决 RPi 中的问题。重要的是代码可以在 Ubuntu 桌面中找到,但可能是 RPi 处理速度较慢。

这是我的代码片段:

fourcc = cv2.cv.CV_FOURCC(*'XVID')
videoOut = cv2.VideoWriter("video_clip.avi", fourcc, 20.0, (640, 480))
start_time = time.time()
frame_count = 0
while True:
    ret, frame = cap.read()
    videoOut.write(frame)  # write each frame to make video clip
    frame_count += 1

    print int(time.time()-start_time)  # print the seconds
    if int(time.time()-start_time) == 10:
        videoOut.release()
        break
        # get out of loop after 10 sec video
print 'frame count =', frame_count 
# gives me 84 but expected is 20.0 * 10 = 200

前段时间我也有同样的问题。我做了很多搜索,但没有找到解决方案。问题是通过的 fps 是视频 播放 的速率。这并不意味着将以该 FPS 录制 视频。 AFAIK,没有直接的方法来设置记录的 FPS。如果您记录的 FPS 太高,您可以降低采样率(即每个时间段只保留 1 帧)。但从你的描述来看,似乎比要求的要低得多。这是硬件限制,对此无能为力。

关于设置记录的 FPS,我找到了解决方法。我在捕获列表中的 all 帧后创建了 videoWriter。这样我就可以计算出记录的FPS,在创建的时候传给VideoWriter

如果您 运行 内存不足,则制作帧列表可能无法工作。另一种方法是动态计算 fps,然后 remux the video with the new fps using ffmpeg.

import numpy as np
from skvideo import io
import cv2, sys
import time
import os

if __name__ == '__main__':

    file_name = 'video_clip.avi'

    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    videoOut = cv2.VideoWriter(file_name, fourcc, 30.0, (640, 480))
    cap = cv2.VideoCapture(0)

    if not cap.isOpened() or not videoOut.isOpened():
        exit(-1)

    start_time = time.time()
    frame_count = 0
    duration = 0
    while True:
        ret, frame = cap.read()
        if not ret:
            print('empty frame')
            break
        videoOut.write(frame)  # write each frame to make video clip
        frame_count += 1

        duration = time.time()-start_time
        if int(duration) == 10:
            videoOut.release()
            cap.release()
            break

    actualFps = np.ceil(frame_count/duration)

    os.system('ffmpeg -y -i {} -c copy -f h264 tmp.h264'.format(file_name))
    os.system('ffmpeg -y -r {} -i tmp.h264 -c copy {}'.format(actualFps,file_name))