Skip to content

Instantly share code, notes, and snippets.

@dreness
Created April 30, 2021 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreness/c68895ba5d5d6e93777988840fba6e45 to your computer and use it in GitHub Desktop.
Save dreness/c68895ba5d5d6e93777988840fba6e45 to your computer and use it in GitHub Desktop.
Maybe the same thing as Imagemagick's "bg_removal.sh"
#!/bin/zsh
# an image that looks like the background
WHITE=/Users/andre/Desktop/white.png
# output directory
OUT=/Users/andre/Pictures/mugshots_no_bg
# maybe run us like this:
# find ... -name '*.jpg' | xargs -n 100 -P 4 -J % ~/bin/bg_remove.sh %
for img in $@; do
file=$(basename "${img}")
filename=${file%.*}
filedir=${img:a:h}
pngfile="${filename}.png"
pngpath="${filedir}/${pngfile}"
# Combination of flood-fill and difference mask methods (see below)
magick convert "${img}" "${WHITE}" \
\( -clone 0 -clone 1 -compose Difference -composite \
-fill white -fuzz "10%" +opaque black -fuzz "20%" -blur "0x2" \) \
-delete 1 -alpha off -compose copy_opacity \
-composite "${OUT}/${pngfile}"
done
# https://legacy.imagemagick.org/Usage/masking/#bg_remove
#
# Just a format conversion:
# magick "${img}" "${pngpath}"
#
# Naive flood-fill method that changes the color at position 0,0
# to transparent; no structural awareness, can have holes
#
# magick convert "${pngpath}" "-fuzz" "20%" "-fill" "magenta" \
# "-draw" "color 0,0 floodfill" "-transparent" "magenta" "${pngpath}"
#
# Difference mask method is given an image of the background, but has the
# same drawbacks as the flood-fill method.
#
# magick convert "${filedir}/white.png" "${pngpath}" "-fuzz" "30%" \
# "${filedir}/white.png" -compose ChangeMask -composite "${pngpath}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment