How to Use FFmpeg swaprect Filter to Swap Video Areas
The FFmpeg swaprect video filter allows you to swap two
rectangular areas of the same size within a video frame. This article
provides a quick and clear guide on how to use this filter, detailing
its syntax, parameters, and practical command-line examples to help you
easily exchange video regions.
Understanding the swaprect Syntax
The swaprect filter requires you to define the
dimensions of the rectangles and the top-left coordinates of both areas
you wish to swap. Both rectangles must have the exact same width and
height.
The basic syntax is as follows:
swaprect=w:h:x1:y1:x2:y2
Parameter Breakdown
w: The width of both rectangular areas.h: The height of both rectangular areas.x1: The x-coordinate (horizontal position) of the top-left corner of the first rectangle.y1: The y-coordinate (vertical position) of the top-left corner of the first rectangle.x2: The x-coordinate of the top-left corner of the second rectangle.y2: The y-coordinate of the top-left corner of the second rectangle.
You can use constants within these parameters, such as: *
w or h: Width or height of the rectangle
itself. * iw or ih: Input video width or
height. * a: Aspect ratio of the input video.
Practical Example
Suppose you have a 1920x1080 video, and you want to swap a 300x300 pixel area in the top-left corner with a 300x300 pixel area in the top-right corner.
- Width (
w): 300 - Height (
h): 300 - First rectangle (
x1, y1):0, 0(Top-left corner) - Second rectangle (
x2, y2):1620, 0(Top-right corner, calculated as 1920 - 300)
The FFmpeg command to perform this swap is:
ffmpeg -i input.mp4 -vf "swaprect=300:300:0:0:1620:0" output.mp4Using Dynamic Expressions
You can also use mathematical expressions to determine the
coordinates dynamically. For example, to swap the left half of a video
with the right half of the same video, you can use the input width
(iw) and input height (ih) variables.
To swap two vertical halves of a 1920x1080 video (each half being 960 pixels wide and 1080 pixels high):
ffmpeg -i input.mp4 -vf "swaprect=iw/2:ih:0:0:iw/2:0" output.mp4In this command: * iw/2 sets the width of the swap area
to half the video width. * ih sets the height to the full
video height. * 0:0 targets the left half of the screen. *
iw/2:0 targets the right half of the screen starting at the
midpoint.