Search code examples
python-3.xopencvyolov8

How do I close YOLOv8 video detection on key press?


I want to close the detection window on a key press and not have to stop the entire code. I am able to do it for my image detection but since video runs on a loop I can't find how.

            root.video = filedialog.askopenfilename(initialdir="/desktop", title="Select video to detect")
            cap = cv2.VideoCapture(root.video)

            model = YOLO('best.pt')

            classNames = ['Orange', 'Orange', 'Pomegranate', 'Pomegranate', 'apple', 'apple', 'banana', 'banana',
                          'fruits', 'guava', 'guava', 'guava', 'lime', 'lime']
            while True:
                success, vid = cap.read()
                results = model(img, stream=True)

                        cv2.imshow("DetectVideo", vid)
                        cv2.waitKey(1)

I have tried the following

k = cv2.waitKey(0) #also tried with (1)
print(k)
if k == 27:  # close on ESC key
    cv2.destroyAllWindows()

which basically makes it so it just closes each frame of the video then continues to next frame on key press.


Solution

  • You need to exit from the loop once the ESC key is pressed.

    In your current implementation, the current window will be closed when ESC key is pressed. But the while loop will read the next frame and display it.

    Please update the code portion this way:

    k = cv2.waitKey(0)
    print(k)
    if k == 27:  # close on ESC key
        cv2.destroyAllWindows()
        break
    

    By adding a break, once ESC key is pressed, the current window is closed and the loop execution will be stopped. So, no more frames will be displayed.