Hello Guys,

In this tutorial, I will show you how to play a video file using OpenCV.

To play a video file or to stream a webcam OpenCV has a function named VideoCapture. This function takes only one argument.

If you want to play the video you need to pass the file name with extension. Ex: nature.mp4. Similarly, If you want to stream your webcam you need to pass a number or device index. Which simply means which webcam you want to access. Just in case, If you have more than one webcam.

If you have only one webcam then you have to pass 0 or else if you have two web cameras then for accessing the second web camera you have to pass 1 and so on. 

Once we have initialized the video object by calling the VideoCapture function.
Then we will use an infinite while loop which will iterate till video.read() method returns true.

read() function returns two parameters

 1. Boolean – If True video still playing or False if the video is ended.
 2. Frame – Here frame is simply your picture. 

We have also used imshow function to show a frame.

Program

#import cv2 module
import cv2 as cv

video = cv.VideoCapture("video.mp4")

while True:
    ret,frame = video.read()
    # If condition is used to check whether video is still playing or 
    #ended. True means playing False means video ended
    if ret == True:
        #frame means image
        cv.imshow('video',frame)
        # Pressing a key q to break the loop
        #waitKey is used to display frames with 30seconds halt. So 
        #every frame will be rendered in 30seconds.
        #You can adjust as per your requirement. 
        #Video will be too fast if less time will be provided ex: 
        #waitKey(1)
        #Or too slow if more time is provided Ex: waitKey(60)
        if cv.waitKey(30) & 0xFF == ord('q'):
            break
    else:
        break
        
#release captured resources        
video.release()
#destroy opened windows
cv.destroyAllWindows()


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments