Python,OpenCV:在文件末尾停止捕获

问题描述 投票:0回答:1

(使用OpenCV 4.1)

我正在尝试从视频中捕获屏幕截图。我的意图是让脚本每五分钟捕获一次帧,最多捕获20次。

我的测试视频长20分钟。一旦脚本循环4次,我希望它退出。但是,它循环播放第5次,并从视频结束处捕获2秒。然后它循环第6次,并捕获与第4次循环相同的帧。它会继续重复最后两个循环,直到捕获到20帧为止。

如何获取脚本以确认它已到达视频结尾并停止?

注意:捕获的最后一帧可能不是视频中的最后一帧。例如,如果视频长23分钟,则最后捕获的帧应该在20分钟标记附近。

import datetime
import sys
import time

from cv2 import cv2


def milsec_to_hr_min_sec(milliseconds):  # Returned from CAP_PROP_POS_MSEC
    ms = int(milliseconds)
    seconds = str(int((ms / 1000) % 60))
    minutes = str(int((ms / (1000 * 60)) % 60))
    hours = str(int((ms / (1000 * 60 * 60)) % 24))
    return hours, minutes, seconds


def FrameCapture(path):  # Extract frame
    cap = cv2.VideoCapture(path)
    framerate = cap.get(cv2.CAP_PROP_FPS)
    count = 1
    framecount = 0

    # checks whether frames were extracted
    while True:
        while count < 21 and framecount < cap.get(cv2.CAP_PROP_FRAME_COUNT):
            # Capture frame every 5 minutes
            framecount = count * framerate * 60 * 5
            cap.set(1, framecount)

            # capture frame at timestamp
            success, image = cap.read()
            if success:
                cv2.imwrite(
                    path + " (screencap #%d).jpg" % count, image,
                )
                # Convert timestamp to hr:min:sec
                hours, minutes, seconds = milsec_to_hr_min_sec(
                    cap.get(cv2.CAP_PROP_POS_MSEC)
                )
                print(
                    str(success)
                    + " "
                    + "Captured: screencap #{} at timestamp ".format(count)
                    + hours
                    + "h "
                    + minutes
                    + "m "
                    + seconds
                    + "s"
                )
                count += 1
                if cv2.waitKey(1) & 0xFF == ord("q"):
                    break
            else:
                break

    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()
    print("Finished capture")


# Driver Code
if __name__ == "__main__":

    # Calling the function
    fn = "\\full\path\to\file"
    FrameCapture(fn)

请原谅我的脚本具有hack-y性质。我将它们与从搜索中找到的零件拼凑在一起。

python python-3.x opencv video-capture
1个回答
0
投票

有两种方法:

  • 通过while(true)循环并在break时循环通过frame.empty()。>>
  • 使用:int nFrames = vid_cap.get(CAP_PROP_FRAME_COUNT); //Get the number of frames avaiable in the video获取帧计数,并使用for_loop循环浏览帧。
© www.soinside.com 2019 - 2024. All rights reserved.