Animate Bounding Box Position with FFmpeg Drawbox

To draw a bounding box that changes position over time in FFmpeg, you must use the drawbox video filter and leverage its support for mathematical expressions. By using the time variable t or the frame number variable n inside the coordinates parameters (x and y), you can dynamically calculate the box’s position for every frame of the video. This article provides a straightforward guide and practical command examples to help you animate bounding boxes in FFmpeg.

The Basic Syntax

The drawbox filter accepts several parameters, but to make the box move, you need to focus on x (the horizontal start position) and y (the vertical start position).

The basic structure of the filter is:

-vf "drawbox=x='expression':y='expression':w=width:h=height:color=color_name:thickness=thickness_val"

To animate the box, you replace the static numbers for x and y with math formulas containing the variable t (current timestamp in seconds).


Example 1: Moving Horizontally (Left to Right)

If you want a red bounding box of size 200x200 pixels to start at the left edge of the screen and move right at a speed of 100 pixels per second, use the following command:

ffmpeg -i input.mp4 -vf "drawbox=x='t*100':y=200:w=200:h=200:color=red:thickness=5" -c:a copy output.mp4

Example 2: Moving Diagonally

To move the bounding box both horizontally and vertically over time, apply the t variable to both x and y parameters.

ffmpeg -i input.mp4 -vf "drawbox=x='50+t*80':y='100+t*40':w=150:h=150:color=yellow:thickness=4" -c:a copy output.mp4

Example 3: Moving Based on Video Dimensions

You can use input video dimensions (iw for input width, ih for input height) to keep the animation proportional. The following command moves a box diagonally from the top-left corner to the bottom-right corner of any video, regardless of its resolution, over a duration of 10 seconds:

ffmpeg -i input.mp4 -vf "drawbox=x='(iw/10)*t':y='(ih/10)*t':w=100:h=100:color=green:thickness=5" -c:a copy output.mp4

Useful Variables for Animation Expressions

When designing your motion path, you can use these built-in FFmpeg variables inside your expressions:

Setting Specific Start and End Times

If you only want the animated box to appear during a specific time range (e.g., between second 2 and second 7), append the enable evaluation option to your filter:

ffmpeg -i input.mp4 -vf "drawbox=x='t*150':y='t*100':w=200:h=200:color=blue:thickness=5:enable='between(t,2,7)'" -c:a copy output.mp4