#!/bin/bash
#
# Developed by Fred Weinhaus 10/30/2008 .......... revised 5/23/2019
#
# ------------------------------------------------------------------------------
# 
# 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: localthresh [-m method] [-r radius] [-b bias] [-n negate] infile outfile
# USAGE: localthresh [-help]
#
# OPTIONS:
#
# -m      method            method for computing threshold statistics;
#                           method=1 uses only the local mean;
#                           method=2 uses the local mean and standard deviation;
#                           method=3 used the local mean and mean absolute deviation;
#                           default=1
# -r      radius            radius of window to use; float; radius>=3; default=15
# -b      bias              bias parameter (in percent) for thresholding;
#                           float; bias>=0; default=20
# -n      negate            negate indicates whether to negate the image
#                           before and after processing; negate=yes or no;
#                           default=no
#
###
#
# NAME: LOCALTHRESH
# 
# PURPOSE: To threshold an image to binary (b/w) format using a moving 
# window adaptive thresholding approach.
# 
# DESCRIPTION: LOCALTHRESH thresholds an image to binary (b/w) format
# using a moving window adaptive thresholding approach. For each window
# placement the center pixel is compared to some measure of either mean or
# combination of mean and either standard deviation or mean absolute
# deviation within the window. If the center pixel is larger than this
# measure by some bias value, then the center pixel is made white;
# otherwise it is made black. The moving window is a circle with Gaussian
# profile. NOTE: the image MUST have the "objects" or foreground as white
# and the "non-objects" or background as black. Thus the image must either
# be preprocessed using the IM function -negate or have the script do that
# using its negate parameter. IMPORTANT: For acceptable results, the
# window size generally should be larger than the dimension of the
# "objects" to be detected in the image by the thresholding. Consequently,
# this method is best applied to images of text, small objects or edges.
# 
# OPTIONS: 
# 
# -m method ... METHOD specifies what statistical measure to use to 
# compute the threshold for each window placement. Method 1 compares 
# the center pixel to the window mean, and if larger than the bias, 
# the center is made white; otherwise black. Method 2 compares the 
# center pixel to the window mean plus the bias times the window 
# standard deviation, and if the center pixels is larger, it is made  
# white; otherwise black. Method 3 compares the center pixel to the  
# window mean plus the bias times the square root of window mean  
# absolute deviation and if the center pixel is larger, it is made white;  
# otherwise black. The default is method=1. Note that method=1 is similar  
# to the IM function -lat (but uses a circular gaussian weighted window 
# rather than a square uniform weighted window and more importantly 
# does not suffer from the image shift resulting with the IM -lat 
# function).
# 
# -r radius ... RADIUS specifies the radius for the gaussian profile 
# window. The value may be a float, but must be greater than or equal 
# to 3. The default=15. For acceptable results, the radius generally 
# must be larger than the feature dimension that is to be detected by 
# the thresholding.
# 
# -b bias ... BIAS is the bias parameter used in each of the two 
# methods to determine the threshold. Larger bias values will have 
# the effect of removing more "noise" from the result, but too large 
# a value may remove parts of the foreground objects that are detected. 
# Values for bias are expressed as (percent) floats where bias>=0. 
# The default=20.
#
# -n negate ... NEGATE indicates whether to negate the image before 
# and after processing, since this technique only works when the "object" 
# or foreground is white and the "non-object" or background is black. 
# Values may be either yes or no. The default=no.
# 
# REFERENCES: see the following:
# http://www.dfki.uni-kl.de/~shafait/papers/Shafait-efficient-binarization-SPIE08.pdf
# http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.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
method=1				#1=mean, 2=mean and std, 3=mean and sqrt(mad)
radius=15				#radius>=3
bias=20					#percent bias>=0
negate="no"				#yes or no

# 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 10 ]
	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" = "" ] && errMsg "--- METHOD=$method MUST BE A NON-NEGATIVE INTEGER ---"
					   [ $method -lt 1 -o $method -gt 3 ] && errMsg "--- METHOD=$method MUST BE EITHER 1 OR 2 ---"
					   ;;
				-r)    # get radius
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID RADIUS SPECIFICATION ---"
					   checkMinus "$1"
					   radius=`expr "$1" : '\([.0-9]*\)'`
					   [ "$radius" = "" ] && errMsg "--- RADIUS=$radius MUST BE A NON-NEGATIVE FLOAT ---"
					   radiustest=`echo "$radius < 3" | bc`
					   [ $radiustest -eq 1 ] && errMsg "--- RADIUS=$radius MUST BE A FLOAT GREATER THAN OR EQUAL TO 3 ---"
					   ;;
				-b)    # get bias
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BIAS SPECIFICATION ---"
					   checkMinus "$1"
					   bias=`expr "$1" : '\([.0-9]*\)'`
					   [ "$bias" = "" ] && errMsg "--- BIAS=$bias MUST BE A NON-NEGATIVE FLOAT ---"
					   ;;
				-n)    # get negate
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID NEGATE SPECIFICATION ---"
					   checkMinus "$1"
					   negate="$1"
					   negate=`echo "$negate" | tr '[A-Z]' '[a-z]'`
					   case "$negate" in
					   		yes|y) negate="yes";;
					   		no|n) negate="no";;
					   		*) errMsg "--- NEGATE=$negate MUST BE EITHER YES OR NO ---";;
					   	esac
					   ;;
				 -)    # 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/autothresh1_A_$$.mpc"
tmpA2="$dir/autothresh1_A_$$.cache"
tmpT1="$dir/autothresh1_T_$$.mpc"
tmpT2="$dir/autothresh1_T_$$.cache"
tmpM1="$dir/autothresh1_M_$$.mpc"
tmpM2="$dir/autothresh1_M_$$.cache"
tmpS1="$dir/autothresh1_S_$$.mpc"
tmpS2="$dir/autothresh1_S_$$.cache"
trap "rm -f $tmpA1 $tmpA2 $tmpT1 $tmpT2 $tmpM1 $tmpM2 $tmpS1 $tmpS2; exit 0" 0
trap "rm -f $tmpA1 $tmpA2 $tmpT1 $tmpT2 $tmpM1 $tmpM2 $tmpS1 $tmpS2; exit 1" 1 2 3 15

# 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 localthresh.
# with IM 6.7.4.10, 6.7.6.10, 6.7.8.10
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=""
fi


if convert -quiet "$infile" $setcspace -colorspace gray -alpha off +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	

# setup window filters
	radius=`convert xc: -format "%[fx:$radius/3]" info:`
	size="0x${radius}"


# process image
[ "$negate" = "yes" ] && convert $tmpA1 -negate $tmpA1

# get mean image
convert $tmpA1 -blur "$size" $tmpM1

# NOTE: to form (image1-image2), 
# use convert image2 image1 -compose minus -composite
# or convert image1 image2 +swap -compose minus -composite

# get sos=second order statistic = either std or sqrt(mad)
if [ $method -eq 2 ]; then
	# get standard deviation=std image; std = sqrt( ave(x^2) - ave(x)^2 ); 
	# ave=mean; -gamma 2 is equivalent to sqrt
	convert \( $tmpA1 $tmpA1 -compose multiply -composite -blur "$size" \) \
		\( $tmpM1 $tmpM1 -compose multiply -composite \) +swap \
		-compose minus -composite -gamma 2 $tmpS1

elif [ $method -eq 3 ]; then
	# get sqrt(mean absolute deviation)=sqrt(mad) image;
	# mad=absolute difference of (image - mean)
	convert $tmpA1 $tmpM1 -compose difference -composite -gamma 2 $tmpS1
fi


if [ $method -eq 1 ]; then
	# threshold to white if image > (mean + K) or 
	# image - (mean + K) > 0 or
	# (image - mean) - K > 0 or 
	# (image - mean) > K
	# where K is percent
	#convert $tmpA1 \( $tmpM1 -evaluate add ${bias}% \) +swap -compose minus -composite -threshold 1 $tmpT1
	#convert $tmpA1 $tmpM1 +swap -compose minus -composite -evaluate subtract ${bias}% -threshold 1 $tmpT1

	convert $tmpA1 $tmpM1 +swap -compose minus -composite -threshold ${bias}% $tmpT1

else
	# threshold to white if image > (mean +k*sos) or 
	# image - (mean +k*sos) > 0 or
	# (image - mean) - k*sos > 0
	# where k is fraction, k=K/100 and K is percent

	bias=`convert xc: -format "%[fx:$bias/100]" info:`
		convert $tmpA1 $tmpM1 +swap -compose minus -composite \
		\( $tmpS1 -evaluate multiply ${bias} \) \
		+swap -compose minus -composite \
		-threshold 1 \
		$tmpT1
fi

if [ "$negate" = "yes" ]; then
	convert $tmpT1 -negate "$outfile"
else
	convert $tmpT1 "$outfile"
fi

exit 0
