#!/bin/bash
#
# Developed by Fred Weinhaus 10/08/2007 .......... revised 5/4/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: space [-m mix] [-b bri] [-c con] [-s sat] [-w wn ] [-g mg ] infile outfile
# USAGE: space [-st] infile
# USAGE: space [-h or -help]
#
# OPTIONS:
#
# -m              mix            mixing fraction for desired mean;
#                                0 <= mix <= 1; default=0.5
# -b              bri            brightening gain factor; bri>=0;
#                                default=1 (no change)                             
# -c              con            contrast gain factor; con>=0
#                                default=1 (no change)                              
# -s              sat            saturation gain factor; sat>=0
#                                default=1 (no change) 
# -w              wn             moving window size percentage of image;
#                                nominally between 5 and 20; default=12.5
# -g              mg             maximum gain for standard deviation;
#                                nominally between 5 and 20; default=5
# -st                            get image statistics
# -h or -help                    get help
#
###
#
# NAME: SPACE 
# 
# PURPOSE: To change the contrast and/or brightness in an image adaptively. 
# 
# DESCRIPTION: SPACE is an adaptive technique to enhance an image's 
# brightness and contrast. SPACE is an abbreviation for SPacially 
# Adaptive Contrast Enhancement.
#
# The adaptive formula R = mix*dmean + (1-mix)*bri*M + G*(I-M). Here R is the
# resulting image. The constant dmean=bri*mean, where mean is the global mean
# of the input image. M is the low pass filtered image which is the reduced
# mean image generated by applying a non-overlapping moving average
# convolution to the input image. This image is then re-expanded to its
# original size. (I-M) is the high pass filtered image. G is a gain image,
# which is essentially dstd/S, that is, the desired std divided by the
# reduced and re-expanded standard deviation image, S, generated from the
# reduced mean image and dstd=con*std, where std is the global standard
# deviation of the input image. However to control runaway gain, a gain
# limiting constant is included, which is nominally some value between 5 and
# 20. Thus G = (dstd)/(S + (dstd/mg)). The non-overlapping average is
# typically computed using a window size that is on the order of 5-20% of the
# image size. The average is computed at some location and then the window is
# moved by the same size to get the next area to average. For example, say
# the image is 100x100 and the window size is 10% or 10x10. Then the
# non-overlapping window average would take the first 10x10 window of pixels,
# find the average, and then move 10 pixels over in x and in y and get the
# average of the next 10x10 area of pixels. This would produce a resulting
# image that was 10x10 pixels big. This would then be expanded smoothly back
# to 100x100 pixels in size. The default averaging window size is 12.5% and
# the default max gain is 5. Both are typically between 5 and 20. The window size
# does not seem to be too important, but a smaller window size tends to make
# the result a bit smoother and a larger one a bit coarser. There are times
# when you may want to push the max gain value higher, for example, when trying
# to pull information out of a hazy picture. Note, that as an option, the
# saturation of the image may also be modified. If no parameters are provided, 
# there will still be some change in the input image due to the adaptive 
# behavior even if there is no desired brightness, contrast or saturation 
# provided.
# 
# 
# Arguments: 
#
# -h or -help    ---  displays help information. 
# 
# -m mix --- mix is a fraction between 0 and 1 that controls the mixing between 
# the desired mean and the low pass filtered mean image. A value of 0 results 
# in the use of the low pass filtered image, only. A value of 1 results in the 
# use of the desired mean (constant) value only. The default is 0.5.
# 
# -b bri --- bri is a brightening factor that is a multiplier for both 
# the global mean value and the low pass filtered mean image. It is a floating 
# point value and must be non-negative. Values greater than 1 will increase 
# the brightness and values less than 1 will decrease the brightness. 
# The default is 1 or no gain. 
# 
# -c con --- con is a contrast factor that is a multiplier for the 
# global standard deviation value. It is a floating point value and must be 
# non-negative. Values greater than 1 will increase the contrast and values 
# less than 1 will decrease the contrast. The default is 1 or no gain. 
# 
# -s sat --- sat is a saturation factor. It is used in a post processing step. 
# It is a floating point value and must be non-negative. Values greater than 
# 1 will increase the saturation of the image and values less than 1 will 
# decrease the saturation of the image. The default is 1 or no gain. 
# 
# -w wn --- window is the size as a percentage of the input image for 
# the non-overlapping averaging and standard deviation operations. Typical 
# values are between 5 and 20. Smaller values tend to make the output a bit 
# smoother and larger values tend to make it a bit coarser. The default is 12.5
# (Actually, the true size of the moving window in pixels is the inverse of the
# window value expressed as a fraction. Thus a value of 5(%) corresponds to a 
# 20x20 pixel window and a value of 20(%) corresponds to a 5x5 pixel window.)
# 
# -g mg --- mg is the maximum gain limiting factor on the ration of the 
# desired mean divided by the non-overlapping standard deviation image. Typical 
# values are between 5 and 20. The default is 5.
# 
# NOTE: This script will be slow if not in HDRI mode due to the use of -fx.
#
# 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; 
# mix=mixing fraction; bri=brightness factor 
# con=contrast factor; sat=saturation factor
mix=0.5
bri=1
con=1
sat=""
# wn=averaging window size in percentage of picture size
# mg=max gain factor
wn=12.5
mg=5
stats="false"


# 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 14 ]
	then
	errMsg "--- TOO MANY ARGUMENTS WERE PROVIDED ---"
else
	while [ $# -gt 0 ]
		do
		# get parameters
		case "$1" in
	  -h|-help)    # help information
				   echo ""
				   usage2
				   ;;
		   -st)    # image statistics
				   stats="true"
				   ;;
			-m)    # mix
				   shift  # to get the next parameter - mix
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID MIX SPECIFICATION ---"
				   checkMinus "$1"
				   mix=`expr "$1" : '\([.0-9]*\)'`
				   [ "$mix" = "" ] && errMsg "--- MIX=$mix MUST BE A NON-NEGATIVE FLOATING POINT VALUE (with no sign) ---"
				   mixtest=`echo "$mix < 0" | bc`
				   [ $mixtest -eq 1 ] && errMsg "--- MIX=$mix MUST BE A NON-NEGATIVE FLOATING POINT VALUE ---"
				   ;;
			-b)    # bri
				   shift  # to get the next parameter - bri
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID BRI SPECIFICATION ---"
				   checkMinus "$1"
				   bri=`expr "$1" : '\([.0-9]*\)'`
				   [ "$bri" = "" ] && errMsg "--- BRI=$bri MUST BE A POSITIVE FLOATING POINT VALUE (with no sign) ---"
				   britest=`echo "$bri < 0" | bc`
				   [ $britest -eq 1 ] && errMsg "--- BRI=$bri MUST BE A NON-NEGATIVE FLOATING POINT VALUE ---"
				   ;;
			-c)    # con
				   shift  # to get the next parameter - con
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID CON SPECIFICATION ---"
				   checkMinus "$1"
				   con=`expr "$1" : '\([.0-9]*\)'`
				   [ "$con" = "" ] && errMsg "--- CON=$con MUST BE A NON-NEGATIVE FLOATING POINT VALUE (with no sign) ---"
				   contest=`echo "$bri < 0" | bc`
				   [ $contest -eq 1 ] && errMsg "--- CON=$con MUST BE A NON-NEGATIVE FLOATING POINT VALUE ---"
				   ;;
			-s)    # sat
				   shift  # to get the next parameter - sat
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID SAT SPECIFICATION ---"
				   checkMinus "$1"
				   sat=`expr "$1" : '\([.0-9]*\)'`
				   [ "$sat" = "" ] && errMsg "--- SAT=$sat MUST BE A NON-NEGATIVE FLOATING POINT VALUE (with no sign) ---"
				   sattest=`echo "$sat < 0" | bc`
				   [ $sattest -eq 1 ] && errMsg "--- SAT=$sat MUST BE A NON-NEGATIVE FLOATING POINT VALUE ---"
				   ;;
			-w)    # wn
				   shift  # to get the next parameter - wn
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID WINDOW SPECIFICATION ---"
				   checkMinus "$1"
				   wn=`expr "$1" : '\([.0-9]*\)'`
				   [ "$wn" = "" ] && errMsg "--- WINDOW=$wn MUST BE A POSITIVE FLOATING POINT VALUE (with no sign) ---"
				   wntest=`echo "$wn <= 0" | bc`
				   [ $wntest -eq 1 ] && errMsg "--- WINDOW=$wn MUST BE A POSITIVE FLOATING POINT VALUE ---"
				   ;;
			-g)    # mg
				   shift  # to get the next parameter - mg
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID GAIN SPECIFICATION ---"
				   checkMinus "$1"
				   mg=`expr "$1" : '\([.0-9]*\)'`
				   [ "$mg" = "" ] && errMsg "--- GAIN=$mg MUST BE A POSITIVE FLOATING POINT VALUE (with no sign) ---"
				   mgtest=`echo "$mg <= 0" | bc`
				   [ $mgtest -eq 1 ] && errMsg "--- GAIN=$mg MUST BE A POSITIVE FLOATING POINT VALUE ---"
				   ;;
			 -)    # 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"
	[ "$stats" = "false" ] && outfile=$2
fi


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

# test that outfile provided
if [ "$stats" = "false" ]
	then
	[ "$outfile" = "" ] && errMsg "NO OUTPUT FILE SPECIFIED"
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`


# test for hdri enabled
# NOTE: must put grep before trap using ERR in case it does not find a match
if [ "$im_version" -ge "07000000" ]; then
	hdri_on=`convert -version | grep "HDRI"`	
else
	hdri_on=`convert -list configure | grep "enable-hdri"`
fi


# setup temporary images and auto delete upon exit
# use mpc/cache to hold input image temporarily in memory
tmpA="$dir/space_$$.mpc"
tmpB="$dir/space_$$.cache"
tmpM="$dir/space_mean_$$.mpc"
tmpM2="$dir/space_mean_$$.cache"
tmpS="$dir/space_std_$$.mpc"
tmpS2="$dir/space_std_$$.cache"
tmpME="$dir/space_meane_$$.mpc"
tmpME2="$dir/space_meane_$$.cache"
tmpSE="$dir/space_stde_$$.mpc"
tmpSE2="$dir/space_stde_$$.cache"
tmp0="$dir/space_0_$$.pfm"
tmp1="$dir/space_1_$$.pfm"
tmp2="$dir/space_2_$$.pfm"
tmp3="$dir/space_3_$$.pfm"

trap "rm -f $tmpA $tmpB $tmpM $tmpM2 $tmpS $tmpS2 $tmpME $tmpME2 $tmpSE $tmpSE2 $tmp0 $tmp1 $tmp2 $tmp3;" 0
trap "rm -f $tmpA $tmpB $tmpM $tmpM2 $tmpS $tmpS2 $tmpME $tmpME2 $tmpSE $tmpSE2 $tmp0 $tmp1 $tmp2 $tmp3; exit 1" 1 2 3 15
trap "rm -f $tmpA $tmpB $tmpM $tmpM2 $tmpS $tmpS2 $tmpME $tmpME2 $tmpSE $tmpSE2 $tmp0 $tmp1 $tmp2 $tmp3; exit 1" ERR

# 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 space.
# with IM 6.7.4.10, 6.7.6.10, 6.7.9.0
if [ "$im_version" -lt "06070607" -o "$im_version" -gt "06070707" ]; then
	setcspace="-set colorspace RGB"
else
	setcspace=""
fi
if [ "$im_version" -lt "06070606" -o "$im_version" -gt "06070707" ]; then
	cspace="RGB"
else
	cspace="sRGB"
fi
# no need for setcspace for grayscale or channels after 6.8.5.4
if [ "$im_version" -gt "06080504" ]; then
	setcspace=""
	cspace="sRGB"
fi


# function to get min, max, mean, std from Brightness channel (or Graylevel image)
function imagestats
	{
	data=`convert $1 -verbose info:`
	min=`echo "$data" | sed -n 's/^.*[Mm]in:.*[(]\([0-9.]*\).*$/\1/p ' | head -1`
	[ "$min" = "" ] && errMsg "--- MIN NOT FOUND --- "
	max=`echo "$data" | sed -n 's/^.*[Mm]ax:.*[(]\([0-9.]*\).*$/\1/p ' | head -1`
	[ "$max" = "" ] && errMsg "--- MAX NOT FOUND --- "
	mean=`echo "$data" | sed -n 's/^.*[Mm]ean:.*[(]\([0-9.]*\).*$/\1/p ' | head -1`
	[ "$mean" = "" ] && errMsg "--- MEAN NOT FOUND --- "
	std=`echo "$data" | sed -n 's/^.*[Ss]tandard.*[(]\([0-9.]*\).*$/\1/p ' | head -1`
	[ "$std" = "" ] && errMsg "--- STD NOT FOUND --- "
	#
	# express as percent
	# Note: divide by 1 needed to force bc to honor scale=1; otherwise get 6 digits after decimal point
	min=`echo "scale=1; $min * 100 / 1" | bc`
	max=`echo "scale=1; $max * 100 / 1" | bc`
	mean=`echo "scale=1; $mean * 100 / 1" | bc`
	std=`echo "scale=1; $std * 100 / 1" | bc`
	}


if [ "$stats" = "true" ]
	then
	convert $infile -colorspace Gray $tmp0
	imagestats $tmp0	
	echo ""
	echo "Min (0-100) = $min"
	echo "Max (0-100) = $max"
	echo "Mean (0-100) = $mean"
	echo "Std (0-...) = $std"
	echo ""
else
	if [ "$hdri_on" = "" ]; then
		echo ""
		echo "Please Wait - This May Take Some Time"
		echo ""
	fi
	if convert -quiet "$infile" +repage "$tmpA"
		then
		: 'do nothing special'
		else
			errMsg "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE ---"
	fi

	# get image stats
	convert $tmpA $setcspace -colorspace Gray $tmp0
	imagestats $tmp0	
	
	# get mean
	convert $tmpA -filter box -resize $wn% $tmpM
	
	# get std = sqrt( ave(x^2) - ave(x)^2 )
	# -evaluate pow 0.5 is equivalent to sqrt
	convert \( $tmpA $tmpA -compose multiply -composite -filter box -resize $wn% \) \
		\( $tmpM $tmpM -compose multiply -composite \) +swap \
		-compose minus -composite -evaluate pow 0.5 $tmpS
		
	# expand mean and std images
	dim=`convert $tmpA -format "%wx%h" info:`
	convert $tmpM -resize $dim! $tmpME
	convert $tmpS -resize $dim! $tmpSE
	

if [ "$hdri_on" = "" ]; then
	# get gain image and process output
	dmean=`echo "scale=5; $bri * $mean / 100" | bc`
	dstd=`echo "scale=5; $con * $std / 100" | bc`
	fdmean=`echo "scale=5; $mix * $dmean / 1" | bc`
	dsdmg=`echo "scale=5; $dstd / $mg" | bc`
	mfm1=`echo "scale=5; (1 - $mix) / 1" | bc`
	bfmfm1=`echo "scale=5; $bri * $mfm1 / 1" | bc`
	gain="gn=($dstd)/(u[2]+($dsdmg));"
	convert $tmpA $tmpME $tmpSE -monitor \
		-fx "$gain ($fdmean)+($bfmfm1*v)+(gn*(u-v))" +monitor $tmp3
else
	dmean=`convert xc: -format "%[fx:$bri*$mean]" info:`
	dstd=`convert xc: -format "%[fx:$con*$std/100]" info:`
	fdmean=`convert xc: -format "%[fx:$mix*$dmean]" info:`
	dsdmg=`convert xc: -format "%[fx:100*$dstd/$mg]" info:`
	mfm1=`convert xc: -format "%[fx:1-$mix]" info:`
	bfmfm1=`convert xc: -format "%[fx:$bri*$mfm1]" info:`
	dim=`convert $tmpA -format "%wx%h" info:`

	# second line -- ($fdmean)+($bfmfm1*v)
	# third line -- u[2]+$dsdmg
	# fourth line -- $dstd*(u-v)
	# fifth line -- $dstd*(u-v)/(u[2]+$dsdmg)
	# sixth line -- ($fdmean)+($bfmfm1*v)+$dstd*(u-v)/(u[2]+$dsdmg)
	convert $tmpA $tmpME $tmpSE \
	\( -clone 1 -evaluate multiply $bfmfm1 -evaluate add $fdmean% \) \
	\( -clone 2 -evaluate add $dsdmg% \) \
	\( -clone 0 -clone 1 +swap -define compose:clamp=off -compose minus -composite -evaluate multiply $dstd \) \
	\(  -clone 5 -clone 4 +swap -define compose:clamp=off -compose divide -composite \) \
	-delete 0,1,2,4,5 -define compose:clamp=off -compose plus -composite $tmp3
fi

	
	if [ "$sat" != "" ]
		then		
		convert $tmp3 $tmpA
		convert $tmpA $setcspace -colorspace HSL -channel R -separate $tmp0
		convert $tmpA $setcspace -colorspace HSL -channel G -separate $tmp1
		convert $tmpA $setcspace -colorspace HSL -channel B -separate $tmp2
		convert $tmp1 -evaluate multiply $sat $tmp1
		convert $tmp0 -colorspace HSL \
			$tmp0 -compose CopyRed -composite \
			$tmp1 -compose CopyGreen -composite \
			$tmp2 -compose CopyBlue -composite \
			-colorspace $cspace $tmp3
		fi
	convert $tmp3 "$outfile"
fi
exit 0