Saving Multiple Videos from the Same Input

Problem

You would like to create movies of Patches playing with his ball in multiple formats, from the same set of Patches_ball_###.jpg input files, where ### represents a three digit frame number in the range 001 to 200. You have decided that you want an MJPEG codec movie at 640x480 pixels, and a H264 codec movie at 1280x720 pixels.

Solution

import Draft
from DraftParamParser import ReplaceFilenameHashesWithNumber
from copy import deepcopy

encoderMJPEG = Draft.VideoEncoder( 'PatchesMJPEG.mov', codec='MJPEG',
                        width=640, height=480 )  # Initialize the MJPEG video encoder.
encoderH264 = Draft.VideoEncoder( 'PatchesH264.mov', codec='H264',
                        width=1280, height=720 )  # Initialize the H264 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 )
    frame = Draft.Image.ReadFromFile( currFile )    # Try to read the frame.

    frameCopy = deepcopy( frame )
    frameCopy.Resize( 640, 480 )
    encoderMJPEG.EncodeNextFrame( frameCopy )       # Add the frame to the video.

    frameCopy = deepcopy( frame )
    frameCopy.Resize( 1280, 720 )
    encoderH264.EncodeNextFrame( frameCopy )        # Add the frame to the video.

encoderMJPEG.FinalizeEncoding()     # Finalize and save the resulting video.
encoderH264.FinalizeEncoding()      # Finalize and save the resulting video.

Discussion

We need a seperate encoder object for each movie we are creating. We can then add the resized frames to the matching encoders. Be sure to remember to finalize each of the encoders.

To avoid a degredation in image quality from resizing multiple times, we work with a copy of the original image each time we want the frame in a new size. Since assigning an image to a new variable (img2 = img1) does not actually duplicate the internal data, we need to use the deepcopy() method from the copy module. Since we don’t need the original frame any more after adding the frame to the last (in this case second) of the encoders, we could skip the final deep copy, and simply resize and encode the original frame.

See Also

Create a QuickTime Movie and Resize an Image in the Basic Cookbook.