Life2Coding
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.

Requirements:

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

Goals:

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

Documentation:

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

Open video file for video playing

Parameters:          

  • 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, …)

Steps:

  • Load the video file using cv2.VideoCapture()
  • Read video frames using cv2.VideoCapture.read()
  • 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 = cap.read()

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

        cv2.imshow('Video Life2Coding', frame)

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

    cv2.destroyAllWindows()

def main():
    play_videoFile('bigbuckbunny720p5mb.mp4',mirror=False)

if __name__ == '__main__':
    main()

Output:

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.