-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalthresh
executable file
·323 lines (294 loc) · 11.4 KB
/
localthresh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#!/bin/bash
#
# Developed by Fred Weinhaus 10/30/2008 .......... revised 6/13/2013
#
# USAGE: localthresh [-m method] [-s size] [-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=yes.
#
# 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 -n '/^###/q; /^#/!q; s/^#//; s/^ //; 4,$p' "$PROGDIR/$PROGNAME"
}
usage2()
{
echo >&2 ""
echo >&2 "$PROGNAME:" "$@"
sed >&2 -n '/^######/q; /^#/!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 -regard-warnings "$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