【问题标题】:How to get frame from video by its index via OpenCV and Python?如何通过 OpenCV 和 Python 通过索引从视频中获取帧?
【发布时间】:2018-02-16 10:59:44
【问题描述】:

我需要通过帧索引访问视频中的帧。到目前为止,我使用了这样的代码:

video = cv2.VideoCapture(video_path)
status, frame = video.read()

代码读取第一帧。如果我重复使用该代码,我将获得下一帧。但是如何通过索引直接访问任何帧呢?

也就是说,如果我想要第二帧,如何不调用read()两次直接访问第二帧?

【问题讨论】:

    标签: python opencv video


    【解决方案1】:

    使用VideoCapture::set()CAP_PROP_POS_FRAMES 属性id 来设置要读取的帧的位置。

    myFrameNumber = 50
    cap = cv2.VideoCapture("video.mp4")
    
    # get total number of frames
    totalFrames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    
    # check for valid frame number
    if myFrameNumber >= 0 & myFrameNumber <= totalFrames:
        # set frame position
        cap.set(cv2.CAP_PROP_POS_FRAMES,myFrameNumber)
    
    while True:
        ret, frame = cap.read()
        cv2.imshow("Video", frame)
        if cv2.waitKey(20) & 0xFF == ord('q'):
            break
    
    cv2.destroyAllWindows()
    

    【讨论】:

    • cap.set(1, myFrameNumber) 是 python 3 所必需的
    • 感谢@zindarod 的帮助!也建议在cv2.destroyAllWindows()前加cap.release()
    【解决方案2】:
    import os
    folder= 'frames'
    os.mkdir(folder)
    import cv2
    vidcap = cv2.VideoCapture('four.mp4')
    def getFrame(sec):
        vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
        hasFrames,image = vidcap.read()
        if hasFrames:
            cv2.imwrite("image"+str(count)+".jpg", image)     # save frame as JPG file
        return hasFrames
    sec = 0
    frameRate = 0.5 #//it will capture image in each 0.5 second
    count=1
    success = getFrame(sec)
    while success:
        count = count + 1
        sec = sec + frameRate
        sec = round(sec, 2)
        success = getFrame(sec)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2017-12-31
      • 2015-09-08
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多