简体   繁体   中英

Closing video window using close “X” button in OpenCV, Python

I am displaying live video from a camera using OpenCV in Python. This is the code:

capture = cv.CaptureFromCAM(0)
if capture:
    cv.NamedWindow("Live Video", cv.CV_WINDOW_AUTOSIZE)
    frame = cv.QueryFrame(capture)
    if frame:
        cv.ShowImage("Live Video", frame)    
        cv.WaitKey(0)

cv.DestroyWindow("Live Video")

Now, I can only close my video window by pressing "esc", but nothing happens when I click on my window's close "X" button. Is there a way to make that work?

With the cv2 Python module there is a way to do that, I posted the solution here:

https://stackoverflow.com/a/37881722/2897426

This post is just for reference so anyone looking for it can find it

I had this same issue and I found an easy way to do it:

You can use cv2.getWindowProperty(windowName, cv2.WND_PROP_VISIBLE) to check if the current window is visible, and if it's not you can destroy the window. The method returns a 1 if it is visible and 0 if it is not. Below is an implementation:


while True: 
    _, frame = cap.read()

    cv2.imshow(windowName, frame)
    keyCode = cv2.waitKey(1)

    if cv2.getWindowProperty(windowName, cv2.WND_PROP_VISIBLE) <1:
        break
cv2.destroyAllWindows()

The accepted answer links to a solution that will never work as 0 is included in >=0, and uses the wrong second argument in cv2.getWindowProperty() , while the issues only gets indirectly solved later in the thread. I'm adding this as an answer as I could not find the correct solution when I first visited this thread, and this was exactly what I needed and used.

OpenCV does not have this feature, and only handles key presses by default.

If you want to do this, you must use the handle of the window manager that creates your windows (GTK, QT, ...).

This post describes a similar issue in case you use windows. Let me know if not ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM