python 3 +opencv 3.4(三)--视频基本语句
2018-03-30 本文已影响0人
五秋木
-
opencv提供读取视频的类有:VideoCapture 和VideoWriter
-
创建一个读取视频对象:
videoCapture = cv2.VideoCapture('1.mp4')
-
获取其中一帧图片:
success,frame=videoCapture.read()
,success表示是否成功,frame表示获取的帧图片。格式为BGR -
获取读取视频每帧的信息:
fps = videoCapture.get(cv2.CAP_PROP_FPS) #帧速率 size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
-
创建新的视频,先创建一个视频写入对象:
videoWriter = cv2.VideoWriter('out.avi',cv2.VideoWriter_fourcc('I','4','2','0'),fps,size)
其中必须指定帧速率fps和帧大小size,指定视频编解码器:- cv2.VideoWriter_fourcc('I','4','2','0'),YUV颜色编码,AVI格式输出。
- cv2.VideoWriter_fourcc('P','I','M','1'),MPEG-1编码,AVI格式输出。
- cv2.VideoWriter_fourcc('X','V','I','D'),MPEG-4编码,AVI格式输出。
- cv2.VideoWriter_fourcc('F','L','V','1'),Flash编码,flv格式输出。
-
将本地视频复制下来并使用VideoWriter.write(frame)来复制视频,不过没有了声音。代码如下:
import cv2 videoCapture = cv2.VideoCapture('1.mp4') fps = videoCapture.get(cv2.CAP_PROP_FPS) #帧速率 size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT))) #尺寸大小 #avi格式 videoWriter = cv2.VideoWriter('out.avi',cv2.VideoWriter_fourcc('I','4','2','0'),fps,size) #FLV格式 videoWriter2 = cv2.VideoWriter('out.flv',cv2.VideoWriter_fourcc('F','L','V','1'),fps,size) success, frame=videoCapture.read() while success: videoWriter.write(frame) videoWriter2.write(frame) success,frame=videoCapture.read()
-
控制摄像头并录制部分视频。
- 创建videoCapture来获得摄像头的帧流。
cameraCapture=cv2.VideoCapture(0)
,用0表示摄像头的设备索引,而不在是用视频来作为参数。 - 设置fps帧速率和size每帧大小
fps = videoCapture.get(cv2.CAP_PROP_FPS) #帧速率
size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT))) #尺寸大小
- 创建videoWriter对象,并指定输出格式,帧速率和大小。
videoWriter=cv2.VideoWriter('camera_out.flv',cv2.VideoWriter_fourcc('F','L','V','1'),fps,size)
- 从摄像头读取每帧图像并保存到videoWriter对象中
success, frame=cameraCapture.read() numFrameRemaining=10*fps-1 while success and numFrameRemaining>0: videoWriter.write(frame) success, frame=cameraCapture.read() numFrameRemaining-=1
- 关闭摄像头:
cameraCapture.release()
- 创建videoCapture来获得摄像头的帧流。
-
摄像头控制:使用错误的设备索引,在read时会返回(false,none),摄像头是否正确打开,可以使用
VideoCapture.isOpened
来判断。 -
多个摄像头:不在使用read,而是使用grab()和retrive()。
未实现 -
实时显示视频流:新建一个窗口,在其中实时显示摄像头的视频。代码如下:
import cv2 clicked=False def onMouse(event,x,y,flags,param): #一旦点击鼠标执行 global clicked if event==cv2.EVENT_LBUTTONDBLCLK: #左键双击执行以下 clicked=True cameraCapture=cv2.VideoCapture(0) cv2.namedWindow('MyWindow') cv2.setMouseCallback('MyWindow',onMouse) #设置鼠标点击之后动作 print('Shiwing camera feed, Click window or press any key to stop') success,frame = cameraCapture.read() while success and cv2.waitKey(1)==-1 and not clicked: #cv2.waitKey(1)==-1表示没有任何键盘输入 cv2.imshow('MyWindow', frame) success,frame = cameraCapture.read() cv2.destroyAllWindows() cameraCapture.release()
-
Cameo项目:人脸跟踪和图像处理,没看懂