python暂停和恢复_使用Python暂停和重新启动视频

1586010002-jmsa.png

I have several video and I want to go through them frame by frame, and annotate some of them by pressing a keyboard key (which depends on the frame). For many of the frames I won't press any key. Here is what I have so far:

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

So this is showing each frame for 0.5 seconds, and associates to each frame where I press a button, the given letter. What I need now is an option such that for a given frame I can stop the video at that frame for as long as I need, by pressing "Space" for example, in order to think about how to annotate it, then press "Space" again to continue the video, once I decide how to annotate. How can I add this pause/continue option? Thank you!

解决方案

You can implement a pause/resume feature by determining what key was pressed from the return value of cv2.waitKey(). To pause the video, you can pass no parameter (or 0) to cv2.waitKey() which will wait indefinitely until there is a key press then it will resume the video. From the 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.

To determine if the spacebar was pressed, we can check if the returned value is 32. If this key was pressed then we indefinitely pause the frame until any key is pressed then we resume the video. Here's an example:

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

In the future if you want to perform some action after pressing a key, you can determine the "key code" with this script:

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值