-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLSD.java
2281 lines (1962 loc) · 69.9 KB
/
LSD.java
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
/*----------------------------------------------------------------------------
LSD - Line Segment Detector on digital images
This code is part of the following publication and was subject
to peer review:
"LSD: a Line Segment Detector" by Rafael Grompone von Gioi,
Jeremie Jakubowicz, Jean-Michel Morel, and Gregory Randall,
Image Processing On Line, 2012. DOI:10.5201/ipol.2012.gjmr-lsd
http://dx.doi.org/10.5201/ipol.2012.gjmr-lsd
Copyright (c) 2007-2011 rafael grompone von gioi <grompone@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** @file lsd.c
LSD module code
@author rafael grompone von gioi <grompone@gmail.com>
Java port
@author chris anfractuosity.com
*/
/*----------------------------------------------------------------------------*/
/** @mainpage LSD code documentation
This is an implementation of the Line Segment Detector described
in the paper:
"LSD: A Fast Line Segment Detector with a False Detection Control"
by Rafael Grompone von Gioi, Jeremie Jakubowicz, Jean-Michel Morel,
and Gregory Randall, IEEE Transactions on Pattern Analysis and
Machine Intelligence, vol. 32, no. 4, pp. 722-732, April, 2010.
and in more details in the CMLA Technical Report:
"LSD: A Line Segment Detector, Technical Report",
by Rafael Grompone von Gioi, Jeremie Jakubowicz, Jean-Michel Morel,
Gregory Randall, CMLA, ENS Cachan, 2010.
The version implemented here includes some further improvements
described in the following publication, of which this code is part:
"LSD: a Line Segment Detector" by Rafael Grompone von Gioi,
Jeremie Jakubowicz, Jean-Michel Morel, and Gregory Randall,
Image Processing On Line, 2012. DOI:10.5201/ipol.2012.gjmr-lsd
http://dx.doi.org/10.5201/ipol.2012.gjmr-lsd
The module's main function is lsd().
The source code is contained in two files: lsd.h and lsd.c.
HISTORY:
- version 1.6 - nov 2011:
- changes in the interface,
- max_grad parameter removed,
- the factor 11 was added to the number of test
to consider the different precision values
tested,
- a minor bug corrected in the gradient sorting
code,
- the algorithm now also returns p and log_nfa
for each detection,
- a minor bug was corrected in the image scaling,
- the angle comparison in "isaligned" changed
from < to <=,
- "eps" variable renamed "log_eps",
- "lsd_scale_region" interface was added,
- minor changes to comments.
- version 1.5 - dec 2010: Changes in 'refine', -W option added,
and more comments added.
- version 1.4 - jul 2010: lsd_scale interface added and doxygen doc.
- version 1.3 - feb 2010: Multiple bug correction and improved code.
- version 1.2 - dec 2009: First full Ansi C Language version.
- version 1.1 - sep 2009: Systematic subsampling to scale 0.8 and
correction to partially handle "angle problem".
- version 1.0 - jan 2009: First complete Megawave2 and Ansi C Language
version.
@author rafael grompone von gioi <grompone@gmail.com>
*/
/*----------------------------------------------------------------------------*/
import java.util.ArrayList;
import java.awt.Point;
/*----------------------------------------------------------------------------*/
/** Rectangle points iterator.
The integer coordinates of pixels inside a rectangle are
iteratively explored. This structure keep track of the fprocess and
functions ri_ini(), ri_inc(), ri_end(), and ri_del() are used in
the process. An example of how to use the iterator is as follows:
\code
struct rect * rec = XXX; // some rectangle
rect_iter * i;
for( i=ri_ini(rec); !ri_end(i); ri_inc(i) )
{
// your code, using 'i->x' and 'i->y' as coordinates
}
ri_del(i); // delete iterator
\endcode
The pixels are explored 'column' by 'column', where we call
'column' a set of pixels with the same x value that are inside the
rectangle. The following is an schematic representation of a
rectangle, the 'column' being explored is marked by colons, and
the current pixel being explored is 'x,y'.
\verbatim
vx[1],vy[1]
* *
* *
* *
* ye
* : *
vx[0],vy[0] : *
* : *
* x,y *
* : *
* : vx[2],vy[2]
* : *
y ys *
^ * *
| * *
| * *
+---> x vx[3],vy[3]
\endverbatim
The first 'column' to be explored is the one with the smaller x
value. Each 'column' is explored starting from the pixel of the
'column' (inside the rectangle) with the smallest y value.
The four corners of the rectangle are stored in order that rotates
around the corners at the arrays 'vx[]' and 'vy[]'. The first
point is always the one with smaller x value.
'x' and 'y' are the coordinates of the pixel being explored. 'ys'
and 'ye' are the start and end values of the current column being
explored. So, 'ys' < 'ye'.
*/
class rect_itr {
double[] vx; /* rectangle's corner X coordinates in circular order */
double[] vy; /* rectangle's corner Y coordinates in circular order */
double ys, ye; /* start and end Y values of current 'column' */
int x, y; /* coordinates of currently explored pixel */
rect_itr() {
vx = new double[4];
vy = new double[4];
}
}
class image_double {
double[] data;
int xsize, ysize;
image_double(int xsize, int ysize) {
this.xsize = xsize;
this.ysize = ysize;
data = new double[xsize * ysize];
}
image_double(int xsize, int ysize, double[] data) {
this.xsize = xsize;
this.ysize = ysize;
this.data = data;
}
}
/*----------------------------------------------------------------------------*/
/**
* Chained list of coordinates.
*/
class coorlist {
int x, y;
coorlist next;
};
public class LSD {
double[] inv = new double[TABSIZE]; /*
* table to keep computed inverse
* values
*/
/** ln(10) */
double M_LN10 = 2.30258509299404568402;
/** PI */
double M_PI = 3.14159265358979323846;
int FALSE = 0;
int TRUE = 1;
/** Label for pixels with undefined gradient. */
double NOTDEF = -1024.0;
/** 3/2 pi */
double M_3_2_PI = 4.71238898038;
/** 2 pi */
double M_2__PI = 6.28318530718;
/** Label for pixels not used in yet. */
int NOTUSED = 0;
/** Label for pixels already used in detection. */
int USED = 1;
/*----------------------------------------------------------------------------*/
/**
* Chained list of coordinates.
*/
class Coorlist {
int x, y;
Coorlist next;
};
void error(String msg) {
System.err.println("LSD Error: " + msg);
throw new RuntimeException("major error");
}
/*----------------------------------------------------------------------------*/
/**
* Doubles relative error factor
*/
double RELATIVE_ERROR_FACTOR = 100.0;
private double calculateMachineEpsilonDouble() {
float machEps = 1.0f;
do
machEps /= 2.0f;
while ((double) (1.0 + (machEps / 2.0)) != 1.0);
return machEps;
}
/*----------------------------------------------------------------------------*/
/**
* Compare doubles by relative error.
*
* The resulting rounding error after floating point computations depend on
* the specific operations done. The same number computed by different
* algorithms could present different rounding errors. For a useful
* comparison, an estimation of the relative rounding error should be
* considered and compared to a factor times EPS. The factor should be
* related to the cumulated rounding error in the chain of computation.
* Here, as a simplification, a fixed factor is used.
*/
boolean double_equal(double a, double b) {
double abs_diff, aa, bb, abs_max;
/* trivial case */
if (a == b)
return true;
abs_diff = Math.abs(a - b);
aa = Math.abs(a);
bb = Math.abs(b);
abs_max = aa > bb ? aa : bb;
/*
* DBL_MIN is the smallest normalized number, thus, the smallest number
* whose relative error is bounded by DBL_EPSILON. For smaller numbers,
* the same quantization steps as for DBL_MIN are used. Then, for
* smaller numbers, a meaningful "relative" error should be computed by
* dividing the difference by DBL_MIN.
*/
if (abs_max < -Double.MAX_VALUE)
abs_max = -Double.MAX_VALUE;
/* equal if relative error <= factor x eps */
return (abs_diff / abs_max) <= (RELATIVE_ERROR_FACTOR * calculateMachineEpsilonDouble());
}
/*----------------------------------------------------------------------------*/
/**
* Computes Euclidean distance between point (x1,y1) and point (x2,y2).
*/
static double dist(double x1, double y1, double x2, double y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
/*----------------------------------------------------------------------------*/
/*----------------------- 'list of n-tuple' data type ------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/**
* 'list of n-tuple' data type
*
* The i-th component of the j-th n-tuple of an n-tuple list 'ntl' is
* accessed with:
*
* ntl.values[ i + j * ntl.dim ]
*
* The dimension of the n-tuple (n) is:
*
* ntl.dim
*
* The number of n-tuples in the list is:
*
* ntl.size
*
* The maximum number of n-tuples that can be stored in the list with the
* allocated memory at a given time is given by:
*
* ntl.max_size
*/
class ntuple_list {
int size;
int max_size;
int dim;
double[] values;
/*----------------------------------------------------------------------------*/
/**
* Create an n-tuple list and allocate memory for one element.
*
* @param dim
* the dimension (n) of the n-tuple.
*/
ntuple_list(int dim) {
/* check parameters */
if (dim == 0)
error("new_ntuple_list: 'dim' must be positive.");
/* initialize list */
size = 0;
max_size = 1;
this.dim = dim;
/* get memory for tuples */
// n_tuple.values = new ArrayList(); (double *) malloc( *
// sizeof(double)
// );
// if( n_tuple.values == NULL ) error("not enough memory.");
values = new double[dim * max_size];
}
}
/*----------------------------------------------------------------------------*/
/**
* Enlarge the allocated memory of an n-tuple list.
*/
void enlarge_ntuple_list(ntuple_list n_tuple) {
/* check parameters */
// if( n_tuple == null || n_tuple.values == null || n_tuple.max_size ==
// 0 )
// error("enlarge_ntuple_list: invalid n-tuple.");
/* duplicate number of tuples */
n_tuple.max_size *= 2;
/* realloc memory */
//System.out.println("THIS IS ACTUALLY WRONG!!!!!!!!!!");
int oldlen = n_tuple.values.length;
double [] arr = new double[n_tuple.dim * n_tuple.max_size];
for(int i=0; i < oldlen; i++){
arr[i] = n_tuple.values[i];
}
n_tuple.values = arr;
}
/*----------------------------------------------------------------------------*/
/**
* Add a 7-tuple to an n-tuple list.
*/
void add_7tuple(ntuple_list out, double v1, double v2, double v3,
double v4, double v5, double v6, double v7) {
/* check parameters */
if (out == null)
error("add_7tuple: invalid n-tuple input.");
if (out.dim != 7)
error("add_7tuple: the n-tuple must be a 7-tuple.");
/* if needed, alloc more tuples to 'out' */
if (out.size == out.max_size)
enlarge_ntuple_list(out);
if (out.values == null)
error("add_7tuple: invalid n-tuple input.");
/* add new 7-tuple */
out.values[out.size * out.dim + 0] = v1;
out.values[out.size * out.dim + 1] = v2;
out.values[out.size * out.dim + 2] = v3;
out.values[out.size * out.dim + 3] = v4;
out.values[out.size * out.dim + 4] = v5;
out.values[out.size * out.dim + 5] = v6;
out.values[out.size * out.dim + 6] = v7;
/* update number of tuples counter */
out.size++;
}
/*----------------------------------------------------------------------------*/
/*----------------------------- Image Data Types -----------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/**
* char image data type
*
* The pixel value at (x,y) is accessed by:
*
* image.data[ x + y * image.xsize ]
*
* with x and y integer.
*/
class image_char {
int[] data;
int xsize, ysize;
image_char(int xsize, int ysize) {
this.xsize = xsize;
this.ysize = ysize;
}
image_char(int xsize, int ysize, int fill_value) {
data = new int[xsize * ysize]; /* create image */
int N = xsize * ysize;
int i;
/* initialize */
for (i = 0; i < N; i++)
data[i] = fill_value;
this.xsize = xsize;
this.ysize = ysize;
}
}
class image_int {
int[] data;
int xsize, ysize;
image_int(int xsize, int ysize) {
this.xsize = xsize;
this.ysize = ysize;
}
image_int(int xsize, int ysize, int fill_value) {
data = new int[xsize * ysize]; /* create image */
int N = xsize * ysize;
int i;
/* initialize */
for (i = 0; i < N; i++)
data[i] = fill_value;
}
}
class rect {
double x1, y1, x2, y2; /* first and second point of the line segment */
double width; /* rectangle width */
double x, y; /* center of the rectangle */
double theta; /* angle */
double dx, dy; /* (dx,dy) is vector oriented as the line segment */
double prec; /* tolerance angle */
double p; /* probability of a point with angle within 'prec' */
};
image_double new_image_double_ptr(int xsize, int ysize, double[] data) {
image_double image = new image_double(xsize, ysize);
/* check parameters */
if (xsize == 0 || ysize == 0)
error("new_image_double_ptr: invalid image size.");
/* set image */
image.data = data;
return image;
}
/*----------------------------------------------------------------------------*/
/*----------------------------- NFA computation ------------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/**
* Computes the natural logarithm of the absolute value of the gamma
* function of x using the Lanczos approximation. See
* http://www.rskey.org/gamma.htm
*
* The formula used is
*
* @f[ \Gamma(x) = \frac{ \sum_{n=0}^{N} q_n x^n }{ \Pi_{n=0}^{N} (x+n) }
* (x+5.5)^{x+0.5} e^{-(x+5.5)}
* @f] so
* @f[ \log\Gamma(x) = \log\left( \sum_{n=0}^{N} q_n x^n \right) + (x+0.5)
* \log(x+5.5) - (x+5.5) - \sum_{n=0}^{N} \log(x+n)
* @f] and q0 = 75122.6331530, q1 = 80916.6278952, q2 = 36308.2951477, q3 =
* 8687.24529705, q4 = 1168.92649479, q5 = 83.8676043424, q6 =
* 2.50662827511.
*/
double log_gamma_lanczos(double x) {
double[] q = { 75122.6331530, 80916.6278952, 36308.2951477,
8687.24529705, 1168.92649479, 83.8676043424, 2.50662827511 };
double a = (x + 0.5) * Math.log(x + 5.5) - (x + 5.5);
double b = 0.0;
int n;
for (n = 0; n < 7; n++) {
a -= Math.log(x + (double) n);
b += q[n] * Math.pow(x, (double) n);
}
return a + Math.log(b);
}
/*----------------------------------------------------------------------------*/
/**
* Computes the natural logarithm of the absolute value of the gamma
* function of x using Windschitl method. See http://www.rskey.org/gamma.htm
*
* The formula used is
*
* @f[ \Gamma(x) = \sqrt{\frac{2\pi}{x}} \left( \frac{x}{e} \sqrt{
* x\sinh(1/x) + \frac{1}{810x^6} } \right)^x
* @f] so
* @f[ \log\Gamma(x) = 0.5\log(2\pi) + (x-0.5)\log(x) - x + 0.5x\log\left(
* x\sinh(1/x) + \frac{1}{810x^6} \right).
* @f] This formula is a good approximation when x > 15.
*/
double log_gamma_windschitl(double x) {
return 0.918938533204673
+ (x - 0.5)
* Math.log(x)
- x
+ 0.5
* x
* Math.log(x * Math.sinh(1 / x) + 1
/ (810.0 * Math.pow(x, 6.0)));
}
/*----------------------------------------------------------------------------*/
/**
* Computes the natural logarithm of the absolute value of the gamma
* function of x. When x>15 use log_gamma_windschitl(), otherwise use
* log_gamma_lanczos().
*/
double log_gamma(double x) {
return ((x) > 15.0 ? log_gamma_windschitl(x) : log_gamma_lanczos(x));
}
/*----------------------------------------------------------------------------*/
/**
* Size of the table to store already computed inverse values.
*/
static int TABSIZE = 100000;
/*----------------------------------------------------------------------------*/
/**
* Computes -log10(NFA).
*
* NFA stands for Number of False Alarms:
*
* @f[ \mathrm{NFA} = NT \cdot B(n,k,p)
* @f]
*
* - NT - number of tests - B(n,k,p) - tail of binomial distribution
* with parameters n,k and p:
* @f[ B(n,k,p) = \sum_{j=k}^n \left(\begin{array}{c}n\\j\end{array}\right)
* p^{j} (1-p)^{n-j}
* @f]
*
* The value -log10(NFA) is equivalent but more intuitive than NFA: - -1
* corresponds to 10 mean false alarms - 0 corresponds to 1 mean false
* alarm - 1 corresponds to 0.1 mean false alarms - 2 corresponds to
* 0.01 mean false alarms - ...
*
* Used this way, the bigger the value, better the detection, and a
* logarithmic scale is used.
* @param n
* ,k,p binomial parameters.
* @param logNT
* logarithm of Number of Tests
*
* The computation is based in the gamma function by the
* following relation:
* @f[ \left(\begin{array}{c}n\\k\end{array}\right) = \frac{ \Gamma(n+1) }{
* \Gamma(k+1) \cdot \Gamma(n-k+1) }.
* @f] We use efficient algorithms to compute the logarithm of the gamma
* function.
*
* To make the computation faster, not all the sum is computed, part of
* the terms are neglected based on a bound to the error obtained (an
* error of 10% in the result is accepted).
*/
double nfa(int n, int k, double p, double logNT) {
double tolerance = 0.1; /* an error of 10% in the result is accepted */
double log1term, term, bin_term, mult_term, bin_tail, err, p_term;
int i;
/* check parameters */
if (n < 0 || k < 0 || k > n || p <= 0.0 || p >= 1.0)
error("nfa: wrong n, k or p values.");
/* trivial cases */
if (n == 0 || k == 0)
return -logNT;
if (n == k)
return -logNT - (double) n * Math.log10(p);
/* probability term */
p_term = p / (1.0 - p);
/* compute the first term of the series */
/*
* binomial_tail(n,k,p) = sum_{i=k}^n bincoef(n,i) * p^i * (1-p)^{n-i}
* where bincoef(n,i) are the binomial coefficients. But bincoef(n,k) =
* gamma(n+1) / ( gamma(k+1) * gamma(n-k+1) ). We use this to compute
* the first term. Actually the log of it.
*/
log1term = log_gamma((double) n + 1.0) - log_gamma((double) k + 1.0)
- log_gamma((double) (n - k) + 1.0) + (double) k * Math.log(p)
+ (double) (n - k) * Math.log(1.0 - p);
term = Math.exp(log1term);
/* in some cases no more computations are needed */
if (double_equal(term, 0.0)) /* the first term is almost zero */
{
if ((double) k > (double) n * p) /* at begin or end of the tail? */
return -log1term / M_LN10 - logNT; /*
* end: use just the first
* term
*/
else
return -logNT; /* begin: the tail is roughly 1 */
}
/* compute more terms if needed */
bin_tail = term;
for (i = k + 1; i <= n; i++) {
/*
* As term_i = bincoef(n,i) * p^i * (1-p)^(n-i) and
* bincoef(n,i)/bincoef(n,i-1) = n-1+1 / i, then, term_i / term_i-1
* = (n-i+1)/i * p/(1-p) and term_i = term_i-1 * (n-i+1)/i *
* p/(1-p). 1/i is stored in a table as they are computed, because
* divisions are expensive. p/(1-p) is computed only once and stored
* in 'p_term'.
*/
bin_term = (double) (n - i + 1)
* (i < TABSIZE ? (inv[i] != 0.0 ? inv[i]
: (inv[i] = 1.0 / (double) i)) : 1.0 / (double) i);
mult_term = bin_term * p_term;
term *= mult_term;
bin_tail += term;
if (bin_term < 1.0) {
/*
* When bin_term<1 then mult_term_j<mult_term_i for j>i. Then,
* the error on the binomial tail when truncated at the i term
* can be bounded by a geometric series of form term_i * sum
* mult_term_i^j.
*/
err = term
* ((1.0 - Math.pow(mult_term, (double) (n - i + 1)))
/ (1.0 - mult_term) - 1.0);
/*
* One wants an error at most of tolerance*final_result, or:
* tolerance * abs(-log10(bin_tail)-logNT). Now, the error that
* can be accepted on bin_tail is given by
* tolerance*final_result divided by the derivative of -log10(x)
* when x=bin_tail. that is: tolerance *
* abs(-log10(bin_tail)-logNT) / (1/bin_tail) Finally, we
* truncate the tail if the error is less than: tolerance *
* abs(-log10(bin_tail)-logNT) * bin_tail
*/
if (err < tolerance * Math.abs(-Math.log10(bin_tail) - logNT)
* bin_tail)
break;
}
}
return -Math.log10(bin_tail) - logNT;
}
/*----------------------------------------------------------------------------*/
/*----------------------------- Gaussian filter ------------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/**
* Compute a Gaussian kernel of length 'kernel->dim', standard deviation
* 'sigma', and centered at value 'mean'.
*
* For example, if mean=0.5, the Gaussian will be centered in the middle
* point between values 'kernel->values[0]' and 'kernel->values[1]'.
*/
void gaussian_kernel(ntuple_list kernel, double sigma, double mean) {
double sum = 0.0;
double val;
int i;
/* check parameters */
if (kernel == null || kernel.values == null)
error("gaussian_kernel: invalid n-tuple 'kernel'.");
if (sigma <= 0.0)
error("gaussian_kernel: 'sigma' must be positive.");
/* compute Gaussian kernel */
if (kernel.max_size < 1)
enlarge_ntuple_list(kernel);
kernel.size = 1;
for (i = 0; i < kernel.dim; i++) {
val = ((double) i - mean) / sigma;
kernel.values[i] = Math.exp(-0.5 * val * val);
sum += kernel.values[i];
}
/* normalization */
if (sum >= 0.0)
for (i = 0; i < kernel.dim; i++)
kernel.values[i] /= sum;
}
/*----------------------------------------------------------------------------*/
/**
* Scale the input image 'in' by a factor 'scale' by Gaussian sub-sampling.
*
* For example, scale=0.8 will give a result at 80% of the original size.
*
* The image is convolved with a Gaussian kernel
*
* @f[ G(x,y) = \frac{1}{2\pi\sigma^2} e^{-\frac{x^2+y^2}{2\sigma^2}}
* @f] before the sub-sampling to prevent aliasing.
*
* The standard deviation sigma given by: - sigma = sigma_scale / scale,
* if scale < 1.0 - sigma = sigma_scale, if scale >= 1.0
*
* To be able to sub-sample at non-integer steps, some interpolation is
* needed. In this implementation, the interpolation is done by the
* Gaussian kernel, so both operations (filtering and sampling) are done
* at the same time. The Gaussian kernel is computed centered on the
* coordinates of the required sample. In this way, when applied, it
* gives directly the result of convolving the image with the kernel and
* interpolated to that particular position.
*
* A fast algorithm is done using the separability of the Gaussian
* kernel. Applying the 2D Gaussian kernel is equivalent to applying
* first a horizontal 1D Gaussian kernel and then a vertical 1D Gaussian
* kernel (or the other way round). The reason is that
* @f[ G(x,y) = G(x) * G(y)
* @f] where
* @f[ G(x) = \frac{1}{\sqrt{2\pi}\sigma} e^{-\frac{x^2}{2\sigma^2}}.
* @f] The algorithm first applies a combined Gaussian kernel and sampling
* in the x axis, and then the combined Gaussian kernel and sampling in
* the y axis.
*/
image_double gaussian_sampler(image_double in, double scale,
double sigma_scale) {
image_double aux, out;
ntuple_list kernel;
int N, M, h, n, x, y, i;
int xc, yc, j, double_x_size, double_y_size;
double sigma, xx, yy, sum, prec;
/* check parameters */
if (in == null || in.data == null || in.xsize == 0 || in.ysize == 0)
error("gaussian_sampler: invalid image.");
if (scale <= 0.0)
error("gaussian_sampler: 'scale' must be positive.");
if (sigma_scale <= 0.0)
error("gaussian_sampler: 'sigma_scale' must be positive.");
/* compute new image size and get memory for images */
if (in.xsize * scale > (double) Integer.MAX_VALUE
|| in.ysize * scale > (double) Integer.MAX_VALUE)
error("gaussian_sampler: the output image size exceeds the handled size.");
N = (int) Math.ceil(in.xsize * scale);
M = (int) Math.ceil(in.ysize * scale);
aux = new image_double(N, in.ysize);
out = new image_double(N, M);
/* sigma, kernel size and memory for the kernel */
sigma = scale < 1.0 ? sigma_scale / scale : sigma_scale;
/*
* The size of the kernel is selected to guarantee that the the first
* discarded term is at least 10^prec times smaller than the central
* value. For that, h should be larger than x, with e^(-x^2/2sigma^2) =
* 1/10^prec. Then, x = sigma * sqrt( 2 * prec * ln(10) ).
*/
prec = 3.0;
h = (int) Math.ceil(sigma * Math.sqrt(2.0 * prec * Math.log(10.0)));
n = 1 + 2 * h; /* kernel size */
kernel = new ntuple_list(n);
/* auxiliary double image size variables */
double_x_size = (int) (2 * in.xsize);
double_y_size = (int) (2 * in.ysize);
/* First subsampling: x axis */
for (x = 0; x < aux.xsize; x++) {
/*
* x is the coordinate in the new image. xx is the corresponding
* x-value in the original size image. xc is the integer value, the
* pixel coordinate of xx.
*/
xx = (double) x / scale;
/*
* coordinate (0.0,0.0) is in the center of pixel (0,0), so the
* pixel with xc=0 get the values of xx from -0.5 to 0.5
*/
xc = (int) Math.floor(xx + 0.5);
gaussian_kernel(kernel, sigma, (double) h + xx - (double) xc);
/*
* the kernel must be computed for each x because the fine offset
* xx-xc is different in each case
*/
for (y = 0; y < aux.ysize; y++) {
sum = 0.0;
for (i = 0; i < kernel.dim; i++) {
j = xc - h + i;
/* symmetry boundary condition */
while (j < 0)
j += double_x_size;
while (j >= double_x_size)
j -= double_x_size;
if (j >= (int) in.xsize)
j = double_x_size - 1 - j;
sum += in.data[j + y * in.xsize] * kernel.values[i];
}
aux.data[x + y * aux.xsize] = sum;
}
}
/* Second subsampling: y axis */
for (y = 0; y < out.ysize; y++) {
/*
* y is the coordinate in the new image. yy is the corresponding
* x-value in the original size image. yc is the integer value, the
* pixel coordinate of xx.
*/
yy = (double) y / scale;
/*
* coordinate (0.0,0.0) is in the center of pixel (0,0), so the
* pixel with yc=0 get the values of yy from -0.5 to 0.5
*/
yc = (int) Math.floor(yy + 0.5);
gaussian_kernel(kernel, sigma, (double) h + yy - (double) yc);
/*
* the kernel must be computed for each y because the fine offset
* yy-yc is different in each case
*/
for (x = 0; x < out.xsize; x++) {
sum = 0.0;
for (i = 0; i < kernel.dim; i++) {
j = yc - h + i;
/* symmetry boundary condition */
while (j < 0)
j += double_y_size;
while (j >= double_y_size)
j -= double_y_size;
if (j >= (int) in.ysize)
j = double_y_size - 1 - j;
sum += aux.data[x + j * aux.xsize] * kernel.values[i];
}
out.data[x + y * out.xsize] = sum;
}
}
return out;
}
/*----------------------------------------------------------------------------*/
/*--------------------------------- Gradient ---------------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/**
* Computes the direction of the level line of 'in' at each point.
*
* The result is: - an image_double with the angle at each pixel, or NOTDEF
* if not defined. - the image_double 'modgrad' (a pointer is passed as
* argument) with the gradient magnitude at each point. - a list of pixels
* 'list_p' roughly ordered by decreasing gradient magnitude. (The order is
* made by classifying points into bins by gradient magnitude. The
* parameters 'n_bins' and 'max_grad' specify the number of bins and the
* gradient modulus at the highest bin. The pixels in the list would be in
* decreasing gradient magnitude, up to a precision of the size of the
* bins.) - a pointer 'mem_p' to the memory used by 'list_p' to be able to
* free the memory when it is not used anymore.
*/
image_double modgrad;
coorlist[] mem_p;
coorlist list_p;
image_double ll_angle(image_double in, double threshold,
/* coorlist [] list_p, *//* void ** mem_p, */
/* image_double modgrad, */int n_bins) {
image_double g;
int n, p, x, y, adr, i;
double com1, com2, gx, gy, norm, norm2;
/*
* the rest of the variables are used for pseudo-ordering the gradient
* magnitude values
*/
int list_count = 0;
coorlist[] list;
coorlist[] range_l_s; /* array of pointers to start of bin list */
coorlist[] range_l_e; /* array of pointers to end of bin list */
coorlist start;
coorlist end;
double max_grad = 0.0;
/* check parameters */
if (in == null || in.data == null || in.xsize == 0 || in.ysize == 0)
error("ll_angle: invalid image.");
if (threshold < 0.0)
error("ll_angle: 'threshold' must be positive.");
if (list_p == null) {
error("ll_angle: null pointer 'list_p'.");
// list_p = new coorlist();
}
// if (mem_p == null)
// error("ll_angle: null pointer 'mem_p'.");
// if (modgrad == null)
// error("ll_angle: null pointer 'modgrad'.");
if (n_bins == 0)
error("ll_angle: 'n_bins' must be positive.");
/* image size shortcuts */
n = in.ysize;
p = in.xsize;
list = new coorlist[n * p];
for (int z = 0; z < n * p; z++) {
list[z] = new coorlist();
}
mem_p = list;
/* allocate output image */
g = new image_double(in.xsize, in.ysize);
/* get memory for the image of gradient modulus */
modgrad = new image_double(in.xsize, in.ysize);
/* get memory for "ordered" list of pixels */
// list = new coorlist[n * p];// (struct coorlist *) calloc( (size_t)
// (n*p), sizeof(struct coorlist) );
range_l_s = new coorlist[n_bins];
range_l_e = new coorlist[n_bins];
if (list == null || range_l_s == null || range_l_e == null)
error("not enough memory.");
for (i = 0; i < n_bins; i++) {