我正在尝试通过使用 OpenCV (Python) 单击两个键(n 和 p)来关闭视频。 但是,我不明白为什么通过将特定行添加到循环末尾它不起作用。 事实上,使用这个特定的代码:
import cv2
import numpy as np
# Create a VideoCapture object and read from input file
cap = cv2.VideoCapture('randomvideo.mpg')
# Check if video opened successfully
if (cap.isOpened()== False):
print("Error opening file")
# Read until video is completed
while(cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
if ret == True:
# Display the resulting frame
cv2.imshow('Frame',frame)
cv2.waitKey(25)
我可以在播放结束时锁定视频,但是通过添加:
# Break the loop
else:
if 0xFF == (ord('n')) or 0xFF == (ord('p')):
break
我无法通过按两个键来关闭它。
有什么建议吗?
附言还有一种方法可以记录按下了哪个键吗?
提前致谢
最佳答案
您可以通过检查 cv2.waitKey()
的返回值来记录按下了哪个键。来自documentation :
It returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed.
所以你可以检查 n
或 p
是否像这样被按下
key = cv2.waitKey(25)
if key == ord('n') or key == ord('p'):
break
这是您的代码的工作版本
import cv2
cap = cv2.VideoCapture('randomvideo.mpg')
if not cap.isOpened():
print("Error opening file")
while(cap.isOpened()):
ret, frame = cap.read()
if ret:
cv2.imshow('frame',frame)
key = cv2.waitKey(25)
if key == ord('n') or key == ord('p'):
break
关于python - 通过单击两个键以 OpenCV VideoCapture 结束时发出关闭视频的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58840278/