#!/bin/bash
#
# Developed by Fred Weinhaus 10/13/2008 .......... revised 4/25/2015
#
# ------------------------------------------------------------------------------
# 
# 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: autowhite [-m method] [-p percent] infile outfile
# USAGE: autowhite [-help]
#
# OPTIONS:
#
# -m      method            method to adjust white balance;  
#                           method=1 is multiplicative adjust;
#                           method=2 is additivie adjust; default=1
# -p      percent           percent pixels closest to white to get average;
#                           float; 0<=percent<=100; default=1
#
###
#
# NAME: AUTOWHITE 
# 
# PURPOSE: To automatically adjust the white balance of an image.
# 
# DESCRIPTION: AUTOWHITE automatically adjusts the white balance of an 
# image. Two methods are available. Method 1 uses a multiplicative 
# adjustment using -recolor (-color-matrix). Method 2 uses an additive 
# adjustment using -evaluate add. Both methods compute RGB channel averages 
# of a user specified percentage of pixels closest to white. The channel 
# averages are used in a ratio compared with white in method 1 and as  
# a difference from white in method 2.
# 
# OPTIONS: 
# 
# -m method ... METHOD defines how the white balance adjustment will 
# be handled. Method 1 uses a multiplicative adjustment using -recolor 
# (-color-matrix), where the matrix values are the ratios of 100% to the  
# channel averages in percent graylevel. Method 2 uses an additive adjustment 
# using -evaluate add, where the additive amount is the percent difference 
# of the channel averages from 100%. Method 1 is generally superior. 
# Method 2 often shifts the overall color oddly. The default is method=1.
# 
# -p percent ... PERCENT is the percentage of pixels closest in color 
# to white that is used to compute the average graylevel of each RGB 
# channel in the image. Values are floats between 0 and 100. Default=1
#
# 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=1				#1=multiplicative, 2=additive
percent=1				#percent pixels closest to white

# 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 6 ]
	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
					   ;;
				-m)    # get  method
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID METHOD SPECIFICATION ---"
					   checkMinus "$1"
					   method=`expr "$1" : '\([0-9]*\)'`
					   [ $method -ne 1 -a $method -ne 2 ] && errMsg "--- METHOD=$methode MUST BE EITHER 1 OR 2 ---"
					   ;;
				-p)    # get percent
					   shift  # to get the next parameter - radius,sigma
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID PERCENT SPECIFICATION ---"
					   checkMinus "$1"
					   percent=`expr "$1" : '\([.0-9]*\)'`
					   [ "$percent" = "" ] && errMsg "--- PERCENT=$percent MUST BE A NON-NEGATIVE FLOAT ---"
					   percenttestA=`echo "$percent < 0" | bc`
					   percenttestB=`echo "$percent > 100" | bc`
					   [ $percenttestA -eq 1 -o $percenttestB -eq 1 ] && errMsg "--- PERCENT=$percent 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"


tmpA1="$dir/autowhite_1_$$.mpc"
tmpA2="$dir/autowhite_1_$$.cache"
tmpM1="$dir/autowhite_M_$$.mpc"
tmpM2="$dir/autowhite_M_$$.cache"
tmpT1="$dir/autowhite_T_$$.mpc"
tmpT2="$dir/autowhite_T_$$.cache"
tmpR1="$dir/autowhite_R_$$.mpc"
tmpR2="$dir/autowhite_R_$$.cache"
tmpG1="$dir/autowhite_G_$$.mpc"
tmpG2="$dir/autowhite_G_$$.cache"
tmpB1="$dir/autowhite_B_$$.mpc"
tmpB2="$dir/autowhite_B_$$.cache"
trap "rm -f $tmpA1 $tmpA2 $tmpM1 $tmpM2 $tmpT1 $tmpT2 $tmpR1 $tmpR2 $tmpG1 $tmpG2 $tmpB1 $tmpB2;" 0
trap "rm -f $tmpA1 $tmpA2 $tmpM1 $tmpM2 $tmpT1 $tmpT2 $tmpR1 $tmpR2 $tmpG1 $tmpG2 $tmpB1 $tmpB2; exit 1" 1 2 3 15
trap "rm -f $tmpA1 $tmpA2 $tmpM1 $tmpM2 $tmpT1 $tmpT2 $tmpR1 $tmpR2 $tmpG1 $tmpG2 $tmpB1 $tmpB2; exit 1" ERR

# test infile exists and readable
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 HAG 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 image size
ww=`convert $tmpA1 -format "%w" info:`
hh=`convert $tmpA1 -format "%h" info:`


# get colorspace
# colorspace swapped at IM 6.7.5.5, but not properly fixed until 6.7.6.6
# before swap verbose info reported colorspace=RGB after colorspace=sRGB
# not all formats report grayscale for colorspace (gif, tiff, jpg do not), but type will be grayscale
colorspace=`identify -ping -verbose $tmpA1 | sed -n 's/^.*Colorspace: \([^ ]*\).*$/\1/p'`
if [ "$colorspace" != "RGB" -a "$colorspace" != "sRGB" ]; then
	errMsg "--- FILE $infile MUST BE RGB, sRGB ---"
fi


# 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



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
	}

getAverage()
	{
	getChannelMean "$1"
	# get ave in range 0-100
	# note both mean and mask_mean are in range 0-100
	# note average of just near_white values mean of masked image divided by
	# the fraction of white pixels (from mask)
	# which is the mean in range 0 to 1 divided by 100
	ave=`convert xc: -format "%[fx:100*$mean/$maskmean]" info:`
	[ "$ave" = "0" -o "$ave" = "0.0" ] && ave=100
	ratio=`convert xc: -format "%[fx:100/$ave]" info:`
	diff=`convert xc: -format "%[fx:(100-$ave)]" info:`
	}

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

# process image

# get mask of top percent closest to white
# approximation using negated saturation and brightness channels multiplied
convert $tmpA1 $setcspace -colorspace HSB -channel G -negate -channel GB -separate +channel \
	-compose multiply -composite +channel \
	-contrast-stretch 0,${percent}% -fill black +opaque white \
	$tmpM1

# get mean of mask
getChannelMean $tmpM1
maskmean=$mean
#echo "maskmean=$maskmean"

# use mask image to isolate user supplied percent of pixels closest to white
# then get ave graylevel for each channel of mask selected pixels

convert $tmpR1 $tmpM1 -compose multiply -composite $tmpT1
getAverage "$tmpT1"
redratio=$ratio
#echo "R: ave=$ave; redratio=$ratio; reddiff=$diff"
[ $method -eq 2 ] && convert $tmpR1 -evaluate add $diff% $tmpR1

convert $tmpG1 $tmpM1 -compose multiply -composite $tmpT1
getAverage "$tmpT1"
greenratio=$ratio
#echo "G: ave=$ave; greenratio=$ratio; greendiff=$diff"
[ $method -eq 2 ] && convert $tmpG1 -evaluate add $diff% $tmpG1

convert $tmpB1 $tmpM1 -compose multiply -composite $tmpT1
getAverage "$tmpT1"
blueratio=$ratio
bluediff=$diff
#echo "B: ave=$ave; blueratio=$ratio; bluediff=$diff"
[ $method -eq 2 ] && convert $tmpB1 -evaluate add $diff% $tmpB1

if [ $method -eq 2 ]; then
	convert $tmpR1 $tmpG1 $tmpB1 -combine -colorspace $cspace "$outfile"
elif [ $method -eq 1 ]; then
	convert $tmpA1 $process "$redratio 0 0 0 $greenratio 0 0 0 $blueratio" "$outfile"
fi

exit 0

	



