Skip to content

Instantly share code, notes, and snippets.

@TimothyRHuertas
Created June 20, 2017 23:24
Show Gist options
  • Save TimothyRHuertas/b22e1a252447ab97aa0f8de7c65f96b8 to your computer and use it in GitHub Desktop.
Save TimothyRHuertas/b22e1a252447ab97aa0f8de7c65f96b8 to your computer and use it in GitHub Desktop.
Use ffmpeg to center crop and scale an image to 1:1
#Given a video of any aspect ratio this script will extract center cropped thumbnails at 299x299.
#Useful for gathering image training data.
#Assumes ffmpeg 3.3.2
#If you get an error about exact that means you are using an older version of ffmpeg
#Simply remove the :exact=1.
#This will make it work, but may cause the output size to be off by a pixel
#Script assumes you are downsampling.
#!/bin/bash
PATH_TO_VID=myvideo.mov
PATH_TO_OUT_DIR=out
ffmpeg -i "$PATH_TO_VID" -y -an -q 0 -vf scale="'if(gt(iw,ih),-1,299):if(gt(iw,ih),299,-1)', crop=299:299:exact=1" $PATH_TO_OUT_DIR/%06d.jpg
@BiatuAutMiahn
Copy link

How can I crop the aspect ratio out of the video frame to give an exclusive fullscreen? For example, I have a video that has a smaller height than my display, I want to crop left and right so that the height matches that of my display. Also I may come across a video that has height greater than my display, so the top/bottom needs cropped.

Basically, I'm trying to eliminate scaling as the image is more crisp when being cropped instead of being scaled down. And in this instance Im trying to crop 16:9 out of a 1920x800 video and scale that to 1920x1080. Or whatever resolution the device may be.

@TimothyRHuertas
Copy link
Author

That should be what the script does. Just change the OUTPUT_WIDTH to 1920. To be clear that will cause some upscaling since the extra 280 (1080-800) pixels (height) have to come from somewhere. If you don’t want to scale your only other option is letterboxing.

@BiatuAutMiahn
Copy link

ok ty

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment