通过单击两个键以 OpenCV VideoCapture 结束时发出关闭视频的问题

Issue closing a video when it ends with OpenCV VideoCapture by clicking two keys

我正在尝试通过使用 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

按这两个键无法关闭

有什么建议吗?

P.S。有没有一种方法可以记录按下了哪个键?

提前致谢

您可以通过检查 cv2.waitKey() 中的 return 值来记录按下了哪个键。来自 documentation:

It returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed.

所以你可以检查np是否像这样被按下

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