opencv-python: video write

Recent attempts to run YOLOv3 effect, want to read the video, frame by frame processing, display and save the video, click here in conjunction with the code simple recording method -

def test_video(model, video_path, video_out_path):
    cap = cv2.VideoCapture(video_path)
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    out = cv2.VideoWriter(video_out_path, fourcc, fps=20.0, frameSize=(1920, 1080))
    pre_time = 0
    while(True):
        # time
        curr_time = time.time()
        print(curr_time-pre_time)
        pre_time = curr_time
        # process
        ret, frame = cap.read()
        frame_pil = Image.fromarray(frame)  # opencv to PIL.Image
        frame_pil = test_image(model, image=frame_pil, conf_thres=0.5)
        frame = np.asarray(frame_pil)   # PIL.Image to opencv
        cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
        cv2.imshow('frame', frame)
        # save
        out.write(frame)
        if cv2.waitKey(1) == 113:
            break
    cap.release()
    out.release()
  • Video read : CAP = cv2.VideoCapture (video_path) , reading video according video_path path, such as in the present embodiment the input video_path = "/xxxxx/video_name.mp4"; and then, in a loop, can be used " RET, Frame cap.read = () "frame by frame to get" return, frame "the. (Return to True / False, whether read on behalf of normal)
  • Video Display : cv2.imshow ( 'Frame', Frame) , the processing result display frame by frame
  • Video saved : the fourcc = cv2.VideoWriter_fourcc (* 'MJPG') specifies the video codec 4 byte code; OUT = cv2.VideoWriter (video_out_path, the fourcc, FPS = 20.0, the frameSize = (1920, 1080)) is set to save the path , fourcc, fps, frameSize.

Note , frameSize must match the frame (width, height), fourcc also need to set the correct (before with no success of DIVX), or likely to cause damage to the video can not be read.

Published 52 original articles · won praise 4 · Views 2158

Guess you like

Origin blog.csdn.net/qq_42191914/article/details/103453414