Stabilize Shaky Video Using FFmpeg Vidstab

This guide provides a step-by-step tutorial on how to stabilize shaky camera footage using FFmpeg and the open-source vid.stab library. You will learn how to run a highly effective two-pass stabilization process using the vidstabdetect filter to analyze video motion and the vidstabtransform filter to apply smoothing transformations, resulting in a clean, professional-looking video.

To use these filters, your version of FFmpeg must be compiled with the --enable-libvidstab configuration flag. You can verify this by running ffmpeg -filters in your terminal and checking if vidstabdetect and vidstabtransform are listed.


Step 1: The First Pass (Motion Detection)

In the first pass, the vidstabdetect filter analyzes the video frame-by-frame to identify camera shakiness and rotation. It generates a temporary .trf (transform) file containing the stabilization data.

Run the following command in your terminal:

ffmpeg -i input.mp4 -vf vidstabdetect=shakiness=10:accuracy=15:result=transforms.trf -f null -

Parameter Breakdown: * -i input.mp4: Specifies your shaky source video. * vidstabdetect: Activates the motion detection filter. * shakiness=10: Sets how shaky the video is (scale from 1 to 10, where 10 is highly shaky). * accuracy=15: Sets the accuracy of the detection (scale from 1 to 15, where 15 is the highest accuracy but takes longer to process). * result=transforms.trf: The name of the temporary file where the motion vectors will be saved. * -f null -: Directs FFmpeg to discard the video output for this pass, as we only need the generated .trf file. This speeds up the process significantly.


Step 2: The Second Pass (Applying Stabilization)

In the second pass, the vidstabtransform filter reads the .trf file generated in Step 1 and applies the actual stabilization to the video.

Run the following command to generate your stabilized video:

ffmpeg -i input.mp4 -vf vidstabtransform=input=transforms.trf:smoothing=30:zoom=5 -c:v libx264 -crf 18 -c:a copy output.mp4

Parameter Breakdown: * vidstabtransform: Activates the stabilization transform filter. * input=transforms.trf: Directs the filter to read the motion data from the file created in Step 1. * smoothing=30: The number of frames used to calculate the low-pass filter (smoothness). A higher number (e.g., 30–50) results in smoother video but may require more cropping. * zoom=5: Zooms into the video by 5% to hide the empty black borders created when the filter shifts the video frames to counteract shakiness. * -c:v libx264 -crf 18: Re-encodes the stabilized video using the H.264 codec at a high-quality visual setting (CRF 18). * -c:a copy: Copies the original audio stream without re-encoding to preserve quality and save processing time. * output.mp4: The final, stabilized output video file.


Useful Adjustments