Skip to main content

Image background remover

Remove arbitrary background, resize to square, and add a single-colour background for images in ./input directory.

gist link

Attachment Type Size
Image background remover.md text/markdown 182.0B
process.sh application/x-sh 2.4KiB

Image background remover.md – text/markdown, 182.0B

A bash script to replace the background with a single colour and resize the image to square.

Uses background remover and ImageMagick.


process.sh – application/x-sh, 2.4KiB

#!/bin/bash

remove_background() {
    echo "[$2] remove background:"
    file=$2
    input="$1/$file"
    output="./output/$file.png"
    
    # https://github.com/nadermx/backgroundremover
    backgroundremover -i "$input" -o "$output"
}

generate_alpha() {
    echo "[$1] fix alpha:"
    file=$1
    output="./output/$file.png"
    alpha="./alpha/$file.png"
    
    convert "$output" -alpha extract "$alpha"
    convert "$alpha" \
            -define connected-components:mean-color=true \
            -define connected-components:area-threshold=30 \
            -connected-components 4 "$alpha"
}

apply_alpha() {
    echo "[$2] apply alpha:"
    file=$2
    input="$1/$file"
    output="./output/$file.png"
    alpha="./alpha/$file.png"
    convert "$input" "$alpha" -alpha off -compose copy_opacity -composite "$output"
}

copy_transparent() {
    echo "[$1] copy transparent"
    file=$1
    output="./output/$file.png"
    transparent="./transparent/$file.png"
    
    cp $output $transparent
}


make_square() {
    echo "[$1] make square:"
    file=$1
    input="./output/$file.png"
    output=$input
    
    width=`identify -format "%w" "$input"`
    height=`identify -format "%h" "$input"`
    size=$(($width>$height ? $width : $height))
    convert "$input" -trim -resize ${size}x${size} -background Transparent \
            -gravity center -extent ${size}x${size} "$output"
}

make_color_variant() {
    echo "[$1] make color variant: $3"
    file=$1
    color=$2
    colorname=$3
    input="./output/$file.png"
    output="./$colorname/$file.png"
    
    convert "$input" -background $color -alpha remove -alpha off "$output"
}

dir="./$1"
if [ -z "$1" ]; then
    dir="./input"
fi
files=`ls "$dir"`
#colors="magenta=Magenta black=Black white=White cyan=Cyan yellow=Yellow brand=#64B7D6"
colors="magenta=Magenta white=White brand=#64B7D6"

mkdir -p "./output"
mkdir -p "./alpha"
mkdir -p "./transparent"

for item in $colors
do
    name=`echo $item | sed -e 's/=.*//g'`
    mkdir -p "./$name"
done

for f in $files
do
    mogrify -auto-orient "./$dir/$f"
    
    if [ ! -f "./alpha/$f.png" ]; then
      remove_background "$dir" "$f"
      generate_alpha "$f"
    fi
    apply_alpha "$dir" "$f"
    copy_transparent "$f"
    make_square "$f"
    
    for item in $colors
    do
        name=`echo $item | sed -e 's/=.*//g'`
        color=`echo $item | sed -e 's/.*=//g'`
        make_color_variant "$f" "$color" "$name"
    done
done