一、读取写入视频文件
1 import cv2 2 3 # 创建一个视屏捕获对象 4 videoCapture = cv2.VideoCapture('AVI.avi') 5 6 # 获取视频的属性值,cv2.CAP_PROP_FPS获取视频帧率 7 fps = videoCapture.get(cv2.CAP_PROP_FPS) 8 9 # cv2.CAP_PROP_FRAME_WIDTH/HEIGHT 返回float类型 获取视频帧的宽高10 size = int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), \11 int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT))12 13 '''14 创建一个写入对象,将帧写入输出的视频15 cv2.VideoWriter_fourcc()函数指定编码器为 I42016 fps 和 size 指定输出的帧率和尺寸17 '''18 videoWrite = cv2.VideoWriter('Out.avi',19 cv2.VideoWriter_fourcc('I', '4', '2', '0'),20 fps, size21 )22 23 '''24 对捕获到的视频对象进行读取帧,success表示是否成功读取一帧,frame表示当前帧。25 循环读取写入输出视频。26 '''27 success, frame = videoCapture.read()28 while success:29 videoWrite.write(frame)30 success, frame = videoCapture.read()
二、捕获摄像头帧
1 import cv2 2 3 cameraCapture = cv2.VideoCapture(0) 4 5 fps = 30 6 7 size = int(cameraCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), \ 8 int(cameraCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)) 9 10 videoWriter = cv2.VideoWriter(11 'OutVideo_GRAB.avi',12 cv2.VideoWriter_fourcc('I', '4', '2', '0'),13 fps,14 size15 )16 17 success, frame = cameraCapture.read()18 19 numFramesRemaining = 10 * fps20 while success and numFramesRemaining > 0:21 videoWriter.write(frame)22 success, frame = cameraCapture.read()23 numFramesRemaining -= 1
和视频的读取写入没有什么差异,都是需要先创建一个VideoCapture Object来操作,下述是细微差别:
3 Line:VideoCapture(0),其中 0 代表设备,还可以1,2,3 分别代表不同的摄像头(如果存在),也可以输入网络摄像头,直接替换成URL即可
5 Line:需要手动设置fps的值
19 Line:需要设定一个时间,numFramesRemaining代表持续捕获300个帧,而每30个帧为一秒,所以将生成一个10秒钟的视频文件
三、窗口显示图片
1 import cv22 3 img = cv2.imread('CopyPic.png')4 cv2.imshow('', img)5 cv2.waitKey()6 cv2.destroyAllWindows()
四、窗口显示摄像头
1 import cv2 2 3 # 检测窗口是否被点击 4 clicked = False 5 6 7 # 定义鼠标事件处理函数 8 def onMouse(event: int, x, y, flags, param): 9 global clicked10 if event == cv2.EVENT_LBUTTONUP:11 clicked = True12 13 14 # 创建一个视频对象15 cameraCapture = cv2.VideoCapture(0)16 # 定义窗口命17 cv2.namedWindow('Camera')18 # 将鼠标回调函数,将鼠标事件处理函数和窗口关联起来19 cv2.setMouseCallback('Camera', onMouse)20 21 print('Showing camera feed. Click window or press any key to stop.')22 # 获取当前时间的摄像头帧23 success, frame = cameraCapture.read()24 25 # 循环获取当前时间的摄像头帧,当按下任意按键 or 点击鼠标时则停止显示26 while success and cv2.waitKey(1) == -1 and not clicked:27 cv2.imshow('Camera', frame)28 success, frame = cameraCapture.read()29 30 # 关闭窗口31 cv2.destroyAllWindows()32 33 # 释放摄像头资源34 cameraCapture.release()
针对多摄像头,我们需要先探明摄像头的设备号:
1 import cv2 2 3 for item in range(10): 4 # 创建一个object 5 camera = cv2.VideoCapture(item) 6 7 # 查询此摄像头是否能打开,如果不能则跳过,并输出一条 Error Message 8 if not camera.isOpened(): 9 print(f"Can\'t open camera {item}")10 continue11 12 # 读取摄像头帧率13 while True:14 success, frame = camera.read()15 # 当摄像头帧读取失败则跳过16 if not success:17 break18 19 cv2.imshow(f'Camera device number: {item}', frame)20 21 # 等待1毫秒,检查用户是否有键盘输入‘q’22 if cv2.waitKey(1) == ord('q'):23 break24 25 camera.release()26 cv2.destroyAllWindows()