cv2.VideoWriter的输出不正确,速度更快了。

3

我正在尝试使用OpenCV的cv2.VideoWriter来记录一段视频,但是输出结果不正确。例如,10秒的视频只有2秒,而且会加速播放。以下是我的代码。欢迎任何建议和想法。另外,输出视频没有声音。谢谢!!!

主机:树莓派

语言:Python

import numpy as np
import cv2
import time

# Define the duration (in seconds) of the video capture here
capture_duration = 10

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output3.avi',fourcc, 20.0, (640,480))

start_time = time.time()
while( int(time.time() - start_time) < capture_duration ):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

检查您的摄像头属性:https://askubuntu.com/a/687140/486771 - zindarod
1个回答

3
您的代码忽略了两个重要因素:
while循环中的帧计数:
您想以20帧每秒(fps)的速度写入10秒的视频。这给您整个视频共200帧。为了实现这一点,在捕获并将每一帧写入文件之前,您需要注意while循环内的等待时间。如果忽略等待时间,则会导致:
  frameCount = 0
  while( int(time.time() - start_time) < capture_duration ):
      # we assume that all the operations inside the loop take 0 seconds to accomplish.

      frameCount = frameCount+1

  print('Total frames: ',frameCount)

在上面的例子中,如果忽略等待时间,在10秒内会写入数千帧到视频文件。现在以20 fps的速度计算,10秒钟的帧数为200帧,为了达到这个帧数,每一帧写入文件之前需要等待50毫秒。
  frameCount = 0
  while( int(time.time() - start_time) < capture_duration ):
      # wait 50 milliseconds before each frame is written.
      cv2.waitKey(50)

      frameCount = frameCount+1

  print('Total frames: ',frameCount)

在上面的示例中,总帧数大约为200。
VideoCapture :: read()是一个阻塞I / O调用:
cap.read()函数执行两个操作,即VideoCapture :: grab()和VideoCapture :: retrieve()。此函数等待下一帧被抓取,然后解码并返回图像。等待时间取决于您的相机fps。
因此,例如,如果您的相机fps为6,则在10秒内您将捕获60帧。您已将20 fps设置为VideoWriter属性;以20 fps播放的60帧视频大约为3秒钟。
要查看相机在10秒内捕获了多少帧,请执行以下操作:
  frameCount = 0
  while( int(time.time() - start_time) < capture_duration ):
      # wait for camera to grab next frame
      ret, frame = cap.read()
      # count number of frames
      frameCount = frameCount+1

  print('Total frames: ',frameCount)

1
它使用 Genius iSlim 2000AF V2 真正的即插即用功能。根据相机规格,它支持640 x 480 @ 30 fps的视频捕捉。然而,我只得到了60帧10秒钟的视频,fps为6fps。你有什么想法吗? - user3470406

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接