Split a Movie into Single Frames

Problem

You have a movie of Patches playing with his ball, ‘Patches.mov’, and you want to extract the individual frames into jpegs named Patches_###.jpg, where ### will be replaced by the corresponding three digit frame number.

Solution

import Draft
from DraftParamParser import ReplaceFilenameHashesWithNumber

frameNum = 1        # What number the first frame (jpeg) will have.
decoder = Draft.VideoDecoder( 'Patches.mov' )       # Initialize the video decoder.
frame = Draft.Image.CreateImage( 1, 1 )     # Create an image object.

while decoder.DecodeNextFrame( frame ) :
    currFile = ReplaceFilenameHashesWithNumber( 'decode/Patches_###.jpg', frameNum )
    frame.WriteToFile( currFile )
    frameNum += 1

Discussion

To separate a video into single frames, we need a VideoDecoder and an Image object. We initialize the VideoDecoder using the (path and) name of the movie we wish to decode, in this case, Patches.mov. The initial size of the Image is irrelevant, as the decoder will resize the image to fit the frame.

The call to DecodeNextFrame() attempts to save the next movie frame (if there is one) into the Image object, frame, and returns a boolean (true/false) to indicate if it was successful. Because the frame variable gets modified as a parameter, and a boolean is returned, we can use the call in our while loop to determine how long to loop: if another frame is successfully decoded, we want to process it and continue. If a frame wasn’t successfully decoded, either we’ve reached the end of the movie, or some other problem is preventing us from continuing. Either way, there’s no frame to process, and the loop stops.

Inside the loop we know we have a frame to save. We use the output path and filename pattern, ‘decode/Patches_###.jpg’ and frame number to produce a unique file name using ReplaceFilenameHashesWithNumber(), then write the frame to this file. Finally we increase the frame number, so that the next frame will be written to a differently numbered file.

Once the script has finished, the individual frames will be stored in the decode subdirectory (note: this script assumes the subdirectory named decode already exists), in separate files named Patches_001.jpg, Patches_002.jpg, Patches_003.jpg, etc., for as many frames as we decoded from the movie.