Opencv Python 简明教程

OpenCV Python - Play Video from File

VideoCapture() 函数也可以从视频文件中而不是摄像机中提取帧。因此,我们只需要把摄像机索引替换为在 OpenCV 窗口中播放的视频文件的名称。

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)

虽然这对于渲染视频文件来说已足够,但如果它带有音频,音频不会一同播放。为此,你需要安装 ffpyplayer 模块。

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 是 FFmpeg 库的 Python 绑定,可用于播放和编写媒体文件。要安装,请使用 pip 安装器实用程序,并使用以下命令。

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

pip3 install ffpyplayer

该模块中 MediaPlayer 对象的 get_frame() 方法返回一个音频帧,它将与从视频文件中读取的每个帧一起播放。

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()