python&opencv捕获摄像头的帧

因为捕获摄像头几乎和读取视频文件一模一样,所以这次注释就少点。
下面这个例子,捕获摄像头10s,并生成avi视频:

import cv2

cameraCapture = cv2.VideoCapture(0)

fps = 30#这里是个估值
size = (int(cameraCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(cameraCapture.get(cv2.CAP_PROP_FRAME_COUNT)))#获得码率及尺寸

videoWrite = cv2.VideoWriter('outputVid.avi',cv2.VideoWriter_fourcc('I','4','2','0'),
                             fps,size)

success,frame = cameraCapture.read()
numFramesRenaining = 10*fps - 1

while success and numFramesRenaining>1:
    cv2.imshow('outputVid.avi',frame)
    cv2.waitKey(1)  # 延迟
    videoWrite.write(frame)
    success,frame = cameraCapture.read()
    numFramesRenaining-=1

cameraCapture.release()

注:VideoCapture类的get()方法不能返回摄像头帧速率的准确值,它总是返回0.
所以要么对帧速率做出假设,要么用计时器来测量。(后一种会更准确点)

如果是一组或者是一个多头摄像头时,read()方法就不合适了。

你可能感兴趣的:(python&opencv)