It is very simple to use opencv to record video data into files. opencv provides us with a class that specifically saves video frames into video files. We can call it directly.- VideoWriter: Video data can be saved into multimedia files through VideoWriter.
- Write: the api for formally writing files. You need to specify the encoding format, output path, video frame rate, and resolution.
- Release: force the cache to disk
import cv2
from cv2 import waitKey
fourcc=cv2.VideoWriter_fourcc(*'MJPG')
# 创建video对象
vw=cv2.VideoWriter('111.mp4',fourcc,25,(1280,720))
cv2.namedWindow('video',cv2.WINDOW_NORMAL)
# 获取视频设备
cap=cv2.VideoCapture(0)
while 1:
# 从摄像头读视频帧
ret,frame=cap.read()
cv2.imshow('video',frame)
# 写数据到多媒体文件
vw.write(frame)
# 等待键盘事件,如果按q键就退出
key=cv2.waitKey(1)
if key==ord('q'):
break
# 释放VideoCaptrue
cap.release()
# 释放VideoWriter资源
vw.release()
cv2.destroyAllWindows()