-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

Gautam Chettiar
  • 449
  • 2
  • 11
Payam
  • 57
  • 7
  • 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. – Gautam Chettiar Sep 24 '22 at 09: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. – furas Sep 24 '22 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` – furas Sep 24 '22 at 10:32
  • [OpenCV Python: How to detect if a window is closed? - Stack Overflow](https://stackoverflow.com/questions/35003476/opencv-python-how-to-detect-if-a-window-is-closed) – furas Sep 24 '22 at 10:34

1 Answers1

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