-
Notifications
You must be signed in to change notification settings - Fork 536
/
apriltag_quad_thresh.c
2002 lines (1623 loc) · 61.3 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
/* Copyright (C) 2013-2016, The Regents of The University of Michigan.
All rights reserved.
This software was developed in the APRIL Robotics Lab under the
direction of Edwin Olson, [email protected]. This software may be
available under alternative licensing terms; contact the address above.
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 Regents of The University of Michigan.
*/
// 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.
#define _USE_MATH_DEFINES
#include <math.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include "apriltag.h"
#include "common/image_u8x3.h"
#include "common/zarray.h"
#include "common/unionfind.h"
#include "common/timeprofile.h"
#include "common/zmaxheap.h"
#include "common/postscript_utils.h"
#include "common/math_util.h"
#ifdef _WIN32
static inline long int random(void)
{
return rand();
}
#endif
static inline uint32_t u64hash_2(uint64_t x) {
return (2654435761 * x) >> 32;
}
struct uint64_zarray_entry
{
uint64_t id;
zarray_t *cluster;
struct uint64_zarray_entry *next;
};
struct pt
{
// Note: these represent 2*actual value.
uint16_t x, y;
int16_t gx, gy;
float slope;
};
struct unionfind_task
{
int y0, y1;
int w, h, s;
unionfind_t *uf;
image_u8_t *im;
};
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;
int tag_width;
bool normal_border;
bool reversed_border;
};
struct cluster_task
{
int y0;
int y1;
int w;
int s;
int nclustermap;
unionfind_t* uf;
image_u8_t* im;
zarray_t* clusters;
};
struct minmax_task {
int ty;
image_u8_t *im;
uint8_t *im_max;
uint8_t *im_min;
};
struct blur_task {
int ty;
image_u8_t *im;
uint8_t *im_max;
uint8_t *im_min;
uint8_t *im_max_tmp;
uint8_t *im_min_tmp;
};
struct threshold_task {
int ty;
apriltag_detector_t *td;
image_u8_t *im;
image_u8_t *threshim;
uint8_t *im_max;
uint8_t *im_min;
};
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
};
struct cluster_hash
{
uint32_t hash;
uint64_t id;
zarray_t* data;
};
// 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;
//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_old = cosf(normal_theta);
// ny_old = sinf(normal_theta);
//}
// Instead of using the above cos/sin method, pose it as an eigenvalue problem.
double eig_small = 0.5*(Cxx + Cyy - sqrtf((Cxx - Cyy)*(Cxx - Cyy) + 4*Cxy*Cxy));
if (lineparm) {
lineparm[0] = Ex;
lineparm[1] = Ey;
double eig = 0.5*(Cxx + Cyy + sqrtf((Cxx - Cyy)*(Cxx - Cyy) + 4*Cxy*Cxy));
double nx1 = Cxx - eig;
double ny1 = Cxy;
double M1 = nx1*nx1 + ny1*ny1;
double nx2 = Cxy;
double ny2 = Cyy - eig;
double M2 = nx2*nx2 + ny2*ny2;
double nx, ny, M;
if (M1 > M2) {
nx = nx1;
ny = ny1;
M = M1;
} else {
nx = nx2;
ny = ny2;
M = M2;
}
double length = sqrtf(M);
if (fabs(length) < 1e-12) {
lineparm[2] = lineparm[3] = 0;
}
else {
lineparm[2] = nx/length;
lineparm[3] = ny/length;
}
}
// 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 = N*eig_small;
// mean squared error
if (mse)
*mse = eig_small;
}
float pt_compare_angle(struct pt *a, struct pt *b) {
return a->slope - b->slope;
}
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. Maybe make a multiple of JPEG block size to increase robustness
// to JPEG compression artifacts?
int ksz = imin(20, sz / 12);
// can't fit a quad if there are too few points.
if (ksz < 2)
return 0;
double *errs = malloc(sizeof(double)*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 = malloc(sizeof(double)*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 = malloc(sizeof(float)*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(double)*sz);
free(y);
free(f);
}
int *maxima = malloc(sizeof(int)*sz);
double *maxima_errs = malloc(sizeof(double)*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++;
}
}
free(errs);
// if we didn't get at least 4 maxima, we can't fit a quad.
if (nmaxima < 4){
free(maxima);
free(maxima_errs);
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 = malloc(sizeof(double)*nmaxima);
memcpy(maxima_errs_copy, maxima_errs, sizeof(double)*nmaxima);
// 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;
free(maxima_errs_copy);
}
free(maxima_errs);
int best_indices[4];
double best_error = HUGE_VALF;
double err01, err12, err23, err30;
double mse01, mse12, mse23, mse30;
double params01[4], params12[4];
// disallow quads where the angle is less than a critical value.
double max_dot = td->qtp.cos_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, NULL, &err23, &mse23);
if (mse23 > td->qtp.max_line_fit_mse)
continue;
fit_line(lfps, sz, i3, i0, NULL, &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;
}
}
}
}
}
free(maxima);
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(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);
zmaxheap_destroy(heap);
int idx = 0;
for (int i = 0; i < sz; i++) {
if (segs[i].is_vertex) {
indices[idx++] = i;
}
}
free(segs);
return 1;
}
/**
* Compute statistics that allow line fit queries to be
* efficiently computed for any contiguous range of indices.
*/
struct line_fit_pt* compute_lfps(int sz, zarray_t* cluster, image_u8_t* im) {
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));
}
{
// 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;
}
}
return lfps;
}
static inline void ptsort(struct pt *pts, int sz)
{
#define MAYBE_SWAP(arr,apos,bpos) \
if (pt_compare_angle(&(arr[apos]), &(arr[bpos])) > 0) { \
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.
struct pt *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 (pt_compare_angle(&(as[apos]), &(bs[bpos])) < 0) \
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));
free(tmp);
#undef MERGE
}
// 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 tag_width,
bool normal_border,
bool reversed_border) {
int res = 0;
int sz = zarray_size(cluster);
if (sz < 24) // Synchronize with later check.
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.
struct pt *p1;
zarray_get_volatile(cluster, 0, &p1);
uint16_t xmax = p1->x;
uint16_t xmin = p1->x;
uint16_t ymax = p1->y;
uint16_t ymin = p1->y;
for (int pidx = 1; pidx < zarray_size(cluster); pidx++) {
struct pt *p;
zarray_get_volatile(cluster, pidx, &p);
if (p->x > xmax) {
xmax = p->x;
} else if (p->x < xmin) {
xmin = p->x;
}
if (p->y > ymax) {
ymax = p->y;
} else if (p->y < ymin) {
ymin = p->y;
}
}
if ((xmax - xmin)*(ymax - ymin) < tag_width) {
return 0;
}
// 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?)
float cx = (xmin + xmax) * 0.5 + 0.05118;
float cy = (ymin + ymax) * 0.5 + -0.028581;
float dot = 0;
float quadrants[2][2] = {{-1*(2 << 15), 0}, {2*(2 << 15), 2 << 15}};
for (int pidx = 0; pidx < zarray_size(cluster); pidx++) {
struct pt *p;
zarray_get_volatile(cluster, pidx, &p);
float dx = p->x - cx;
float dy = p->y - cy;
dot += dx*p->gx + dy*p->gy;
float quadrant = quadrants[dy > 0][dx > 0];
if (dy < 0) {
dy = -dy;
dx = -dx;
}
if (dx < 0) {
float tmp = dx;
dx = dy;
dy = -tmp;
}
p->slope = quadrant + dy/dx;
}
// Ensure that the black border is inside the white border.
quad->reversed_border = dot < 0;
if (!reversed_border && quad->reversed_border) {
return 0;
}
if (!normal_border && !quad->reversed_border) {
return 0;
}
// we now sort the points according to theta. This is a prepatory
// step for segmenting them into four lines.
if (1) {
ptsort((struct pt*) cluster->data, zarray_size(cluster));
}
struct line_fit_pt *lfps = compute_lfps(sz, cluster, im);
int indices[4];
if (1) {
if (!quad_segment_maxima(td, cluster, lfps, indices))
goto finish;
} else {
if (!quad_segment_agg(cluster, lfps, indices))
goto finish;
}
double lines[4][4];
for (int i = 0; i < 4; i++) {
int i0 = indices[i];
int i1 = indices[(i+1)&3];
double mse;
fit_line(lfps, sz, i0, i1, lines[i], NULL, &mse);
if (mse > 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)
//
// rearrange (solve for lambdas)
//
// [u0_x -u1_x ] [lambda0] = [ p1_x - p0_x ]
// [u0_y -u1_y ] [lambda1] [ p1_y - p0_y ]
//
// remember that lines[i][0,1] = p, lines[i][2,3] = NORMAL vector.
// We want the unit vector, so we need the perpendiculars. Thus, below
// we have swapped the x and y components and flipped the y components.
double A00 = lines[i][3], A01 = -lines[(i+1)&3][3];
double A10 = -lines[i][2], A11 = lines[(i+1)&3][2];
double B0 = -lines[i][0] + lines[(i+1)&3][0];
double B1 = -lines[i][1] + lines[(i+1)&3][1];
double det = A00 * A11 - A10 * A01;
// inverse.
if (fabs(det) < 0.001) {
res = 0;
goto finish;
}
double W00 = A11 / det, W01 = -A01 / det;
// solve
double L0 = W00*B0 + W01*B1;
// compute intersection
quad->p[i][0] = lines[i][0] + L0*A00;
quad->p[i][1] = lines[i][1] + L0*A10;
res = 1;
}
// reject quads that are too small
if (1) {
double area = 0;
// get area of triangle formed by points 0, 1, 2, 0
double length[3], p;
for (int i = 0; i < 3; i++) {
int idxa = i; // 0, 1, 2,
int idxb = (i+1) % 3; // 1, 2, 0
length[i] = sqrt(sq(quad->p[idxb][0] - quad->p[idxa][0]) +
sq(quad->p[idxb][1] - quad->p[idxa][1]));
}
p = (length[0] + length[1] + length[2]) / 2;
area += sqrt(p*(p-length[0])*(p-length[1])*(p-length[2]));
// get area of triangle formed by points 2, 3, 0, 2
for (int i = 0; i < 3; i++) {
int idxs[] = { 2, 3, 0, 2 };
int idxa = idxs[i];
int idxb = idxs[i+1];
length[i] = sqrt(sq(quad->p[idxb][0] - quad->p[idxa][0]) +
sq(quad->p[idxb][1] - quad->p[idxa][1]));
}
p = (length[0] + length[1] + length[2]) / 2;
area += sqrt(p*(p-length[0])*(p-length[1])*(p-length[2]));
if (area < 0.95*tag_width*tag_width) {
res = 0;
goto finish;
}
}
// reject quads whose cumulative angle change isn't equal to 2PI
if (1) {
for (int i = 0; i < 4; i++) {
int i0 = i, i1 = (i+1)&3, i2 = (i+2)&3;
double dx1 = quad->p[i1][0] - quad->p[i0][0];
double dy1 = quad->p[i1][1] - quad->p[i0][1];
double dx2 = quad->p[i2][0] - quad->p[i1][0];
double dy2 = quad->p[i2][1] - quad->p[i1][1];
double cos_dtheta = (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2));
if ((cos_dtheta > td->qtp.cos_critical_rad || cos_dtheta < -td->qtp.cos_critical_rad) || dx1*dy2 < dy1*dx2) {
res = 0;
goto finish;
}
}
}
finish:
free(lfps);
return res;
}
#define DO_UNIONFIND2(dx, dy) if (im->buf[(y + dy)*s + x + dx] == v) unionfind_connect(uf, y*w + x, (y + dy)*w + x + dx);
static void do_unionfind_first_line(unionfind_t *uf, image_u8_t *im, int w, int s)
{
int y = 0;
uint8_t v;
for (int x = 1; x < w - 1; x++) {
v = im->buf[y*s + x];
if (v == 127)
continue;
DO_UNIONFIND2(-1, 0);
}
}
static void do_unionfind_line2(unionfind_t *uf, image_u8_t *im, int w, int s, int y)
{