How can I close a cv2 window?

时间:2016-05-13 15:35:20

标签: python

I build a python module that calls an IP Camera, but when I try to close the window generated by cv2 the window is generated again and again in an infinite loop. Can you help me with this?

This is the script

import cv2

source = "rtsp://admin:admin2016@192.168.1.2//Streaming/Channels/2"
cap = cv2.VideoCapture(source)

ok_flag = True

while ok_flag:
    (ok_flag, img) = cap.read()

    if not ok_flag:
        break

    cv2.imshow("CallingCamera View", img)
    if cv2.waitKey(1) == 27:
        ok_flag = False
        break  
cv2.destroyAllWindows()

2 个答案:

答案 0 :(得分:2)

我无法完全复制你的错误(我最终用你的代码崩溃了python),但我确实想出了一个修复程序。

while ok_flag:
    (ok_flag, img) = cap.read()
    cv2.imshow("CallingCamera View", img)
    if cv2.waitkey(0) ==27:
        ok_flag = False

cv2.destroyAllWindows()

我不确定你是否有理由将waitKey时间设置为1ms,因为测试目的将其设置为0(永远)工作方式相同。我想把它设置为1ms,你会得到最新的图片吗?我的测试使用驻留在桌面上的静态图像运行。否则删除两个中断和if not ok_flag语句似乎解决了所有问题。你并不真的需要那些,因为只要ok_flag转到False,循环就会终止。

答案 1 :(得分:0)

cv2.destroyWindow("shown_img")

该参数与用于cv2.imshow("shown_img", img)的参数相同