videocapture窗口未关闭-OpenCV

时间:2020-04-19 14:28:57

标签: python opencv

我正在尝试使用网络摄像头捕获实时视频。
而且我从互联网上学到的代码也很吸引人。
但是当我将opencv更新到4.2.0之后存在一个问题。无论我尝试多少次,videoCapture窗口都不会关闭。

源代码

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    frame = cv.flip(frame,1)
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # Our operations on the frame come here
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv.imshow('frame', gray)
    if cv.waitKey(1) == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

1 个答案:

答案 0 :(得分:1)

您可以在while循环的末尾添加以下内容,以检测窗口是否关闭并终止循环:

    if cv.getWindowProperty('frame', cv.WND_PROP_VISIBLE) < 1:
        break

如果窗口getWindowProperty不再存在,则frame将返回0。