Play Video Files using OpenCV in Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.


First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3


In this tutorial, I will show you how to play video files like a videoplayer using OpenCV with Python coding.


Python: cv2.VideoCapture(filename) → <VideoCapture object>

Open video file for video playing


  • filename – name of the opened video file (eg. video.avi) or image sequence (eg. img_%02d.jpg, which will read samples like img_00.jpg, img_01.jpg, img_02.jpg, …)


  • Load the video file using cv2.VideoCapture()
  • Read video frames using
  • Display each frame using cv2.imshow()
  • Wait for keyboard button press using cv2.waitKey()
  • Release the VideoCapture object using cv2.VideoCapture.release()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2

def play_videoFile(filePath,mirror=False):

    cap = cv2.VideoCapture(filePath)
    cv2.namedWindow('Video Life2Coding',cv2.WINDOW_AUTOSIZE)
    while True:
        ret_val, frame =

        if mirror:
            frame = cv2.flip(frame, 1)

        cv2.imshow('Video Life2Coding', frame)

        if cv2.waitKey(1) == 27:
            break  # esc to quit


def main():

if __name__ == '__main__':


play-video-426x250 Play Video Files using OpenCV in Python

life2coding_icon [] Play Video Files using OpenCV in Python

One thought on “Play Video Files using OpenCV in Python

  1. Prasanna Kumar

    I am unable to load video file to OpenCV.It is showing the following error

    warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:901)
    warning: hello.mp4 (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:902)

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.