I have an MP4 file of a screen recording that I need to crop. How can I do this with ffmpeg
?
1 Answer
Use the crop
filter:
ffmpeg -i in.mp4 -vf "crop=out_w:out_h:x:y" out.mp4
Where the options are as follows:
- use "-vf" or -"filter:v" - depending on your version of ffmpeg/avconv
out_w
is the width of the output rectangleout_h
is the height of the output rectanglex
andy
specify the top left corner of the output rectangle (coordinates start at (0,0) in the top left corner of the input)
Original image
Original 320x240 image
How out_w, out_h, w and h fit into the picture
Example 1
To crop a 80×60 section, starting from position (200, 100):
ffmpeg -i in.mp4 -vf "crop=80:60:200:100" -c:a copy out.mp4
- The audio is stream copied in this example, so re-encoding is avoided.
Example 2
To crop the bottom right quarter:
ffmpeg -i in.mp4 -vf "crop=in_w/2:in_h/2:in_w/2:in_h/2" -c:a copy out.mp4
This is the same as:
ffmpeg -i in.mp4 -vf "crop=320/2:240/2:320/2:240/2" -c:a copy out.mp4
Which is the same as:
ffmpeg -i in.mp4 -vf "crop=160:120:160:120" -c:a copy out.mp4
- You can refer to the input image size with
in_w
andin_h
as shown in this first example. The output width and height can also be used without_w
andout_h
.
Example 3
Crop 20 pixels from the top, and 20 from the bottom:
ffmpeg -i in.mp4 -vf "crop=in_w:in_h-40" -c:a copy out.mp4
- The filter will automatically center the crop if
x
andy
are omitted such as in this example.
Previewing
You can take a crop (heh heh) and preview it live with ffplay
:
ffplay -i input -vf "crop=in_w:in_h-40"
This way you can experiment and adjust your cropping without the need to encode, view, repeat.
Notes
Default encoder for MP4 is
libx264
(H.264 video) ormpeg4
(MPEG-4 Part 2 video) depending on yourffmpeg
build. See FFmpeg Wiki: H.264 Video Encoding Guide for more info.Instead of cropping and re-encoding, consider cropping upon playback. This is possible with any player worth using.
Ancient
ffmpeg
builds used-croptop
,-cropbottom
,-cropleft
,-cropright
options instead of thecrop
filter. If this is the case for you then get a modernffmpeg
. Development is very active and there is no reason to use an antique.
-
4
-
6worth to mention this technique (with the
crop
filter) re-encodes the video, see stackoverflow.com/questions/33378548/… if re-encoding matters for you– abernierCommented Oct 14, 2017 at 9:58 -
5edited to change the outdated
-filter:v
to the more up to date and simpler to type-vf
. Cheers! Commented Dec 15, 2017 at 0:35 -
20If you're trying to remove black bars around your video (piallarbox, letterbox, windowbox etc.) use
cropdetect
first to have ffmpeg print cropping parameters for you:ffmpeg.exe -i vid.mp4 -vf cropdetect out.mp4
– ShayanCommented Sep 6, 2019 at 21:38 -
9For those who wonder,
-vf
is an alias for-filter:v
. Commented Jan 10, 2020 at 10:53