Animate Bounding Box Position in FFmpeg

This article explains how to create an animated bounding box with dynamic coordinates over time using FFmpeg’s drawbox filter. By embedding time-based expressions into the spatial parameters (x, y, w, and h), you can move, resize, and conditionally display bounding boxes across frames without external tracking metadata.

Basic Syntax of the drawbox Filter

The drawbox filter draws a colored rectangle on the input video. Its standard parameters include:

  • x: Horizontal position of the top-left corner.
  • y: Vertical position of the top-left corner.
  • w: Width of the box.
  • h: Height of the box.
  • color: Border or fill color (supports hex codes, color names, and alpha transparency, e.g., red@0.5).
  • thickness: Border thickness in pixels. Set to fill to create a solid box.

To animate the box over time, pass an expression enclosed in quotes to x, y, w, or h using FFmpeg’s internal variables:

  • t: Current timestamp in seconds.
  • n: Current frame number (starting at 0).
  • iw / ih: Input video width and height.

Creating Linear Movement

To move a bounding box at a constant speed, define x or y as a function of the timestamp t.

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

In this command:

  • The box starts at x = 100 and moves right at 50 pixels per second.
  • The box starts at y = 150 and moves downward at 20 pixels per second.
  • thickness=3 draws an outline rather than a filled box.

Moving Between Specific Time Ranges

To restrict the animation to a specific time window or pause movement after reaching a destination, use conditional functions such as if(), between(), min(), or max().

Example: Move Only Between Seconds 2 and 6

ffmpeg -i input.mp4 -vf "drawbox=x='if(between(t,2,6), 100 + 60*(t-2), if(lt(t,2), 100, 340))':y=200:w=150:h=100:color=yellow:thickness=2" -c:a copy output.mp4
  • Before t = 2, the horizontal position remains fixed at x = 100.
  • Between t = 2 and t = 6, it moves right at 60 pixels per second.
  • After t = 6, it remains static at x = 340.

Animating Dimensions Alongside Position

Both position and dimension parameters accept time-based expressions simultaneously. This allows the bounding box to expand or contract as it moves:

ffmpeg -i input.mp4 -vf "drawbox=x='50*t':y='30*t':w='100 + 10*t':h='80 + 8*t':color=green@0.8:thickness=4" -c:a copy output.mp4

Here, the box moves diagonally across the frame while growing proportionally in both width and height at every frame.

Making the Bounding Box Appear and Disappear

To toggle the visibility of the animated box entirely, combine the position expressions with the enable option:

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

The bounding box will only render between second 1.5 and second 7.0, animating along the X-axis while active.