如何在python-opencv中加载高质量视频并正常播放?

时间:2018-02-06 10:33:40

标签: python-3.x numpy opencv

import numpy as np
import cv2

cap = cv2.VideoCapture('1440pHD.mp4')
while(cap.isOpened()):

    ret, frame = cap.read()
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

2 个答案:

答案 0 :(得分:0)

如果您想以正常速度播放视频,则需要找出帧速率或每秒帧数(fps):

import cv2
if __name__ == '__main__' :

    video = cv2.VideoCapture("video.mp4");

    # Find OpenCV version
    (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')

    if int(major_ver)  < 3 :
        fps = video.get(cv2.cv.CV_CAP_PROP_FPS)
        print "Frames per second using video.get(cv2.cv.CV_CAP_PROP_FPS): {0}".format(fps)
    else :
        fps = video.get(cv2.CAP_PROP_FPS)
        print "Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}".format(fps)

   video.release(); 

此处有更多详情:https://www.learnopencv.com/how-to-find-frame-rate-or-frames-per-second-fps-in-opencv-python-cpp/

然后,不要在waitKey()中等待1 ms,而应考虑fps。

例如,如果您的视频为30fps,则需要为每个1000/30 = 33.333 ms播放一帧。在这种情况下,你应该做大约waitKey(33)。

如果你需要更好的精确度,你应该跟踪经过的时间(使用time.time()函数)和你玩过的帧数,并相应地调整waitKey参数。

如果您的视频播放速度比应该播放的速度慢,则必须跳过画面

答案 1 :(得分:0)

如果要以正常播放速率播放视频。以下功能可以帮助您正常播放视频。

def readVideo():
    # Read the video 
    capture = cv2.VideoCapture("video1.mp4")
    # get the versions of cv2 and convert them to a python list [major_version, minor_version, subminor_version]
    versions = str(cv2.__version__).split('.')

   # check if the major version integer value is less or greater than 3
   if int(versions[0]) < 3:
       # if less fps will be equal to
       fps = capture.get(cv2.cv.CV_CAP_PROP_FPS)
   else:
       # if greater fps will be
       fps = capture.get(cv2.CAP_PROP_FPS)
   while True:
       success, img = capture.read()
       cv2.imshow("Video", img)
       # On the waitKey() pass the integer value of 1000/fps as shown bellow
       if cv2.waitKey(int(1000/fps)) & 0xFF == ord('q'):
          # quit the loop when q is pressed
          break
   return capture.release() and cv2.destroyAllWindows()
# call the function
readVideo()

祝你好运