forked from mapillary/OpenSfM
-
Notifications
You must be signed in to change notification settings - Fork 38
/
io.py
1520 lines (1312 loc) · 46.5 KB
/
io.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
import json
import logging
import os
import shutil
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Union, Dict, Any, Iterable, List, IO, Tuple, TextIO, Optional
import cv2
import numpy as np
import pyproj
from numpy import ndarray
from opensfm import context, features, geo, pygeometry, pymap, types
from PIL import Image
import rasterio
import sys
from rasterio.plot import reshape_as_image
import warnings
warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)
logger: logging.Logger = logging.getLogger(__name__)
logging.getLogger("rasterio").setLevel(logging.WARNING)
logging.getLogger("PIL").setLevel(logging.WARNING)
def camera_from_json(key: str, obj: Dict[str, Any]) -> pygeometry.Camera:
"""
Read camera from a json object
"""
camera = None
pt = obj.get("projection_type", "perspective")
if pt == "perspective":
camera = pygeometry.Camera.create_perspective(
obj["focal"], obj.get("k1", 0.0), obj.get("k2", 0.0)
)
elif pt == "brown":
camera = pygeometry.Camera.create_brown(
obj["focal_x"],
obj["focal_y"] / obj["focal_x"],
np.array([obj.get("c_x", 0.0), obj.get("c_y", 0.0)]),
np.array(
[
obj.get("k1", 0.0),
obj.get("k2", 0.0),
obj.get("k3", 0.0),
obj.get("p1", 0.0),
obj.get("p2", 0.0),
]
),
)
elif pt == "fisheye":
camera = pygeometry.Camera.create_fisheye(
obj["focal"], obj.get("k1", 0.0), obj.get("k2", 0.0)
)
elif pt == "fisheye_opencv":
camera = pygeometry.Camera.create_fisheye_opencv(
obj["focal_x"],
obj["focal_y"] / obj["focal_x"],
np.array([obj.get("c_x", 0.0), obj.get("c_y", 0.0)]),
np.array(
[
obj.get("k1", 0.0),
obj.get("k2", 0.0),
obj.get("k3", 0.0),
obj.get("k4", 0.0),
]
),
)
elif pt == "fisheye62":
camera = pygeometry.Camera.create_fisheye62(
obj["focal_x"],
obj["focal_y"] / obj["focal_x"],
np.array([obj.get("c_x", 0.0), obj.get("c_y", 0.0)]),
np.array(
[
obj.get("k1", 0.0),
obj.get("k2", 0.0),
obj.get("k3", 0.0),
obj.get("k4", 0.0),
obj.get("k5", 0.0),
obj.get("k6", 0.0),
obj.get("p1", 0.0),
obj.get("p2", 0.0),
]
),
)
elif pt == "fisheye624":
camera = pygeometry.Camera.create_fisheye624(
obj["focal_x"],
obj["focal_y"] / obj["focal_x"],
np.array([obj.get("c_x", 0.0), obj.get("c_y", 0.0)]),
np.array(
[
obj.get("k1", 0.0),
obj.get("k2", 0.0),
obj.get("k3", 0.0),
obj.get("k4", 0.0),
obj.get("k5", 0.0),
obj.get("k6", 0.0),
obj.get("p1", 0.0),
obj.get("p2", 0.0),
obj.get("s0", 0.0),
obj.get("s1", 0.0),
obj.get("s2", 0.0),
obj.get("s3", 0.0),
]
),
)
elif pt == "radial":
camera = pygeometry.Camera.create_radial(
obj["focal_x"],
obj["focal_y"] / obj["focal_x"],
np.array([obj.get("c_x", 0.0), obj.get("c_y", 0.0)]),
np.array(
[
obj.get("k1", 0.0),
obj.get("k2", 0.0),
]
),
)
elif pt == "simple_radial":
camera = pygeometry.Camera.create_simple_radial(
obj["focal_x"],
obj["focal_y"] / obj["focal_x"],
np.array([obj.get("c_x", 0.0), obj.get("c_y", 0.0)]),
obj.get("k1", 0.0),
)
elif pt == "dual":
camera = pygeometry.Camera.create_dual(
obj.get("transition", 0.5),
obj["focal"],
obj.get("k1", 0.0),
obj.get("k2", 0.0),
)
elif pygeometry.Camera.is_panorama(pt):
camera = pygeometry.Camera.create_spherical()
else:
raise NotImplementedError
camera.id = key
camera.width = int(obj.get("width", 0))
camera.height = int(obj.get("height", 0))
return camera
def pose_from_json(obj: Dict[str, Any]) -> pygeometry.Pose:
pose = pygeometry.Pose()
pose.rotation = obj["rotation"]
if "translation" in obj:
pose.translation = obj["translation"]
return pose
def bias_from_json(obj: Dict[str, Any]) -> pygeometry.Similarity:
return pygeometry.Similarity(obj["rotation"], obj["translation"], obj["scale"])
def assign_shot_attributes(obj: Dict[str, Any], shot: pymap.Shot) -> None:
shot.metadata = json_to_pymap_metadata(obj)
if "scale" in obj:
shot.scale = obj["scale"]
if "covariance" in obj:
shot.covariance = np.array(obj["covariance"])
if "merge_cc" in obj:
shot.merge_cc = obj["merge_cc"]
if "vertices" in obj and "faces" in obj:
shot.mesh.vertices = obj["vertices"]
shot.mesh.faces = obj["faces"]
def shot_in_reconstruction_from_json(
reconstruction: types.Reconstruction,
key: str,
obj: Dict[str, Any],
rig_instance_id: Optional[str] = None,
rig_camera_id: Optional[str] = None,
is_pano_shot: bool = False,
) -> pymap.Shot:
"""
Read shot from a json object and append it to a reconstruction
"""
pose = pose_from_json(obj)
if is_pano_shot:
shot = reconstruction.create_pano_shot(key, obj["camera"], pose)
else:
shot = reconstruction.create_shot(
key, obj["camera"], pose, rig_camera_id, rig_instance_id
)
assign_shot_attributes(obj, shot)
return shot
def single_shot_from_json(
key: str, obj: Dict[str, Any], camera: pygeometry.Camera
) -> pymap.Shot:
"""
Read shot from a json object
"""
pose = pose_from_json(obj)
shot = pymap.Shot(key, camera, pose)
assign_shot_attributes(obj, shot)
return shot
def point_from_json(
reconstruction: types.Reconstruction, key: str, obj: Dict[str, Any]
) -> pymap.Landmark:
"""
Read a point from a json object
"""
point = reconstruction.create_point(key, obj["coordinates"])
point.color = obj["color"]
return point
def rig_camera_from_json(key: str, obj: Dict[str, Any]) -> pymap.RigCamera:
"""
Read a rig cameras from a json object
"""
pose = pygeometry.Pose()
pose.rotation = obj["rotation"]
pose.translation = obj["translation"]
rig_camera = pymap.RigCamera(pose, key)
return rig_camera
def rig_cameras_from_json(obj: Dict[str, Any]) -> Dict[str, pymap.RigCamera]:
"""
Read rig cameras from a json object
"""
rig_cameras = {}
for key, value in obj.items():
rig_cameras[key] = rig_camera_from_json(key, value)
return rig_cameras
def rig_instance_from_json(
reconstruction: types.Reconstruction, instance_id: str, obj: Dict[str, Any]
) -> None:
"""
Read any rig instance from a json shot object
"""
reconstruction.add_rig_instance(pymap.RigInstance(instance_id))
pose = pygeometry.Pose()
pose.rotation = obj["rotation"]
pose.translation = obj["translation"]
reconstruction.rig_instances[instance_id].pose = pose
def rig_instance_camera_per_shot(obj: Dict[str, Any]) -> Dict[str, Tuple[str, str]]:
"""
Given JSON root data, return (rig_instance_id, rig_camera_id) per shot.
"""
panoshots = set(obj["pano_shots"].keys()) if "pano_shots" in obj else {}
rig_shots = {}
if "rig_instances" in obj:
rig_shots = {
s_key: (i_key, c_key)
for i_key, ri in obj["rig_instances"].items()
for s_key, c_key in ri["rig_camera_ids"].items()
if s_key not in panoshots
}
return rig_shots
def reconstruction_from_json(obj: Dict[str, Any]) -> types.Reconstruction:
"""
Read a reconstruction from a json object
"""
reconstruction = types.Reconstruction()
# Extract cameras
for key, value in obj["cameras"].items():
camera = camera_from_json(key, value)
reconstruction.add_camera(camera)
# Extract camera biases
if "biases" in obj:
for key, value in obj["biases"].items():
transform = bias_from_json(value)
reconstruction.set_bias(key, transform)
# Extract rig models
if "rig_cameras" in obj:
for key, value in obj["rig_cameras"].items():
reconstruction.add_rig_camera(rig_camera_from_json(key, value))
# Extract rig instances from shots
if "rig_instances" in obj:
for key, value in obj["rig_instances"].items():
rig_instance_from_json(reconstruction, key, value)
# Extract shots
rig_shots = rig_instance_camera_per_shot(obj)
for key, value in obj["shots"].items():
shot_in_reconstruction_from_json(
reconstruction,
key,
value,
rig_camera_id=rig_shots[key][1] if key in rig_shots else None,
rig_instance_id=rig_shots[key][0] if key in rig_shots else None,
is_pano_shot=False,
)
# Extract points
if "points" in obj:
for key, value in obj["points"].items():
point_from_json(reconstruction, key, value)
# Extract pano_shots
if "pano_shots" in obj:
for key, value in obj["pano_shots"].items():
shot_in_reconstruction_from_json(
reconstruction, key, value, is_pano_shot=True
)
# Extract reference topocentric frame
if "reference_lla" in obj:
lla = obj["reference_lla"]
reconstruction.reference = geo.TopocentricConverter(
lla["latitude"], lla["longitude"], lla["altitude"]
)
return reconstruction
def reconstructions_from_json(obj: List[Dict[str, Any]]) -> List[types.Reconstruction]:
"""
Read all reconstructions from a json object
"""
return [reconstruction_from_json(i) for i in obj]
def cameras_from_json(obj: Dict[str, Any]) -> Dict[str, pygeometry.Camera]:
"""
Read cameras from a json object
"""
cameras = {}
for key, value in obj.items():
cameras[key] = camera_from_json(key, value)
return cameras
def camera_to_json(camera) -> Dict[str, Any]:
"""
Write camera to a json object
"""
if camera.projection_type == "perspective":
return {
"projection_type": camera.projection_type,
"width": camera.width,
"height": camera.height,
"focal": camera.focal,
"k1": camera.k1,
"k2": camera.k2,
}
elif camera.projection_type == "brown":
return {
"projection_type": camera.projection_type,
"width": camera.width,
"height": camera.height,
"focal_x": camera.focal,
"focal_y": camera.focal * camera.aspect_ratio,
"c_x": camera.principal_point[0],
"c_y": camera.principal_point[1],
"k1": camera.k1,
"k2": camera.k2,
"p1": camera.p1,
"p2": camera.p2,
"k3": camera.k3,
}
elif camera.projection_type == "fisheye":
return {
"projection_type": camera.projection_type,
"width": camera.width,
"height": camera.height,
"focal": camera.focal,
"k1": camera.k1,
"k2": camera.k2,
}
elif camera.projection_type == "fisheye_opencv":
return {
"projection_type": camera.projection_type,
"width": camera.width,
"height": camera.height,
"focal_x": camera.focal,
"focal_y": camera.focal * camera.aspect_ratio,
"c_x": camera.principal_point[0],
"c_y": camera.principal_point[1],
"k1": camera.k1,
"k2": camera.k2,
"k3": camera.k3,
"k4": camera.k4,
}
elif camera.projection_type == "fisheye62":
return {
"projection_type": camera.projection_type,
"width": camera.width,
"height": camera.height,
"focal_x": camera.focal,
"focal_y": camera.focal * camera.aspect_ratio,
"c_x": camera.principal_point[0],
"c_y": camera.principal_point[1],
"k1": camera.k1,
"k2": camera.k2,
"k3": camera.k3,
"k4": camera.k4,
"k5": camera.k5,
"k6": camera.k6,
"p1": camera.p1,
"p2": camera.p2,
}
elif camera.projection_type == "fisheye624":
return {
"projection_type": camera.projection_type,
"width": camera.width,
"height": camera.height,
"focal_x": camera.focal,
"focal_y": camera.focal * camera.aspect_ratio,
"c_x": camera.principal_point[0],
"c_y": camera.principal_point[1],
"k1": camera.k1,
"k2": camera.k2,
"k3": camera.k3,
"k4": camera.k4,
"k5": camera.k5,
"k6": camera.k6,
"p1": camera.p1,
"p2": camera.p2,
"s0": camera.s0,
"s1": camera.s1,
"s2": camera.s2,
"s3": camera.s3,
}
elif camera.projection_type == "simple_radial":
return {
"projection_type": camera.projection_type,
"width": camera.width,
"height": camera.height,
"focal_x": camera.focal,
"focal_y": camera.focal * camera.aspect_ratio,
"c_x": camera.principal_point[0],
"c_y": camera.principal_point[1],
"k1": camera.k1,
}
elif camera.projection_type == "radial":
return {
"projection_type": camera.projection_type,
"width": camera.width,
"height": camera.height,
"focal_x": camera.focal,
"focal_y": camera.focal * camera.aspect_ratio,
"c_x": camera.principal_point[0],
"c_y": camera.principal_point[1],
"k1": camera.k1,
"k2": camera.k2,
}
elif camera.projection_type == "dual":
return {
"projection_type": camera.projection_type,
"width": camera.width,
"height": camera.height,
"focal": camera.focal,
"k1": camera.k1,
"k2": camera.k2,
"transition": camera.transition,
}
elif pygeometry.Camera.is_panorama(camera.projection_type):
return {
"projection_type": camera.projection_type,
"width": camera.width,
"height": camera.height,
}
else:
raise NotImplementedError
def shot_to_json(shot: pymap.Shot) -> Dict[str, Any]:
"""
Write shot to a json object
"""
obj: Dict[str, Any] = {
"rotation": list(shot.pose.rotation),
"translation": list(shot.pose.translation),
"camera": shot.camera.id,
}
if shot.metadata is not None:
obj.update(pymap_metadata_to_json(shot.metadata))
if shot.mesh is not None:
obj["vertices"] = [list(vertice) for vertice in shot.mesh.vertices]
obj["faces"] = [list(face) for face in shot.mesh.faces]
if hasattr(shot, "scale"):
obj["scale"] = shot.scale
if hasattr(shot, "covariance"):
obj["covariance"] = shot.covariance.tolist()
if hasattr(shot, "merge_cc"):
obj["merge_cc"] = shot.merge_cc
return obj
def rig_instance_to_json(rig_instance: pymap.RigInstance) -> Dict[str, Any]:
"""
Write a rig instance to a json object
"""
return {
"translation": list(rig_instance.pose.translation),
"rotation": list(rig_instance.pose.rotation),
"rig_camera_ids": rig_instance.rig_camera_ids,
}
def rig_camera_to_json(rig_camera: pymap.RigCamera) -> Dict[str, Any]:
"""
Write a rig camera to a json object
"""
obj = {
"rotation": list(rig_camera.pose.rotation),
"translation": list(rig_camera.pose.translation),
}
return obj
def pymap_metadata_to_json(metadata: pymap.ShotMeasurements) -> Dict[str, Any]:
obj = {}
if metadata.orientation.has_value:
obj["orientation"] = metadata.orientation.value
if metadata.capture_time.has_value:
obj["capture_time"] = metadata.capture_time.value
if metadata.gps_accuracy.has_value:
obj["gps_dop"] = metadata.gps_accuracy.value
if metadata.gps_position.has_value:
obj["gps_position"] = list(metadata.gps_position.value)
if metadata.gravity_down.has_value:
obj["gravity_down"] = list(metadata.gravity_down.value)
if metadata.compass_angle.has_value and metadata.compass_accuracy.has_value:
obj["compass"] = {
"angle": metadata.compass_angle.value,
"accuracy": metadata.compass_accuracy.value,
}
else:
if metadata.compass_angle.has_value:
obj["compass"] = {"angle": metadata.compass_angle.value}
elif metadata.compass_accuracy.has_value:
obj["compass"] = {"accuracy": metadata.compass_accuracy.value}
if metadata.sequence_key.has_value:
obj["skey"] = metadata.sequence_key.value
return obj
def json_to_pymap_metadata(obj: Dict[str, Any]) -> pymap.ShotMeasurements:
metadata = pymap.ShotMeasurements()
if obj.get("orientation") is not None:
metadata.orientation.value = obj.get("orientation")
if obj.get("capture_time") is not None:
metadata.capture_time.value = obj.get("capture_time")
if obj.get("gps_dop") is not None:
metadata.gps_accuracy.value = obj.get("gps_dop")
if obj.get("gps_position") is not None:
metadata.gps_position.value = obj.get("gps_position")
if obj.get("skey") is not None:
metadata.sequence_key.value = obj.get("skey")
if obj.get("gravity_down") is not None:
metadata.gravity_down.value = obj.get("gravity_down")
if obj.get("compass") is not None:
compass = obj.get("compass")
if "angle" in compass:
metadata.compass_angle.value = compass["angle"]
if "accuracy" in compass:
metadata.compass_accuracy.value = compass["accuracy"]
return metadata
def point_to_json(point: pymap.Landmark) -> Dict[str, Any]:
"""
Write a point to a json object
"""
return {
"color": list(point.color.astype(float)),
"coordinates": list(point.coordinates),
}
def reconstruction_to_json(reconstruction: types.Reconstruction) -> Dict[str, Any]:
"""
Write a reconstruction to a json object
"""
obj = {"cameras": {}, "shots": {}, "points": {}, "biases": {}}
# Extract cameras
for camera in reconstruction.cameras.values():
obj["cameras"][camera.id] = camera_to_json(camera)
# Extract cameras biases
for camera_id, bias in reconstruction.biases.items():
obj["biases"][camera_id] = bias_to_json(bias)
# Extract rig models
if len(reconstruction.rig_cameras):
obj["rig_cameras"] = {}
for rig_camera in reconstruction.rig_cameras.values():
obj["rig_cameras"][rig_camera.id] = rig_camera_to_json(rig_camera)
if len(reconstruction.rig_instances):
obj["rig_instances"] = {}
for rig_instance in reconstruction.rig_instances.values():
obj["rig_instances"][rig_instance.id] = rig_instance_to_json(rig_instance)
# Extract shots
for shot in reconstruction.shots.values():
obj["shots"][shot.id] = shot_to_json(shot)
# Extract points
for point in reconstruction.points.values():
obj["points"][point.id] = point_to_json(point)
# Extract pano_shots
if hasattr(reconstruction, "pano_shots"):
if len(reconstruction.pano_shots) > 0:
obj["pano_shots"] = {}
for shot in reconstruction.pano_shots.values():
obj["pano_shots"][shot.id] = shot_to_json(shot)
# Extract reference topocentric frame
if reconstruction.reference:
ref = reconstruction.reference
obj["reference_lla"] = {
"latitude": ref.lat,
"longitude": ref.lon,
"altitude": ref.alt,
}
return obj
def reconstructions_to_json(
reconstructions: Iterable[types.Reconstruction],
) -> List[Dict[str, Any]]:
"""
Write all reconstructions to a json object
"""
return [reconstruction_to_json(i) for i in reconstructions]
def cameras_to_json(cameras: Dict[str, pygeometry.Camera]) -> Dict[str, Dict[str, Any]]:
"""
Write cameras to a json object
"""
obj = {}
for camera in cameras.values():
obj[camera.id] = camera_to_json(camera)
return obj
def bias_to_json(bias: pygeometry.Similarity) -> Dict[str, Any]:
return {
"rotation": list(bias.rotation),
"translation": list(bias.translation),
"scale": bias.scale,
}
def rig_cameras_to_json(
rig_cameras: Dict[str, pymap.RigCamera]
) -> Dict[str, Dict[str, Any]]:
"""
Write rig cameras to a json object
"""
obj = {}
for rig_camera in rig_cameras.values():
obj[rig_camera.id] = rig_camera_to_json(rig_camera)
return obj
def camera_from_vector(
camera_id: str,
width: int,
height: int,
projection_type: str,
parameters: List[float],
) -> pygeometry.Camera:
"""Build a camera from a serialized vector of parameters."""
if projection_type == "perspective":
focal, k1, k2 = parameters
camera = pygeometry.Camera.create_perspective(focal, k1, k2)
elif projection_type == "brown":
fx, fy, cx, cy, k1, k2, p1, p2, k3 = parameters
camera = pygeometry.Camera.create_brown(
fx, fy / fx, np.array([cx, cy]), np.array([k1, k2, k3, p1, p2])
)
elif projection_type == "fisheye":
focal, k1, k2 = parameters
camera = pygeometry.Camera.create_fisheye(focal, k1, k2)
elif projection_type == "fisheye_opencv":
fx, fy, cx, cy, k1, k2, k3, k4 = parameters
camera = pygeometry.Camera.create_fisheye_opencv(
fx, fy / fx, np.array([cx, cy]), np.array([k1, k2, k3, k4])
)
elif projection_type == "fisheye62":
fx, fy, cx, cy, k1, k2, k3, k4, k5, k6, p1, p2 = parameters
camera = pygeometry.Camera.create_fisheye62(
fx, fy / fx, np.array([cx, cy]), np.array([k1, k2, k3, k4, k5, k6, p1, p2])
)
elif projection_type == "fisheye624":
fx, fy, cx, cy, k1, k2, k3, k4, k5, k6, p1, p2, s0, s1, s2, s3 = parameters
camera = pygeometry.Camera.create_fisheye624(
fx,
fy / fx,
np.array([cx, cy]),
np.array([k1, k2, k3, k4, k5, k6, p1, p2, s0, s1, s2, s3]),
)
elif projection_type == "radial":
fx, fy, cx, cy, k1, k2 = parameters
camera = pygeometry.Camera.create_radial(
fx, fy / fx, np.array([cx, cy]), np.array([k1, k2])
)
elif projection_type == "simple_radial":
fx, fy, cx, cy, k1 = parameters
camera = pygeometry.Camera.create_simple_radial(
fx, fy / fx, np.array([cx, cy]), k1
)
elif projection_type == "dual":
focal, k1, k2, transition = parameters
camera = pygeometry.Camera.create_dual(transition, focal, k1, k2)
elif pygeometry.Camera.is_panorama(projection_type):
camera = pygeometry.Camera.create_spherical()
else:
raise NotImplementedError
camera.id = camera_id
camera.width = width
camera.height = height
return camera
def camera_to_vector(camera: pygeometry.Camera) -> List[float]:
"""Serialize camera parameters to a vector of floats."""
if camera.projection_type == "perspective":
parameters = [camera.focal, camera.k1, camera.k2]
elif camera.projection_type == "brown":
parameters = [
camera.focal,
camera.focal * camera.aspect_ratio,
camera.principal_point[0],
camera.principal_point[1],
camera.k1,
camera.k2,
camera.p1,
camera.p2,
camera.k3,
]
elif camera.projection_type == "fisheye":
parameters = [camera.focal, camera.k1, camera.k2]
elif camera.projection_type == "fisheye_opencv":
parameters = [
camera.focal,
camera.focal * camera.aspect_ratio,
camera.principal_point[0],
camera.principal_point[1],
camera.k1,
camera.k2,
camera.k3,
camera.k4,
]
elif camera.projection_type == "fisheye62":
parameters = [
camera.focal,
camera.focal * camera.aspect_ratio,
camera.principal_point[0],
camera.principal_point[1],
camera.k1,
camera.k2,
camera.k3,
camera.k4,
camera.k5,
camera.k6,
camera.p1,
camera.p2,
]
elif camera.projection_type == "fisheye624":
parameters = [
camera.focal,
camera.focal * camera.aspect_ratio,
camera.principal_point[0],
camera.principal_point[1],
camera.k1,
camera.k2,
camera.k3,
camera.k4,
camera.k5,
camera.k6,
camera.p1,
camera.p2,
camera.s0,
camera.s1,
camera.s2,
camera.s3,
]
elif camera.projection_type == "radial":
parameters = [
camera.focal,
camera.focal * camera.aspect_ratio,
camera.principal_point[0],
camera.principal_point[1],
camera.k1,
camera.k2,
]
elif camera.projection_type == "simple_radial":
parameters = [
camera.focal,
camera.focal * camera.aspect_ratio,
camera.principal_point[0],
camera.principal_point[1],
camera.k1,
]
elif camera.projection_type == "dual":
parameters = [
camera.focal,
camera.k1,
camera.k2,
camera.transition,
]
elif pygeometry.Camera.is_panorama(camera.projection_type):
parameters = []
else:
raise NotImplementedError
return parameters
def _read_gcp_list_lines(
lines: Iterable[str],
projection,
exifs: Dict[str, Dict[str, Any]],
) -> List[pymap.GroundControlPoint]:
points = {}
for line in lines:
words = line.split(None, 6)
easting, northing, alt, pixel_x, pixel_y = map(float, words[:5])
key = (easting, northing, alt)
shot_tokens = words[5].split(None)
shot_id = shot_tokens[0]
if shot_id not in exifs:
continue
if key in points:
point = points[key]
else:
# Convert 3D coordinates
if np.isnan(alt):
alt = 0
has_altitude = False
else:
has_altitude = True
if projection is not None:
lat, lon = projection.transform(easting, northing)
else:
lon, lat = easting, northing
point = pymap.GroundControlPoint()
if len(words) > 6:
point.id = words[6].strip()
else:
point.id = "GCP-%d" % len(points)
point.lla = {"latitude": lat, "longitude": lon, "altitude": alt}
point.has_altitude = has_altitude
points[key] = point
# Convert 2D coordinates
d = exifs[shot_id]
coordinates = features.normalized_image_coordinates(
np.array([[pixel_x, pixel_y]]), d["width"], d["height"]
)[0]
o = pymap.GroundControlPointObservation()
o.shot_id = shot_id
o.projection = coordinates
point.add_observation(o)
return list(points.values())
def _parse_utm_projection_string(line: str) -> str:
"""Convert strings like 'WGS84 UTM 32N' to a proj4 definition."""
words = line.lower().split()
assert len(words) == 3
zone = line.split()[2].upper()
if zone[-1] == "N":
zone_number = int(zone[:-1])
zone_hemisphere = "north"
elif zone[-1] == "S":
zone_number = int(zone[:-1])
zone_hemisphere = "south"
else:
zone_number = int(zone)
zone_hemisphere = "north"
s = "+proj=utm +zone={} +{} +ellps=WGS84 +datum=WGS84 +units=m +no_defs"
return s.format(zone_number, zone_hemisphere)
def _parse_projection(line: str) -> Optional[pyproj.Transformer]:
"""Build a proj4 from the GCP format line."""
crs_4326 = pyproj.CRS.from_epsg(4326)
if line.strip() == "WGS84":
return None
elif line.upper().startswith("WGS84 UTM"):
return pyproj.Transformer.from_proj(
pyproj.CRS(_parse_utm_projection_string(line)), crs_4326
)
elif "+proj" in line:
return pyproj.Transformer.from_proj(pyproj.CRS(line), crs_4326)
elif line.upper().startswith("EPSG:"):
return pyproj.Transformer.from_proj(
pyproj.CRS.from_epsg(int(line.split(":")[1])), crs_4326
)
else:
raise ValueError("Un-supported geo system definition: {}".format(line))
def _valid_gcp_line(line: str) -> bool:
stripped = line.strip()
return stripped != "" and stripped[0] != "#"
def read_gcp_list(fileobj, exif: Dict[str, Any]) -> List[pymap.GroundControlPoint]:
"""Read a ground control points from a gcp_list.txt file.
It requires the points to be in the WGS84 lat, lon, alt format.
If reference is None, topocentric data won't be initialized.
"""
all_lines = fileobj.readlines()
lines = iter(filter(_valid_gcp_line, all_lines))
projection = _parse_projection(next(lines))
points = _read_gcp_list_lines(lines, projection, exif)
return points
def read_ground_control_points(fileobj: IO) -> List[pymap.GroundControlPoint]:
"""Read ground control points from json file"""
obj = json_load(fileobj)
points = []
for point_dict in obj["points"]:
point = pymap.GroundControlPoint()
point.id = point_dict["id"]
lla = point_dict.get("position")
if lla:
point.lla = lla
point.has_altitude = "altitude" in point.lla
observations = []
observing_images = set()
for o_dict in point_dict["observations"]:
o = pymap.GroundControlPointObservation()
o.shot_id = o_dict["shot_id"]
if o.shot_id in observing_images:
logger.warning(
"GCP {} has multiple observations in image {}".format(
point.id, o.shot_id
)
)
observing_images.add(o.shot_id)
if "projection" in o_dict:
o.projection = np.array(o_dict["projection"])
observations.append(o)
point.observations = observations
points.append(point)
return points
def write_ground_control_points(
gcp: List[pymap.GroundControlPoint],
fileobj: IO,
) -> None:
"""Write ground control points to json file."""
obj = {"points": []}
for point in gcp:
point_obj = {}
point_obj["id"] = point.id
if point.lla:
point_obj["position"] = {
"latitude": point.lla["latitude"],
"longitude": point.lla["longitude"],
}
if point.has_altitude:
point_obj["position"]["altitude"] = point.lla["altitude"]
point_obj["observations"] = []
for observation in point.observations:
point_obj["observations"].append(
{
"shot_id": observation.shot_id,
"projection": tuple(observation.projection),
}
)