如何在 Python 中从 mp4 视频中获取一随机帧?

Chr*_*ner 2 python youtube-api python-2.7 python-3.x

我的目录中有一个 mp4 视频,我需要从 Python 中捕获一个随机帧。我该如何去做呢?

我目前正在使用这段代码,但它正在抓取第一帧。我需要它从所有帧中随机挑​​选。

mp4_directory = 'video.mp4'
frames = 324000
random_frame = random.randrange(0, frames)

vidcap = cv2.VideoCapture(mp4_directory)
success,image = vidcap.read()
count = random_frame - 1
while count < random_frame:
    cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file      
    success,image = vidcap.read()
    print('Read a new frame: ', success)
    count += 1
Run Code Online (Sandbox Code Playgroud)

小智 5

尝试这样的事情:

vidcap = cv2.VideoCapture("myvideo.mp4")
# get total number of frames
totalFrames = vidcap.get(cv2.CAP_PROP_FRAME_COUNT)
randomFrameNumber=random.randint(0, totalFrames)
# set frame position
vidcap.set(cv2.CAP_PROP_POS_FRAMES,randomFrameNumber)
success, image = vidcap.read()
if success:
    cv2.imwrite("random_frame.jpg", image)
Run Code Online (Sandbox Code Playgroud)