python 视频存储

    cap = cv2.VideoCapture("./host1.mp4") 

'''视频保存设置'''
    out = 'inference/video'    #视频保存目录
    p = time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time()))
    save_path = str(Path(out) / Path(p))
    print("save_path:", save_path)

    vid_path, vid_writer = None, None
    Is_recover = True   # 是否复原图像
    save_vid = True     # 是否保存检测后的图像
    show_video = False   # 是否显示图像


    org_fps = cap.get(cv2.CAP_PROP_FPS)
    org_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    org_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    while True:
        ret, frame = cap.read()  # 读取帧

        if save_vid:
            if vid_path != save_path: 
                vid_path = save_path
                if isinstance(vid_writer, cv2.VideoWriter):
                    vid_writer.release()  # release previous video writer

                if Is_recover:  # video
                    fps = org_fps
                    print("fps",fps)
                    w = org_w
                    h = org_h
                    print("w h", w, h)

                else:  # stream
                    fps, w, h = 60, 640, 480
                    print("w h", w, h)

                vid_writer = cv2.VideoWriter(save_path+'.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))

            vid_writer.write(frame_copy if Is_recover else frame)

            if cv2.waitKey(1) & 0xFF == ord('q'):  # 按‘q’退出 也可以更换别的结束条件
                vid_writer.release()  # release previous video writer
                cv2.destroyAllWindows()
                break
     
    cap.release()
    

每次运行程序,保存的视频名字以本地时间为准
在这里插入图片描述
需要注意的是如果保存的视频无法打卡,一般是
vid_writer.release() # release previous video writer
没有正确运行,导致视频无法打开,只要运行了上面这句,就可以打开视频

你可能感兴趣的:(python,opencv,计算机视觉)