How to Close a Video Window Automatically After It Ends in Python using OpenCV



Python


In this article, we show how to close a video window automatically after it ends in Python using the OpenCV module.

Without specific code added to a video display program in Python, after the video ends, the window will remain open.

Many times, it is desired that the window displaying the video closes when the video ends.

We can do this easily with so simple code in Python.

This is shown in the following code below.



Let's now go over this code.

So the video we are working with is a video named yoga.mp4.

We start at the line, while cap.isOpened()

This checks to see whether the video exists and can be opened.

If the video exists and can be opened, then we create the variables, ret and frame, and set it equal to cap.read()

The ret holds a value of either True or False. As long as there are still frames remaining in the video, ret holds a value of True.

The frame value holds the actual image of each frame.

How we let the video window close automatically after the video ends is dependent on the ret value.

As long as ret is true, we know there are more frames left in the video.

Therefore, if ret is no longer true, we know that there are no more frames remaining in the video, meaning the video has ended.

Therefore, we use an else statement to the if ret == True statement

If ret is no longer true, we know the video has ended. Therefore, underneath this else statement, we break our code.

This then releases the read() function and destroys the window, closing the window.

So monitoring the ret value allows us to know when the video ends and when we should close the video window.

And this is how we can close a video automatically after it ends in Python using the OpenCV module.


Related Resources

How to Draw a Rectangle in Python using OpenCV

How to Draw a Circle in Python using OpenCV

How to Draw a Line in Python using OpenCV

How to Add Text to an Image in Python using OpenCV

How to Display an OpenCV image in Python with Matplotlib

How to Use Callback functions to Connect Images to Events in Python using OpenCV

How to Check for Multiple Events in Python using OpenCV



HTML Comment Box is loading comments...