English 中文(简体)
OpenCV Python - Play Videos
  • 时间:2024-12-22

OpenCV Python - Play Video from File


Previous Page Next Page  

The VideoCapture() function can also retrieve frames from a video file instead of a camera. Hence, we have only replaced the camera index with the video file’s name to be played on the OpenCV window.


video=cv2.VideoCapture(file)

While this should be enough to start rendering a video file, if it is accompanied by sound. The sound will not play along. For this purpose, you will need to install the ffpyplayer module.

FFPyPlayer

FFPyPlayer is a python binding for the FFmpeg pbrary for playing and writing media files. To install, use pip installer utipty by using the following command.


pip3 install ffpyplayer

The get_frame() method of the MediaPlayer object in this module returns the audio frame which will play along with each frame read from the video file.

Following is the complete code for playing a video file along with its audio −


import cv2

from ffpyplayer.player import MediaPlayer
file="video.mp4"

video=cv2.VideoCapture(file)
player = MediaPlayer(file)
while True:
   ret, frame=video.read()
   audio_frame, val = player.get_frame()
   if not ret:
      print("End of video")
      break
   if cv2.waitKey(1) == ord("q"):
      break
   cv2.imshow("Video", frame)
   if val !=  eof  and audio_frame is not None:
      #audio
      img, t = audio_frame
video.release()
cv2.destroyAllWindows()
Advertisements