Python如何使用OpenCV播放视频?代码实现

2021年4月8日16:41:59 发表评论 718 次浏览

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

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

为了捕获视频,我们需要创建一个VideoCapture对象。视频捕获具有设备索引或视频文件的名称。设备索引只是指定哪个相机的数字。如果我们传递0,那么第一个摄像头是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()

注意:视频文件应与执行程序的目录位于同一目录中。

输出如下:

视频样本帧:

Python如何使用OpenCV播放视频?代码实现

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

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: