首页 > 解决方案 > 如何使用 Python 播放视频?

问题描述

我想创建一个简单的程序来帮助我打开我想要的任何视频,只需写下视频的名称;有没有我可以使用的库。

标签: pythonvideo

解决方案


在 python 中处理图像和视频的最常见方法是使用 opencv,它是一个功能强大的库,可让您读取 imgs、视频并显示它们。如果您只想重现视频,可以使用如下代码:

import cv2


videoName = yourVideoPathAndName #'DJI_0209.MP4'

#create a videoCapture Object (this allow to read frames one by one)
video = cv2.VideoCapture(videoName)
#check it's ok
if video.isOpened():
    print('Video Succefully opened')
else:
    print('Something went wrong check if the video name and path is correct')


#define a scale lvl for visualization
scaleLevel = 3 #it means reduce the size to 2**(scaleLevel-1)


windowName = 'Video Reproducer'
cv2.namedWindow(windowName )
#let's reproduce the video
while True:
    ret,frame = video.read() #read a single frame 
    if not ret: #this mean it could not read the frame 
         print("Could not read the frame")   
         cv2.destroyWindow(windowName)
         break

    reescaled_frame  = frame
    for i in range(scaleLevel-1):
        reescaled_frame = cv2.pyrDown(reescaled_frame)

    cv2.imshow(windowName, reescaled_frame )

    waitKey = (cv2.waitKey(1) & 0xFF)
    if  waitKey == ord('q'): #if Q pressed you could do something else with other keypress
         print("closing video and exiting")
         cv2.destroyWindow(windowName)
         video.release()
         break

推荐阅读