📜  Python|使用 OpenCV 播放视频

📅  最后修改于: 2022-05-13 01:54:40.212000             🧑  作者: Mango

Python|使用 OpenCV 播放视频

OpenCV (开源计算机视觉)是一个计算机视觉库,包含对图像或视频执行操作的各种功能。 OpenCV 库可用于对视频执行多种操作。

让我们看看如何使用 OpenCV Python播放视频。

要捕获视频,我们需要创建一个VideoCapture object 。 VideoCapture 具有设备索引或视频文件的名称。设备索引只是指定哪个相机的数字。如果我们传递 0 那么它是第一台摄像机,1 是第二台摄像机,依此类推。我们逐帧捕捉视频。
句法 :

cv2.VideoCapture(0): Means first camera or webcam.
cv2.VideoCapture(1):  Means second camera or webcam.
cv2.VideoCapture("file name.mp4"): Means video file

下面是实现:

# importing libraries
import cv2
import numpy as np
   
# Create a VideoCapture object and read from input file
cap = cv2.VideoCapture('tree.mp4')
   
# Check if camera opened successfully
if (cap.isOpened()== False): 
  print("Error opening video  file")
   
# Read until video is completed
while(cap.isOpened()):
      
  # Capture frame-by-frame
  ret, frame = cap.read()
  if ret == True:
   
    # Display the resulting frame
    cv2.imshow('Frame', frame)
   
    # Press Q on keyboard to  exit
    if cv2.waitKey(25) & 0xFF == ord('q'):
      break
   
  # Break the loop
  else: 
    break
   
# When everything done, release 
# the video capture object
cap.release()
   
# Closes all the frames
cv2.destroyAllWindows()

注意:视频文件应与执行程序的目录相同。
输出:

视频样本帧:

相关文章:如何以反向模式播放视频。