PHP前端开发

python如何实现视频的读取与保存功能(代码实例)

百变鹏仔 3小时前 #Python
文章标签 如何实现

本篇文章给大家带来的内容是介绍python如何实现视频读取与保存功能。有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所助。

1.打开摄像头

#打开摄像头import cv2cap = cv2.VideoCapture(0)while(True):    ret,frame = cap.read()#返回两个值,第一个为bool类型,如果读到帧返回True,如果没读到帧返回False,第二个值为帧图像    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)    cv2.imshow('frame',gray)    if cv2.waitKey(1)==27:        breakcap.release()cv2.destroyAllWindows()

2.读取视频文件

#打开视频文件import cv2cap = cv2.VideoCapture('vtest.avi')while(True):    ret,frame = cap.read()#返回两个值,第一个为bool类型,如果读到帧返回True,如果没读到帧返回False,第二个值为帧图像     if(ret):        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)        cv2.imshow('input',gray)    else:        break    if cv2.waitKey(1)==27:        breakcap.release()cv2.destroyAllWindows()

3.保存视频文件

#保存视频文件import cv2fourcc = cv2.VideoWriter_fourcc(*'XVID')#视频编码格式out = cv2.VideoWriter('save.avi',fourcc,20,(640,480))#第三个参数为帧率,第四个参数为每帧大小cap = cv2.VideoCapture(0)while(True):    ret,frame = cap.read()    if(ret):        cv2.imshow('input',frame)        out.write(frame)    else:        break    if(cv2.waitKey(1)==27):        breakcap.release()out.release()cv2.destroyAllWindows()