Search code examples
imagevideoffmpegextract

How to extract frames from all videos in a folder using ffmpeg


I'm currently able to extract images from a file using the following line

ffmpeg -i inputfile.avi -r 1 image-%d.jpeg

However, I want to apply this to all the files in a folder, and place it in an output folder.

Suppose I have the current folder holding all videos:

input-videos/

----subfolder1/

------video.avi

----subfolder2/

------video.avi

I want everything in the output folder:

output/

----subfolder1/

------video/

----------*.jpeg

----subfolder2/

------video/

----------*.jpeg

What is the simplest way to go about this using a bash script? (or something else better)


Solution

  • If the folder depth is constant, the file extension is always avi and the top folders are called "input-videos" and "output":

    #!/bin/bash
    for file in input-videos/*/*.avi; do
        destination="output${file:12:${#file}-17}";
        mkdir -p "$destination";
        ffmpeg -i "$file" -r 1 "$destination/image-%d.jpeg";
    done
    

    If the top folders are just called anything and can be anywhere and the file extension is different, here's a script that you can call like ./script.sh <input folder> <output folder> <file extension>:

    #!/bin/bash
    if [ "$1" == '' ] || [ "$2" == '' ] || [ "$3" == '' ]; then
        echo "Usage: $0 <input folder> <output folder> <file extension>";
        exit;
    fi
    for file in "$1"/*/*."$3"; do
        destination="$2${file:${#1}:${#file}-${#1}-${#3}-1}";
        mkdir -p "$destination";
        ffmpeg -i "$file" -r 1 "$destination/image-%d.jpeg";
    done