Skip to content

Instantly share code, notes, and snippets.

@hoehrmann
Created October 13, 2016 20:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoehrmann/a41cde0d8e75448c624ace563fa70a63 to your computer and use it in GitHub Desktop.
Save hoehrmann/a41cde0d8e75448c624ace563fa70a63 to your computer and use it in GitHub Desktop.
#!/bin/bash
#####################################################################
# Copyright (c) 2016 Bjoern Hoehrmann <bjoern@hoehrmann.de>. GPLv3+.
#
# Given image + color, creates mask encoding pixel's LAB color diff.
#####################################################################
path_in="$1"
color_rgb="$2"
path_out="$3"
threshold="$4"
#####################################################################
# Validate command line arguments
#####################################################################
if [ -z "$path_in" ] || [ -z "$color_rgb" ] || [ -z "$path_out" ]
then
echo "Usage: $0 ./image.png '#00FF00' ./output_mask.png [0.1]"
exit 1
fi
# TODO: might make sense to validate the parameter syntax
# Default value for threshold.
if [ -z "$threshold" ]
then
threshold="0.1"
fi
#####################################################################
# Create a copy of the input image with the same dimensions as the
# input image. This image will be overwritten in the second step.
#####################################################################
convert "$path_in" \
-fill "$color_rgb" \
-draw 'color 0,0 reset' \
"$path_out"
#####################################################################
# Compute mask from euclidean distance for each pixel color value in
# CIELab colorspace and save the result in a grayscale image.
#####################################################################
convert \
\( "$path_out" -colorspace CIELab \) \
\( "$path_in" -colorspace CIELab \) \
-alpha on \
-channel A \
-fx "x=( pow(v.r - u.r, 2) + pow(v.g - u.g, 2) \
+ pow(v.b - u.b, 2) ) / (3)); x < $threshold ? x : 1" \
-alpha extract \
"$path_out"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment