获取VideoCapture实例
1 2 3 4 5 6 7 8
| strem_capture = cv2.VideoCapture("rtst://192.168.0.0/live/demo")
file_capture = cv2.VideoCapture('demo.mp4')
capture = cv2.VideoCapture(0)
|
获取摄像头编号可使用ls -al /dev/ |grep video
,输出信息以video
开头其后缀为数字即为可能的摄像头编号。
检查获取VideoCapture实例是否成功
1 2 3
| if not capture.isOpened(): return
|
获取视频流信息
1 2 3 4 5 6 7 8
| width = capture.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cpature.get(cv2.CAP_PROP_FRAME_HEIGHT)
fps = capture.get(cv2.CAP_PROP_FPS)
|
获取帧画面
1
| success, frame = capture.read()
|
当需要同时处理多路摄像头时一般使用grab()
和retrieve()
代替
1 2 3 4 5 6 7
| success_1 = capture.grab() success_2 = stream_capture.grab()
if success_1 and success_2: frame_1 = capture.retrieve() frame_2 = stream_capture.retrieve()
|
设置分辨率
1 2 3 4 5
| capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
|
保存视频文件
无论是视频文件存储还是摄像头画面保存都是用VideoWriter
类,初始化时需要传入文件名(包含文件格式)、视频编解码器、视频保存帧率 、分辨率,保存视频的帧率最好和读入的帧率一致,分辨率可以更改,只是要求写入的帧大小要与分辨率保持一致。
若指定的文件名已存在则会覆盖文件。
1 2 3
| writer = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'MP4V'), 30, (1080,1920)) writer.write(frame)
|
释放资源
不管是VideoCapture
还是VideoWriter
类,使用完都应该释放资源
1 2 3 4 5
| capture.release()
writer.release()
|
完整示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
import cv2 import time
capture = cv2.VideoCapture('rtsp://192.168.0.0/live/demo) fourcc = cv2.VideoWriter_fourcc(*'MP$v') # 或H264,H265 fps = capture.get(cv2.CAP_PROP_FPS) width = capture.get(cv2.CAP_PROP_FRAME_WIDTH) height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
writer = cv2.VideoWriter('demo.mp4', fourcd, fps, (height, width))
while True: if not capture.isOpened(): time.sleep(0.5) continue success, frame = capture.read() if success: cv2.imshow('DEMO', frame) # 显示画面 writer.write(frame) # 保存视频文件 if (cv2.waitKey(20) & 0xff) == ord('q'): # 等待20ms并判断是否按下'q'退出,waitkey只能传入整数, break
capture.release() # 释放VideoCapture writer.release() # 释放VideoWriter cv2.destroyAllWindows() # 销毁所有opencv显示窗口
|