Skip to content

Instantly share code, notes, and snippets.

@digiguru
Created November 30, 2023 10:25
Show Gist options
  • Save digiguru/799185b0aedf9157aa89440bff059646 to your computer and use it in GitHub Desktop.
Save digiguru/799185b0aedf9157aa89440bff059646 to your computer and use it in GitHub Desktop.
frame_extractor.sh
#!/bin/bash
# Check if enough arguments are passed
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <source_video> <frame_interval> <change_percentage>"
exit 1
fi
# Assign the arguments to variables
SOURCE_VIDEO="$1"
FRAME_INTERVAL="$2"
CHANGE_PERCENTAGE="$3"
# Directory for extracted frames
mkdir -p frames
mkdir -p diff_frames
# Check if the frames directory is empty
if [ -z "$(ls -A frames)" ]; then
# Extract frames from the video and get the total number of frames
total_frames=$(ffmpeg -i "$SOURCE_VIDEO" -vf "select=not(mod(n\,$FRAME_INTERVAL))" -vsync vfr frames/frame_%04d.png |& grep -oP 'frame=\s*\K\d+' | tail -1)
else
echo "Frames already extracted. Skipping extraction..."
total_frames=$(ls frames | wc -l)
fi
# Initialize variables
previous_frame=""
current_frame=""
frame_count=0
# Function to update progress bar
update_progress_bar() {
local current=$1
local total=$2
local percent=$((200*$current/$total % 2 + 100*$current/$total))
local progress_bar=$(printf "[%-${total}s]" $(for i in $(seq 1 $((percent/2))); do printf "#"; done))
printf "\r$progress_bar %d%%" $percent
}
# Iterate over extracted frames
for frame in frames/*.png; do
current_frame=$frame
if [ ! -z "$previous_frame" ]; then
# Compare the current frame with the previous frame
difference=$(compare -metric MAE "$previous_frame" "$current_frame" null: 2>&1 | awk '{print $1}')
echo "$previous_frame to $current_frame = $difference vs $CHANGE_PERCENTAGE"
change_ratio=$(echo "$difference $FRAME_INTERVAL" | awk '{print ($1 * 100) / ($2 * 2)}')
echo "$change_ratio > $CHANGE_PERCENTAGE"
# Check if the change is significant
if [ $(echo "$change_ratio > $CHANGE_PERCENTAGE" | bc) -eq 1 ]; then
cp "$current_frame" diff_frames/
fi
fi
previous_frame=$current_frame
((frame_count++))
update_progress_bar $frame_count $total_frames
done
echo -e "\nSignificant frames saved in diff_frames directory."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment