Skip to content

Instantly share code, notes, and snippets.

@logickoder
Created July 12, 2026 09:35
Show Gist options
  • Select an option

  • Save logickoder/7a53b417011afb4458aa37c1fdb5f12c to your computer and use it in GitHub Desktop.

Select an option

Save logickoder/7a53b417011afb4458aa37c1fdb5f12c to your computer and use it in GitHub Desktop.
Extract one screenshot per scene change using ffmpeg
#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# scene_capture.sh — Extract one screenshot per scene change using ffmpeg
#
# Usage:
# ./scene_capture.sh [OPTIONS] <input_video>
#
# Options:
# -o <dir> Output directory (default: ./scenes)
# -t <0.0–1.0> Scene-change threshold (default: auto-detected)
# -f <jpg|png> Output image format (default: jpg)
# -q <1–31> JPEG quality (lower=better, jpg only, default: 2)
# -h Show this help
#
# Examples:
# ./scene_capture.sh video.mp4
# ./scene_capture.sh -o /tmp/shots -t 0.08 -f png video.mp4
# ./scene_capture.sh -t 0.15 recording.mp4 # fewer, bigger cuts only
# ─────────────────────────────────────────────────────────────────────────────
set -euo pipefail
# ── Defaults ─────────────────────────────────────────────────────────────────
OUT_DIR="./scenes"
THRESHOLD="" # empty = auto-detect
FMT="jpg"
QUALITY=2 # ffmpeg -q:v (jpg only; 1=best, 31=worst)
# ── Helpers ──────────────────────────────────────────────────────────────────
usage() {
grep '^#' "$0" | grep -v '#!/' | sed 's/^# \{0,1\}//'
exit 0
}
die() { echo "ERROR: $*" >&2; exit 1; }
require() { command -v "$1" &>/dev/null || die "'$1' not found — install ffmpeg."; }
# ── Parse args ────────────────────────────────────────────────────────────────
while getopts ":o:t:f:q:h" opt; do
case $opt in
o) OUT_DIR="$OPTARG" ;;
t) THRESHOLD="$OPTARG" ;;
f) FMT="$OPTARG" ;;
q) QUALITY="$OPTARG" ;;
h) usage ;;
:) die "Option -$OPTARG requires an argument." ;;
\?) die "Unknown option -$OPTARG" ;;
esac
done
shift $((OPTIND - 1))
[[ $# -lt 1 ]] && die "No input file specified. Run with -h for help."
INPUT="$1"
[[ -f "$INPUT" ]] || die "File not found: $INPUT"
[[ "$FMT" =~ ^(jpg|png)$ ]] || die "Format must be jpg or png."
require ffmpeg
require ffprobe
require awk
# ── Auto-detect threshold ─────────────────────────────────────────────────────
# Strategy: scan all frame scene scores, then pick a threshold that keeps
# roughly 10–30 frames (good for most videos up to ~10 min).
# Falls back to 0.3 for regular footage, lower for screen recordings.
auto_threshold() {
local input="$1"
echo " → Scanning scene scores…" >&2
local scores
scores=$(ffmpeg -i "$input" \
-vf "select='gte(scene,0)',metadata=print:key=lavfi.scene_score" \
-vsync vfr -f null - 2>&1 \
| grep "scene_score" | awk -F'=' '{print $2}' | sort -rn)
if [[ -z "$scores" ]]; then
echo "0.3" # safe fallback
return
fi
local max_score
max_score=$(echo "$scores" | head -1)
# Count frames at candidate thresholds (percentage of max_score)
local candidates=(0.90 0.70 0.50 0.40 0.30 0.20 0.15 0.10 0.08 0.06 0.05)
for pct in "${candidates[@]}"; do
local t
t=$(awk -v m="$max_score" -v p="$pct" 'BEGIN{printf "%.4f", m*p}')
local count
count=$(echo "$scores" | awk -v th="$t" '$1 >= th {c++} END{print c+0}')
if (( count >= 5 && count <= 40 )); then
echo " → Auto threshold: $t (${count} scenes, max score was $max_score)" >&2
echo "$t"
return
fi
done
# Nothing in range — return something that at least gives a few frames
local fallback
fallback=$(echo "$scores" | awk 'NR==5{print; exit}')
echo " → Auto threshold fallback: $fallback" >&2
echo "$fallback"
}
# ── Main ──────────────────────────────────────────────────────────────────────
echo "────────────────────────────────────────────"
echo " scene_capture.sh"
echo " Input : $INPUT"
mkdir -p "$OUT_DIR"
if [[ -z "$THRESHOLD" ]]; then
THRESHOLD=$(auto_threshold "$INPUT")
fi
echo " Threshold : $THRESHOLD"
echo " Output : $OUT_DIR/scene_%04d.$FMT"
echo "────────────────────────────────────────────"
# Build ffmpeg output args based on format
if [[ "$FMT" == "jpg" ]]; then
OUT_ARGS=(-q:v "$QUALITY")
else
OUT_ARGS=()
fi
ffmpeg -i "$INPUT" \
-vf "select='gt(scene,${THRESHOLD})',metadata=print:file=${OUT_DIR}/timestamps.txt" \
-vsync vfr \
"${OUT_ARGS[@]}" \
"${OUT_DIR}/scene_%04d.${FMT}" \
-hide_banner -loglevel error
COUNT=$(ls "${OUT_DIR}"/scene_*.${FMT} 2>/dev/null | wc -l)
echo " ✓ Extracted $COUNT screenshot(s) → $OUT_DIR"
echo ""
# Print a tidy summary of timestamps
if [[ -f "${OUT_DIR}/timestamps.txt" && $COUNT -gt 0 ]]; then
echo " # │ Timestamp"
echo "───┼──────────────"
i=1
while IFS= read -r line; do
if [[ "$line" =~ pts_time:([0-9.]+) ]]; then
t="${BASH_REMATCH[1]}"
# Convert seconds to HH:MM:SS
hms=$(awk -v s="$t" 'BEGIN{
h=int(s/3600); m=int((s%3600)/60); sec=s%60
printf "%02d:%02d:%06.3f", h, m, sec
}')
printf " %2d │ %s (%.2fs)\n" "$i" "$hms" "$t"
((i++))
fi
done < "${OUT_DIR}/timestamps.txt"
fi
echo ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment