#!/bin/bash
#
# Developed by Fred Weinhaus 10/14/2008 .......... revised 11/6/2014
#
# ------------------------------------------------------------------------------
# 
# 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: autocolor [-m method] [-c clipmode] [-l cliplow] [-h cliphigh] [-n neutralgray] infile outfile
# USAGE: autocolor [-help]
#
# OPTIONS:
#
# -m      method            method to adjust neutral color; method=gamma, 
#                           recolor, none; default=recolor
# -c      clipmode          clip channels mode; clip=together or separate; 
#                           default=separate
# -l      cliplow           clip percent on low end of histogram; 
#                           float; 0<=cliplow<=100; default=0.1
# -h      cliphigh          clip percent on high end of histogram;
#                           float; 0<=cliphigh<=100; default=same as cliplow
# -n      neutralgray       neutral gray value (percent); float between 
#                           0 and 100; default=mean of luminance
#
###
#
# NAME: AUTOCOLOR 
# 
# PURPOSE: To automatically color balance and image.
# 
# DESCRIPTION: AUTOCOLOR automatically color balance and image by shifting 
# the mean value of each channel to the neutral gray value. There are
# three methods that can be used. The first uses -gamma computed from the 
# neutral gray value and mean of each of the RGB channels. The second uses 
# -recolor (or -color-matrix) computed from the neutral gray value and mean 
# of each of the RGB channels. The third skips this step. In addition to 
# corrrecting the neutral color, the histogram is stretched to full black 
# and white using the clip values.
# 
# OPTIONS: 
# 
# -m method ... METHOD defines how the neutral color will be set. The 
# choices are gamma (g), recolor (r) or none (n). Method=gamma uses 
# -gamma to shift the mean value to neutral gray. Method=recolor uses 
# -recolor (-color-matrix) to shift the mean value to neutral gray. 
# Method=none skips this processing and only does the clip operation. 
# If method=none and clipmode=together, then the result of the script will 
# be equivalent to IM -contrast-stretch with a change in contrast, but no 
# color change. The default=gamma.
# 
# -c clipmode ... CLIPMODE specifies whether to clip the channels 
# in unison or independently. The choices are: together (t) or 
# separate (s). The default=together
# 
# Note: generally the best choices seem to be either method=recolor 
# with clipmode=separate or method=gamma with clipmode=together.
# 
# -l cliplow ... CLIPLOW is the cumulative percent at the low end of the 
# histogram whose graylevel will be stretch to full black. Values are 
# floats between 0 and 100. If cliplow=0, then the stretch will locate 
# the minimum value in the channel histogram. The default=0.1
# 
# -h cliphigh ... CLIPHIGH is the cumulative percent at the high end of  
# the histogram whose graylevel will be stretch to full white. Values are 
# floats between 0 and 100. If cliplow=0, then the stretch will locate 
# the maximum value in the channel histogram. The default=same as cliplow.
# 
# -n neutralgray ... NEUTRALGRAY is the graylevel for a given channel  
# to which the mean value will be adjusted. Values are floats between  
# 0 and 100. The default is computed from the average of the luminance 
# channel. Other choices are 50 for mid-gray or 84 which is equivalent 
# to 18% neutral gray. Using larger values will make the resulting image 
# brighter.
# 
# 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
method=recolor			#gamma, recolor or blend
cliplow=0.1				#0 for min/max; 0.1 for nominal clip
cliphigh=""				#same as cliplow
ngray=""				#""=ave of luminance; 50=mid-range; 84=214/255 corresp to 18% neutral gray
clipmode="separate"		#clip=together or separate
luma="Rec601Luma"		#Rec601Luma=Gray or Rec709Luma

# 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 12 ]
	then
	errMsg "--- TOO MANY ARGUMENTS WERE PROVIDED ---"
else
	while [ $# -gt 0 ]
		do
			# get parameter values
			case "$1" in
		     -help)    # help information
					   echo ""
					   usage2
					   exit 0
					   ;;
				-m)    # get  method
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID METHOD SPECIFICATION ---"
					   checkMinus "$1"
					   method=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$method" in 
					   		gamma) ;;
					   		g) method="gamma";;
					   		recolor) ;;
					   		r) method="recolor";;
					   		none) ;;
					   		n) method="none";;
					   		*) errMsg "--- METHOD=$method IS AN INVALID VALUE ---" 
					   	esac
					   ;;
				-n)    # get neutralgray
					   shift  # to get the next parameter - mix
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID NEUTRALGRAY SPECIFICATION ---"
					   checkMinus "$1"
					   ngray=`expr "$1" : '\([.0-9]*\)'`
					   [ "$ngray" = "" ] && errMsg "--- NEUTRALGRAY=$ngray MUST BE AN FLOAT ---"
					   ngraytestA=`echo "$ngray < 0" | bc`
					   ngraytestB=`echo "$ngray > 100" | bc`
					   [ $ngraytestA -eq 1 -o $ngraytestB -eq 1 ] && errMsg "--- NEUTRALGRAY=$ngray MUST BE AN FLOAT BETWEEN 0 AND 100 ---"
					   ;;
				-c)    # get  clipmode
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID CLIPMODE SPECIFICATION ---"
					   checkMinus "$1"
					   clipmode=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$clipmode" in 
					   		together) ;;
					   		t) clipmode="together";;
					   		separate) ;;
					   		s) clipmode="separate";;
					   		*) errMsg "--- CLIPMODE=$clipmode IS AN INVALID VALUE ---" 
					   	esac
					   ;;
				-l)    # get cliplow
					   shift  # to get the next parameter - radius,sigma
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID CLIPLOW SPECIFICATION ---"
					   checkMinus "$1"
					   cliplow=`expr "$1" : '\([.0-9]*\)'`
					   [ "$cliplow" = "" ] && errMsg "--- CLIPLOW=$cliplow MUST BE A NON-NEGATIVE FLOAT ---"
					   cliplowtestA=`echo "$cliplow < 0" | bc`
					   cliplowtestB=`echo "$cliplow > 100" | bc`
					   [ $cliplowtestA -eq 1 -o $cliplowtestB -eq 1 ] && errMsg "--- CLIPLOW=$cliplow MUST BE AN FLOAT BETWEEN 0 AND 100 ---"
					   ;;
				-h)    # get cliphigh
					   shift  # to get the next parameter - radius,sigma
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID CLIPHIGH SPECIFICATION ---"
					   checkMinus "$1"
					   cliphigh=`expr "$1" : '\([.0-9]*\)'`
					   [ "$cliphigh" = "" ] && errMsg "--- CLIPHIGH=$cliphigh MUST BE A NON-NEGATIVE FLOAT ---"
					   cliphightestA=`echo "$cliphigh < 0" | bc`
					   cliphightestB=`echo "$cliphigh > 100" | bc`
					   [ $cliphightestA -eq 1 -o $cliphightestB -eq 1 ] && errMsg "--- CLIPHIGH=$cliphigh MUST BE AN FLOAT BETWEEN 0 AND 100 ---"
					   ;;
				 -)    # STDIN and end of arguments
					   break
					   ;;
				-*)    # any other - argument
					   errMsg "--- UNKNOWN OPTION ---"
					   ;;
		     	 *)    # end of arguments
					   break
					   ;;
			esac
			shift   # next option
	done
	#
	# get infile and outfile
	infile="$1"
	outfile="$2"
fi

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

# test that outfile provided
[ "$outfile" = "" ] && errMsg "NO OUTPUT FILE SPECIFIED"


# setup temporary images
tmpA1="$dir/autocolor_1_$$.mpc"
tmpA2="$dir/autocolor_1_$$.cache"
tmpI1="$dir/autocolor_2_$$.mpc"
tmpI2="$dir/autocolor_2_$$.cache"
tmpR1="$dir/autocolor_R_$$.mpc"
tmpR2="$dir/autocolor_R_$$.cache"
tmpG1="$dir/autocolor_G_$$.mpc"
tmpG2="$dir/autocolor_G_$$.cache"
tmpB1="$dir/autocolor_B_$$.mpc"
tmpB2="$dir/autocolor_B_$$.cache"
tmpL1="$dir/autocolor_L_$$.mpc"
tmpL2="$dir/autocolor_L_$$.cache"
trap "rm -f $tmpA1 $tmpA2 $tmpI1 $tmpI2 $tmpR1 $tmpR2 $tmpG1 $tmpG2 $tmpL1 $tmpL2 $tmpB1 $tmpB2;" 0
trap "rm -f $tmpA1 $tmpA2 $tmpI1 $tmpI2 $tmpR1 $tmpR2 $tmpG1 $tmpG2 $tmpL1 $tmpL2 $tmpB1 $tmpB2; exit 1" 1 2 3 15
trap "rm -f $tmpA1 $tmpA2 $tmpI1 $tmpI2 $tmpR1 $tmpR2 $tmpG1 $tmpG2 $tmpL1 $tmpL2 $tmpB1 $tmpB2; exit 1" ERR


if convert -quiet "$infile" +repage "$tmpA1"
	then
	: ' do nothing '
else
	errMsg "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE ---"
fi

# get im version
im_version=`convert -list configure | \
sed '/^LIB_VERSION_NUMBER */!d;  s//,/;  s/,/,0/g;  s/,0*\([0-9][0-9]\)/\1/g' | head -n 1`

# get im version
im_version=`convert -list configure | \
	sed '/^LIB_VERSION_NUMBER */!d; s//,/;  s/,/,0/g;  s/,0*\([0-9][0-9]\)/\1/g' | head -n 1`

# colorspace RGB and sRGB swapped between 6.7.5.5 and 6.7.6.7 
# though probably not resolved until the latter
# then -colorspace gray changed to linear between 6.7.6.7 and 6.7.8.2 
# then -separate converted to linear gray channels between 6.7.6.7 and 6.7.8.2,
# though probably not resolved until the latter
# so -colorspace HSL/HSB -separate and -colorspace gray became linear
# but we need to use -set colorspace RGB before using them at appropriate times
# so that results stay as in original script
# The following was determined from various version tests using autolevel.
# with IM 6.7.4.10, 6.7.6.10, 6.7.8.6
if [ "$im_version" -lt "06070606" -o "$im_version" -gt "06070707" ]; then
	cspace="RGB"
else
	cspace="sRGB"
fi
if [ "$im_version" -lt "06070607" -o "$im_version" -gt "06070707" ]; then
	setcspace="-set colorspace RGB"
else
	setcspace=""
fi
# no need for setcspace for grayscale or channels after 6.8.5.4
if [ "$im_version" -gt "06080504" ]; then
	setcspace=""
	cspace="sRGB"
fi


#assume an RGB/sRGB input image colorspace
convert $tmpA1 $setcspace -channel R -separate $tmpR1
convert $tmpA1 $setcspace -channel G -separate $tmpG1
convert $tmpA1 $setcspace -channel B -separate $tmpB1
if [ "$im_version" -ge "07000000" ]; then
	convert $tmpA1 $setcspace -grayscale $luma $tmpL1
else
	convert $tmpA1 $setcspace -colorspace $luma $tmpL1
fi


getChannelMean()
	{
	img="$1"
	if [ "$im_version" -ge "06030901" ]
		then 
		mean=`convert $img -format "%[mean]" info:`
		mean=`convert xc: -format "%[fx:100*$mean/quantumrange]" info:`
	else
		data=`convert $img -verbose info:`
		mean=`echo "$data" | sed -n 's/^.*[Mm]ean:.*[(]\([0-9.]*\).*$/\1/p ' | head -1`
		mean=`convert xc: -format "%[fx:100*$mean]" info:`
	fi
	}


# convert cliphigh to complement for IM -contrast-stretch
[ "$cliphigh" = "" ] && cliphigh=$cliplow
[ "$im_version" -lt "06040700" ] && cliphigh=`convert xc: -format "%[fx:100-$cliphigh]" info:`

# get ngray from mean of luminance
if [ "$ngray" = "" ]; then
	getChannelMean "$tmpL1"
	ngray=$mean
fi

# set up -recolor or -color-matrix
if [ "$im_version" -lt "06060100" ]; then
	process="-recolor"
else
	process="-color-matrix"
fi
	
#echo ""
# process colorbalance
if [ "$method" != "none" ]; then

	getChannelMean "$tmpR1"
	if [ "$method" = "gamma" ]; then 
		gammaval=`convert xc: -format "%[fx:log($mean/100)/log($ngray/100)]" info:`
		#echo "R: ngray=$ngray; mean=$mean; gamma=$gammaval"
		convert $tmpR1 -gamma $gammaval $tmpR1
	elif [ "$method" = "recolor" ]; then 
		[ "$mean" = "0" -o "$mean" = "0.0" ] && mean=100
		redratio=`convert xc: -format "%[fx:$ngray/$mean]" info:`
		#echo "R: ngray=$ngray; mean=$mean; colorratio=$redratio"
	fi
	
	getChannelMean "$tmpG1"
	if [ "$method" = "gamma" ]; then 
		gammaval=`convert xc: -format "%[fx:log($mean/100)/log($ngray/100)]" info:`
		#echo "G: ngray=$ngray; mean=$mean; gamma=$gammaval"
		convert $tmpG1 -gamma $gammaval $tmpG1
	elif [ "$method" = "recolor" ]; then 
		[ "$mean" = "0" -o "$mean" = "0.0" ] && mean=100
		greenratio=`convert xc: -format "%[fx:$ngray/$mean]" info:`
		#echo "G: ngray=$ngray; mean=$mean; colorratio=$greenratio"
	fi
	
	getChannelMean "$tmpB1"
	if [ "$method" = "gamma" ]; then 
		gammaval=`convert xc: -format "%[fx:log($mean/100)/log($ngray/100)]" info:`
		#echo "B: ngray=$ngray; mean=$mean; gamma=$gammaval"
		convert $tmpB1 -gamma $gammaval $tmpB1
	elif [ "$method" = "recolor" ]; then 
		[ "$mean" = "0" -o "$mean" = "0.0" ] && mean=100
		blueratio=`convert xc: -format "%[fx:$ngray/$mean]" info:`
		#echo "B: ngray=$ngray; mean=$mean; colorratio=$blueratio"
	fi
	
	if [ "$method" = "recolor" ]; then 
		convert $tmpA1 $process "$redratio 0 0 0 $greenratio 0 0 0 $blueratio" $tmpA1
		convert $tmpA1 $setcspace -channel R -separate $tmpR1
		convert $tmpA1 $setcspace -channel G -separate $tmpG1
		convert $tmpA1 $setcspace -channel B -separate $tmpB1
	fi
fi

# process clip and combine
# (note: clip works better after gamma or recolor rather than before)
if [ "$clipmode" = "separate" ]; then
	convert $tmpR1 -contrast-stretch ${cliplow}%,${cliphigh}% $tmpR1
	convert $tmpG1 -contrast-stretch ${cliplow}%,${cliphigh}% $tmpG1
	convert $tmpB1 -contrast-stretch ${cliplow}%,${cliphigh}% $tmpB1
	convert $tmpR1 $tmpG1 $tmpB1 -combine -colorspace $cspace "$outfile"
elif [ "$clipmode" = "together" ]; then
	convert $tmpR1 $tmpG1 $tmpB1 -combine -colorspace $cspace $tmpA1
	convert $tmpA1 -contrast-stretch ${cliplow}%,${cliphigh}% "$outfile"
fi
#echo ""

exit 0

	



