/
mincstats.c
1964 lines (1743 loc) · 63.8 KB
/
mincstats.c
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* mincstats.c
*
* Andrew Janke - a.janke@gmail.com
* Centre for Magnetic Resonance
* University of Queensland, Australia
*
* $Log: mincstats.c,v $
* Revision 1.24 2007-12-11 12:43:01 rotor
* * added static to all global variables in main programs to avoid linking
* problems with libraries (compress in mincconvert and libz for example)
*
* Revision 1.23 2007/09/27 01:06:31 rotor
* * bugfix to histogram stats with a zero volume, discovered by Simon, fixed by
* Claude
*
* Revision 1.22 2005/07/29 16:46:21 bert
* Add warning message for mincstats -mask w/o -mask_range, -mask_binvalue, etc.
*
* Revision 1.21 2005/07/25 19:56:52 bert
* Fix pct_T calculation by taking into account a possibly non-zero histogram floor
*
* Revision 1.20 2005/05/20 15:39:45 bert
* Remove and/or conditionalize test code for memory-mapped files (see HDF5_MMAP_TEST)
*
* Revision 1.19 2004/12/14 23:39:36 bert
* New bimodal threshold algorithms
*
* Revision 1.18 2004/12/06 15:28:50 rotor
* * Hopefully the final bug-fix for the BiModalT calculation
*
* Revision 1.17 2004/11/01 22:38:39 bert
* Eliminate all references to minc_def.h
*
* Revision 1.16 2004/10/18 08:20:35 rotor
* * Changes to mincstats
* - Fixed bug in calculation of BiModalT
* - changed default # of histogram bins to 65536 (from 10000)
*
* Revision 1.15 2004/04/27 15:29:22 bert
* Added milog_init() call during initialization
*
* Revision 1.14 2003/09/05 18:29:40 bert
* Avoid passing NULL to fprintf when no mask file is specified, to avoid seg. faults reported by Richard Boyes.
*
* Revision 1.13 2003/08/20 05:52:55 rotor
* * INDENTATION changes only (merging my and peter neelins code!)
*
* Revision 1.12 2003/08/20 05:45:10 rotor
* * Fixed broken calculation of Median value from histogram.
*
* Revision 1.11 2002/09/05 00:41:57 rotor
* ----------------------------------------------------------------------
* Fixed clash of C/L arguments in mincstats (-max and -max_bins)
* -max_bins has now been changed to -int_max_bins
*
* Committing in .
*
* Modified Files:
* mincstats.c
* ----------------------------------------------------------------------
*
* Revision 1.10 2002/04/08 21:46:34 jgsled
* fixed problem where mincstats segmentation fault when trying to close a NULL file pointer
*
* Revision 1.9 2002/01/09 13:23:16 neelin
* Removed extraneous newline for histogram output with -quiet turned on.
*
* Revision 1.8 2001/12/11 14:36:00 neelin
* Added -discrete_histogram and -integer_histogram, as well as
* -world_only options.
*
* Revision 1.7 2001/12/10 14:11:45 neelin
* Obtained speed improvement by only doing CoM summing when needed.
*
* Revision 1.6 2001/12/06 21:54:25 neelin
* Check for -quiet when printing volume and mask ranges.
*
* Revision 1.5 2001/12/06 21:48:16 neelin
* Significant modifications to get mincstats working. Also added support
* for multiple ranges in the volume and the mask. Added -binvalue and
* -maskbinvalue options.
*
* Revision 1.4 2001/12/05 17:20:13 neelin
* Lots of fixes to get it working. Also fixed up centre of mass calculation
* and display.
*
* Revision 1.2 2001/11/28 21:59:39 neelin
* Significant modifications. Removed dependencies on volume_io.
* Added support for centre-of-mass calculation.
* Compiles but crashes under linux.
*
* Revision 1.1 2001/11/28 21:54:08 neelin
* *** empty log message ***
*
*
* Thu Feb 1 17:16:21 EST 2001 - completed filename checking and other
* mundane stuff - first release 1.0
* Wed Jan 31 14:33:30 EST 2001 - finished -entropy, -median and -histogram
* Fri Jan 19 15:25:44 EST 2001 - created first version from minccount as a
* mirror of Alex Zijdenbos + John Sleds
* volume_stats proggy with less memory
* overhead
* Original version - 1999 sometime..
*
* A few notes on the stats in here.
* Median - This is a "histogram median" based upon calculating
* the volume of histogram above and below the median
* Thus the more bins the more accurate the approximation
* Majority - This is the centre of the largest bin in the histogram
* BiModalT - The Bi-Modal Threshold calculated using the method described in
* Otsu N, "A Threshold Selection Method from Grey-level Histograms"
* IEEE Trans on Systems, Man and Cybernetics. 1979, 9:1;62-66.
* Entropy - This is what is called "Shannon Entropy" of a histogram
* H(x) = - Sum(P(i) * log2(P(i))
* Where P(i) is the bin probability
* PctT - The threshold needed for a particular "Critical percentage" of
* of a histogram.
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#include <limits.h>
#include <float.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <ParseArgv.h>
#include <voxel_loop.h>
#ifndef TRUE
# define TRUE 1
# define FALSE 0
#endif
#define SQR(x) ((x)*(x))
#define CUBE(x) ((x)*(x)*(x))
#define QUAD(x) ((x)*(x)*(x)*(x))
#define WORLD_NDIMS 3
#define DEFAULT_VIO_BOOL (-1)
#define BINS_DEFAULT 2000
/* Double_Array structure */
typedef struct {
int numvalues;
double *values;
} Double_Array;
/* Stats structure */
typedef struct {
double vol_range[2];
double mask_range[2];
double *histogram;
double hvoxels;
double vvoxels;
double volume;
double vol_per;
double hist_per;
double min;
double max;
double sum;
double sum2;
double shift;
double shiftsum;
double shiftsum2;
double mu; /* current estimate of mean. */
double M2; /* for calculation of second moment */
double M3; /* for calculation of third moment */
double M4; /* for calculation of fourth moment */
double mean;
double variance;
double stddev;
double voxel_com_sum[WORLD_NDIMS];
double voxel_com[WORLD_NDIMS];
double world_com[WORLD_NDIMS];
double median;
double majority;
double biModalT;
double pct_T;
double entropy;
} Stats_Info;
/* Function prototypes */
void do_math(void *caller_data, long num_voxels, int input_num_buffers,
int input_vector_length, double *input_data[], int output_num_buffers,
int output_vector_length, double *output_data[], Loop_Info * loop_info);
void do_stats(double value, long index[], Stats_Info * stats);
void print_result(char *title, double result);
long get_minc_nvoxels(int mincid);
double get_minc_voxel_volume(int mincid);
void get_minc_attribute(int mincid, char *varname, char *attname,
int maxvals, double vals[]);
int get_minc_ndims(int mincid);
void find_minc_spatial_dims(int mincid, int space_to_dim[], int dim_to_space[]);
void get_minc_voxel_to_world(int mincid,
double voxel_to_world[WORLD_NDIMS][WORLD_NDIMS + 1]);
void normalize_vector(double vector[]);
void transform_coord(double out_coord[],
double transform[WORLD_NDIMS][WORLD_NDIMS + 1],
double in_coord[]);
void print_com(Stats_Info * stats);
int get_double_list(char *dst, char *key, char *nextarg);
void verify_range_options(Double_Array * min, Double_Array * max,
Double_Array * range, Double_Array * binvalue);
void init_stats(Stats_Info * stats, int hist_bins);
void free_stats(Stats_Info * stats);
/* Argument variables */
int max_buffer_size_in_kb = 4 * 1024;
static int verbose = FALSE;
static int quiet = FALSE;
static int clobber = FALSE;
static int ignoreNaN = DEFAULT_VIO_BOOL;
static double fillvalue = -DBL_MAX;
static int All = FALSE;
static int Vol_Count = FALSE;
static int Vol_Per = FALSE;
static int Vol = FALSE;
static int Min = FALSE;
static int Max = FALSE;
static int Sum = FALSE;
static int Sum2 = FALSE;
static int Mean = FALSE;
static int Variance = FALSE;
static int Stddev = FALSE;
static int Skewness = FALSE;
static int Kurtosis = FALSE;
static int CoM = FALSE;
static int World_Only = FALSE;
static int Hist = FALSE;
static int Hist_Count = FALSE;
static int Hist_Per = FALSE;
static int Median = FALSE;
static int Majority = FALSE;
static int BiModalT = FALSE;
static int PctT = FALSE;
static double pctT = -1.0;
static int Entropy = FALSE;
/* Alternative methods of calculating the bimodal threshold */
#define BMT_OTSU 1 /* Otsu algorithm (default) */
#define BMT_KITTLER 2 /* Kittler-Illingworth algorithm */
#define BMT_KAPUR 3 /* Kapur et al. algorithm */
#define BMT_SIMPLE 4 /* Simple mean-of-means, citation unknown */
static int BMTMethod = BMT_OTSU;
static Double_Array vol_min = { 0, NULL };
static Double_Array vol_max = { 0, NULL };
static Double_Array vol_range = { 0, NULL };
static Double_Array vol_binvalue = { 0, NULL };
static int num_ranges;
char *mask_file;
static Double_Array mask_min = { 0, NULL };
static Double_Array mask_max = { 0, NULL };
static Double_Array mask_range = { 0, NULL };
static Double_Array mask_binvalue = { 0, NULL };
static int num_masks;
char *hist_file;
static int hist_bins = BINS_DEFAULT;
static double hist_sep;
static double hist_range[2] = { -DBL_MAX, DBL_MAX };
static int discrete_histogram = FALSE;
static int integer_histogram = FALSE;
static int max_bins = 65536;
/* Global Variables to store info for stats */
Stats_Info **stats_info = NULL;
double voxel_volume;
double nvoxels;
int space_to_dim[WORLD_NDIMS] = { -1, -1, -1 };
int dim_to_space[MAX_VAR_DIMS];
int file_ndims = 0;
/* Argument table */
static ArgvInfo argTable[] = {
{NULL, ARGV_HELP, (char *)NULL, (char *)NULL, "General options:"},
{"-verbose", ARGV_CONSTANT, (char *)TRUE, (char *)&verbose,
"Print out extra information."},
{"-quiet", ARGV_CONSTANT, (char *)TRUE, (char *)&quiet,
"Print requested values only."},
{"-clobber", ARGV_CONSTANT, (char *)TRUE, (char *)&clobber,
"Clobber existing files."},
{"-noclobber", ARGV_CONSTANT, (char *)FALSE, (char *)&clobber,
"Do not clobber existing files (default)."},
{"-max_buffer_size_in_kb",
ARGV_INT, (char *)1, (char *)&max_buffer_size_in_kb,
"maximum size of internal buffers."},
{NULL, ARGV_HELP, (char *)NULL, (char *)NULL, "\nVoxel selection options:"},
{"-floor", ARGV_FUNC, (char *)get_double_list, (char *)&vol_min,
"Ignore voxels below this value (list)"},
{"-ceil", ARGV_FUNC, (char *)get_double_list, (char *)&vol_max,
"Ignore voxels above this value (list)"},
{"-range", ARGV_FUNC, (char *)get_double_list, (char *)&vol_range,
"Ignore voxels outside this range (list)"},
{"-binvalue", ARGV_FUNC, (char *)get_double_list, (char *)&vol_binvalue,
"Include voxels within 0.5 of this value (list)"},
{"-mask", ARGV_STRING, (char *)1, (char *)&mask_file,
"<mask.mnc> Use mask file for calculations."},
{"-mask_floor", ARGV_FUNC, (char *)get_double_list, (char *)&mask_min,
"Exclude mask voxels below this value (list)"},
{"-mask_ceil", ARGV_FUNC, (char *)get_double_list, (char *)&mask_max,
"Exclude mask voxels above this value (list)"},
{"-mask_range", ARGV_FUNC, (char *)get_double_list, (char *)&mask_range,
"Exclude voxels outside this range (list)"},
{"-mask_binvalue", ARGV_FUNC, (char *)get_double_list, (char *)&mask_binvalue,
"Include mask voxels within 0.5 of this value (list)"},
{"-ignore_nan", ARGV_CONSTANT, (char *)TRUE, (char *)&ignoreNaN,
"Exclude NaN values from stats (default)."},
{"-include_nan", ARGV_CONSTANT, (char *)FALSE, (char *)&ignoreNaN,
"Treat NaN values as zero."},
{"-replace_nan", ARGV_FLOAT, (char *)1, (char *)&fillvalue,
"Replace NaNs with specified value."},
{NULL, ARGV_HELP, (char *)NULL, (char *)NULL, "\nHistogram Options:"},
{"-histogram", ARGV_STRING, (char *)1, (char *)&hist_file,
"<hist_file> Compute histogram."},
{"-hist_bins", ARGV_INT, (char *)1, (char *)&hist_bins,
"<number> of bins in each histogram."},
{"-bins", ARGV_INT, (char *)1, (char *)&hist_bins,
"synonym for -hist_bins."},
{"-hist_floor", ARGV_FLOAT, (char *)1, (char *)&hist_range[0],
"Histogram floor value. (incl)"},
{"-hist_ceil", ARGV_FLOAT, (char *)1, (char *)&hist_range[1],
"Histogram ceiling value. (incl)"},
{"-hist_range", ARGV_FLOAT, (char *)2, (char *)&hist_range,
"Histogram floor and ceiling. (incl)"},
{"-discrete_histogram", ARGV_CONSTANT, (char *)TRUE, (char *)&discrete_histogram,
"Match histogram bins to data discretization"},
{"-integer_histogram", ARGV_CONSTANT, (char *)TRUE, (char *)&integer_histogram,
"Set histogram bins to unit width"},
{"-int_max_bins", ARGV_INT, (char *)1, (char *)&max_bins,
"Set maximum number of histogram bins for integer histograms"},
{NULL, ARGV_HELP, (char *)NULL, (char *)NULL, "\nStatistics (Printed in this order)"},
{"-all", ARGV_CONSTANT, (char *)TRUE, (char *)&All,
"all statistics (default)."},
{"-none", ARGV_CONSTANT, (char *)TRUE, (char *)&Vol_Count,
"synonym for -count. (from volume_stats)"},
{"-count", ARGV_CONSTANT, (char *)TRUE, (char *)&Vol_Count,
"# of voxels."},
{"-percent", ARGV_CONSTANT, (char *)TRUE, (char *)&Vol_Per,
"percentage of valid voxels."},
{"-volume", ARGV_CONSTANT, (char *)TRUE, (char *)&Vol,
"volume (in mm3)."},
{"-min", ARGV_CONSTANT, (char *)TRUE, (char *)&Min,
"minimum value."},
{"-max", ARGV_CONSTANT, (char *)TRUE, (char *)&Max,
"maximum value."},
{"-sum", ARGV_CONSTANT, (char *)TRUE, (char *)&Sum,
"sum."},
{"-sum2", ARGV_CONSTANT, (char *)TRUE, (char *)&Sum2,
"sum of squares."},
{"-mean", ARGV_CONSTANT, (char *)TRUE, (char *)&Mean,
"mean value."},
{"-variance", ARGV_CONSTANT, (char *)TRUE, (char *)&Variance,
"variance."},
{"-stddev", ARGV_CONSTANT, (char *)TRUE, (char *)&Stddev,
"standard deviation."},
{"-CoM", ARGV_CONSTANT, (char *)TRUE, (char *)&CoM,
"centre of mass of the volume."},
{"-com", ARGV_CONSTANT, (char *)TRUE, (char *)&CoM,
"centre of mass of the volume."},
{"-world_only", ARGV_CONSTANT, (char *)TRUE, (char *)&World_Only,
"print CoM in world coords only."},
{"-skewness", ARGV_CONSTANT, (char *)TRUE, (char *)&Skewness,
"sample skewness (3rd moment)"},
{"-kurtosis", ARGV_CONSTANT, (char *)TRUE, (char *)&Kurtosis,
"sample kurtosis (4th moment)"},
{NULL, ARGV_HELP, (char *)NULL, (char *)NULL, "\nHistogram Dependant Statistics:"},
{"-hist_count", ARGV_CONSTANT, (char *)TRUE, (char *)&Hist_Count,
"# of voxels portrayed in Histogram."},
{"-hist_percent",
ARGV_CONSTANT, (char *)TRUE, (char *)&Hist_Per,
"percentage of histogram voxels."},
{"-median", ARGV_CONSTANT, (char *)TRUE, (char *)&Median,
"median value."},
{"-majority", ARGV_CONSTANT, (char *)TRUE, (char *)&Majority,
"most frequently occurring histogram bin."},
{"-biModalT", ARGV_CONSTANT, (char *)TRUE, (char *)&BiModalT,
"value separating a volume into 2 classes."},
{"-pctT", ARGV_FLOAT, (char *)1, (char *)&pctT,
"<%> threshold at the supplied % of data."},
{"-entropy", ARGV_CONSTANT, (char *)TRUE, (char *)&Entropy,
"entropy of the volume."},
{"-otsu", ARGV_CONSTANT, (char *)BMT_OTSU, (char *)&BMTMethod,
"Use Otsu '97 algorithm for bimodal threshold (default)"},
{"-kittler", ARGV_CONSTANT, (char *)BMT_KITTLER, (char *)&BMTMethod,
"Use Kittler&Illingworth '86 algorithm for bimodal threshold"},
{"-kapur", ARGV_CONSTANT, (char *)BMT_KAPUR, (char *)&BMTMethod,
"Use Kapur et al. '85 algorithm for bimodal threshold"},
{"-simple", ARGV_CONSTANT, (char *)BMT_SIMPLE, (char *)&BMTMethod,
"Use simple mean-of-means algorithm for bimodal threshold"},
{NULL, ARGV_HELP, NULL, NULL, ""},
{NULL, ARGV_END, NULL, NULL, NULL}
};
/* Alternative thresholding algorithm. This is more computationally
* expensive than some of the alternatives, and doesn't seem to do a
* great job. On the other hand it doesn't seem to fail like the
* current algorithm.
*/
static double
simple_threshold(double *histogram, double *hist_centre, int hist_bins)
{
double sum1, sum2;
double mean1, mean2;
double testthreshold;
double newthreshold;
int newthreshold_bin;
double count1, count2;
int c;
/* Start with a guess of the bimodal threshold.
*/
newthreshold = ceil(hist_centre[hist_bins / 2]);
newthreshold_bin = hist_bins / 2;
for (;;) {
sum1 = 0.0;
sum2 = 0.0;
count1 = 0.0;
count2 = 0.0;
/* Calculate the mean of the bins on each side of the
* proposed threshold.
*/
for (c = 0; c < newthreshold_bin; c++) {
sum1 += (hist_centre[c] * histogram[c]);
count1 += histogram[c];
}
for (c = newthreshold_bin; c < hist_bins; c++) {
sum2 += (hist_centre[c] * histogram[c]);
count2 += histogram[c];
}
/* Avoid divide by zero
*/
if (count1 == 0.0 || count2 == 0.0) {
continue;
}
mean1 = sum1 / count1;
mean2 = sum2 / count2;
/* The new threshold is the mean of the means.
*/
testthreshold = ceil((mean1 + mean2) / 2);
/* If the threshold is unchanged, that is our final
* guess.
*/
if (newthreshold == testthreshold) {
break; /* Return result */
}
else {
/* Adopt the new guess and try again until we converge.
*/
newthreshold = testthreshold;
for (c = 0; c < hist_bins; c++) {
if (newthreshold == ceil(hist_centre[c])) {
newthreshold_bin = c;
break;
}
}
}
}
return (newthreshold);
}
/** This copyright applies to the following functions:
*
* otsu_threshold()
* kittler_threshold()
* kapur_threshold()
*
* These functions were extracted from the "xite" package from this
* source. The functions were extensively modified, however, by me
* to generalize the functions for our purposes. Any bugs are
* therefore my responsibility (bert 2004-12-14).
*
* Copyright 1990, Blab, UiO
* Image processing lab, Department of Informatics
* University of Oslo
* E-mail: blab@ifi.uio.no
*________________________________________________________________
*
* Permission to use, copy, modify and distribute this software and
* its documentation for any purpose and without fee is hereby
* granted, provided that this copyright notice appear in all copies
* and that both that copyright notice and this permission notice
* appear in supporting documentation and that the name of B-lab,
* Department of Informatics or University of Oslo not be used in
* advertising or publicity pertaining to distribution of the software
* without specific, written prior permission.
*
* B-LAB DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
* NO EVENT SHALL B-LAB BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* Otsu, N. "A threshold selection method from gray-level histograms",
* IEEE Transactions on Systems, Man, and Cybernetics, vol T-SMC 9,
* No 1, pp 62-66, 1979.
*/
static double
otsu_threshold(const double histo[], const double hist_centre[], int hist_bins)
{
double threshold;
double criterion;
double expr_1; /* Temporary for common subexpression */
int i, k; /* Generic loop counters */
long omega_k;
double sigma_b_k;
double mu_T;
double mu_k;
long sum;
int k_low, k_high;
/* Ignore outlying zero bins */
for (k_low = 0; (histo[k_low] <= 0.0) && (k_low < hist_bins-1); k_low++)
;
for (k_high = hist_bins-1; (histo[k_high] <= 0) && (k_high > 0); k_high--)
;
if (k_high < k_low) /* Check for pathological histogram. */
return 0.0; /* Nothing to see here. */
sum = 0L;
mu_T = 0.0;
for (i = k_low; i <= k_high; i++) {
sum += histo[i];
mu_T += hist_centre[i] * histo[i];
}
mu_T /= (double)sum;
criterion = 0.0;
threshold = hist_centre[(k_high - k_low + 1 ) / 2];
omega_k = 0L;
mu_k = 0.0;
for (k = k_low; k <= k_high ; k++) {
omega_k += (long)histo[k];
if( omega_k == 0L || omega_k >= sum )
continue;
mu_k += hist_centre[k] * histo[k];
expr_1 = mu_T * omega_k - mu_k;
sigma_b_k = expr_1 * expr_1 / ( (double) omega_k * ( sum - omega_k ) );
if (criterion < sigma_b_k) {
criterion = sigma_b_k;
threshold = hist_centre[k];
}
}
return threshold;
}
/* Kittler, J. & Illingworth J., "Minimum error thresholding", Pattern
* Recognition, vol 19, pp 41-47, 1986.
*/
static double
kittler_threshold (double hist_bin[], double hist_centre[], int hist_size)
{
double threshold;
double criterion;
int g;
double n;
int T_low, T_high;
double P_1_T, P_2_T, P_tot;
double mu_1_T, mu_2_T;
double sum_gh_1, sum_gh_2, sum_gh_tot;
double sum_ggh_1, sum_ggh_2, sum_ggh_tot;
double sigma_1_T, sigma_2_T;
double J_T;
criterion = 1e10;
threshold = hist_centre[hist_size / 2 + 1];
J_T = criterion;
T_low = 0;
while ((hist_bin[T_low] == 0) && (T_low < hist_size - 1)) {
T_low++;
}
T_high = hist_size - 1;
while ((hist_bin[T_high] == 0) && (T_high > 0)) {
T_high--;
}
n = 0;
for (g = T_low; g <= T_high; g++) {
n += hist_bin[g];
}
P_1_T = hist_bin[T_low];
P_tot = 0;
for (g = T_low; g <= T_high; g++) {
P_tot += hist_bin[g];
}
sum_gh_1 = hist_centre[T_low] * hist_bin[T_low];
sum_gh_tot = 0.0;
for (g = T_low; g <= T_high; g++) {
sum_gh_tot += hist_centre[g] * hist_bin[g];
}
sum_ggh_1 = hist_centre[T_low] * hist_centre[T_low] * hist_bin[T_low];
sum_ggh_tot = 0.0;
for (g = T_low; g <= T_high; g++) {
sum_ggh_tot += hist_centre[g] * hist_centre[g] * hist_bin[g];
}
for (g = T_low + 1; g < T_high - 1; g++) {
P_1_T += hist_bin[g];
P_2_T = P_tot - P_1_T;
sum_gh_1 += hist_centre[g] * hist_bin[g];
sum_gh_2 = sum_gh_tot - sum_gh_1;
mu_1_T = sum_gh_1 / P_1_T;
mu_2_T = sum_gh_2 / P_2_T;
sum_ggh_1 += hist_centre[g] * hist_centre[g] * hist_bin[g];
sum_ggh_2 = sum_ggh_tot - sum_ggh_1;
sigma_1_T = sum_ggh_1 / P_1_T - mu_1_T * mu_1_T;
sigma_2_T = sum_ggh_2 / P_2_T - mu_2_T * mu_2_T;
/* Equation (15) in the article */
if ((sigma_1_T != 0.0) && (P_1_T != 0) &&
(sigma_2_T != 0.0) && (P_2_T != 0)) {
J_T = 1 + 2 * (P_1_T * log(sigma_1_T) + P_2_T * log(sigma_2_T))
- 2 * (P_1_T * log(P_1_T) + P_2_T * log(P_2_T) );
}
if (criterion > J_T) {
criterion = J_T;
threshold = hist_centre[g];
}
}
return threshold;
}
/*
Kapur, Sahoo & Wong "A new method for Gray-level picture
thresholding using the entropy of the histogram", Computer Vision,
Graphics, and Image Processing, vol 29, pp 273-285, 1985.
*/
#define BIN_TINY 1e-6
static double
kapur_threshold(double histo[], double hist_centre[], int hist_bins)
{
double threshold;
double Phi, Phi_max;
int i, k;
double *p = malloc(sizeof(double) * hist_bins);
double *P = malloc(sizeof(double) * hist_bins);
double *H = malloc(sizeof(double) * hist_bins);
double sum;
sum = 0;
for (i = 0; i < hist_bins; i++) {
sum += histo[i];
}
for (i = 0; i < hist_bins; i++) {
p[i] = histo[i] * 1.0 / sum;
}
P[0] = p[0];
for (i = 1; i < hist_bins; i++) {
P[i] = P[i - 1] + p[i];
}
if (histo[0] == 0) {
H[0] = 0;
}
else {
H[0] = -p[0] * log(p[0]);
}
for (i = 1; i < hist_bins; i++) {
if (histo[i] == 0) {
H[i] = H[i - 1];
}
else {
H[i] = H[i - 1] - p[i] * log(p[i]);
}
}
Phi_max = -10e10;
threshold = hist_centre[hist_bins / 2];
for (k = 0; k <= hist_bins - 1; k++) {
if ((P[k] > BIN_TINY) && (1 - P[k] > BIN_TINY)) {
Phi = log(P[k] * (1 - P[k]))
+ H[k] / P[k]
+ (H[hist_bins - 1] - H[k]) / (1.0 - P[k]);
if (Phi_max < Phi) {
Phi_max = Phi;
threshold = hist_centre[k];
}
}
}
free(p);
free(P);
free(H);
return threshold;
}
int main(int argc, char *argv[])
{
char **infiles;
int nfiles;
Loop_Options *loop_options;
int mincid, imgid;
int idim;
int irange, imask;
double real_range[2], valid_range[2];
nc_type datatype;
int is_signed;
double voxel_to_world[WORLD_NDIMS][WORLD_NDIMS + 1];
Stats_Info *stats;
FILE *FP;
double scale, voxmin, voxmax;
int result_code;
milog_init(argv[0]);
/* Get arguments */
if(ParseArgv(&argc, argv, argTable, 0) || (argc != 2)) {
(void)fprintf(stderr, "\nUsage: %s [options] <infile.mnc>\n", argv[0]);
(void)fprintf(stderr, " %s -help\n\n", argv[0]);
exit(EXIT_FAILURE);
}
nfiles = argc - 1;
infiles = &argv[1];
infiles[1] = &mask_file[0];
if(infiles[1] != NULL) {
nfiles++;
}
/* Check for NaN options */
if(ignoreNaN == DEFAULT_VIO_BOOL) {
ignoreNaN = (fillvalue != -DBL_MAX);
}
if(ignoreNaN && fillvalue == -DBL_MAX) {
fillvalue = 0.0;
}
/* Check range options: not over-specified and put values
in vol_min/vol_max */
verify_range_options(&vol_min, &vol_max, &vol_range, &vol_binvalue);
num_ranges = vol_min.numvalues;
/* Check mask range options: not over-specified and put values
in mask_min/mask_max */
verify_range_options(&mask_min, &mask_max, &mask_range, &mask_binvalue);
num_masks = mask_min.numvalues;
if (mask_file != NULL && num_masks == 1 &&
*mask_min.values == -DBL_MAX && *mask_max.values == DBL_MAX) {
fprintf(stderr,
"%s: Warning: Mask specified without a range. Mask will be ignored.\n",
argv[0]);
}
/* Check histogramming options */
if((discrete_histogram && integer_histogram) ||
((discrete_histogram || integer_histogram) && (hist_bins != BINS_DEFAULT))) {
(void)fprintf(stderr,
"Please specify only -discrete_histogram, -integer_histogram or -bins\n");
exit(EXIT_FAILURE);
}
/* init PctT boolean before checking */
if(pctT >= 0.0) {
PctT = TRUE;
pctT /= 100;
}
else {
pctT = 0.0;
}
/* if nothing selected, do everything */
if(!Vol_Count && !Vol_Per && !Vol && !Min && !Max && !Sum && !Sum2 &&
!Mean && !Variance && !Stddev && !Hist_Count && !Hist_Per &&
!Median && !Majority && !BiModalT && !PctT && !Entropy && !CoM &&
!Skewness && !Kurtosis) {
All = TRUE;
Hist = TRUE;
}
if((hist_file != NULL) || Hist_Count || Hist_Per ||
Median || Majority || BiModalT || PctT || Entropy) {
Hist = TRUE;
}
if(hist_bins <= 0)
Hist = FALSE;
/* do checking on arguments */
if(hist_bins < 1) {
(void)fprintf(stderr, "%s: Must have one or more bins for a histogram\n", argv[0]);
exit(EXIT_FAILURE);
}
if(access(infiles[0], 0) != 0) {
(void)fprintf(stderr, "%s: Couldn't find %s\n", argv[0], infiles[0]);
exit(EXIT_FAILURE);
}
if(infiles[1] != NULL && access(infiles[1], 0) != 0) {
(void)fprintf(stderr, "%s: Couldn't find mask file: %s\n", argv[0], infiles[1]);
exit(EXIT_FAILURE);
}
if(hist_file != NULL && !clobber && access(hist_file, 0) != -1) {
(void)fprintf(stderr, "%s: Histogram %s exists! (use -clobber to overwrite)\n",
argv[0], hist_file);
exit(EXIT_FAILURE);
}
/* Open the file to get some information */
mincid = miopen(infiles[0], NC_NOWRITE);
imgid = ncvarid(mincid, MIimage);
nvoxels = get_minc_nvoxels(mincid);
voxel_volume = get_minc_voxel_volume(mincid);
(void)miget_datatype(mincid, imgid, &datatype, &is_signed);
(void)miget_image_range(mincid, real_range);
(void)miget_valid_range(mincid, imgid, valid_range);
file_ndims = get_minc_ndims(mincid);
find_minc_spatial_dims(mincid, space_to_dim, dim_to_space);
get_minc_voxel_to_world(mincid, voxel_to_world);
/* Check whether discrete histogramming makes sense - i.e. not
floating-point. Silently ignore the option if it does not make sense. */
if(datatype == NC_FLOAT || datatype == NC_DOUBLE) {
discrete_histogram = FALSE;
}
/* set up the histogram definition, if needed */
if(Hist) {
if(hist_range[0] == -DBL_MAX) {
if(vol_min.numvalues == 1 && vol_min.values[0] != -DBL_MAX)
hist_range[0] = vol_min.values[0];
else
hist_range[0] = real_range[0];
}
if(hist_range[1] == DBL_MAX) {
if(vol_max.numvalues == 1 && vol_max.values[0] != DBL_MAX)
hist_range[1] = vol_max.values[0];
else
hist_range[1] = real_range[1];
}
if(discrete_histogram) {
/* Convert histogram range to voxel values and round, then
convert back. */
scale = (real_range[1] == real_range[0]) ? 0.0 :
(valid_range[1] - valid_range[0]) / (real_range[1] - real_range[0]);
voxmin = rint((hist_range[0] - real_range[0]) * scale + valid_range[0]);
voxmax = rint((hist_range[1] - real_range[0]) * scale + valid_range[0]);
if(real_range[1] != real_range[0])
scale = 1.0 / scale;
hist_range[0] = (voxmin - valid_range[0]) * scale + real_range[0];
hist_range[1] = (voxmax - valid_range[0]) * scale + real_range[0];
/* Figure out number of bins and bin width */
hist_bins = voxmax - voxmin;
if(hist_bins <= 0) {
hist_sep = 1.0;
hist_bins = 0;
}
else {
hist_sep = (hist_range[1] - hist_range[0]) / hist_bins;
}
/* Shift the ends of the histogram down and up by half a bin
and add one to the number of bins */
hist_range[0] -= hist_sep / 2.0;
hist_range[1] += hist_sep / 2.0;
hist_bins++;
}
else if(integer_histogram) {
/* Add and subtract the 0.01 in order to ensure that a range that
is already properly specified stays that way. Ie. [-0.5,255.5]
does not change, regardless of the type of rounding done to .5 */
hist_range[0] = (int)rint(hist_range[0] + 0.01);
hist_range[1] = (int)rint(hist_range[1] - 0.01);
hist_bins = hist_range[1] - hist_range[0] + 1.0;
hist_range[0] -= 0.5;
hist_range[1] += 0.5;
hist_sep = 1.0;
}
else {
hist_sep = (hist_range[1] - hist_range[0]) / hist_bins;
}
if((discrete_histogram || integer_histogram) && (hist_bins > max_bins)) {
(void)fprintf(stderr,
"Too many bins in histogram (%d) - please increase -int_max_bins if appropriate\n",
hist_bins);
exit(EXIT_FAILURE);
}
}
/* Initialize the stats structure */
stats_info = malloc(num_ranges * sizeof(*stats_info));
for(irange = 0; irange < num_ranges; irange++) {
stats_info[irange] = malloc(num_masks * sizeof(**stats_info));
for(imask = 0; imask < num_masks; imask++) {
stats = &stats_info[irange][imask];
init_stats(stats, hist_bins);
stats->vol_range[0] = vol_min.values[irange];
stats->vol_range[1] = vol_max.values[irange];
stats->mask_range[0] = mask_min.values[imask];
stats->mask_range[1] = mask_max.values[imask];
}
}
/* Get a quick estimate of the mean to shift values
when calculating the variance */
stats->shift = (real_range[0] + real_range[1])/2.0;
/* Do math */
loop_options = create_loop_options();
set_loop_first_input_mincid(loop_options, mincid);
set_loop_verbose(loop_options, verbose);
set_loop_buffer_size(loop_options, (long)1024 * max_buffer_size_in_kb);
result_code = voxel_loop(nfiles, infiles, 0, NULL, NULL, loop_options,
do_math, NULL);
free_loop_options(loop_options);
/* Open the histogram file if it will be needed */
if(hist_file == NULL) {
FP = NULL;
}
else {
FP = fopen(hist_file, "w");
if(FP == NULL) {
perror("Error opening histogram file");
exit(EXIT_FAILURE);
}
}
/* Loop over ranges and masks, calculating results */
for(irange = 0; irange < num_ranges; irange++) {
for(imask = 0; imask < num_masks; imask++) {
stats = &stats_info[irange][imask];
stats->vol_per = stats->vvoxels / nvoxels * 100;
stats->hist_per = stats->hvoxels / nvoxels * 100;
stats->mean = (stats->vvoxels > 0) ? stats->sum / stats->vvoxels : 0.0;
/* Calculate variance of the shifted values to avoid cancellation issues */
stats->variance =
(stats->vvoxels > 1) ?
(stats->shiftsum2 - SQR(stats->shiftsum) / stats->vvoxels) / (stats->vvoxels - 1)
: 0.0;
stats->stddev = sqrt(stats->variance);
stats->volume = voxel_volume * stats->vvoxels;
for(idim = 0; idim < WORLD_NDIMS; idim++) {
if(stats->sum != 0.0)
stats->voxel_com[idim] = stats->voxel_com_sum[idim] / stats->sum;
else
stats->voxel_com[idim] = 0.0;
}
transform_coord(stats->world_com, voxel_to_world, stats->voxel_com);
/* Do the histogram calculations */