Python OpenCV cv2.waitKey(1) 导致视频 window 到 freeze/not 响应

Python OpenCV cv2.waitKey(1) cause video window to freeze/not responding

所以我运行正在编写这段代码。

import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture("Resources/test_video.mp4")
while True:
    success, img = cap.read()
    if img is None:
        break
    img = cv2.resize(img, (frameWidth, frameHeight))
    cv2.imshow("Result", img)
    keyPressed = cv2.waitKey(5)
    if keyPressed == ord('q'):
        break;

test_video.mp4 是一个简短的 video here 在它完成 运行ning 的那一刻,“结果”window 冻结并且变得没有响应。即使我按“Q”,也没有任何反应。

我运行 Anaconda Spyder 上的程序。 cv2 使用 pip install opencv-python

安装

编辑:代码已修复,因此 window 在按下“q”时退出

尝试在末尾添加这两行:

import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture("Resources/test_video.mp4")
    while True:
        success, img = cap.read()
        if img is None:
            break
        #img = cv2.resize(img, (frameWidth, frameHeight))
        cv2.imshow("Result", img)
        if cv2.waitKey(1) and 0xFF == ord('q'):
             break
cap.release()
cv2.destroyAllWindows()

可能是脚本末尾未能释放资源。请参阅此 post 以获取更多参考:What's the meaning of cv2.videoCapture.release()?

这似乎也是一个常见问题。参见 and

编辑:更新以响应 'q' 上要求退出视频的评论。替换行:

if cv2.waitKey(1) and 0xFF == ord('q'):
    break

有:

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

经过测试,行为符合预期,使用:

  • Python 3.7
  • OpenCV 3.4.2