Configure FFmpeg Lenscorrection Filter k1 and k2
This guide explains how to configure the quadratic (k1)
and double-quadratic (k2) correction factors in the FFmpeg
lenscorrection filter. You will learn the syntax of the
filter, how the parameters affect the image, and how to choose the right
values to correct barrel and pincushion lens distortion in your
videos.
The lenscorrection filter in FFmpeg corrects radial lens
distortion using a polynomial model. This is particularly useful for
correcting the “fisheye” effect produced by action cameras, wide-angle
lenses, and drones.
Filter Syntax and Parameters
The basic syntax for the filter is:
lenscorrection=cx=cx_val:cy=cy_val:k1=k1_val:k2=k2_valcx: The relative horizontal center of distortion (ranging from0.0to1.0). The default is0.5(the exact center).cy: The relative vertical center of distortion (ranging from0.0to1.0). The default is0.5(the exact center).k1: The quadratic correction factor. This parameter has the strongest effect on the correction near the center of the image.k2: The double-quadratic correction factor. This parameter has a stronger effect on the edges of the image.
Understanding the Correction Values
The filter uses a mathematical formula to map pixels from the corrected image back to the distorted source image based on their distance (\(r\)) from the center:
\[\text{Source Radius} = r \cdot (1 + k_1 \cdot r^2 + k_2 \cdot r^4)\]
To configure the coefficients correctly, observe the type of distortion in your footage:
- Barrel Distortion (Fisheye): Straight lines curve
outward toward the edges of the frame. To correct this, use
negative values for
k1andk2. - Pincushion Distortion: Straight lines curve inward
toward the center. To correct this, use positive values
for
k1andk2.
Practical Examples
1. Correcting Moderate Fisheye / Barrel Distortion
For standard action cameras with a wide-angle lens, you will need
negative values. Start with a stronger k1 and a smaller
k2 to clean up the edges.
ffmpeg -i input.mp4 -vf "lenscorrection=cx=0.5:cy=0.5:k1=-0.222:k2=0.045" output.mp42. Correcting Heavy Fisheye Distortion
For extremely wide lenses, both k1 and k2
must be adjusted to prevent the corners of the image from stretching
excessively or bending backwards.
ffmpeg -i input.mp4 -vf "lenscorrection=k1=-0.333:k2=-0.125" output.mp4(Note: If cx and cy are omitted, they
default to 0.5.)
How to Find the Right k1 and k2 Values
Because every lens is different, finding the exact values requires a systematic approach:
- Use a grid: Record a flat grid, a brick wall, or a door frame with straight horizontal and vertical lines.
- Test incrementally: Start by setting
k2=0and adjustingk1in increments of0.05(e.g.,-0.05,-0.10,-0.15) until the lines near the center of the frame are straight. - Fine-tune the edges: Once the center is straight,
you may notice the corners are still curved or overly stretched. Adjust
k2in small increments (e.g.,-0.01to-0.05) to correct the outermost edges of the frame.