-
Notifications
You must be signed in to change notification settings - Fork 15
/
test-projection-uncertainty.py
executable file
·2816 lines (2292 loc) · 130 KB
/
test-projection-uncertainty.py
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
#!/usr/bin/env python3
r'''Uncertainty-quantification test
I run a number of synthetic-data camera calibrations, applying some noise to the
observed inputs each time. I then look at the distribution of projected world
points, and compare that distribution with theoretical predictions.
This test checks two different types of calibrations:
--fixed cam0: we place camera0 at the reference coordinate system. So camera0
may not move, and has no associated extrinsics vector. The other cameras and
the frames move. When evaluating at projection uncertainty I pick a point
referenced off the frames. As the frames move around, so does the point I'm
projecting. But together, the motion of the frames and the extrinsics and the
intrinsics should map it to the same pixel in the end.
--fixed frames: the reference coordinate system is attached to the frames,
which may not move. All cameras may move around and all cameras have an
associated extrinsics vector. When evaluating at projection uncertainty I also
pick a point referenced off the frames, but here any point in the reference
coord system will do. As the cameras move around, so does the point I'm
projecting. But together, the motion of the extrinsics and the intrinsics
should map it to the same pixel in the end.
Exactly one of these two arguments is required.
The lens model we're using must appear: either "--model opencv4" or "--model
opencv8" or "--model splined"
'''
import sys
import argparse
import re
import os
def parse_args():
parser = \
argparse.ArgumentParser(description = __doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--fixed',
type=str,
choices=('cam0','frames'),
required=True,
help='''Are we putting the origin at camera0, or are all the frames at a fixed (and
non-optimizeable) pose? One or the other is required.''')
parser.add_argument('--model',
type=str,
choices=('opencv4','opencv8','splined'),
required = True,
help='''Which lens model we're using. Must be one of
('opencv4','opencv8','splined')''')
parser.add_argument('--Nframes',
type=int,
default=50,
help='''How many chessboard poses to simulate. These are dense observations: every
camera sees every corner of every chessboard pose''')
parser.add_argument('--Nsamples',
type=int,
default=100,
help='''How many random samples to evaluate''')
parser.add_argument('--Ncameras',
type = int,
default = 4,
help='''How many cameras to simulate. By default we use 4. The values of those 4 are
hard-coded, so --Ncameras must be <= 4''')
parser.add_argument('--range-to-boards',
type=float,
default=4.0,
help='''Nominal range to the simulated chessboards''')
parser.add_argument('--observations-left-right-with-gap',
action='store_true',
help='''If given, we produce chessboards views on the
left and right, with a gap in the center. Tested with
--range-to-boards 0.9 --Ncameras 1''')
parser.add_argument('--distances',
type=str,
default='5,inf',
help='''Comma-separated list of distance where we test the uncertainty predictions.
Numbers and "inf" understood. The first value on this
list is used for visualization in --show-distribution''')
parser.add_argument('--observed-pixel-uncertainty',
type=float,
default=1.5,
help='''The level of the input pixel noise to simulate.
Defaults to 1 stdev = 1.5 pixels''')
parser.add_argument('--non-vanilla',
action='store_true',
help='''If given, run tests with the non-vanilla
scenarios (moving camera, different reference frames).
Only implemented with --Ncameras 1 --fixed cam0''')
parser.add_argument('--points',
action='store_true',
help='''By default we do everything with chessboard
observations. If --points, we simulate the same
chessboard observations, but we calibrate with discrete
observations of points in the chessboard. --points
enables the unity_cam01 regularization to make the solve
non-singular''')
parser.add_argument('--do-sample',
action='store_true',
help='''By default we don't run the time-intensive
samples of the calibration solves. This runs a very
limited set of tests, and exits. To perform the full set
of tests, pass --do-sample''')
parser.add_argument('--show-distribution',
action='store_true',
help='''If given, we produce plots showing the
distribution of samples. --make-documentation-plots also
does this, albeit slightly differently: it makes a
multiplot, not a separate plot for each camera.
--make-documentation-plots also makes many other plots''')
parser.add_argument('--write-models',
action='store_true',
help='''If given, we write the resulting models to disk for further analysis''')
parser.add_argument('--make-documentation-plots',
type=str,
help='''If given, we produce plots for the
documentation. Takes one argument: a string describing
this test. This will be used in the filenames of the
resulting plots. To make interactive plots, pass ""''')
parser.add_argument('--terminal-pdf',
type=str,
help='''The gnuplotlib terminal for --make-documentation-plots .PDFs. Omit this
unless you know what you're doing''')
parser.add_argument('--terminal-svg',
type=str,
help='''The gnuplotlib terminal for --make-documentation-plots .SVGs. Omit this
unless you know what you're doing''')
parser.add_argument('--terminal-png',
type=str,
help='''The gnuplotlib terminal for --make-documentation-plots .PNGs. Omit this
unless you know what you're doing''')
parser.add_argument('--explore',
action='store_true',
help='''If given, we drop into a REPL at the end''')
parser.add_argument('--extra-observation-at',
type=float,
help='''Adds one extra observation at the given distance''')
parser.add_argument('--reproject-perturbed',
choices=('mean-pcam',
'meanq',
'bestq',
'worstq',
'fit-boards-ref',
'diff',
'cross-reprojection--rrp-empirical',
'cross-reprojection--rrp-Jfp',
'cross-reprojection--rrp-Je',
'cross-reprojection--rpr-empirical',
'cross-reprojection--rpr-Jfp',
'cross-reprojection--rpr-Je'),
default = 'mean-pcam',
help='''Which reproject-after-perturbation method to use. This is for experiments.
Some of these methods will be probably wrong.''')
parser.add_argument('--compare-baseline-against-mrcal-2.4',
action='store_true',
dest='compare_baseline_against_mrcal_2_4',
help='''If given, compare against mrcal 2.4. Only some
paths support this. If we cannot honor this option, we
throw an error''')
args = parser.parse_args()
if args.non_vanilla:
if not (args.fixed == 'cam0' and args.Ncameras == 1):
print("--non-vanilla works ONLY with --fixed cam0 --Ncameras 1",
file=sys.stderr)
sys.exit(1)
args.distances = args.distances.split(',')
for i in range(len(args.distances)):
if args.distances[i] == 'inf':
args.distances[i] = None
else:
if re.match("[0-9deDE.-]+", args.distances[i]):
s = float(args.distances[i])
else:
print('--distances is a comma-separated list of numbers or "inf"', file=sys.stderr)
sys.exit(1)
args.distances[i] = s
return args
args = parse_args()
if args.Ncameras <= 0 or args.Ncameras > 4:
print(f"Ncameras must be in [0,4], but got {args.Ncameras}. Giving up", file=sys.stderr)
sys.exit(1)
if args.points and not re.match('cross-reprojection', args.reproject_perturbed):
print("--points is currently implemented ONLY with --reproject-perturbed cross-reprojection-...",
file = sys.stderr)
sys.exit(1)
testdir = os.path.dirname(os.path.realpath(__file__))
# I import the LOCAL mrcal since that's what I'm testing
sys.path[:0] = f"{testdir}/..",
import mrcal
import testutils
import copy
import numpy as np
import numpysane as nps
from test_calibration_helpers import calibration_baseline,calibration_make_non_vanilla,calibration_boards_to_points,calibration_sample
fixedframes = (args.fixed == 'frames')
import tempfile
import atexit
import shutil
workdir = tempfile.mkdtemp()
def cleanup():
global workdir
try:
shutil.rmtree(workdir)
workdir = None
except:
pass
atexit.register(cleanup)
terminal = dict(pdf = args.terminal_pdf,
svg = args.terminal_svg,
png = args.terminal_png,
gp = 'gp')
pointscale = dict(pdf = 1,
svg = 1,
png = 1,
gp = 1)
pointscale[""] = 1.
def shorter_terminal(t):
# Adjust the terminal string to be less tall. Makes the multiplots look
# better: less wasted space
m = re.match("(.*)( size.*?,)([0-9.]+)(.*?)$", t)
if m is None: return t
return m.group(1) + m.group(2) + str(float(m.group(3))*0.8) + m.group(4)
if args.make_documentation_plots:
print(f"Will write documentation plots to {args.make_documentation_plots}-xxxx.pdf and .svg")
if terminal['svg'] is None: terminal['svg'] = 'svg size 800,600 noenhanced solid dynamic font ",14"'
if terminal['pdf'] is None: terminal['pdf'] = 'pdf size 8in,6in noenhanced solid color font ",16"'
if terminal['png'] is None: terminal['png'] = 'pngcairo size 1024,768 transparent noenhanced crop font ",12"'
extraset = dict()
for k in pointscale.keys():
extraset[k] = f'pointsize {pointscale[k]}'
# I want the RNG to be deterministic
np.random.seed(0)
############# Set up my world, and compute all the perfect positions, pixel
############# observations of everything
object_spacing = 0.1
object_width_n = 10
object_height_n = 9
calobject_warp_true = np.array((0.002, -0.005))
extrinsics_rt_fromref_true = \
np.array(((0, 0, 0, 0, 0, 0),
(0.08, 0.2, 0.02, 1., 0.9, 0.1),
(0.01, 0.07, 0.2, 2.1, 0.4, 0.2),
(-0.1, 0.08, 0.08, 3.4, 0.2, 0.1), ))
if args.points:
# Needed for the unity_cam01 regularization. I reset the nominal distance to
# 1.0
extrinsics_rt_fromref_true[:,3:] /= nps.mag(extrinsics_rt_fromref_true[1,3:])
extrinsics_rt_fromref_true = extrinsics_rt_fromref_true[:args.Ncameras]
if args.observations_left_right_with_gap:
calibration_baseline_kwargs = \
dict(x_noiseradius = 2.5 / 4.,
y_noiseradius = 2.5,
x_offset = 2.5 / 2.,
x_mirror = True)
else:
calibration_baseline_kwargs = dict()
if args.compare_baseline_against_mrcal_2_4:
calibration_baseline_kwargs['avoid_oblique_views'] = False
# The "baseline" is a solve with perfect, noiseless observations, reoptimized
# with regularization. The results will be close to the perfect err=0 solve, but
# not exactly
optimization_inputs_baseline, \
models_true, \
frames_points_true = \
calibration_baseline(args.model,
args.Ncameras,
args.Nframes,
args.extra_observation_at,
object_width_n,
object_height_n,
object_spacing,
extrinsics_rt_fromref_true,
calobject_warp_true,
fixedframes,
testdir,
range_to_boards = args.range_to_boards,
report_points = False,
optimize = False,
**calibration_baseline_kwargs)
if args.non_vanilla:
# Compute the different scenarios of what is moving and what is the
# reference frame. I will use those later. THOSE ARE NOT YET OPTIMIZED; I
# will do that later
optimization_inputs_baseline_moving_cameras_refcam0 = \
copy.deepcopy(optimization_inputs_baseline)
calibration_make_non_vanilla(optimization_inputs_baseline_moving_cameras_refcam0,
moving_cameras = True,
ref_frame0 = False)
if args.points: calibration_boards_to_points(optimization_inputs_baseline_moving_cameras_refcam0)
optimization_inputs_baseline_moving_cameras_refframe0 = \
copy.deepcopy(optimization_inputs_baseline)
calibration_make_non_vanilla(optimization_inputs_baseline_moving_cameras_refframe0,
moving_cameras = True,
ref_frame0 = True)
if args.points: calibration_boards_to_points(optimization_inputs_baseline_moving_cameras_refframe0)
if args.points: calibration_boards_to_points(optimization_inputs_baseline)
x_baseline_unoptimized = \
mrcal.optimizer_callback(**optimization_inputs_baseline,
no_jacobian = True,
no_factorization = True)[1]
mrcal.optimize(**optimization_inputs_baseline)
x_baseline_optimized = \
mrcal.optimizer_callback(**optimization_inputs_baseline,
no_jacobian = True,
no_factorization = True)[1]
lensmodel = optimization_inputs_baseline['lensmodel']
imagersizes = optimization_inputs_baseline['imagersizes']
intrinsics_true = nps.cat( *[m.intrinsics()[1] \
for m in models_true] )
models_baseline = \
[ mrcal.cameramodel( optimization_inputs = optimization_inputs_baseline,
icam_intrinsics = i) \
for i in range(args.Ncameras) ]
# I evaluate the projection uncertainty of this vector. In each camera. I'd like
# it to be center-ish, but not AT the center. So I look at 1/3 (w,h). I want
# this to represent a point in a globally-consistent coordinate system. Here I
# have fixed frames, so using the reference coordinate system gives me that
# consistency. Note that I look at q0 for each camera separately, so I'm going
# to evaluate a different world point for each camera
q0_baseline = imagersizes[0]/3.
# I reimplemented much of the uncertainty logic since the method in mrcal 2.4,
# and I want to make sure that the new implementation doesn't break anything.
# With some inputs the results should be EXACTLY the same, and I verify that
# here. I got the reference data by checking out the 'release-2.4' branch, and
# applying this patch to print the uncertainty results:
r'''
diff --git a/test/test-projection-uncertainty.py b/test/test-projection-uncertainty.py
index bbd0d750..a7debe20 100755
--- a/test/test-projection-uncertainty.py
+++ b/test/test-projection-uncertainty.py
@@ -1094,6 +1094,6 @@
worstcase = True,
msg = f"Regularization bias small-enough for camera {icam} at distance={'infinity' if distance is None else distance}")
-for icam in (0,3):
+for icam in range(args.Ncameras):
# I move the extrinsics of a model, write it to disk, and make sure the same
# uncertainties come back
@@ -1160,6 +1160,10 @@
relative = True,
msg = f"var(dq) (infinity) is invariant to point scale for camera {icam}")
+ print(f"{Var_dq_ref=}")
+ print(f"{Var_dq_inf_ref=}")
+sys.exit()
+
if not args.do_sample:
testutils.finish()
sys.exit()
'''
# I then ran the test program twice, to generate the output for several
# different scenarios
r'''
test/test-projection-uncertainty.py \
--fixed cam0 \
--model opencv4 \
--Ncameras 1
test/test-projection-uncertainty.py \
--fixed cam0 \
--model opencv4 \
--Ncameras 4
'''
if args.compare_baseline_against_mrcal_2_4:
if \
args.model == 'opencv4' and \
args.Nframes == 50 and \
args.extra_observation_at is None and \
object_width_n == 10 and \
object_height_n == 9 and \
object_spacing == 0.1 and \
args.range_to_boards == 4.0 and \
args.reproject_perturbed == 'mean-pcam' and \
args.observed_pixel_uncertainty == 1.5 and \
not fixedframes and \
not args.points:
# assuming these are at the correct, nominal values:
# extrinsics_rt_fromref_true
# calobject_warp_true
if args.Ncameras == 1:
# The values reported by mrcal 2.4
Var_dq_ref = np.array([[[389.84692117, 166.10448933],
[166.10448933, 250.77439795]]])
Var_dq_inf_ref = np.array([[[30.06831569, 14.20492251],
[14.20492251, 16.75554809]]])
elif args.Ncameras == 4:
Var_dq_ref = np.array(([[22.65023795, 7.20500655],
[ 7.20500655, 17.29990464]],
[[37.51131869, 9.30598142],
[ 9.30598142, 17.77739599]],
[[28.8054302 , 10.66808841],
[10.66808841, 20.76171949]],
[[36.16253686, 16.06114737],
[16.06114737, 26.95796495]]))
Var_dq_inf_ref = np.array(([[1.19879461, 0.45313079],
[0.45313079, 0.91451931]],
[[1.90196461, 0.53617757],
[0.53617757, 0.76472281]],
[[1.65878182, 0.64492073],
[0.64492073, 0.92189559]],
[[2.64985186, 1.16716666],
[1.16716666, 1.30752352]]))
else:
raise Exception(f"Given --compare-baseline-against-mrcal-2.4, but an unknown scenario requested: {args.Ncameras=}")
for icam in range(args.Ncameras):
model = models_baseline[icam]
# At 1.0m out
p_cam_baseline = mrcal.unproject( q0_baseline, *model.intrinsics(),
normalize = True)
Var_dq = \
mrcal.projection_uncertainty( p_cam_baseline * 1.0,
model = model,
atinfinity = False,
method = 'mean-pcam',
observed_pixel_uncertainty = args.observed_pixel_uncertainty)
Var_dq_inf = \
mrcal.projection_uncertainty( p_cam_baseline * 1.0,
model = model,
atinfinity = True,
method = 'mean-pcam',
observed_pixel_uncertainty = args.observed_pixel_uncertainty )
testutils.confirm_equal(Var_dq, Var_dq_ref[icam],
eps = 1e-6,
worstcase = True,
msg = f"var(dq) for camera {icam}/{args.Ncameras} matches the legacy implementation in mrcal 2.4")
testutils.confirm_equal(Var_dq_inf, Var_dq_inf_ref[icam],
eps = 1e-6,
worstcase = True,
msg = f"var(dq) at infinity for camera {icam}/{args.Ncameras} matches the legacy implementation in mrcal 2.4")
testutils.finish()
sys.exit()
else:
raise Exception("Given --compare-baseline-against-mrcal-2.4, but an unknown scenario requested")
if not args.points:
frames_true = frames_points_true
indices_frame_camintrinsics_camextrinsics = optimization_inputs_baseline['indices_frame_camintrinsics_camextrinsics']
observations_board_true = optimization_inputs_baseline['observations_board']
args.Nframes = len(optimization_inputs_baseline['frames_rt_toref'])
indices_point_camintrinsics_camextrinsics = None
points_true = None
observations_point_true = None
Npoints = None
else:
points_true = frames_points_true
indices_point_camintrinsics_camextrinsics = optimization_inputs_baseline['indices_point_camintrinsics_camextrinsics']
observations_point_true = optimization_inputs_baseline['observations_point']
Npoints = len(optimization_inputs_baseline['points'])
indices_frame_camintrinsics_camextrinsics = None
frames_true = None
observations_board_true = None
if args.make_documentation_plots is not None:
import gnuplotlib as gp
if args.make_documentation_plots:
for extension in ('pdf','svg','png','gp'):
processoptions_output = dict(wait = False,
terminal = terminal[extension],
_set = extraset[extension],
hardcopy = f'{args.make_documentation_plots}--simulated-geometry.{extension}')
gp.add_plot_option(processoptions_output, 'set', 'xyplane relative 0')
mrcal.show_geometry(models_baseline,
show_calobjects = True,
unset='key',
title='',
axis_scale = 1.0,
**processoptions_output)
if extension == 'pdf':
os.system(f"pdfcrop {processoptions_output['hardcopy']}")
else:
processoptions_output = dict(wait = True)
gp.add_plot_option(processoptions_output, 'set', 'xyplane relative 0')
mrcal.show_geometry(models_baseline,
show_calobjects = True,
title='',
axis_scale = 1.0,
**processoptions_output)
# shape (Nframes,Nh*Nw,2) or None
def observed_boards(icam):
if indices_frame_camintrinsics_camextrinsics is not None:
# shape (Nframes,Nh,Nw,2)
o = observations_board_true[indices_frame_camintrinsics_camextrinsics[:,1]==icam, ..., :2]
# shape (Nframes,Nh*Nw,2)
return (nps.mv(nps.clump(nps.mv(o,-1,-3), n=-2),-1,-2),
dict(legend = np.array([f"Board {i}" for i in range(o.shape[0],)])))
return None
# shape (Npoints,2) or None
def observed_points(icam):
if indices_point_camintrinsics_camextrinsics is not None:
return observations_point_true[indices_point_camintrinsics_camextrinsics[:,1]==icam, ..., :2]
return None
# plot tuples to display the observed_boards and/or observed_points,
# depending on what we have
def observed_pixels(icam):
t = []
o = observed_boards(icam)
if o is not None: t.append(o)
o = observed_points(icam)
if o is not None: t.append(o)
return t
if args.make_documentation_plots:
for extension in ('pdf','svg','png','gp'):
obs_cam = [ ( (*observed_pixels(icam),),
(q0_baseline, dict(_with = f'points pt 3 lw 2 lc "red" ps {2*pointscale[extension]}'))) \
for icam in range(args.Ncameras) ]
processoptions_output = dict(wait = False,
terminal = shorter_terminal(terminal[extension]),
_set = extraset[extension],
hardcopy = f'{args.make_documentation_plots}--simulated-observations.{extension}')
gp.add_plot_option(processoptions_output, 'set', ('xtics 1000', 'ytics 1000'))
gp.plot( *obs_cam,
tuplesize=-2,
_with='dots',
square=1,
_xrange=(0, models_true[0].imagersize()[0]-1),
_yrange=(models_true[0].imagersize()[1]-1, 0),
multiplot = 'layout 2,2',
**processoptions_output)
if extension == 'pdf':
os.system(f"pdfcrop {processoptions_output['hardcopy']}")
else:
obs_cam = [ ( (*observed_pixels(icam),),
(q0_baseline, dict(_with = f'points pt 3 lw 2 lc "red" ps {2*pointscale[""]}'))) \
for icam in range(args.Ncameras) ]
processoptions_output = dict(wait = True)
gp.plot( *obs_cam,
tuplesize=-2,
_with='dots',
square=1,
_xrange=(0, models_true[0].imagersize()[0]-1),
_yrange=(models_true[0].imagersize()[1]-1, 0),
multiplot = 'layout 2,2',
**processoptions_output)
# These are at the no-noise-but-with-regularization optimum
intrinsics_baseline = nps.cat( *[m.intrinsics()[1] for m in models_baseline] )
extrinsics_baseline_mounted = nps.cat( *[m.extrinsics_rt_fromref() for m in models_baseline] )
frames_baseline = optimization_inputs_baseline['frames_rt_toref']
points_baseline = optimization_inputs_baseline['points']
calobject_warp_baseline = optimization_inputs_baseline['calobject_warp']
if args.write_models:
for i in range(args.Ncameras):
filename = f"/tmp/models-true-camera{i}.cameramodel"
models_true [i].write(filename)
print(f"Wrote '{filename}'")
filename = f"/tmp/models-baseline-camera{i}.cameramodel"
models_baseline[i].write(filename)
print(f"Wrote '{filename}'")
if not args.do_sample:
sys.exit()
else:
# I wrote the no-input-noise-optimized model ("baseline"). I will write
# out the result from the first noise sample later
pass
def reproject_perturbed__common(q, distance,
# shape (Ncameras, Nintrinsics)
baseline_intrinsics,
# shape (Ncameras, 6)
baseline_rt_cam_ref,
# shape (Nframes, 6)
baseline_rt_ref_frame,
# shape (Npoints, 3)
baseline_points,
# shape (2)
baseline_calobject_warp,
# dict
baseline_optimization_inputs,
# shape (..., Ncameras, Nintrinsics)
query_intrinsics,
# shape (..., Ncameras, 6)
query_rt_cam_ref,
# shape (..., Nframes, 6)
query_rt_ref_frame,
# shape (Npoints, 3)
query_points,
# shape (..., 2)
query_calobject_warp,
# shape (...)
query_optimization_inputs,
# shape (..., Nstate)
query_b_unpacked,
# shape (..., Nobservations_board,Nheight,Nwidth, 2)
query_q_noise_board,
# shape (..., Nobservations_point, 2)
query_q_noise_point):
r'''Common logic for args.reproject_perturbed in
mean-pcam
meanq
bestq
worstq
Here I reproject the same q into all N cameras at the same time. I.e. this
is looking at Ncameras separate uncertainty computations at once
'''
if not (baseline_points is None or baseline_points.size == 0) or \
not (query_points is None or query_points .size == 0):
raise Exception("Only implemented for board-only solves")
# shape (Ncameras, 3)
p_cam_baseline = mrcal.unproject(q, lensmodel, baseline_intrinsics,
normalize = True) * distance
# shape (Ncameras, 3)
p_ref_baseline = \
mrcal.transform_point_rt( mrcal.invert_rt(baseline_rt_cam_ref),
p_cam_baseline )
if fixedframes:
p_ref_query = p_ref_baseline
else:
# shape (Nframes, Ncameras, 3)
# The point in the coord system of all the frames
p_frames = mrcal.transform_point_rt( \
nps.dummy(mrcal.invert_rt(baseline_rt_ref_frame),-2),
p_ref_baseline)
# shape (..., Nframes, Ncameras, 3)
p_ref_query_allframes = \
mrcal.transform_point_rt( nps.dummy(query_rt_ref_frame, -2),
p_frames )
if args.reproject_perturbed == 'mean-pcam':
# Mean 3D point
if fixedframes:
# shape (..., Ncameras, 3)
p_cam_query = \
mrcal.transform_point_rt(query_rt_cam_ref, p_ref_query)
else:
# shape (..., Nframes, Ncameras, 3)
p_cam_query_allframes = \
mrcal.transform_point_rt(nps.dummy(query_rt_cam_ref,-3), p_ref_query_allframes)
# shape (..., Ncameras, 3)
p_cam_query = np.mean( p_cam_query_allframes, axis = -3)
# shape (..., Ncameras, 2)
return mrcal.project(p_cam_query, lensmodel, query_intrinsics)
else:
# I'm looking at projections q, NOT points p. Several paths here:
# meanq
# bestq
# worstq
if fixedframes:
raise Exception("meanq,bestq,worstq not implemented if fixedframes. MAYBE is possible, but not useful-enough to think about")
# shape (..., Nframes, Ncameras, 3)
p_cam_query_allframes = \
mrcal.transform_point_rt(nps.dummy(query_rt_cam_ref,-3), p_ref_query_allframes)
# shape (..., Nframes, Ncameras, 2)
q_reprojected = mrcal.project(p_cam_query_allframes,
lensmodel, nps.dummy(query_intrinsics,-3))
if args.reproject_perturbed == 'meanq':
return np.mean(q_reprojected, axis=-3)
if args.reproject_perturbed == 'bestq' or \
args.reproject_perturbed == 'worstq':
# shape (..., Nframes, Ncameras)
q_err = nps.norm2(q_reprojected - q)
# shape (..., 1, Ncameras)
if args.reproject_perturbed == 'bestq':
i = q_err.argmin(axis=-2, keepdims=True)
else:
i = q_err.argmax(axis=-2, keepdims=True)
# shape (..., Nframes=1, Ncameras, 2)
q_reprojected = np.take_along_axis(q_reprojected, nps.dummy(i,-1), axis=-3)
# shape (..., Ncameras, 2)
q_reprojected = q_reprojected[...,0,:,:]
return q_reprojected
raise Exception(f"Unknown {args.reproject_perturbed=}")
def reproject_perturbed__fit_boards_ref(q, distance,
# shape (Ncameras, Nintrinsics)
baseline_intrinsics,
# shape (Ncameras, 6)
baseline_rt_cam_ref,
# shape (Nframes, 6)
baseline_rt_ref_frame,
# shape (Npoints, 3)
baseline_points,
# shape (2)
baseline_calobject_warp,
# dict
baseline_optimization_inputs,
# shape (..., Ncameras, Nintrinsics)
query_intrinsics,
# shape (..., Ncameras, 6)
query_rt_cam_ref,
# shape (..., Nframes, 6)
query_rt_ref_frame,
# shape (Npoints, 3)
query_points,
# shape (..., 2)
query_calobject_warp,
# shape (...)
query_optimization_inputs,
# shape (..., Nstate)
query_b_unpacked,
# shape (..., Nobservations_board,Nheight,Nwidth, 2)
query_q_noise_board,
# shape (..., Nobservations_point, 2)
query_q_noise_point):
r'''Reproject by explicitly computing a procrustes fit to align the reference
coordinate systems of the two solves. We match up the two sets of chessboard
points
'''
calobject_height,calobject_width = baseline_optimization_inputs['observations_board'].shape[1:3]
# shape (Nsamples, Nh, Nw, 3)
if query_calobject_warp.ndim > 1:
calibration_object_query = \
nps.cat(*[ mrcal.ref_calibration_object(calobject_width, calobject_height,
baseline_optimization_inputs['calibration_object_spacing'],
calobject_warp=calobject_warp) \
for calobject_warp in query_calobject_warp] )
else:
calibration_object_query = \
mrcal.ref_calibration_object(calobject_width, calobject_height,
baseline_optimization_inputs['calibration_object_spacing'],
calobject_warp=query_calobject_warp)
# shape (Nsamples, Nframes, Nh, Nw, 3)
pcorners_ref_query = \
mrcal.transform_point_rt( nps.dummy(query_rt_ref_frame, -2, -2),
nps.dummy(calibration_object_query, -4))
# shape (Nh, Nw, 3)
calibration_object_baseline = \
mrcal.ref_calibration_object(calobject_width, calobject_height,
baseline_optimization_inputs['calibration_object_spacing'],
calobject_warp=baseline_calobject_warp)
# frames_ref.shape is (Nframes, 6)
# shape (Nframes, Nh, Nw, 3)
pcorners_ref_baseline = \
mrcal.transform_point_rt( nps.dummy(baseline_rt_ref_frame, -2, -2),
calibration_object_baseline)
# shape (Nsamples,4,3)
Rt_refq_refb = \
mrcal.align_procrustes_points_Rt01( \
# shape (Nsamples,N,3)
nps.mv(nps.clump(nps.mv(pcorners_ref_query, -1,0),n=-3),0,-1),
# shape (N,3)
nps.clump(pcorners_ref_baseline, n=3))
# shape (Ncameras, 3)
p_cam_baseline = mrcal.unproject(q, lensmodel, baseline_intrinsics,
normalize = True) * distance
# shape (Ncameras, 3). In the ref coord system
p_ref_baseline = \
mrcal.transform_point_rt( mrcal.invert_rt(baseline_rt_cam_ref),
p_cam_baseline )
# shape (Nsamples,Ncameras,3)
p_ref_query = \
mrcal.transform_point_Rt(nps.mv(Rt_refq_refb,-3,-4),
p_ref_baseline)
# shape (..., Ncameras, 3)
p_cam_query = \
mrcal.transform_point_rt(query_rt_cam_ref, p_ref_query)
# shape (..., Ncameras, 2)
q1 = mrcal.project(p_cam_query, lensmodel, query_intrinsics)
if q1.shape[-3] == 1: q1 = q1[0,:,:]
return q1
# The others broadcast implicitly, while THIS main function really cannot handle
# outer dimensions, and needs an explicit broadcasting loop
@nps.broadcast_define(((2,), (),
('Ncameras', 'Nintrinsics'),
('Ncameras', 6),
('Nframes', 6),
('Npoints', 3),
(2,),
(),
('Ncameras', 'Nintrinsics'),
('Ncameras', 6),
('Nframes', 6),
('Npoints', 3),
(2,),
(),
('Nstate',),
('Nobservations','Nheight','Nwidth', 2),
('Nobservations', 2)),
('Ncameras',2))
def reproject_perturbed__diff(q, distance,
# shape (Ncameras, Nintrinsics)
baseline_intrinsics,
# shape (Ncameras, 6)
baseline_rt_cam_ref,
# shape (Nframes, 6)
baseline_rt_ref_frame,
# shape (Npoints, 3)
baseline_points,
# shape (2)
baseline_calobject_warp,
# dict
baseline_optimization_inputs,
# shape (..., Ncameras, Nintrinsics)
query_intrinsics,
# shape (..., Ncameras, 6)
query_rt_cam_ref,
# shape (..., Nframes, 6)
query_rt_ref_frame,
# shape (Npoints, 3)
query_points,
# shape (..., 2)
query_calobject_warp,
# shape (...)
query_optimization_inputs,
# shape (..., Nstate)
query_b_unpacked,
# shape (..., Nobservations_board,Nheight,Nwidth, 2)
query_q_noise_board,
# shape (..., Nobservations_point, 2)
query_q_noise_point):
r'''Reproject by using the "diff" method to compute a rotation
'''
# shape (Ncameras, 3)
p_cam_baseline = mrcal.unproject(q, lensmodel, baseline_intrinsics,
normalize = True) * distance
p_cam_query = np.zeros((args.Ncameras, 3), dtype=float)
for icam in range (args.Ncameras):
# This method only cares about the intrinsics
model_baseline = \
mrcal.cameramodel( intrinsics = (lensmodel, baseline_intrinsics[icam]),
imagersize = imagersizes[0] )
model_query = \
mrcal.cameramodel( intrinsics = (lensmodel, query_intrinsics[icam]),
imagersize = imagersizes[0] )
implied_Rt10_query = \
mrcal.projection_diff( (model_baseline,
model_query),
distance = distance,
use_uncertainties = False,
focus_center = None,
focus_radius = 1000.)[3]
mrcal.transform_point_Rt( implied_Rt10_query, p_cam_baseline[icam],
out = p_cam_query[icam] )
# shape (Ncameras, 2)
return \
mrcal.project( p_cam_query,
lensmodel, query_intrinsics)
def reproject_perturbed__cross_reprojection(q, distance,
# shape (Ncameras, Nintrinsics)
baseline_intrinsics,
# shape (Ncameras, 6)
baseline_rt_cam_ref,
# shape (Nframes, 6)
baseline_rt_ref_frame,
# shape (Npoints, 3)
baseline_point,
# shape (2)
baseline_calobject_warp,
# dict