简体   繁体   中英

Save video clip from longer video between two timestamps in Python cv2

I have an hour-long video that I would like to save a clip between two timestamps-- say, 11:20-11:35. Is the best way to do this frame-by-frame, or is there a better way?

Here's the gist of what I did frame-by-frame. If there's a less lossy way to do it, I'd love to know! I know I could do it from the terminal using ffmpeg, but I am curious for how to best do it using cv2.

def get_clip(input_filename, output_filename,  start_sec, end_sec):
    # input and output videos are probably mp4
    vidcap = cv2.VideoCapture(input_filename)
    
    # math to find starting and ending frame number
    fps = find_frames_per_second(vidcap)
    start_frame = int(start_sec*fps)
    end_frame = int(end_sec*fps)
    vidcap.set(cv2.CAP_PROP_POS_FRAMES,start_frame)
    
    # open video writer
    vidwrite = cv2.VideoWriter(output_filename, cv2.VideoWriter_fourcc(*'MP4V'), fps, get_frame_size(vidcap))
    
    success, image = vidcap.read()
    frame_count = start_frame
    while success and (frame_count < end_frame):
        vidwrite.write(image)  # write frame into video
        success, image = vidcap.read()  # read frame from video
        frame_count+=1
    vidwrite.release()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM