opencv调用摄像头保存视频
文章目录
- opencv调用摄像头保存视频
-
- [保存视频(采用默认分辨率640 x 480)](#保存视频(采用默认分辨率640 x 480))
- 保存视频(指定分辨率,例1280×720))
保存视频(采用默认分辨率640 x 480)
python
import cv2
import time
# 定义视频捕捉对象
cap = cv2.VideoCapture(1) # 参数0代表计算机的默认摄像头
# 获取视频的宽度和高度
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
# 定义VideoWriter对象并初始
out = cv2.VideoWriter('C:/Users/Desktop/0527.mp4',cv2.VideoWriter_fourcc(*'mp4v'), 20.0, (frame_width, frame_height))
while(cap.isOpened()):
ret, frame = cap.read() # 读取
if ret:
cv2.imshow('frame', frame)
# 写入帧到输出视频文件
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()
保存视频(指定分辨率,例1280×720)
初始化与保存帧大小一致
python
import cv2
import time
# 定义视频捕捉对象
cap = cv2.VideoCapture(1) # 参数0代表计算机的默认摄像头
# 获取视频的宽度和高度
frame_width = 1280
frame_height =720
# 定义VideoWriter对象并初始
out = cv2.VideoWriter('C:/Users/Desktop/0527.mp4',cv2.VideoWriter_fourcc(*'mp4v'), 20.0, (frame_width, frame_height))
while(cap.isOpened()):
ret, frame = cap.read() # 读取
if ret:
frame_resize=cv2.resize(frame,(1280,720))
cv2.imshow('frame', frame)
# 写入帧到输出视频文件
out.write(frame_resize)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()