How to Read and Show Video in Python using CV2 (OpenCV)

You can read and show the video in Python using CV2 (OpenCV) by following the given code. I highly recommend you get the “Computer Vision: Models, Learning, and Inference Book” to learn Computer Vision.

How to Read and Show Video in Python using CV2 (OpenCV)
How to Read and Show Video in Python using CV2 (OpenCV)

Read and Show Video using CV2

Import the OpenCV library. If OpenCV is not installed in your system then first install it using This Method. Then capture the video from the location. In my case “C:\\AiHints” is the location and “cars.mp4” is the name of the video. Change it according to your video location and name. Press the key ‘q’ to exit the video. The function cv2.destroyAllWindows() will destroy all the windows that we created.

#cv2 is used for OpenCV library
import cv2
#Capture the Video from location
video = cv2.VideoCapture("C:\\AiHints\\cars.mp4")
#It will return the frames (Video = Combination of Frames)
while(video.isOpened()):
    ret,frame = video.read()
#Show the frames   
    if ret == True:
        cv2.imshow("Car Video",frame)
#Press key 'q' to exit video
        if cv2.waitKey(2) & 0xFF == ord('q'):
            break
    else:
        break        
video.release()
cv2.destroyAllWindows()

Leave a Comment

Your email address will not be published.