#!/bin/bash

#!/bin/bash
# 
# Developed by Fred Weinhaus 10/13/2017 .......... revised  6/2/2025
#
# ------------------------------------------------------------------------------
# 
# 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: trimcorners [-f fuzzval] [-c ccolor] [-r radius] [-b bias] [-g graphic] [-t thick] 
# [-s scolor] [-S sides] infile outfile
# USAGE: trimcorners [-h or -help]
# 
# OPTIONS:
# 
# -f     fuzzval     fuzz amount in percent for floodfilling the corners; float>=0; 
#                    default=5
# -c     ccolor      corner color for adding a border before the floodfill; any   
#                    valid IM color may be specified; default will be determined  
#                    automatically from the color of top left corner pixel
# -r     radius      radius of morphologic close to clean up the mask generated by  
#                    the floodfill process; integers>=0; default=1
# -b     bias        bias (offsets) from each side to shift and make the crop smaller 
#                    in area than the automatically determined size; 4 comma separated 
#                    non-negative integers in order of left, top, right, bottom; if  
#                    only the first value is specified, it will be used for the  
#                    remaining ones; default=0
# -g     graphic     make an optional output image that is a box drawn on the input 
#                    showing where the crop will be made; choices are yes or no; 
#                    default=no; if graphic=yes, then the extra image will be the 
#                    input name with "_box" added
# -s     scolor      stroke color to use when drawing the graphic box on the input;
#                    any valid IM color may be specified; default=red
# -t     thick       thickness (strokewidth) of the box lines to be drawn when 
#                    graphic=yes; integer>=0; default=1
# -S     sides       the sides to trim; choices are LR (for left and right),  
#                    TB (for top and bottom) or A (for all four sides)
# 
###
# 
# NAME: TRIMCORNERS 
#  
# PURPOSE: To crop the image to removed rounded corners.
# 
# DESCRIPTION: TRIMCORNERS automatically crops the image to removed rounded
# corners. A fuzz value is specified to floodfill the corner regions to make a
# binary mask from the image. The mask will be black in the corners and white
# elsewhere. From this mask the diagonals of the image are extracted and search
# from the ends to find the first occurrences of white. The coordinates extracted
# are then used to create the crop dimensions and the image cropped to form the
# output.
# 
# 
# Arguments: 
# 
# -f fuzzval ... FUZZVAL is the fuzz amount in percent for floodfilling the corners. 
# Values are floats>=0. The default=5.
# 
# -c ccolor ... CCOLOR is the corner color for adding a border before the floodfill. 
# Any valid IM color may be specified. The default will be determined automatically 
# from the color of top left corner pixel.
# 
# -r radius ... RADIUS of morphologic close to clean up the mask generated by the 
# floodfill process; integers>=0; default=1.
# 
# -b bias ... BIAS (offsets) from each side to shift and make the crop smaller in area 
# than the automatically determined size. Values are 4 comma separated non-negative 
# integers in order of left, top, right, bottom. If only the first value is specified, 
# it will be used for the remaining ones. The default=0.
# 
# -g graphic ... GRAPHIC is a flag to make an optional output image that is a box drawn 
# on the input showing where the crop will be made. The choices are yes or no.  
# The default=no. If graphic=yes, then the extra image will be the input name with 
# "_box" added.
# 
# -s scolor ... SCOLOR is the stroke color to use when drawing the graphic box on the 
# input Any valid IM color may be specified. The default=red.
# 
# -t thick ... THICK is the hickness (strokewidth) of the box lines to be drawn when 
# graphic=yes. Values are integers>=0. The default=1.
# 
# -S sides ... SIDES to trim. The choices are LR (for left and right),  
# TB (for top and bottom) or A (for all four sides)
# 
# NOTE: If there are regions in the image that touch the corners and have nearly the 
# same color as the corners, then this process may make the crop smaller than desired.
# 
# 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; 
fuzzval=5
ccolor=""
bias="0"
radius=1
graphic="no"
thick=1
scolor="red"
sides="all"


# 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 18 ]
	then
	errMsg "--- TOO MANY ARGUMENTS WERE PROVIDED ---"
else
	while [ $# -gt 0 ]
		do
		# get parameters
		case "$1" in
	  -h|-help)    # help information
				   echo ""
				   usage2
				   ;;
			-f)    # fuzzval
				   shift  # to get the next parameter - fuzzval
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID FUZZVAL SPECIFICATION ---"
				   checkMinus "$1"
				   fuzzval=`expr "$1" : '\([.0-9]*\)'`
				   [ "$fuzzval" = "" ] && errMsg "--- FUZZVAL=$fuzzval MUST BE A NON-NEGATIVE FLOATING POINT VALUE (with no sign) ---"
				   ;;
			-c)    # ccolor
				   shift  # to get the next parameter
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID CORNER COLOR SPECIFICATION ---"
				   checkMinus "$1"
				   ccolor=$1
				   ;;
			-b)    # 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]*\)'`
				   count=`echo "$bias" | sed 's/ *//g' | sed 's/,/ /g' | wc -w`
				   [ $count -gt 4 ] && errMsg "--- BIAS=$bias HAS TOO MANY COMMA SEPARATED INTEGERS ---"
				   ;;
			-r)    # 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 INTEGER VALUE (with no sign) ---"
				   ;;
			-g)    # graphic
				   shift  # to get the next parameter
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID GRAPHIC SPECIFICATION ---"
				   checkMinus "$1"
				   graphic=`echo "$1" | tr "[:upper:]" "[:lower:]"`
				   case "$graphic" in
						yes|y) graphic="yes" ;;
						 no|n) graphic="no" ;;
						*)  errMsg "--- GRAPHIC=$graphic IS NOT A VALID VALUE ---" ;;
				   esac
				   ;;
			-s)    # scolor
				   shift  # to get the next parameter
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID STROKE COLOR SPECIFICATION ---"
				   checkMinus "$1"
				   scolor=$1
				   ;;
			-t)    # thick
				   shift  # to get the next parameter
				   # test if parameter starts with minus sign 
				   errorMsg="--- INVALID THICK SPECIFICATION ---"
				   checkMinus "$1"
				   thick=`expr "$1" : '\([0-9]*\)'`
				   [ "$thick" = "" ] && errMsg "--- THICK=$thick MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
				   ;;
			-S)    # sides
				   shift  # to get the next parameter
				   # test if parameter starts with minus sign
				   errorMsg="--- INVALID SIDES SPECIFICATION ---"
				   checkMinus "$1"
				   sides=`echo "$1" | tr "[:upper:]" "[:lower:]"`
				   case "$sides" in
						LR|lr) sides="lr";;
						TB|tb) sides="tb";;
						A|a|ALL|all) sides="all";;
						*)  errMsg "--- SIDES=$sides IS NOT A VALID VALUE ---" ;;
				   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"


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


# setup temporary images
tmpA1="$dir/trimcorners_1_$$.mpc"
tmpB1="$dir/trimcorners_1_$$.cache"
tmpA2="$dir/trimcorners_2_$$.mpc"
tmpB2="$dir/trimcorners_2_$$.cache"
trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2; exit 0" 0
trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2; exit 1" 1 2 3 15

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


# 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 dimensions
declare `convert -ping $tmpA1 -format "W=%w\nH=%h\n" info:`
#echo "W=$W; H=$H;"

if [ "$ccolor" = "" ]; then
	ccolor=`convert $tmpA1 -format "%[pixel:u.p{0,0}]" info:`
	#echo "ccolor=$ccolor;"
fi

# set up floodfill
if [ "$im_version" -ge "07000000" ]; then
	matte_alpha="alpha"
else
	matte_alpha="matte"
fi

# set up for radius
if [ "$radius" != "0" ]; then
	closing="-morphology close octagon:$radius"
else
	closing=""
fi

# floodfill to make black corners and rest white
convert $tmpA1 -bordercolor "$ccolor" -border 1 \
	-fuzz $fuzzval% -fill none \
	-draw "$matte_alpha 0,0 floodfill" \
	-channel a -separate \
	-shave 1x1 \
	$closing \
	$tmpA2

# rotate counterclockwise so diagonal is horizontal and crop center line.
angle=`convert xc: -format "%[fx:-(180/pi)*atan($H/$W)]" info:`
diag=`convert xc: -format "%[fx:round(hypot($H,$W))]" info:`
#echo "angle=$angle; diag=$diag;"
trimvals=`convert $tmpA2 \
	-virtual-pixel background -background black \
	+distort SRT "$angle" +repage \
	-gravity center -crop ${diag}x1+0+0 +repage \
	-bordercolor black -border 1 \
	-format "%@" info:`
#echo "trimvals=$trimvals"
# get diagonal offsets 
# note: xoff includes 1 extra due to border, which makes the other end 1 short, so add 2 to offset from other end
wd=`echo $trimvals | cut -dx -f1`
xoff=`echo $trimvals | cut -d+ -f2`
#echo "wd=$wd; xoff=$xoff;"
topleft=$xoff
btmright=$((diag-wd-xoff+2))
#echo "topleft=$topleft; btmright=$btmright"
# get x and y components of diagonal offsets
absang=`convert xc: -format "%[fx:abs($angle)]" info:`
topleftx=`convert xc: -format "%[fx:ceil($topleft*cos($absang*pi/180))]" info:`
toplefty=`convert xc: -format "%[fx:ceil($topleft*sin($absang*pi/180))]" info:`
btmrightx=`convert xc: -format "%[fx:$W-1-floor($btmright*cos($absang*pi/180))]" info:`
btmrighty=`convert xc: -format "%[fx:$H-1-floor($btmright*sin($absang*pi/180))]" info:`
#echo "topleftx=$topleftx; toplefty=$toplefty; btmrightx=$btmrightx; btmrighty=$btmrighty;"

# rotate clockwise so diagonal is horizontal and crop center line.
angle=`convert xc: -format "%[fx:-($angle)]" info:`
echo "angle=$angle; diag=$diag;"
trimvals=`convert $tmpA2 \
	-virtual-pixel background -background black \
	+distort SRT "$angle" +repage \
	-gravity center -crop ${diag}x1+0+0 +repage \
	-bordercolor black -border 1 \
	-format "%@" info:`
#echo "trimvals=$trimvals"
# get diagonal offsets 
# note: xoff includes 1 extra due to border, which makes the other end 1 short, so add 2 to offset from other end
wd=`echo $trimvals | cut -dx -f1`
xoff=`echo $trimvals | cut -d+ -f2`
#echo "wd=$wd; xoff=$xoff;"
btmleft=$xoff
topright=$((diag-wd-xoff-2))
#echo "btmleft=$btmleft; topright=$topright"
# get x and y components of diagonal offsets
absang=`convert xc: -format "%[fx:abs($angle)]" info:`
btmleftx=`convert xc: -format "%[fx:ceil($btmleft*cos($absang*pi/180))]" info:`
btmlefty=`convert xc: -format "%[fx:$H-1-floor($btmleft*sin($absang*pi/180))]" info:`
toprightx=`convert xc: -format "%[fx:$W-1-floor($topright*cos($absang*pi/180))]" info:`
toprighty=`convert xc: -format "%[fx:ceil($topright*sin($absang*pi/180))]" info:`
#echo "btmleftx=$btmleftx; btmlefty=$btmlefty; toprightx=$toprightx; toprighty=$toprighty;"

# get biases
leftbias=`echo "$bias" | cut -d, -f1`
topbias=`echo "$bias" | cut -d, -f2`
rightbias=`echo "$bias" | cut -d, -f3`
btmbias=`echo "$bias" | cut -d, -f4`
#echo "leftbias=$leftbias; topbias=$topbias; rightbias=$rightbias; btmbias=$btmbias;"


# get furthest offsets from corners
leftx=`convert xc: -format "%[fx:max($topleftx,$btmleftx)+$leftbias]" info:`
rightx=`convert xc: -format "%[fx:min($toprightx,$btmrightx)-$rightbias]" info:`
topy=`convert xc: -format "%[fx:max($toplefty,$toprighty)+$topbias]" info:`
btmy=`convert xc: -format "%[fx:min($btmlefty,$btmrighty)+$btmbias]" info:`
#echo "leftx=$leftx; rightx=$rightx; topy=$topy; btmy=$btmy;"

# set sides
if [ "$sides" = "lr" ]; then
	topy=0
	btmy=$((H-1))
elif [ "$sides" = "tb" ]; then
	leftx=0
	rightx=$((W-1))
fi

# get crop coordinates
xc=$((left_count+dxo))
yc=$((top_count+dyo))
wwc=$((ww-right_count-left_count))
hhc=$((hh-bottom_count-top_count))
cropbox="${wwc}x${hhc}+${xc}+${yc}"
echo "cropbox=$cropbox;"

# get size and offsets for crop
width=$(($rightx-$leftx+1))
height=$(($btmy-$topy+1))
xoff=$leftx
yoff=$topy
echo "cropbox=${width}x${height}+${xoff}+${yoff}"

# crop image
convert $tmpA1 -crop ${width}x${height}+${xoff}+${yoff} +repage "$outfile"


# draw optional box on input
if [ "$graphic" = "yes" ]; then
	outname=`convert -ping "$infile" -format "%t" info:`
	suffix=`convert -ping "$infile" -format "%e" info:`
	polygon="$leftx,$topy $rightx,$topy $rightx,$btmy $leftx,$btmy"
	# note: if draw a polygon, the strokewidth would show the box slightly inside the borders the thicker it was made
	# so so make just draw filled white box on black background 
	# and use morphology edgein to create an inner line and compose with red over the image
	convert $tmpA1 \
		\( -clone 0 -fill "$scolor" -colorize 100 \) \
		\( -clone 0 -fill black -colorize 100 -fill white -draw "polygon $polygon" -alpha off -morphology edgein octagon:$thick \) \
		-compose over -composite ${outname}_box.$suffix
fi


exit 0



