Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I close a cv2 window?

Tags:

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:[email protected]//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()
like image 698
Patricio Palacios Avatar asked Feb 08 '23 01:02

Patricio Palacios


2 Answers

I couldn't quite replicate your error (I ended up crashing Python with your code), but I did come up with a fix.

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

cv2.destroyAllWindows()

I wasn't sure if you had a reason for setting the waitKey time to 1ms or not, for testing purposes setting it to 0 (forever) worked just the same. I guess setting it to 1ms for you would get you the most recent image? My test was run with a static image residing on my desktop. Otherwise removing the two breaks and the if not ok_flag statement seemed to iron everything out. You don't really need those since as soon as ok_flag goes to False the loop terminates.

like image 52
Grr Avatar answered Feb 19 '23 22:02

Grr


cv2.destroyWindow("shown_img")

The parameter is the same as used for cv2.imshow("shown_img", img)

like image 32
user1109729 Avatar answered Feb 19 '23 21:02

user1109729