参考:OpenCV截取指定时间范围内的视频(python)_Qyun_lucky_star的博客-CSDN博客
import cv2def capture_video(video_path, result_video_path, video, result_video, start_time, end_time):"""功能&#xff1a;截取短视频参数&#xff1a;video_path&#xff1a;需要截取的视频路径result_video_path&#xff1a;截取后的视频存放的路径video&#xff1a;需要截取的视频的名称&#xff08;不带后缀&#xff09;result_video&#xff1a;截取了的视频的名称&#xff08;不带后缀&#xff09;start_time&#xff1a;截取开始时间&#xff08;单位s&#xff09;end_time&#xff1a;截取结束时间&#xff08;单位s&#xff09;"""# 读取视频cap &#61; cv2.VideoCapture(video_path &#43; video)# 读取视频帧率fps_video &#61; cap.get(cv2.CAP_PROP_FPS)# 设置写入视频的编码格式fourcc &#61; cv2.VideoWriter_fourcc(*"mp4v")# 获取视频宽度和高度frame_width &#61; int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))frame_height &#61; int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))# 设置写视频的对象videoWriter &#61; cv2.VideoWriter(result_video_path &#43; result_video, fourcc, fps_video, (frame_width, frame_height))# 初始化一个计数器count &#61; 0while (cap.isOpened()):# 按帧读取视频里的图片ret, frame &#61; cap.read()# 如果视频没有读取结束if ret &#61;&#61; True:# 计数器加一count &#43;&#61; 1# 截取相应时间内的视频信息if(count > (start_time * fps_video) and count <&#61; (end_time * fps_video)):# 将图片写入视屏videoWriter.write(frame)if(count &#61;&#61; (end_time * fps_video)):breakelse:# 写入视屏结束videoWriter.release()breakif __name__ &#61;&#61; &#39;__main__&#39;:video_path &#61; "./"result_video_path &#61; "result/"video &#61; "中长跑视频回放2.mp4"result_video &#61; "result_test_video.mp4"start_time &#61; 7 * 60 &#43; 0end_time &#61; 7 * 60 &#43; 6capture_video(video_path, result_video_path, video, result_video, start_time, end_time)# 切成帧"""import cv2video &#61; "./result/result_test_video.mp4"cap &#61; cv2.VideoCapture(video)frame_id &#61; 0while (cap.isOpened()):ret, frame &#61; cap.read()if ret&#61;&#61;True:cv2.imwrite(&#39;./2/&#39;&#43;str(frame_id)&#43;&#39;.jpg&#39;,frame)frame_id&#43;&#61;1else:cap.release()"""