Search code examples
pythonmatlabvideosubsampling

Subsampling videos to save every Nth frame


I have thousands of 30sec/20fps/.avi videos (so 600 frames total per video). I need to automate subsampling these videos in order to save every 100th frame (every 5 seconds). Any picture format is fine.

Is there an easy way to do this in either Matlab (R2015b) or Python+libraries?


Solution

  • In MATLAB:

    you can use VideoWriter object or imwrite, depends on the desired output format:

    vin = VideoReader('vid1.mp4');
    vout = VideoWriter('vid-out.mp4');
    framenum = 0;
    everyNframe = 100;
    vout.open();
    while vin.hasFrame
        frame = vin.readFrame;
        if rem(framenum,everyNframe) == 0
            vout.writeVideo(frame);
            % OR
            imwrite(frame, [num2str(framenum,'%04i') '.jpg']);
            disp(framenum)
        end
        framenum = framenum + 1;
    end
    vout.close();
    

    another option the ffwd the input video to the next desired frame is by setting vin.CurrentTime, but for some reason it is slower than simply read 100 frames.