#!/bin/bash
#
# Developed by Fred Weinhaus 6/12/2017 .......... revised 6/12/2017
#
# ------------------------------------------------------------------------------
# 
# Licensing:
# 
# Copyright © Fred Weinhaus
# 
# My scripts are available free of charge for non-commercial use, ONLY.
# 
# For use of my scripts in commercial (for-profit) environments or 
# non-free applications, please contact me (Fred Weinhaus) for 
# licensing arrangements. My email address is fmw at alink dot net.
# 
# If you: 1) redistribute, 2) incorporate any of these scripts into other 
# free applications or 3) reprogram them in another scripting language, 
# then you must contact me for permission, especially if the result might 
# be used in a commercial or for-profit environment.
# 
# My scripts are also subject, in a subordinate manner, to the ImageMagick 
# license, which can be found at: http://www.imagemagick.org/script/license.php
# 
# ------------------------------------------------------------------------------
# 
####
#
# USAGE: colorfulness infile
# USAGE: colorfulness [-h or -help]
# 
###
# 
# NAME: COLORFULNESS
# 
# PURPOSE: To compute a metric that represents the colorfulness of an image.
# 
# DESCRIPTION: COLORFULNESS computes a metric that represents the colorfulness of an 
# image. Values range between 0 and about 81. When normalized, then the values are 
# modified by a scaling factor of (1/81) so they range from 0 to 1. Both values are 
# presented as "unnormalized (normalized)". The largest colorfulness appears to 
# correspond to equal parts red, green and blue.
#
# References: 
# http://www.pyimagesearch.com/2017/06/05/computing-image-colorfulness-with-opencv-and-python/
# https://infoscience.epfl.ch/record/33994/files/HaslerS03.pdf
# 
# CAVEAT: No guarantee that this script will work on all platforms, 
# nor that trapping of inconsistent parameters is complete and 
# foolproof. Use At Your Own Risk. 
# 
######
# 

# set default values
# none

# set directory for temporary files
dir="."    # suggestions are dir="." or dir="/tmp"

# set up functions to report Usage and Usage with Description
PROGNAME=`type $0 | awk '{print $3}'`  # search for executable on path
PROGDIR=`dirname $PROGNAME`            # extract directory of program
PROGNAME=`basename $PROGNAME`          # base name of program
usage1() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^###/g;  /^#/!q;  s/^#//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}
usage2() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^######/g;  /^#/!q;  s/^#*//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}


# function to report error messages
errMsg()
	{
	echo ""
	echo $1
	echo ""
	usage1
	exit 1
	}


# function to test for minus at start of value of second part of option 1 or 2
checkMinus()
	{
	test=`echo "$1" | grep -c '^-.*$'`   # returns 1 if match; 0 otherwise
    [ $test -eq 1 ] && errMsg "$errorMsg"
	}

# test for correct number of arguments and get values
if [ $# -eq 0 ]
	then
	# help information
   echo ""
   usage2
   exit 0
elif [ $# -gt 1 ]
	then
	errMsg "--- TOO MANY ARGUMENTS WERE PROVIDED ---"
else
	while [ $# -gt 0 ]
		do
			# get parameter values
			case "$1" in
		  -h|-help)    # help information
					   echo ""
					   usage2
					   exit 0
					   ;;
				 -)    # STDIN and end of arguments
					   break
					   ;;
				-*)    # any other - argument
					   errMsg "--- UNKNOWN OPTION ---"
					   ;;
		     	 *)    # end of arguments
					   break
					   ;;
			esac
			shift   # next option
	done
	#
	# get infile
	infile="$1"
fi

# test that infile provided
[ "$infile" = "" ] && errMsg "--- NO INPUT FILE SPECIFIED ---"


# setup temporary images
tmpA1="$dir/colorfulness_1_$$.mpc"
tmpB1="$dir/colorfulness_1_$$.cache"
tmpRG1="$dir/colorfulness_RG_$$.mpc"
tmpRG2="$dir/colorfulness_RG_$$.cache"
tmpYB1="$dir/colorfulness_YB_$$.mpc"
tmpYB2="$dir/colorfulness_YB_$$.cache"
trap "rm -f $tmpA1 $tmpB1 $tmpRG1 $tmpRG2 $tmpYB1 $tmpYB2; exit 0" 0
trap "rm -f $tmpA1 $tmpB1 $tmpRG1 $tmpRG2 $tmpYB1 $tmpYB2; exit 1" 1 2 3 15

# read the input image into the temporary cached image and test if valid
convert -quiet "$infile" -alpha off +repage "$tmpA1" ||
	echo "--- 1 FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO size  ---"


# get RG image
convert $tmpA1 -colorspace sRGB -channel rg -separate +channel -compose difference -composite $tmpRG1

# get YB image
convert $tmpA1 -colorspace sRGB -channel rgb -separate +channel \
	\( -clone 0 -clone 1 -evaluate-sequence mean \) \
	\( -clone 2 \) -delete 0-2 \
	-compose difference -composite $tmpYB1
	
# compute squared means
meanRGsq=`convert $tmpRG1 -format "%[fx:mean*mean]" info:`
meanYBsq=`convert $tmpYB1 -format "%[fx:mean*mean]" info:`
mean=`convert xc: -format "%[fx:sqrt($meanRGsq+$meanYBsq)]" info:`

# compute squared stds
stdRGsq=`convert $tmpRG1 -format "%[fx:standard_deviation*standard_deviation]" info:`
stdYBsq=`convert $tmpYB1 -format "%[fx:standard_deviation*standard_deviation]" info:`
std=`convert xc: -format "%[fx:sqrt($stdRGsq+$stdYBsq)]" info:`

	
# compute colorfulness metric
# max value seems to be 80.9897 out of 100 for 1/3 each red, green and blue appended image
colorfulness=`convert xc: -format "%[fx:100*($std + 0.3*$mean)]" info:`
colorfulness_norm=`convert xc: -format "%[fx:(1/81)*$colorfulness]" info:`

echo "$colorfulness ($colorfulness_norm)"

exit 0






