-1

i have a simple webcam opening using cv2 module:

cap=cv2.VideoCapture(0)
while True:
    ret, img = cap.read()
    cv2.imshow('webcam',img)
    k=cv2.waitKey(10)
    if k == 27:
        break
cap.release()
cv2.destroyWindows()

this program runs for ever, although i try to close it, the only way is closing vsCode

4
  • 1
    k == 27, that means Esc is the way to break out from OpenCV's loop. Go to the window displaying the webcam feed and press the Escape Key. Commented Sep 24, 2022 at 9:35
  • cv2 window doesn't stop your loop when you close window using button [X]. You have to use key ESC to stop loop and then it will close window too. I some question I saw some function to check if window is visible to stop loop when you use button [X] but this not popular so I don't remember code. Commented Sep 24, 2022 at 10:31
  • did you try to use Ctrl+C in terminal/console to stop code? Normally it works. VS Code should have also button to stop executing code - so it shouldn't need to close all VS Code Commented Sep 24, 2022 at 10:32
  • OpenCV Python: How to detect if a window is closed? - Stack Overflow Commented Sep 24, 2022 at 10:34

1 Answer 1

-1

You can close the webcam window by clicking on your webcam window and press esc while if you want to close it with specific alphabet then you can use the below code to destroy the window by pressing q.

import cv2
cap=cv2.VideoCapture(0)
while True:
    ret, img = cap.read()
    cv2.imshow('webcam',img)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break        
cap.release()
cv2.destroyAllWindows()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.