python - 视频捕获窗口未关闭 - OpenCV

标签 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()

最佳答案

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

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

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

关于python - 视频捕获窗口未关闭 - OpenCV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61305973/

相关文章:

python - 一个ndarray的索引问题

python - django-cms makemigrations错误: No module named 'packaging'

Python - 除非指定,否则使用 pytest 跳过测试

python - Django url 模式顺序和正则表达式

python - 获取 Pandas DataFrame 中重叠年龄范围内的年龄总和

android - 是否可以从资源中加载 CascadeClassifier .xml 文件

opencv - 训练数据和词汇表的区别——词袋

c++ - 实现椭圆结构元素

c++ - 绘制凸面缺陷 C++ OpenCV

python - 为 opencv python 包安装 gstreamer 支持