我正在尝试使用 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()
最佳答案
您忽略了代码中的两个重要因素:
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)
关于python - cv2.VideoWriter 的输出不正确。更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49567637/