使用cv2剪切视频importcv2defclip_video(source_video,target_video,start_time,end_time):cap=cv2.VideoCapture(source_video)ifnotcap.isOpened():logger_warning('videoisnotopened')else:success,frame=cap.read()f_shape=frame.shapef_height=f_shape[0]#原始视频图像的高度f_width=f_shape[1]fps=cap.get(5)#帧率frame_number=cap.get(7)#视频file帧数duration=frame_number/fps#视频总帧数/帧率time/second[视频时间一共有多少秒]ifstart_time>durationorend_time>duration:returnstart_time=fps*float(start_time)end_time=fps*float(end_time)#AVI格式编码输出XVIDfour_cc=cv2.VideoWriter_fourcc(*'H264')video_writer=cv2.VideoWriter(target_video,four_cc,fps,(int(f_width),int(f_height)))num=0whileTrue:success,frame=cap.read()ifint(start_time)<=int(num)<=int(end_time):ifsuccess:video_writer.write(frame)else:breaknum+=1ifnum>frame_number:breakcap.release()VideoWriter_fourcc编码格式:fourcc表示四字码(Four-CharacterCodes),顾名思义,encoding由四个组成以下是VideoWriter_fourcc对象的一些常用参数。注意:字符顺序不能混淆cv2.VideoWriter_fourcc('I','4','2','0'),参数为YUV编码类型,文件名后缀为.avicv2.VideoWriter_fourcc('P','I','M','I'),参数为MPEG-1编码类型,文件名后缀为.avicv2.VideoWriter_fourcc('X','V','I','D'),参数为MPEG-4编码类型,文件名后缀为.avicv2.VideoWriter_fourcc('T','H','E','O'),参数为OggVorbis,文件名后缀为.ogvcv2.VideoWriter_fourcc('F','L','V','1'),参数为Flash视频,文件名后缀为.flv
