#!/usr/bin/env bash
set -euo pipefail
if [[ $# -ne 4 ]]; then
echo "usage: crop-sheet.sh "
exit 1
fi
input="$1"
width="$2"
height="$3"
outdir="$4"
mkdir -p "$outdir"
rm -f "${outdir}"/*.png
magick "$input" -crop "${width}x${height}" +repage "${outdir}/%03d.png"
count=0
for file in "${outdir}"/*.png; do
[[ -f "$file" ]] || continue
dims=$(magick "$file" -format "%wx%h" info:)
if [[ "$dims" != "${width}x${height}" ]]; then
rm "$file"
continue
fi
mean=$(magick "$file" -format "%[mean]" info:)
if [[ "$mean" == "0" ]]; then
rm "$file"
else
(( ++count ))
fi
done
echo "$count"