在本文中,Python通过调用OpenCV模块模拟了行车记录仪的工作全流程,包括如下功能:
- Python调用摄像头
- 根据使用者输入的时间长度进行录像并保存到本地
- 自动删除超过一定时间的视频文件
案例代码:
import time import cv2 video_time = int(input('请输入每个视频的长度(单位为秒):')) cap = cv2.VideoCapture(0) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fourcc = cv2.VideoWriter.fourcc(*'mp4v') last_start_time = time.time() out = cv2.VideoWriter('./video/' + 'output-' + str(int(time.time())) + '.mp4', fourcc, 20.0, (width, height)) while cap.isOpened() and ((cv2.waitKey(1) & 0xFF) != ord('q')): if time.time() - last_start_time >= video_time: out.release() out = cv2.VideoWriter('./video/' + 'output-' + str(int(time.time())) + '.mp4', fourcc, 20.0, (width, height)) last_start_time = time.time() ret, frame = cap.read() if ret: out.write(frame) cv2.imshow('My Camera', frame) else: break out.release() cap.release() cv2.destroyWindow()
原创文章,作者:朋远方,如若转载,请注明出处:https://caovan.com/opencvchangyongcaozuozhimonixingchejiluyi/.html