我用相机拍摄了一段视频,固定帧率为25 fps,并试图用OpenCV读取。
当我使用OpenCV阅读视频文件时,它会播放,但播放速度非常快。 我希望我的程序以25 fps播放视频。如何配置OpenCV以25 fps读取视频文件?
我的代码:
import numpy as np
import cv2
cap = cv2.VideoCapture('vtest.avi')
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
答案 0 :(得分:0)
我找到了一些解决方案。 我把延迟时间用于捕获循环。我在从视频文件中捕获新图像之前检查延迟。这是我的解决方案代码。 谢谢,大家。
import numpy as np
import cv2
from time import time as timer
import sys
video = cv2.VideoCapture('2.avi')
fps = video.get(cv2.CAP_PROP_FPS)
fps /= 1000
framerate = timer()
elapsed = int()
cv2.namedWindow('ca1', 0)
while(video.isOpened()):
start = timer()
# print(start)
ret, frame = video.read()
cv2.imshow('ca1',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
diff = timer() - start
while diff < fps:
diff = timer() - start
elapsed += 1
if elapsed % 5 == 0:
sys.stdout.write('\r')
sys.stdout.write('{0:3.3f} FPS'.format(elapsed / (timer() - framerate)))
sys.stdout.flush()
video.release()
cv2.destroyAllWindows()
答案 1 :(得分:0)
灵感来自您的答案:
while(cap.isOpened()):
ret, frame = cap.read()
now = time.time()
frameLimit = 2.0
#Do your stuff
timeDiff = time.time() - now
if (timeDiff < 1.0/(frameLimit)): sleep( 1.0/(frameLimit) - timeDiff )
答案 2 :(得分:0)
这是解决此问题的有效方法:
fps = vid.get(cv2.CAP_PROP_FPS)
while True:
now = time.time()
_, frame = vid.read()
#Do your thing
timeDiff = time.time() - now
if (timeDiff < 1.0/(fps)):
time.sleep(1.0/(fps) - timeDiff)
答案 3 :(得分:0)
由于这是现有的视频文件,因此无法更改其FPS。但是,当您读取视频文件时,可以更改每帧之间的读取间隔。这是我以25 fps固定帧速率读取的解决方案。这是代码:
import numpy as np
import cv2
import sys
cap = cv2.VideoCapture('C:/Media/videos/Wildlife.wmv')
# Check if camera opened successfully
if (cap.isOpened()== False):
print("Error opening video stream or file")
fps = 25
#if you want to have the FPS according to the video then uncomment this code
#fps = cap.get(cv2.CAP_PROP_FPS)
#calculate the interval between frame.
interval = int(1000/fps)
print("FPS: ",fps, ", interval: ", interval)
# Read the video
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('Frame',gray)
if cv2.waitKey(interval) & 0xFF == ord('q'):
break
# Break the loop
else:
break
cap.release()
cv2.destroyAllWindows()
答案 4 :(得分:-1)
您可以添加所需的fps来代替
下面的'fps'cap.set(cv2.cv.CV_CAP_PROP_FPS, fps)