python - 在 Python 中暂停和重新启动视频

标签 python opencv image-processing video video-capture

我有几个视频,我想逐帧浏览它们,并通过按键盘键(取决于帧)对其中一些进行注释。对于许多帧,我不会按任何键。这是我目前所拥有的:

import numpy as np
import cv2

cap = cv2.VideoCapture('video.mp4')

frame_number = []
annotation_list = []

i = 0
while(True):        
    # Read one frame.
    ret, frame = cap.read()

    # Show one frame.
    cv2.imshow('frame', frame)

    # Set the time between frames in miliseconds
    c = cv2.waitKey(500)
    i = i + 1

    try:
        annotation_list = annotation_list + [chr(c)]
        frame_number = frame_number + [i]
    except:
        continue

所以这显示每个帧 0.5 秒,并与我按下按钮的每个帧相关联,给定的字母。我现在需要的是一个选项,这样对于给定的帧,我可以在该帧停止视频,只要我需要,例如,通过按“空格键”,以考虑如何对其进行注释,然后按“空格键” ” 再次继续视频,一旦我决定如何注释。如何添加此暂停/继续选项?谢谢!

最佳答案

您可以通过根据 cv2.waitKey() 的返回值确定按下的键来实现暂停/恢复功能。要暂停视频,您可以不向 cv2.waitKey() 传递任何参数(或 0),它将无限期地等待,直到有按键按下,然后它将恢复视频。来自docs :

cv2.waitKey() is a keyboard binding function. Its argument is the time in milliseconds. The function waits for specified milliseconds for any keyboard event. If you press any key in that time, the program continues. If 0 is passed, it waits indefinitely for a key stroke. It can also be set to detect specific key strokes like, if key a is pressed etc which we will discuss below.

要确定空格键是否被按下,我们可以检查返回值是否为 32。如果按下此键,那么我们将无限期暂停帧,直到按下任何键,然后我们恢复视频。这是一个例子:

import cv2

cap = cv2.VideoCapture('video.mp4')
if not cap.isOpened():
    print("Error opening video")

while(cap.isOpened()):
    status, frame = cap.read()
    if status:
        cv2.imshow('frame', frame)
    key = cv2.waitKey(500)

    if key == 32:
        cv2.waitKey()
    elif key == ord('q'):
        break

以后如果你想在按键后执行一些操作,你可以用这个脚本来确定“键码”:

import cv2

# Load a test image
image = cv2.imread('1.jpg')

while(True):
    cv2.imshow('image', image)
    key = cv2.waitKey(1)
    # 'q' to stop
    if key == ord('q'):
        break
    # Print key 
    elif key != -1:
        print(key)

关于python - 在 Python 中暂停和重新启动视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59364385/

相关文章:

java - 如何在图像上显示图像不同像素的速度 vector ?

python - 计算列中的唯一值 - pandas Python

python - 使用 tensorflow 后端测试 keras 中多个类的加权分类交叉熵

python - 将数据插入 Cassandra

opencv - 从 OpenCV 中的边获取多边形

c++ - Opencv 2 Mat- 运行时错误

c - 使用 Appsrc Appsink 出错

image-processing - HSV 中的红色范围是多少?

opencv - 图像中的对象检测

python - 为什么我定义的语法不使用标记?