Image Scaling - 2020
FFMpeg is using the libswscale library to resize the input. The libswscale library contains video image scaling and colorspace/pixelformat conversion routines.
Here is our base image (Einstein_500_459.jpg):
When we scale an image without specifying the size, the input dimension is used as the default value.
If we want to resize our image to a specific size (e.g 250x150), we can use the scale filter in its most basic form where v: verbose and f: format in "-vf":
ffmpeg -i Einstein_500_459.jpg -vf scale=250:150 Einstein_250_150.png
There are couple of ways to set the scale:
1. scale=w=250:h=150 2. scale=250:150 3. scale=250x150
If we want to keep the aspect ratio, we need to specify either width or height, and set the one not specified to -1:
ffmpeg -i Einstein_500_459.jpg -vf scale=250:-1 Einstein_250.png
We set the width of the output image to 250 pixels. The ffmpeg will calculate the height of the output image from the aspect ratio of the input image so that output image can have a dimension of 250x230 pixels which has the same aspect ratio of the input.
If we want to stretch the image in such a way to only double the width:
ffmpeg -i Einstein_500_459.jpg -vf scale=iw*2:ih Einstein_double_width.png
In the above command, iw is input width and ih is input height.
Sometimes we need to scale the input image in such way it fits into a specified width x height while keeping the aspect reatio. Suppose we have a placeholder in which we want to scale any given image. This is a little bit tricky, since we need to check the original aspect ratio, in order to decide which component to specify and to set the other component to -1 (to keep the aspect ratio). For example, if we would like to scale our input image into a rectangle with dimensions of 320x240, we could use something like this:
ffmpeg -i Einstein_500_459.jpg -vf scale="'if(gt(a,320/240),320,-1)':'if(gt(a,320/240),-1,240)'" Einstein_320x240_fit.png
Note that we have additional space left on the right side due to the original image not having the same aspect ratio as the placeholder, in which the image was supposed to fit.
ffmpeg -i Einstein_500_459.jpg -vf scale=iw:1/PHI*iw Einstein_greek_harmony.png
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization