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?
            Asked
            
        
        
            Active
            
        
            Viewed 873 times
        
    1
            
            
        
        Christoph Rackwitz
        
- 11,317
 - 4
 - 27
 - 36
 
        Elizabeth Orrico
        
- 171
 - 1
 - 5
 
- 
                    which libraries are you using? `moviepy` allows to cut a portion of the video https://stackoverflow.com/questions/37317140/cutting-out-a-portion-of-video-python – Jun 13 '22 at 16:08
 - 
                    I would prefer to do everything just using cv2 – Elizabeth Orrico Jun 13 '22 at 16:11
 - 
                    just use ffmpeg on the terminal or use a graphical video editing program – Christoph Rackwitz Jun 13 '22 at 18:22
 - 
                    1Do you want to do this once or regularly? Do you need a high performance? OpenCV isnt best suited for this kind of task, because there will be more decoding+encoding quality losses introduced than in a real "video cutting". – Micka Jun 13 '22 at 19:33
 
1 Answers
1
            
            
        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()
        Elizabeth Orrico
        
- 171
 - 1
 - 5
 
- 
                    1OpenCV supports hidden options that are managed by environment variables (regarding FFmpeg arguments). Look for `OPENCV_FFMPEG_WRITER_OPTIONS`. (I don't no if it's working). For higher quality, you may also use H.264 codec instead of `MP4V` (it may not be trivial - look for it in Google). – Rotem Jun 14 '22 at 22:08