使用opencv拦截mp4源文件,输出为mp4defclip_video(source_video,target_video,start_time,end_time):cap=cv2.VideoCapture(source_video)ifnotcap.isOpened():print('视频未打开')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)#视频文件的帧数duration=frame_number/fps#视频总帧数/帧率time/second[视频总时间多少秒]ifstart_time>durationorend_time>duration:returnprint('请注意视频的总时长是%s秒'%str(duration))start_time=fps*float(start_time)end_time=fps*float(end_time)#AVI格式编码输出XVIDfour_cc=cv2.VideoWriter_fourcc(*'XVID')video_writer=cv2.VideoWriter(target_video,four_cc,fps,(int(f_width),int(f_height)))num=0whileTrue:成功,frame=cap.read()ifint(start_time)<=int(num)<=int(end_time):ifsuccess:video_writer.write(frame)else:breaknum+=1ifnum>frame_number:breakcap.release()找到视频上传云盘最后,chrome无法播放问题的根源在于对VideoWriter_fourcc模式的理解four_cc=cv2.VideoWriter_fourcc(*'XVID')fourcc表示四字码(Four-CharacterCodes),正如名字提示,代码由四个字符组成,下面是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。发现以上都不能成功将视频转为mp4编码格式通过度娘查询得到如下信息:https://blog.csdn.net/qq_41494464/article/details/88664507发现只有H264编码的mp4文件可以通过浏览器播放。于是抱着试试的想法,把编码格式改成H264four_cc=cv2.VideoWriter_fourcc(*'H264')再试,制作出来的视频可以在chrome上播放了。移动!
