forked from snavely/bundler_sfm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBundle.cpp
4269 lines (3355 loc) · 135 KB
/
Bundle.cpp
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) 2008-2010 Noah Snavely (snavely (at) cs.cornell.edu)
* and the University of Washington
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 General Public License for more details.
*
*/
/* Bundle.cpp */
/* Bundle adjustment routines */
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <queue>
#include <vector>
#include "defines.h"
#include "horn.h"
#include "image.h"
#include "matrix.h"
#include "qsort.h"
#include "resample.h"
#include "sfm.h"
#include "triangulate.h"
#include "util.h"
#include "BundlerApp.h"
// #include "SifterGraph.h"
#include "BundleAdd.h"
#include "Epipolar.h"
#include "Distortion.h"
/* Use a 180 rotation to fix up the intrinsic matrix */
void FixIntrinsics(double *P, double *K, double *R, double *t)
{
/* Check the parity along the diagonal */
int neg = (K[0] < 0.0) + (K[4] < 0.0) + (K[8] < 0.0);
/* If odd parity, negate the instrinsic matrix */
if ((neg % 2) == 1) {
matrix_scale(3, 3, K, -1.0, K);
matrix_scale(3, 4, P, -1.0, P);
}
/* Now deal with case of even parity */
double fix[9];
matrix_ident(3, fix);
double tmp[9], tmp2[12];
if (K[0] < 0.0 && K[4] < 0.0) {
fix[0] = -1.0;
fix[4] = -1.0;
} else if (K[0] < 0.0) {
fix[0] = -1.0;
fix[8] = -1.0;
} else if (K[4] < 0.0) {
fix[4] = -1.0;
fix[8] = -1.0;
} else {
/* No change needed */
}
matrix_product(3, 3, 3, 3, K, fix, tmp);
memcpy(K, tmp, sizeof(double) * 3 * 3);
double Kinv[9];
matrix_invert(3, K, Kinv);
matrix_product(3, 3, 3, 4, Kinv, P, tmp2);
memcpy(R + 0, tmp2 + 0, sizeof(double) * 3);
memcpy(R + 3, tmp2 + 4, sizeof(double) * 3);
memcpy(R + 6, tmp2 + 8, sizeof(double) * 3);
t[0] = tmp2[3];
t[1] = tmp2[7];
t[2] = tmp2[11];
}
void GetIntrinsics(const camera_params_t &camera, double *K) {
if (!camera.known_intrinsics) {
K[0] = camera.f; K[1] = 0.0; K[2] = 0.0;
K[3] = 0.0; K[4] = camera.f; K[5] = 0.0;
K[6] = 0.0; K[7] = 0.0; K[8] = 1.0;
} else {
memcpy(K, camera.K_known, 9 * sizeof(double));
}
}
/* Compute the angle between two rays */
double ComputeRayAngle(v2_t p, v2_t q,
const camera_params_t &cam1,
const camera_params_t &cam2)
{
double K1[9], K2[9];
GetIntrinsics(cam1, K1);
GetIntrinsics(cam2, K2);
double K1_inv[9], K2_inv[9];
matrix_invert(3, K1, K1_inv);
matrix_invert(3, K2, K2_inv);
double p3[3] = { Vx(p), Vy(p), 1.0 };
double q3[3] = { Vx(q), Vy(q), 1.0 };
double p3_norm[3], q3_norm[3];
matrix_product331(K1_inv, p3, p3_norm);
matrix_product331(K2_inv, q3, q3_norm);
v2_t p_norm = v2_new(p3_norm[0] / p3_norm[2], p3_norm[1] / p3_norm[2]);
v2_t q_norm = v2_new(q3_norm[0] / q3_norm[2], q3_norm[1] / q3_norm[2]);
double R1_inv[9], R2_inv[9];
matrix_transpose(3, 3, (double *) cam1.R, R1_inv);
matrix_transpose(3, 3, (double *) cam2.R, R2_inv);
double p_w[3], q_w[3];
double pv[3] = { Vx(p_norm), Vy(p_norm), -1.0 };
double qv[3] = { Vx(q_norm), Vy(q_norm), -1.0 };
double Rpv[3], Rqv[3];
matrix_product331(R1_inv, pv, Rpv);
matrix_product331(R2_inv, qv, Rqv);
matrix_sum(3, 1, 3, 1, Rpv, (double *) cam1.t, p_w);
matrix_sum(3, 1, 3, 1, Rqv, (double *) cam2.t, q_w);
/* Subtract out the camera center */
double p_vec[3], q_vec[3];
matrix_diff(3, 1, 3, 1, p_w, (double *) cam1.t, p_vec);
matrix_diff(3, 1, 3, 1, q_w, (double *) cam2.t, q_vec);
/* Compute the angle between the rays */
double dot;
matrix_product(1, 3, 3, 1, p_vec, q_vec, &dot);
double mag = matrix_norm(3, 1, p_vec) * matrix_norm(3, 1, q_vec);
return acos(CLAMP(dot / mag, -1.0 + 1.0e-8, 1.0 - 1.0e-8));
}
/* Utility routine for updating an image key vector */
static void RemoveImageKey(ImageKeyVector &vec, int view)
{
int size = (int) vec.size();
int found = 0;
for (int i = 0; i < size; i++) {
if (vec[i].first == view) {
vec.erase(vec.begin() + i);
i--;
size--;
found++;
}
}
if (found == 0)
printf("[RemoveImageKey] Error! Couldn't find view %d\n", view);
else if (found > 1)
printf("[RemoveImageKey] Error! Found too many views %d\n", view);
}
/* Check cheirality for a camera and a point */
bool CheckCheirality(v3_t p, const camera_params_t &camera)
{
double pt[3] = { Vx(p), Vy(p), Vz(p) };
double cam[3];
pt[0] -= camera.t[0];
pt[1] -= camera.t[1];
pt[2] -= camera.t[2];
matrix_product(3, 3, 3, 1, (double *) camera.R, pt, cam);
// EDIT!!!
if (cam[2] > 0.0)
return false;
else
return true;
}
double GetCameraDistance(camera_params_t *c1, camera_params_t *c2)
{
double center1[3];
double Rinv1[9];
matrix_invert(3, c1->R, Rinv1);
memcpy(center1, c1->t, 3 * sizeof(double));
double center2[3];
double Rinv2[9];
matrix_invert(3, c2->R, Rinv2);
memcpy(center2, c2->t, 3 * sizeof(double));
double dx = center1[0] - center2[0];
double dy = center1[1] - center2[1];
double dz = center1[2] - center2[2];
return sqrt(dx * dx + dy * dy + dz * dz);
}
void InitializeCameraParams(const ImageData &data, camera_params_t &camera)
{
matrix_ident(3, camera.R);
camera.t[0] = camera.t[1] = camera.t[2] = 0.0;
camera.f = 0.0;
camera.k[0] = camera.k[1] = 0.0;
camera.k_inv[0] = camera.k_inv[2] = camera.k_inv[3] = 0.0;
camera.k_inv[4] = camera.k_inv[5] = 0.0;
camera.k_inv[1] = 1.0;
camera.f_scale = 1.0;
camera.k_scale = 1.0;
for (int i = 0; i < NUM_CAMERA_PARAMS; i++) {
camera.constrained[i] = 0;
camera.constraints[i] = 0.0;
camera.weights[i] = 0.0;
}
camera.fisheye = data.m_fisheye;
camera.f_cx = data.m_fCx;
camera.f_cy = data.m_fCy;
camera.f_rad = data.m_fRad;
camera.f_angle = data.m_fAngle;
camera.f_focal = data.m_fFocal;
if (data.m_known_intrinsics) {
camera.known_intrinsics = 1;
memcpy(camera.K_known, data.m_K, 9 * sizeof(double));
memcpy(camera.k_known, data.m_k, 5 * sizeof(double));
} else {
camera.known_intrinsics = 0;
}
}
void BundlerApp::
CheckPointKeyConsistency(const std::vector<ImageKeyVector> pt_views,
int *added_order)
{
int num_points = (int) pt_views.size();
int errors = 0;
for (int i = 0; i < num_points; i++) {
int num_views = pt_views[i].size();
for (int j = 0; j < num_views; j++) {
/* check consistency */
ImageKey ik = pt_views[i][j];
int img = added_order[ik.first];
int key = ik.second;
if (m_image_data[img].m_keys[key].m_extra != i) {
printf("[CheckPointKeyConsistency] Error: (%d,%d).m_extra "
"should be %d (m_extra is %d)\n", img, key, i,
m_image_data[img].m_keys[key].m_extra);
errors++;
}
}
}
printf("[CheckPointKeyConsistency] There were %d errors\n", errors);
}
void BundlerApp::ReRunSFM(double *S, double *U, double *V, double *W)
{
// #define RERUN_ADD_POINTS
#ifdef RERUN_ADD_POINTS
/* Compute initial image information */
ComputeGeometricConstraints();
#endif
int num_pts = (int) m_point_data.size();
int num_images = GetNumImages();
/* Initialize all keypoints to have not been matched */
printf("[ReRunSFM] Initializing keypoints...\n");
for (int i = 0; i < num_images; i++) {
int num_keys = GetNumKeys(i);
for (int j = 0; j < num_keys; j++) {
GetKey(i,j).m_extra = -1;
}
}
/* Set up the cameras */
int num_init_cams = 0;
int *added_order = new int[num_images];
int *added_order_inv = new int[num_images];
std::vector<ImageKeyVector> pt_views;
camera_params_t *cameras = new camera_params_t[num_images];
printf("[ReRunSFM] Setting up cameras\n");
for (int i = 0; i < num_images; i++) {
printf(".");
fflush(stdout);
if (m_image_data[i].m_camera.m_adjusted) {
m_image_data[i].LoadKeys(false, !m_optimize_for_fisheye);
#ifdef RERUN_ADD_POINTS
m_image_data[i].ReadKeyColors();
SetTracks(i);
#endif
added_order[num_init_cams] = i;
added_order_inv[i] = num_init_cams;
InitializeCameraParams(m_image_data[i], cameras[num_init_cams]);
/* Restore the camera parameters */
memcpy(cameras[num_init_cams].R, m_image_data[i].m_camera.m_R,
sizeof(double) * 9);
matrix_transpose_product(3, 3, 3, 1,
m_image_data[i].m_camera.m_R,
m_image_data[i].m_camera.m_t,
cameras[num_init_cams].t);
cameras[num_init_cams].t[0] *= -1.0;
cameras[num_init_cams].t[1] *= -1.0;
cameras[num_init_cams].t[2] *= -1.0;
cameras[num_init_cams].f = m_image_data[i].m_camera.m_focal;
cameras[num_init_cams].k[0] = m_image_data[i].m_camera.m_k[0];
cameras[num_init_cams].k[1] = m_image_data[i].m_camera.m_k[1];
/* Set the camera constraints */
SetCameraConstraints(i, cameras + num_init_cams);
if (m_constrain_focal) {
/* Bad hack... */
if (m_image_data[i].m_has_init_focal) {
double diff = cameras[num_init_cams].f -
m_image_data[i].m_init_focal;
if (fabs(diff) / m_image_data[i].m_init_focal < 0.4) {
printf("[ReRunSFM] Constraining focal "
"length for camera %d\n", i);
/* Setup the focal length constraints */
SetFocalConstraint(m_image_data[i],
cameras + num_init_cams);
}
}
}
num_init_cams++;
} else {
added_order_inv[i] = -1;
}
}
printf("\n");
/* Set up the points, visibility mask and projections */
printf("[ReRunSFM] Setting up views...\n");
#ifndef RERUN_ADD_POINTS
v3_t *init_pts = new v3_t[num_pts];
#else
v3_t *init_pts = new v3_t[m_track_data.size()];
#endif
v3_t *colors = new v3_t[num_pts];
for (int i = 0; i < num_pts; i++) {
PointData &pt = m_point_data[i];
int num_views = pt.m_views.size();
// init_pts[i] = v3_new(pt.m_pos[0], pt.m_pos[1], -pt.m_pos[2]);
init_pts[i] = v3_new(pt.m_pos[0], pt.m_pos[1], pt.m_pos[2]);
colors[i] = v3_new(pt.m_color[0], pt.m_color[1], pt.m_color[2]);
ImageKeyVector views;
double *views_arr = new double[num_views];
int *perm = new int[num_views];
for (int j = 0; j < num_views; j++) {
ImageKey ik = pt.m_views[j];
int v = ik.first;
int k = ik.second;
if (m_image_data[v].m_keys[k].m_extra != -1) {
printf("Error! Already assigned this key "
"[%d,%d] <- %d != %d!\n", v, k,
m_image_data[v].m_keys[k].m_extra, i);
}
m_image_data[v].m_keys[k].m_extra = i;
ik.first = added_order_inv[ik.first];
views_arr[j] = (double) v;
views.push_back(ik);
}
/* Sort the views */
qsort_ascending();
qsort_perm(num_views, views_arr, perm);
ImageKeyVector views_sorted;
for (int j = 0; j < num_views; j++) {
views_sorted.push_back(views[perm[j]]);
}
pt_views.push_back(views_sorted);
delete [] views_arr;
delete [] perm;
}
CheckPointKeyConsistency(pt_views, added_order);
#ifdef RERUN_ADD_POINTS
BundleAdjustAddAllNewPoints(num_pts, num_init_cams,
added_order, cameras, init_pts, colors,
0.0, pt_views, 16.0, 2);
#endif
DumpOutputFile(m_output_directory, m_bundle_output_file,
num_images, num_init_cams, num_pts,
added_order, cameras, init_pts, colors, pt_views);
RunSFM(num_pts, num_init_cams, 0, false, cameras,
init_pts, added_order, colors, pt_views,
0, 0, 0, 0.0 /*eps2*/, S, U, V, W);
/* Save the camera parameters and points */
/* Cameras */
for (int i = 0; i < num_images; i++) {
m_image_data[i].m_camera.m_adjusted = false;
}
printf("Focal lengths:\n");
for (int i = 0; i < num_init_cams; i++) {
int img = added_order[i];
m_image_data[img].m_camera.m_adjusted = true;
memcpy(m_image_data[img].m_camera.m_R, cameras[i].R,
9 * sizeof(double));
matrix_product(3, 3, 3, 1,
cameras[i].R, cameras[i].t,
m_image_data[img].m_camera.m_t);
matrix_scale(3, 1,
m_image_data[img].m_camera.m_t, -1.0,
m_image_data[img].m_camera.m_t);
m_image_data[img].m_camera.m_focal = cameras[i].f;
printf(" [%d]: %0.3f\n", img, cameras[i].f);
m_image_data[img].m_camera.Finalize();
}
fflush(stdout);
/* Points */
m_point_data.clear();
for (int i = 0; i < num_pts; i++) {
/* Check if the point is visible in any view */
if ((int) pt_views[i].size() == 0)
continue; /* Invisible */
PointData pdata;
pdata.m_pos[0] = Vx(init_pts[i]);
pdata.m_pos[1] = Vy(init_pts[i]);
pdata.m_pos[2] = Vz(init_pts[i]);
pdata.m_color[0] = (float) Vx(colors[i]);
pdata.m_color[1] = (float) Vy(colors[i]);
pdata.m_color[2] = (float) Vz(colors[i]);
#if 1
for (int j = 0; j < (int) pt_views[i].size(); j++) {
int v = pt_views[i][j].first;
int vnew = added_order[v];
pdata.m_views.push_back(ImageKey(vnew, pt_views[i][j].second));
}
#else
pdata.m_views = pt_views[i];
#endif
m_point_data.push_back(pdata);
}
/* Save the output file */
DumpPointsToPly(m_output_directory, "points_readjusted.ply",
num_pts, num_init_cams, init_pts, colors, cameras);
/* Dump output */
if (m_bundle_output_file != NULL) {
DumpOutputFile(m_output_directory, m_bundle_output_file,
num_images, num_init_cams, num_pts,
added_order, cameras, init_pts, colors, pt_views);
}
delete [] cameras;
delete [] init_pts;
delete [] added_order;
delete [] added_order_inv;
}
static int compare_doubles(const void *d1, const void *d2)
{
double a = *(double *) d1;
double b = *(double *) d2;
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
double BundlerApp::RunSFM(int num_pts, int num_cameras, int start_camera,
bool fix_points,
camera_params_t *init_camera_params,
v3_t *init_pts, int *added_order, v3_t *colors,
std::vector<ImageKeyVector> &pt_views,
int max_iter, int max_iter2,
int verbosity, double eps2,
double *S, double *U, double *V, double *W,
bool remove_outliers, bool final_bundle,
bool write_intermediate)
{
#ifdef __USE_CERES__
if (!m_use_ceres) {
return
RunSFM_SBA(num_pts, num_cameras, start_camera, fix_points,
init_camera_params, init_pts,
added_order, colors, pt_views, eps2, S, U, V, W,
remove_outliers);
} else { /* use_ceres */
return
RunSFM_Ceres(num_pts, num_cameras, start_camera, fix_points,
init_camera_params, init_pts, added_order, colors, pt_views,
max_iter, max_iter2, verbosity, eps2, S, U, V, W,
remove_outliers, final_bundle, write_intermediate);
}
#else
/* Just use SBA */
return
RunSFM_SBA(num_pts, num_cameras, start_camera, fix_points,
init_camera_params, init_pts,
added_order, colors, pt_views, eps2, S, U, V, W,
remove_outliers);
#endif
}
double BundlerApp::RunSFM_SBA(int num_pts, int num_cameras, int start_camera,
bool fix_points,
camera_params_t *init_camera_params,
v3_t *init_pts, int *added_order, v3_t *colors,
std::vector<ImageKeyVector> &pt_views,
double eps2,
double *S, double *U, double *V, double *W,
bool remove_outliers)
{
#define MIN_POINTS 20
int num_outliers = 0;
int total_outliers = 0;
double dist_total = 0.0;
int num_dists = 0;
int *remap = new int [num_pts];
v3_t *nz_pts = new v3_t[num_pts];
const int MIN_OUTLIERS = 40;
do {
if (num_pts - total_outliers < MIN_POINTS) {
printf("[RunSFM] Too few points remaining, exiting!\n");
fflush(stdout);
dist_total = DBL_MAX;
break;
}
/* Set up the vmask and projections */
char *vmask = NULL;
double *projections = NULL;
int num_projections = 0;
for (int i = 0; i < num_pts; i++) {
num_projections += (int) pt_views[i].size();
}
vmask = new char[num_pts * num_cameras];
projections = new double[2 * num_projections];
for (int i = 0; i < num_pts * num_cameras; i++)
vmask[i] = 0;
int arr_idx = 0;
int nz_count = 0;
for (int i = 0; i < num_pts; i++) {
int num_views = (int) pt_views[i].size();
if (num_views > 0) {
for (int j = 0; j < num_views; j++) {
int c = pt_views[i][j].first;
int v = added_order[c];
int k = pt_views[i][j].second;
vmask[nz_count * num_cameras + c] = 1;
projections[2 * arr_idx + 0] = GetKey(v,k).m_x;
projections[2 * arr_idx + 1] = GetKey(v,k).m_y;
arr_idx++;
}
remap[i] = nz_count;
nz_pts[nz_count] = init_pts[i];
nz_count++;
} else {
remap[i] = -1;
}
}
dist_total = 0.0;
num_dists = 0;
bool fixed_focal = m_fixed_focal_length;
clock_t start = clock();
run_sfm(nz_count, num_cameras, start_camera, vmask, projections,
fixed_focal ? 0 : 1, 0,
m_estimate_distortion ? 1 : 0, 1,
init_camera_params, nz_pts,
(m_use_constraints || m_constrain_focal) ? 1 : 0,
(m_use_point_constraints) ? 1 : 0,
m_point_constraints, m_point_constraint_weight,
fix_points ? 1 : 0, m_optimize_for_fisheye, eps2, V, S, U, W);
clock_t end = clock();
printf("[RunSFM] run_sfm took %0.3fs\n",
(double) (end - start) / (double) CLOCKS_PER_SEC);
/* Compute statistics and check for outliers */
start = clock();
double global_reprojection_error = 0;
int global_num_observations = 0;
std::vector<int> outliers;
std::vector<double> reproj_errors;
for (int i = 0; i < num_cameras; i++) {
ImageData &data = m_image_data[added_order[i]];
double K[9] = { init_camera_params[i].f, 0.0, 0.0,
0.0, init_camera_params[i].f, 0.0,
0.0, 0.0, 1.0 };
// double w[3] = { 0.0, 0.0, 0.0 };
double dt[3] = { init_camera_params[i].t[0],
init_camera_params[i].t[1],
init_camera_params[i].t[2] };
/* Compute inverse distortion parameters */
if (m_estimate_distortion) {
double *k = init_camera_params[i].k;
double k_dist[6] = { 0.0, 1.0, 0.0, k[0], 0.0, k[1] };
double w_2 = 0.5 * data.GetWidth();
double h_2 = 0.5 * data.GetHeight();
double max_radius =
sqrt(w_2 * w_2 + h_2 * h_2) / init_camera_params[i].f;
InvertDistortion(6, 6, 0.0, max_radius,
k_dist, init_camera_params[i].k_inv);
}
if (data.m_known_intrinsics) {
double *k = init_camera_params[i].k_known;
double k_dist[8] =
{ 0.0, 1.0, 0.0, k[0], 0.0, k[1], 0.0, k[4]};
double w_2 = 0.5 * data.GetWidth();
double h_2 = 0.5 * data.GetHeight();
double max_radius =
sqrt(w_2 * w_2 + h_2 * h_2) /
init_camera_params[i].K_known[0];
InvertDistortion(8, 6, 0.0, max_radius, k_dist,
init_camera_params[i].k_inv);
}
int num_keys = GetNumKeys(added_order[i]);
int num_pts_proj = 0;
for (int j = 0; j < num_keys; j++) {
if (GetKey(added_order[i], j).m_extra >= 0) {
num_pts_proj++;
}
}
double *dists = new double[num_pts_proj];
int pt_count = 0;
std::vector<Keypoint>::iterator iter;
// for (int j = 0; j < num_keys; j++) {
for (iter = m_image_data[added_order[i]].m_keys.begin();
iter != m_image_data[added_order[i]].m_keys.end();
iter++) {
const Keypoint &key = *iter;
if (key.m_extra >= 0) {
double b[3], pr[2];
double dx, dy, dist;
int pt_idx = key.m_extra;
b[0] = Vx(nz_pts[remap[pt_idx]]);
b[1] = Vy(nz_pts[remap[pt_idx]]);
b[2] = Vz(nz_pts[remap[pt_idx]]);
sfm_project_rd(&(init_camera_params[i]), K,
init_camera_params[i].k,
init_camera_params[i].R, dt, b, pr,
m_estimate_distortion, true);
if (m_optimize_for_fisheye) {
/* Distort the points */
double x = pr[0], y = pr[1];
m_image_data[added_order[i]].
DistortPoint(x, y, pr[0], pr[1]);
}
dx = pr[0] - key.m_x;
dy = pr[1] - key.m_y;
dist = sqrt(dx * dx + dy * dy);
dist_total += dist;
num_dists++;
dists[pt_count] = dist;
pt_count++;
}
}
/* Estimate the median of the distances */
double med = kth_element_copy(num_pts_proj,
iround(0.8 /* 0.9 */ * num_pts_proj),
dists);
median_copy(num_pts_proj, dists);
#define NUM_STDDEV 2.0 // 3.0 // 6.0
double thresh = 1.2 * NUM_STDDEV * med; /* k * stddev */
thresh = CLAMP(thresh, m_min_proj_error_threshold,
m_max_proj_error_threshold);
/* Compute the average reprojection error for this
* camera */
double sum = 0.0;
for (int j = 0; j < num_pts_proj; j++) {
sum += dists[j];
}
double avg = sum / num_pts_proj;
printf("[RunSFM] Mean error cam %d[%d] [%d pts]: %0.3e "
"[med: %0.3e, %0.3e]\n",
i, added_order[i], num_pts_proj, avg,
kth_element_copy(num_pts_proj,
iround(0.5 * num_pts_proj), dists),
thresh);
global_reprojection_error += sum;
global_num_observations += num_pts_proj;
pt_count = 0;
for (int j = 0; j < num_keys; j++) {
int pt_idx = GetKey(added_order[i],j).m_extra;
if (pt_idx < 0)
continue;
/* Don't remove constrained points */
if (m_use_point_constraints &&
Vx(m_point_constraints[pt_idx]) != 0.0) {
pt_count++;
continue;
}
if (dists[pt_count] > thresh) {
/* Remove this point from consideration */
bool found = false;
for (int k = 0; k < (int) outliers.size(); k++) {
if (outliers[k] == pt_idx) {
found = true;
break;
}
}
if (!found) {
outliers.push_back(pt_idx);
reproj_errors.push_back(dists[pt_count]);
}
}
pt_count++;
}
#define OUTPUT_VERBOSE_STATS
#ifdef OUTPUT_VERBOSE_STATS
#define NUM_ERROR_BINS 10
qsort(dists, num_pts_proj, sizeof(double), compare_doubles);
double pr_min = dists[0];
double pr_max = dists[num_pts_proj-1];
double pr_step = (pr_max - pr_min) / NUM_ERROR_BINS;
/* Break histogram into 10 bins */
int idx_count = 0;
for (int i = 0; i < NUM_ERROR_BINS; i++) {
double max = pr_min + (i+1) * pr_step;
int start = idx_count;
while (idx_count < num_pts_proj && dists[idx_count] <= max)
idx_count++;
int bin_size = idx_count - start;
printf(" E[%0.3e--%0.3e]: %d [%0.3f]\n",
max - pr_step, max, bin_size,
bin_size / (double) num_pts_proj);
}
#endif
delete [] dists;
}
printf("[RunSFM] Global mean reprojection error: %0.3e "
"(%d observations)\n",
global_reprojection_error / global_num_observations,
global_num_observations);
/* Remove outlying points */
if (remove_outliers) {
for (int i = 0; i < (int) outliers.size(); i++) {
int idx = outliers[i];
printf("[RunSFM] Removing outlier %d "
"(reproj error: %0.3f)\n", idx, reproj_errors[i]);
if (colors != NULL) {
Vx(colors[idx]) = 0x0;
Vy(colors[idx]) = 0x0;
Vz(colors[idx]) = 0xff;
}
int num_views = (int) pt_views[idx].size();
for (int j = 0; j < num_views; j++) {
int v = pt_views[idx][j].first;
int k = pt_views[idx][j].second;
vmask[idx * num_cameras + v] = 0;
/* Sanity check */
if (GetKey(added_order[v], k).m_extra != idx)
printf("Error! Entry for (%d,%d) "
"should be %d, but is %d\n",
added_order[v], k,
idx, GetKey(added_order[v], k).m_extra);
GetKey(added_order[v], k).m_extra = -2;
}
pt_views[idx].clear();
}
num_outliers = outliers.size();
total_outliers += num_outliers;
end = clock();
printf("[RunSFM] outlier removal took %0.3fs\n",
(double) (end - start) / (double) CLOCKS_PER_SEC);
printf("[RunSFM] Removing %d outliers\n", num_outliers);
}
delete [] vmask;
delete [] projections;
for (int i = 0; i < num_pts; i++) {
if (remap[i] != -1) {
init_pts[i] = nz_pts[remap[i]];
}
}
if (!remove_outliers) break;
} while (num_outliers > MIN_OUTLIERS);
delete [] remap;
delete [] nz_pts;
return dist_total / num_dists;
}
void BundlerApp::ClearCameraConstraints(camera_params_t *params)
{
for (int i = 0; i < NUM_CAMERA_PARAMS; i++) {
params->constrained[i] = false;
params->constraints[i] = 0.0;
params->weights[i] = 0.0;
}
}
void BundlerApp::SetCameraConstraints(int cam_idx, camera_params_t *params)
{
const CameraInfo &cam = m_image_data[cam_idx].m_camera;
params->constrained[0] = cam.m_constrained[0];
params->constrained[1] = cam.m_constrained[1];
params->constrained[2] = cam.m_constrained[2];
params->constrained[3] = cam.m_constrained[3];
params->constrained[4] = cam.m_constrained[4];
params->constrained[5] = cam.m_constrained[5];
params->constrained[6] = cam.m_constrained[6];
if (m_estimate_distortion) {
params->constrained[7] = true;
params->constrained[8] = true;
} else {
params->constrained[7] = false;
params->constrained[8] = false;
}
params->constraints[0] = cam.m_constraints[0];
params->constraints[1] = cam.m_constraints[1];
params->constraints[2] = cam.m_constraints[2];
params->constraints[3] = cam.m_constraints[3];
params->constraints[4] = cam.m_constraints[4];
params->constraints[5] = cam.m_constraints[5];
params->constraints[6] = cam.m_constraints[6];
params->constraints[7] = 0.0;
params->constraints[8] = 0.0;
params->weights[0] = cam.m_constraint_weights[0];
params->weights[1] = cam.m_constraint_weights[1];
params->weights[2] = cam.m_constraint_weights[2];
params->weights[3] = cam.m_constraint_weights[3];
params->weights[4] = cam.m_constraint_weights[4];
params->weights[5] = cam.m_constraint_weights[5];
params->weights[6] = cam.m_constraint_weights[6];
if (m_estimate_distortion) {
params->weights[7] = m_distortion_weight;
params->weights[8] = m_distortion_weight;
} else {
params->weights[7] = 0.0;
params->weights[8] = 0.0;
}
}
void BundlerApp::SetFocalConstraint(const ImageData &data,
camera_params_t *params)
{
if (data.m_has_init_focal) {
params->constrained[6] = true;
params->constraints[6] = data.m_init_focal;
params->weights[6] = m_constrain_focal_weight;
}
}
/* Initialize the bundle adjustment procedure (loading an existing
* model if one exists) */
void BundlerApp::InitializeBundleAdjust(int &num_init_cams,
int *added_order,
int *added_order_inv,
camera_params_t *cameras,
v3_t *points, v3_t *colors,
std::vector<ImageKeyVector> &pt_views,
bool use_constraints)
{
int num_images = GetNumImages();
/* Initialize all keypoints to have not been matched */