1.调用摄像头
#读取摄像头
import cv2
cap=cv2.VideoCapture(0)
#cap=cv2.VideoCapture('output.avi')
if not cap.isOpened():print("Cannot open camera")exit()
while True:# 逐帧捕获ret,frame=cap.read()# 如果正确读取帧,ret为Trueif not ret:break# 显示结果帧cv2.imshow('frame', frame)if cv2.waitKey(1)==ord('q'):break
# 完成所有操作后,释放捕获器
cap.release()
cv2.destroyAllWindows()
2.读取视频
#读取视频
import cv2 as cv
cap=cv.VideoCapture('output.avi')
while cap.isOpened():ret,frame=cap.read()# 如果正确读取帧,ret为Trueif not ret:breakcv.imshow('frame',frame)if cv.waitKey(100)==ord('q'):break
cap.release()
cv.destroyAllWindows()
3.录像
#调用双目摄像头录像
import cv2 as cv
cap=cv.VideoCapture(0)
# 定义编解码器并创建VideoWriter对象
fourcc=cv.VideoWriter_fourcc(*'DIVX')
out=cv.VideoWriter('output.avi',fourcc,20.0,(640,480))
while cap.isOpened():ret,frame=cap.read()if not ret:breakframe=cv.flip(frame,1)# 写翻转的框架out.write(frame)cv.imshow('frame',frame)if cv.waitKey(1) == ord('q'):break
# 完成工作后释放所有内容
cap.release()
out.release()
cv.destroyAllWindows()
录像时,cv.VideoWriter是核心,cv.VideoWriter中,FourCC 是用于指定视频编解码器的4字节代码:
MJPG是mp4
DIVX是avi
FLV1是flv