使用摄像头
capture=cv2.VideoCapture(0)
# 没有摄像头就用视频代替
# capture=cv2.VideoCapture("1.mp4")
指定写入视频帧编码格式
fourcc = cv2.VideoWriter_fourcc(*'XVID')
视频的size
size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
输出视频
out_video = cv2.VideoWriter('camera_test.avi', fourcc, 5.0, size)
写入一帧视频
outvideo.write(frame)
完整代码
import time
import cv2
# 调用摄像头
capture=cv2.VideoCapture(0)
# capture=cv2.VideoCapture("1.mp4")
fourcc = cv2.VideoWriter_fourcc(*'XVID')
size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
out_video = cv2.VideoWriter('camera_test1.avi', fourcc, 5.0, size)
while(True):
t1 = time.time()
# 读取某一帧
ref, frame=capture.read()
# 格式转变,BGRtoRGB
frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
cv2.imshow("video",frame)
# 写入一帧
out_video.write(frame)
if cv2.waitKey(1) == ord('1'): # 按下‘1’退出
break
capture.release()
out_video.release()