-
Notifications
You must be signed in to change notification settings - Fork 2
/
apriltag_quad_thresh.c
1830 lines (1461 loc) · 55.7 KB
/
apriltag_quad_thresh.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
/* (C) 2013-2015, The Regents of The University of Michigan
All rights reserved.
This software may be available under alternative licensing
terms. Contact Edwin Olson, ebolson@umich.edu, for more information.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
// limitation: image size must be <32768 in width and height. This is
// because we use a fixed-point 16 bit integer representation with one
// fractional bit.
#include <math.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include "apriltag.h"
#include "zarray.h"
#include "zhash.h"
#include "unionfind.h"
#include "timeprofile.h"
#include "zmaxheap.h"
#include "postscript_utils.h"
/*
static inline uint32_t u64hash_1(uint64_t x) {
x = ((x >> 16) ^ x) * 0x45d9f3b;
x = ((x >> 16) ^ x) * 0x45d9f3b;
x = ((x >> 16) ^ x);
return (uint32_t) x;
}
*/
static inline double terrible_atan2_quadrant0(double y, double x)
{
if (x > y)
return y/x;
return 2-x/y;
}
static inline double terrible_atan2(double y, double x)
{
const double K = 2*M_PI / 8;
if (x >= 0) {
if (y >= 0)
return K*terrible_atan2_quadrant0(y, x); // quadrant 1
else
return -K*terrible_atan2_quadrant0(-y, x); // quadrant 4
} else {
if (y >= 0)
return K*(4 - terrible_atan2_quadrant0(y, -x)); // quadrant 2
else
return K*(-4 + terrible_atan2_quadrant0(-y, -x)); // quadrant 3
}
}
static inline uint32_t u64hash_2(uint64_t x) {
return (2654435761 * x) >> 32;
return (uint32_t) x;
}
#define TNAME uint64_zarray_hash
#define TKEYTYPE uint64_t
#define TVALTYPE zarray_t*
#define TKEYHASH(pk) (u64hash_2(*(pk)))
#define TKEYEQUAL(pka, pkb) (*(pka) == *(pkb))
#include "common/thash_impl.h"
#undef TKEYEQUAL
#undef TKEYHASH
#undef TKEYTYPE
#undef TVALTYPE
#undef TNAME
#ifndef M_PI
# define M_PI 3.141592653589793238462643383279502884196
#endif
struct pt
{
// Note: these represent 2*actual value.
uint16_t x, y;
float theta;
};
struct unionfind_task
{
int y0, y1;
int w, h, s;
unionfind_t *uf;
image_u8_t *edgeim;
};
struct quad_task
{
zarray_t *clusters;
int cidx0, cidx1; // [cidx0, cidx1)
zarray_t *quads;
apriltag_detector_t *td;
int w, h;
image_u8_t *im;
};
struct remove_vertex
{
int i; // which vertex to remove?
int left, right; // left vertex, right vertex
double err;
};
struct segment
{
int is_vertex;
// always greater than zero, but right can be > size, which denotes
// a wrap around back to the beginning of the points. and left < right.
int left, right;
};
struct line_fit_pt
{
double Mx, My;
double Mxx, Myy, Mxy;
double W; // total weight
};
static inline double sq(double v)
{
return v*v;
}
static inline int imin(int a, int b)
{
return a < b ? a : b;
}
static inline int imax(int a, int b)
{
return a < b ? b : a;
}
static inline void ptsort(struct pt *pts, int sz)
{
#define MAYBE_SWAP(arr,apos,bpos) \
if (arr[apos].theta > arr[bpos].theta) { \
tmp = arr[apos]; arr[apos] = arr[bpos]; arr[bpos] = tmp; \
};
if (sz <= 1)
return;
if (sz == 2) {
struct pt tmp;
MAYBE_SWAP(pts, 0, 1);
return;
}
// NB: Using less-branch-intensive sorting networks here on the
// hunch that it's better for performance.
if (sz == 3) { // 3 element bubble sort is optimal
struct pt tmp;
MAYBE_SWAP(pts, 0, 1);
MAYBE_SWAP(pts, 1, 2);
MAYBE_SWAP(pts, 0, 1);
return;
}
if (sz == 4) { // 4 element optimal sorting network.
struct pt tmp;
MAYBE_SWAP(pts, 0, 1); // sort each half, like a merge sort
MAYBE_SWAP(pts, 2, 3);
MAYBE_SWAP(pts, 0, 2); // minimum value is now at 0.
MAYBE_SWAP(pts, 1, 3); // maximum value is now at end.
MAYBE_SWAP(pts, 1, 2); // that only leaves the middle two.
return;
}
if (sz == 5) {
// this 9-step swap is optimal for a sorting network, but two
// steps slower than a generic sort.
struct pt tmp;
MAYBE_SWAP(pts, 0, 1); // sort each half (3+2), like a merge sort
MAYBE_SWAP(pts, 3, 4);
MAYBE_SWAP(pts, 1, 2);
MAYBE_SWAP(pts, 0, 1);
MAYBE_SWAP(pts, 0, 3); // minimum element now at 0
MAYBE_SWAP(pts, 2, 4); // maximum element now at end
MAYBE_SWAP(pts, 1, 2); // now resort the three elements 1-3.
MAYBE_SWAP(pts, 2, 3);
MAYBE_SWAP(pts, 1, 2);
return;
}
#undef MAYBE_SWAP
// a merge sort with temp storage.
// Use stack storage if it's not too big.
int stacksz = sz;
if (stacksz > 1024)
stacksz = 0;
struct pt _tmp_stack[stacksz];
struct pt *tmp = _tmp_stack;
if (stacksz == 0) {
// it was too big, malloc it instead.
tmp = malloc(sizeof(struct pt) * sz);
}
memcpy(tmp, pts, sizeof(struct pt) * sz);
int asz = sz/2;
int bsz = sz - asz;
struct pt *as = &tmp[0];
struct pt *bs = &tmp[asz];
ptsort(as, asz);
ptsort(bs, bsz);
#define MERGE(apos,bpos) \
if (as[apos].theta < bs[bpos].theta) \
pts[outpos++] = as[apos++]; \
else \
pts[outpos++] = bs[bpos++];
int apos = 0, bpos = 0, outpos = 0;
while (apos + 8 < asz && bpos + 8 < bsz) {
MERGE(apos,bpos); MERGE(apos,bpos); MERGE(apos,bpos); MERGE(apos,bpos);
MERGE(apos,bpos); MERGE(apos,bpos); MERGE(apos,bpos); MERGE(apos,bpos);
}
while (apos < asz && bpos < bsz) {
MERGE(apos,bpos);
}
if (apos < asz)
memcpy(&pts[outpos], &as[apos], (asz-apos)*sizeof(struct pt));
if (bpos < bsz)
memcpy(&pts[outpos], &bs[bpos], (bsz-bpos)*sizeof(struct pt));
if (stacksz == 0)
free(tmp);
#undef MERGE
}
// lfps contains *cumulative* moments for N points, with
// index j reflecting points [0,j] (inclusive).
//
// fit a line to the points [i0, i1] (inclusive). i0, i1 are both [0,
// sz) if i1 < i0, we treat this as a wrap around.
void fit_line(struct line_fit_pt *lfps, int sz, int i0, int i1, double *lineparm, double *err, double *mse)
{
assert(i0 != i1);
assert(i0 >= 0 && i1 >= 0 && i0 < sz && i1 < sz);
double Mx, My, Mxx, Myy, Mxy, W;
int N; // how many points are included in the set?
if (i0 < i1) {
N = i1 - i0 + 1;
Mx = lfps[i1].Mx;
My = lfps[i1].My;
Mxx = lfps[i1].Mxx;
Mxy = lfps[i1].Mxy;
Myy = lfps[i1].Myy;
W = lfps[i1].W;
if (i0 > 0) {
Mx -= lfps[i0-1].Mx;
My -= lfps[i0-1].My;
Mxx -= lfps[i0-1].Mxx;
Mxy -= lfps[i0-1].Mxy;
Myy -= lfps[i0-1].Myy;
W -= lfps[i0-1].W;
}
} else {
// i0 > i1, e.g. [15, 2]. Wrap around.
assert(i0 > 0);
Mx = lfps[sz-1].Mx - lfps[i0-1].Mx;
My = lfps[sz-1].My - lfps[i0-1].My;
Mxx = lfps[sz-1].Mxx - lfps[i0-1].Mxx;
Mxy = lfps[sz-1].Mxy - lfps[i0-1].Mxy;
Myy = lfps[sz-1].Myy - lfps[i0-1].Myy;
W = lfps[sz-1].W - lfps[i0-1].W;
Mx += lfps[i1].Mx;
My += lfps[i1].My;
Mxx += lfps[i1].Mxx;
Mxy += lfps[i1].Mxy;
Myy += lfps[i1].Myy;
W += lfps[i1].W;
N = sz - i0 + i1 + 1;
}
assert(N >= 2);
double Ex = Mx / W;
double Ey = My / W;
double Cxx = Mxx / W - Ex*Ex;
double Cxy = Mxy / W - Ex*Ey;
double Cyy = Myy / W - Ey*Ey;
double nx, ny;
if (1) {
// on iOS about 5% of total CPU spent in these trig functions.
// 85 ms per frame on 5S, example.pnm
//
// XXX this was using the double-precision atan2. Was there a case where
// we needed that precision? Seems doubtful.
double normal_theta = .5 * atan2f(-2*Cxy, (Cyy - Cxx));
nx = cosf(normal_theta);
ny = sinf(normal_theta);
} else {
// 73.5 ms per frame on 5S, example.pnm
double ty = -2*Cxy;
double tx = (Cyy - Cxx);
double mag = ty*ty + tx*tx;
if (mag == 0) {
nx = 1;
ny = 0;
} else {
double norm = sqrtf(ty*ty + tx*tx);
tx /= norm;
// ty is now sin(2theta)
// tx is now cos(2theta). We want sin(theta) and cos(theta)
// due to precision err, tx could still have slightly too large magnitude.
if (tx > 1) {
ny = 0;
nx = 1;
} else if (tx < -1) {
ny = 1;
nx = 0;
} else {
// half angle formula
ny = sqrtf((1 - tx)/2);
nx = sqrtf((1 + tx)/2);
// pick a consistent branch cut
if (ty < 0)
ny = - ny;
}
}
}
if (lineparm) {
lineparm[0] = Ex;
lineparm[1] = Ey;
lineparm[2] = nx;
lineparm[3] = ny;
}
// sum of squared errors =
//
// SUM_i ((p_x - ux)*nx + (p_y - uy)*ny)^2
// SUM_i nx*nx*(p_x - ux)^2 + 2nx*ny(p_x -ux)(p_y-uy) + ny*ny*(p_y-uy)*(p_y-uy)
// nx*nx*SUM_i((p_x -ux)^2) + 2nx*ny*SUM_i((p_x-ux)(p_y-uy)) + ny*ny*SUM_i((p_y-uy)^2)
//
// nx*nx*N*Cxx + 2nx*ny*N*Cxy + ny*ny*N*Cyy
// sum of squared errors
if (err)
*err = nx*nx*N*Cxx + 2*nx*ny*N*Cxy + ny*ny*N*Cyy;
// mean squared error
if (mse)
*mse = nx*nx*Cxx + 2*nx*ny*Cxy + ny*ny*Cyy;
}
int pt_compare_theta(const void *_a, const void *_b)
{
struct pt *a = (struct pt*) _a;
struct pt *b = (struct pt*) _b;
return (a->theta < b->theta) ? -1 : 1;
}
int err_compare_descending(const void *_a, const void *_b)
{
const double *a = _a;
const double *b = _b;
return ((*a) < (*b)) ? 1 : -1;
}
/*
1. Identify A) white points near a black point and B) black points near a white point.
2. Find the connected components within each of the classes above,
yielding clusters of "white-near-black" and
"black-near-white". (These two classes are kept separate). Each
segment has a unique id.
3. For every pair of "white-near-black" and "black-near-white"
clusters, find the set of points that are in one and adjacent to the
other. In other words, a "boundary" layer between the two
clusters. (This is actually performed by iterating over the pixels,
rather than pairs of clusters.) Critically, this helps keep nearby
edges from becoming connected.
*/
int quad_segment_maxima(apriltag_detector_t *td, zarray_t *cluster, struct line_fit_pt *lfps, int indices[4])
{
int sz = zarray_size(cluster);
// ksz: when fitting points, how many points on either side do we consider?
// (actual "kernel" width is 2ksz).
//
// This value should be about: 0.5 * (points along shortest edge).
//
// If all edges were equally-sized, that would give a value of
// sz/8. We make it somewhat smaller to account for tags at high
// aspects.
// XXX Tunable
int ksz = imin(20, sz / 12);
// can't fit a quad if there are too few points.
if (ksz < 2)
return 0;
// printf("sz %5d, ksz %3d\n", sz, ksz);
double errs[sz];
for (int i = 0; i < sz; i++) {
fit_line(lfps, sz, (i + sz - ksz) % sz, (i + ksz) % sz, NULL, &errs[i], NULL);
}
// apply a low-pass filter to errs
if (1) {
double y[sz];
// how much filter to apply?
// XXX Tunable
double sigma = 1; // was 3
// cutoff = exp(-j*j/(2*sigma*sigma));
// log(cutoff) = -j*j / (2*sigma*sigma)
// log(cutoff)*2*sigma*sigma = -j*j;
// how big a filter should we use? We make our kernel big
// enough such that we represent any values larger than
// 'cutoff'.
// XXX Tunable (though not super useful to change)
double cutoff = 0.05;
int fsz = sqrt(-log(cutoff)*2*sigma*sigma) + 1;
fsz = 2*fsz + 1;
// For default values of cutoff = 0.05, sigma = 3,
// we have fsz = 17.
float f[fsz];
for (int i = 0; i < fsz; i++) {
int j = i - fsz / 2;
f[i] = exp(-j*j/(2*sigma*sigma));
}
for (int iy = 0; iy < sz; iy++) {
double acc = 0;
for (int i = 0; i < fsz; i++) {
acc += errs[(iy + i - fsz / 2 + sz) % sz] * f[i];
}
y[iy] = acc;
}
memcpy(errs, y, sizeof(y));
}
int maxima[sz];
double maxima_errs[sz];
int nmaxima = 0;
for (int i = 0; i < sz; i++) {
if (errs[i] > errs[(i+1)%sz] && errs[i] > errs[(i+sz-1)%sz]) {
maxima[nmaxima] = i;
maxima_errs[nmaxima] = errs[i];
nmaxima++;
}
}
// if we didn't get at least 4 maxima, we can't fit a quad.
if (nmaxima < 4)
return 0;
// select only the best maxima if we have too many
int max_nmaxima = td->qtp.max_nmaxima;
if (nmaxima > max_nmaxima) {
double maxima_errs_copy[nmaxima];
memcpy(maxima_errs_copy, maxima_errs, sizeof(maxima_errs_copy));
// throw out all but the best handful of maxima. Sorts descending.
qsort(maxima_errs_copy, nmaxima, sizeof(double), err_compare_descending);
double maxima_thresh = maxima_errs_copy[max_nmaxima];
int out = 0;
for (int in = 0; in < nmaxima; in++) {
if (maxima_errs[in] <= maxima_thresh)
continue;
maxima[out++] = maxima[in];
}
nmaxima = out;
}
int best_indices[4];
double best_error = HUGE_VALF;
double err01, err12, err23, err30;
double mse01, mse12, mse23, mse30;
double params01[4], params12[4], params23[4], params30[4];
// disallow quads where the angle is less than a critical value.
double max_dot = cos(td->qtp.critical_rad); //25*M_PI/180);
for (int m0 = 0; m0 < nmaxima - 3; m0++) {
int i0 = maxima[m0];
for (int m1 = m0+1; m1 < nmaxima - 2; m1++) {
int i1 = maxima[m1];
fit_line(lfps, sz, i0, i1, params01, &err01, &mse01);
if (mse01 > td->qtp.max_line_fit_mse)
continue;
for (int m2 = m1+1; m2 < nmaxima - 1; m2++) {
int i2 = maxima[m2];
fit_line(lfps, sz, i1, i2, params12, &err12, &mse12);
if (mse12 > td->qtp.max_line_fit_mse)
continue;
double dot = params01[2]*params12[2] + params01[3]*params12[3];
if (fabs(dot) > max_dot)
continue;
for (int m3 = m2+1; m3 < nmaxima; m3++) {
int i3 = maxima[m3];
fit_line(lfps, sz, i2, i3, params23, &err23, &mse23);
if (mse23 > td->qtp.max_line_fit_mse)
continue;
fit_line(lfps, sz, i3, i0, params30, &err30, &mse30);
if (mse30 > td->qtp.max_line_fit_mse)
continue;
double err = err01 + err12 + err23 + err30;
if (err < best_error) {
best_error = err;
best_indices[0] = i0;
best_indices[1] = i1;
best_indices[2] = i2;
best_indices[3] = i3;
}
}
}
}
}
if (best_error == HUGE_VALF)
return 0;
for (int i = 0; i < 4; i++)
indices[i] = best_indices[i];
if (best_error / sz < td->qtp.max_line_fit_mse)
return 1;
return 0;
}
// returns 0 if the cluster looks bad.
int quad_segment_agg(apriltag_detector_t *td, zarray_t *cluster, struct line_fit_pt *lfps, int indices[4])
{
int sz = zarray_size(cluster);
zmaxheap_t *heap = zmaxheap_create(sizeof(struct remove_vertex*));
// We will initially allocate sz rvs. We then have two types of
// iterations: some iterations that are no-ops in terms of
// allocations, and those that remove a vertex and allocate two
// more children. This will happen at most (sz-4) times. Thus we
// need: sz + 2*(sz-4) entries.
int rvalloc_pos = 0;
int rvalloc_size = 3*sz;
struct remove_vertex *rvalloc = calloc(rvalloc_size, sizeof(struct remove_vertex));
struct segment *segs = calloc(sz, sizeof(struct segment));
// populate with initial entries
for (int i = 0; i < sz; i++) {
struct remove_vertex *rv = &rvalloc[rvalloc_pos++];
rv->i = i;
if (i == 0) {
rv->left = sz-1;
rv->right = 1;
} else {
rv->left = i-1;
rv->right = (i+1) % sz;
}
fit_line(lfps, sz, rv->left, rv->right, NULL, NULL, &rv->err);
zmaxheap_add(heap, &rv, -rv->err);
segs[i].left = rv->left;
segs[i].right = rv->right;
segs[i].is_vertex = 1;
}
int nvertices = sz;
while (nvertices > 4) {
assert(rvalloc_pos < rvalloc_size);
struct remove_vertex *rv;
float err;
int res = zmaxheap_remove_max(heap, &rv, &err);
if (!res)
return 0;
assert(res);
// is this remove_vertex valid? (Or has one of the left/right
// vertices changes since we last looked?)
if (!segs[rv->i].is_vertex ||
!segs[rv->left].is_vertex ||
!segs[rv->right].is_vertex) {
continue;
}
// we now merge.
assert(segs[rv->i].is_vertex);
segs[rv->i].is_vertex = 0;
segs[rv->left].right = rv->right;
segs[rv->right].left = rv->left;
// create the join to the left
if (1) {
struct remove_vertex *child = &rvalloc[rvalloc_pos++];
child->i = rv->left;
child->left = segs[rv->left].left;
child->right = rv->right;
fit_line(lfps, sz, child->left, child->right, NULL, NULL, &child->err);
zmaxheap_add(heap, &child, -child->err);
}
// create the join to the right
if (1) {
struct remove_vertex *child = &rvalloc[rvalloc_pos++];
child->i = rv->right;
child->left = rv->left;
child->right = segs[rv->right].right;
fit_line(lfps, sz, child->left, child->right, NULL, NULL, &child->err);
zmaxheap_add(heap, &child, -child->err);
}
// we now have one less vertex
nvertices--;
}
free(rvalloc);
int idx = 0;
for (int i = 0; i < sz; i++) {
if (segs[i].is_vertex) {
indices[idx++] = i;
}
}
free(segs);
return 1;
}
// return 1 if the quad looks okay, 0 if it should be discarded
int fit_quad(apriltag_detector_t *td, image_u8_t *im, zarray_t *cluster, struct quad *quad)
{
int res = 0;
int sz = zarray_size(cluster);
if (sz < 4) // can't fit a quad to less than 4 points
return 0;
/////////////////////////////////////////////////////////////
// Step 1. Sort points so they wrap around the center of the
// quad. We will constrain our quad fit to simply partition this
// ordered set into 4 groups.
// compute a bounding box so that we can order the points
// according to their angle WRT the center.
int32_t xmax = 0, xmin = INT32_MAX, ymax = 0, ymin = INT32_MAX;
for (int pidx = 0; pidx < zarray_size(cluster); pidx++) {
struct pt *p;
zarray_get_volatile(cluster, pidx, &p);
xmax = imax(xmax, p->x);
xmin = imin(xmin, p->x);
ymax = imax(ymax, p->y);
ymin = imin(ymin, p->y);
}
// add some noise to (cx,cy) so that pixels get a more diverse set
// of theta estimates. This will help us remove more points.
// (Only helps a small amount. The actual noise values here don't
// matter much at all, but we want them [-1, 1]. (XXX with
// fixed-point, should range be bigger?)
double cx = (xmin + xmax) * 0.5 + 0.05118;
double cy = (ymin + ymax) * 0.5 + -0.028581;
for (int pidx = 0; pidx < zarray_size(cluster); pidx++) {
struct pt *p;
zarray_get_volatile(cluster, pidx, &p);
double dx = p->x - cx;
double dy = p->y - cy;
p->theta = atan2f(dy, dx);
// p->theta = terrible_atan2(dy, dx);
}
// we now sort the points according to theta. This is a prepatory
// step for segmenting them into four lines.
if (1) {
// zarray_sort(cluster, pt_compare_theta);
ptsort((struct pt*) cluster->data, zarray_size(cluster));
// remove duplicate points. (A byproduct of our segmentation system.)
if (1) {
int outpos = 1;
struct pt *last;
zarray_get_volatile(cluster, 0, &last);
for (int i = 1; i < sz; i++) {
struct pt *p;
zarray_get_volatile(cluster, i, &p);
if (p->x != last->x || p->y != last->y) {
if (i != outpos) {
struct pt *out;
zarray_get_volatile(cluster, outpos, &out);
memcpy(out, p, sizeof(struct pt));
}
outpos++;
}
last = p;
}
cluster->size = outpos;
sz = outpos;
}
} else {
// This is a counting sort in which we retain at most one
// point for every bucket; the bucket index is computed from
// theta. Since a good quad completes a complete revolution,
// there's reason to think that we should get a good
// distribution of thetas. We might "lose" a few points due
// to collisions, but this shouldn't affect quality very much.
// XXX tunable. Increase to reduce the likelihood of "losing"
// points due to collisions.
int nbuckets = 4*sz;
#define ASSOC 2
struct pt v[nbuckets][ASSOC];
memset(v, 0, sizeof(v));
// put each point into a bucket.
for (int i = 0; i < sz; i++) {
struct pt *p;
zarray_get_volatile(cluster, i, &p);
assert(p->theta >= -M_PI && p->theta <= M_PI);
int bucket = (nbuckets - 1) * (p->theta + M_PI) / (2*M_PI);
assert(bucket >= 0 && bucket < nbuckets);
for (int i = 0; i < ASSOC; i++) {
if (v[bucket][i].theta == 0) {
v[bucket][i] = *p;
break;
}
}
}
// collect the points from the buckets and put them back into the array.
int outsz = 0;
for (int i = 0; i < nbuckets; i++) {
for (int j = 0; j < ASSOC; j++) {
if (v[i][j].theta != 0) {
zarray_set(cluster, outsz, &v[i][j], NULL);
outsz++;
}
}
}
zarray_truncate(cluster, outsz);
sz = outsz;
}
if (sz < 4)
return 0;
/////////////////////////////////////////////////////////////
// Step 2. Precompute statistics that allow line fit queries to be
// efficiently computed for any contiguous range of indices.
struct line_fit_pt *lfps = calloc(sz, sizeof(struct line_fit_pt));
for (int i = 0; i < sz; i++) {
struct pt *p;
zarray_get_volatile(cluster, i, &p);
if (i > 0) {
memcpy(&lfps[i], &lfps[i-1], sizeof(struct line_fit_pt));
}
if (0) {
// we now undo our fixed-point arithmetic.
double delta = 0.5;
double x = p->x * .5 + delta;
double y = p->y * .5 + delta;
double W;
for (int dy = -1; dy <= 1; dy++) {
int iy = y + dy;
if (iy < 0 || iy + 1 >= im->height)
continue;
for (int dx = -1; dx <= 1; dx++) {
int ix = x + dx;
if (ix < 0 || ix + 1 >= im->width)
continue;
int grad_x = im->buf[iy * im->stride + ix + 1] -
im->buf[iy * im->stride + ix - 1];
int grad_y = im->buf[(iy+1) * im->stride + ix] -
im->buf[(iy-1) * im->stride + ix];
W = sqrtf(grad_x*grad_x + grad_y*grad_y) + 1;
// double fx = x + dx, fy = y + dy;
double fx = ix + .5, fy = iy + .5;
lfps[i].Mx += W * fx;
lfps[i].My += W * fy;
lfps[i].Mxx += W * fx * fx;
lfps[i].Mxy += W * fx * fy;
lfps[i].Myy += W * fy * fy;
lfps[i].W += W;
}
}
} else {
// we now undo our fixed-point arithmetic.
double delta = 0.5; // adjust for pixel center bias
double x = p->x * .5 + delta;
double y = p->y * .5 + delta;
int ix = x, iy = y;
double W = 1;
if (ix > 0 && ix+1 < im->width && iy > 0 && iy+1 < im->height) {
int grad_x = im->buf[iy * im->stride + ix + 1] -
im->buf[iy * im->stride + ix - 1];
int grad_y = im->buf[(iy+1) * im->stride + ix] -
im->buf[(iy-1) * im->stride + ix];
// XXX Tunable. How to shape the gradient magnitude?
W = sqrt(grad_x*grad_x + grad_y*grad_y) + 1;
}
double fx = x, fy = y;
lfps[i].Mx += W * fx;
lfps[i].My += W * fy;
lfps[i].Mxx += W * fx * fx;
lfps[i].Mxy += W * fx * fy;
lfps[i].Myy += W * fy * fy;
lfps[i].W += W;
}
}
int indices[4];
if (1) {
if (!quad_segment_maxima(td, cluster, lfps, indices))
goto finish;
} else {
if (!quad_segment_agg(td, cluster, lfps, indices))
goto finish;
}
// printf("%d %d %d %d\n", indices[0], indices[1], indices[2], indices[3]);
if (0) {
// no refitting here; just use those points as the vertices.
// Note, this is useful for debugging, but pretty bad in
// practice since this code path also omits several
// plausibility checks that save us tons of time in quad
// decoding.
for (int i = 0; i < 4; i++) {
struct pt *p;
zarray_get_volatile(cluster, indices[i], &p);
quad->p[i][0] = .5*p->x; // undo fixed-point arith.
quad->p[i][1] = .5*p->y;
}
res = 1;
} else {
double lines[4][4];
for (int i = 0; i < 4; i++) {
int i0 = indices[i];
int i1 = indices[(i+1)&3];
if (0) {
// if there are enough points, skip the points near the corners
// (because those tend not to be very good.)
if (i1-i0 > 8) {
int t = (i1-i0)/6;
if (t < 0)
t = -t;
i0 = (i0 + t) % sz;
i1 = (i1 + sz - t) % sz;
}
}
double err;
fit_line(lfps, sz, i0, i1, lines[i], NULL, &err);
// XXX VALUE?
if (err > td->qtp.max_line_fit_mse) {
res = 0;
goto finish;
}
}
for (int i = 0; i < 4; i++) {
// solve for the intersection of lines (i) and (i+1)&3.
// p0 + lambda0*u0 = p1 + lambda1*u1, where u0 and u1
// are the line directions.
//
// lambda0*u0 - lambda1*u1 = (p1 - p0)
//