Skipping Missing Frames

Problem

You have around 200 frames of Patches playing with his ball, and you wish to combine them into a QuickTime movie. The individual frames are named using the format Patches_ball_###.jpg, where ### is a three digit frame number in the range 001 to 200. Some of the frames are missing. You’d still like to create the movie, but you’d rather not have to type in the entire list of frames that are there.

Solution

import Draft
from DraftParamParser import ReplaceFilenameHashesWithNumber

encoder = Draft.VideoEncoder( 'Patches.mov' )       # Initialize the video encoder.

# Note that the second parameter of range is one past the last frame number
for currFrame in range( 1, 201 ):
    currFile = ReplaceFilenameHashesWithNumber( 'Patches_ball_###.jpg', currFrame )
    try:
        frame = Draft.Image.ReadFromFile( currFile )        # Try to read the frame.
    except:
        pass        # Reading was unsuccessful, skip frame.
    else:
        encoder.EncodeNextFrame( frame )    # Add the frame to the video.

encoder.FinalizeEncoding()  # Finalize and save the resulting video.

Discussion

If we try to read an image from a file that doesn’t exist, the ReadFromFile() method will throw an exception. Since we want to continue even if some of the images are missing, we use the try/except construct: we try to load in the image; if loading fails, we catch the exception (except) and don’t do anything (pass), otherwise (else), we add the frame to the video.

An alternate method is to replace the try/except construct with an if statement and the exists() function in the os.path module:

if os.path.exists( currFile ):
    frame = Draft.Image.ReadFromFile( currFile )    # Read the frame.
    encoder.EncodeNextFrame( frame )    # Add the frame to the video.

See Also

Create a QuickTime Movie in the Basic Cookbook.