-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathtransforms.py
More file actions
1464 lines (1234 loc) · 51.3 KB
/
transforms.py
File metadata and controls
1464 lines (1234 loc) · 51.3 KB
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
from typing import *
from numbers import Number
import itertools
import torch
from torch import Tensor
import torch.nn.functional as F
from .helpers import batched, totensor
__all__ = [
'perspective_from_fov',
'perspective_from_window',
'intrinsics_from_fov',
'intrinsics_from_focal_center',
'focal_to_fov',
'fov_to_focal',
'intrinsics_to_fov',
'view_look_at',
'extrinsics_look_at',
'perspective_to_intrinsics',
'intrinsics_to_perspective',
'extrinsics_to_view',
'view_to_extrinsics',
'normalize_intrinsics',
'denormalize_intrinsics',
'crop_intrinsics',
'pixel_to_uv',
'pixel_to_ndc',
'uv_to_pixel',
'depth_linear_to_buffer',
'depth_buffer_to_linear',
'project_gl',
'project_cv',
'unproject_gl',
'unproject_cv',
'project',
'unproject',
'skew_symmetric',
'rotation_matrix_from_vectors',
'euler_axis_angle_rotation',
'euler_angles_to_matrix',
'matrix_to_euler_angles',
'matrix_to_quaternion',
'quaternion_to_matrix',
'quaternion_multiply',
'quaternion_inverse',
'matrix_to_axis_angle',
'axis_angle_to_matrix',
'axis_angle_to_quaternion',
'quaternion_to_axis_angle',
'make_affine_matrix',
'random_rotation_matrix',
'lerp',
'slerp',
'slerp_rotation_matrix',
'interpolate_se3_matrix',
'extrinsics_to_essential',
'rotation_matrix_2d',
'rotate_2d',
'translate_2d',
'scale_2d',
'transform_points',
'angle_between'
]
@totensor(_others=torch.float32)
@batched(_others=0)
def perspective_from_fov(
*,
fov_x: Optional[Union[float, Tensor]] = None,
fov_y: Optional[Union[float, Tensor]] = None,
fov_min: Optional[Union[float, Tensor]] = None,
fov_max: Optional[Union[float, Tensor]] = None,
aspect_ratio: Optional[Union[float, Tensor]] = None,
near: Optional[Union[float, Tensor]],
far: Optional[Union[float, Tensor]],
) -> Tensor:
"""
Get OpenGL perspective matrix from field of view
## Returns
(Tensor): [..., 4, 4] perspective matrix
"""
if fov_max is not None:
fx = torch.maximum(1, 1 / aspect_ratio) / torch.tan(fov_max / 2)
fy = torch.maximum(1, aspect_ratio) / torch.tan(fov_max / 2)
elif fov_min is not None:
fx = torch.minimum(1, 1 / aspect_ratio) / torch.tan(fov_min / 2)
fy = torch.minimum(1, aspect_ratio) / torch.tan(fov_min / 2)
elif fov_x is not None and fov_y is not None:
fx = 1 / torch.tan(fov_x / 2)
fy = 1 / torch.tan(fov_y / 2)
elif fov_x is not None:
fx = 1 / torch.tan(fov_x / 2)
fy = fx * aspect_ratio
elif fov_y is not None:
fy = 1 / torch.tan(fov_y / 2)
fx = fy / aspect_ratio
zeros = torch.zeros_like(fx)
ones = torch.ones_like(fx)
perspective = torch.stack([
fx, zeros, zeros, zeros,
zeros, fy, zeros, zeros,
zeros, zeros, (near / far + 1) / (near / far - 1), 2. * near / (near / far - 1),
zeros, zeros, -ones, zeros
], dim=-1).unflatten(-1, (4, 4))
return perspective
@totensor(_others=torch.float32)
@batched(_others=0)
def perspective_from_window(
left: Union[float, Tensor],
right: Union[float, Tensor],
bottom: Union[float, Tensor],
top: Union[float, Tensor],
near: Union[float, Tensor],
far: Union[float, Tensor]
) -> Tensor:
"""
Get OpenGL perspective matrix from the window of z=-1 projection plane
## Returns
(Tensor): [..., 4, 4] perspective matrix
"""
zeros = torch.zeros_like(left)
ones = torch.ones_like(left)
perspective = torch.stack([
2 / (right - left), zeros, (right + left) / (right - left), zeros,
zeros, 2 / (top - bottom), (top + bottom) / (top - bottom), zeros,
zeros, zeros, (near / far + 1) / (near / far - 1), 2. * near / (near / far - 1),
zeros, zeros, -ones, zeros
], dim=-1).unflatten(-1, (4, 4))
return perspective
@totensor(_others=torch.float32)
@batched(_others=0)
def intrinsics_from_focal_center(
fx: Union[float, Tensor],
fy: Union[float, Tensor],
cx: Union[float, Tensor],
cy: Union[float, Tensor]
) -> Tensor:
"""
Get OpenCV intrinsics matrix
## Parameters
focal_x (float | Tensor): focal length in x axis
focal_y (float | Tensor): focal length in y axis
cx (float | Tensor): principal point in x axis
cy (float | Tensor): principal point in y axis
## Returns
(Tensor): [..., 3, 3] OpenCV intrinsics matrix
"""
zeros, ones = torch.zeros_like(fx), torch.ones_like(fx)
ret = torch.stack([
fx, zeros, cx,
zeros, fy, cy,
zeros, zeros, ones
], dim=-1).unflatten(-1, (3, 3))
return ret
@totensor(_others=torch.float32)
@batched(_others=0)
def intrinsics_from_fov(
*,
fov_x: Optional[Union[float, Tensor]] = None,
fov_y: Optional[Union[float, Tensor]] = None,
fov_max: Optional[Union[float, Tensor]] = None,
fov_min: Optional[Union[float, Tensor]] = None,
cx: Union[float, Tensor] = 0.5,
cy: Union[float, Tensor] = 0.5,
aspect_ratio: Optional[Union[float, Tensor]] = None,
) -> Tensor:
"""
Get normalized OpenCV intrinsics matrix from given field of view.
You can provide either fov_x, fov_y, fov_max or fov_min and aspect_ratio
Parameters
----
fov_x (float | Tensor): field of view in x axis
fov_y (float | Tensor): field of view in y axis
fov_max (float | Tensor): field of view in largest dimension
fov_min (float | Tensor): field of view in smallest dimension
cx (float | Tensor): principal point x coordinate
cy (float | Tensor): principal point y coordinate
aspect_ratio (float | Tensor): aspect ratio of the image
Returns
----
(Tensor): [..., 3, 3] OpenCV intrinsics matrix
"""
if fov_max is not None:
fx = torch.maximum(1, 1 / aspect_ratio) / (2 * torch.tan(fov_max / 2))
fy = torch.maximum(1, aspect_ratio) / (2 * torch.tan(fov_max / 2))
elif fov_min is not None:
fx = torch.minimum(1, 1 / aspect_ratio) / (2 * torch.tan(fov_min / 2))
fy = torch.minimum(1, aspect_ratio) / (2 * torch.tan(fov_min / 2))
elif fov_x is not None and fov_y is not None:
fx = 1 / (2 * torch.tan(fov_x / 2))
fy = 1 / (2 * torch.tan(fov_y / 2))
elif fov_x is not None:
fx = 1 / (2 * torch.tan(fov_x / 2))
fy = fx * aspect_ratio
elif fov_y is not None:
fy = 1 / (2 * torch.tan(fov_y / 2))
fx = fy / aspect_ratio
ret = intrinsics_from_focal_center(fx, fy, cx, cy)
return ret
def focal_to_fov(focal: Tensor):
return 2 * torch.atan(0.5 / focal)
def fov_to_focal(fov: Tensor):
return 0.5 / torch.tan(fov / 2)
def intrinsics_to_fov(intrinsics: Tensor) -> Tuple[Tensor, Tensor]:
"NOTE: approximate FOV by assuming centered principal point"
fov_x = focal_to_fov(intrinsics[..., 0, 0])
fov_y = focal_to_fov(intrinsics[..., 1, 1])
return fov_x, fov_y
@totensor(_others=torch.float32)
@batched(1, 1, 1)
def view_look_at(
eye: Tensor,
look_at: Tensor,
up: Tensor
) -> Tensor:
"""
Get OpenGL view matrix looking at something
## Parameters
eye (Tensor): [..., 3] the eye position
look_at (Tensor): [..., 3] the position to look at
up (Tensor): [..., 3] head up direction (y axis in screen space). Not necessarily othogonal to view direction
## Returns
(Tensor): [..., 4, 4], view matrix
"""
z = eye - look_at
x = torch.cross(up, z, dim=-1)
y = torch.cross(z, x, dim=-1)
R = torch.stack([x, y, z], dim=-2)
R = F.normalize(R, dim=-1)
t = -torch.matmul(R, eye[..., None])
return make_affine_matrix(R, t.squeeze(-1))
@totensor(_others=torch.float32)
@batched(1, 1, 1)
def extrinsics_look_at(
eye: Tensor,
look_at: Tensor,
up: Tensor
) -> Tensor:
"""
Get OpenCV extrinsics matrix looking at something
## Parameters
eye (Tensor): [..., 3] the eye position
look_at (Tensor): [..., 3] the position to look at
up (Tensor): [..., 3] head up direction (-y axis in screen space). Not necessarily othogonal to view direction
## Returns
(Tensor): [..., 4, 4], extrinsics matrix
"""
return view_to_extrinsics(view_look_at(eye, look_at, up))
@batched(2)
def perspective_to_intrinsics(perspective: Tensor) -> Tensor:
"""
OpenGL perspective matrix to OpenCV intrinsics
## Parameters
perspective (Tensor): [..., 4, 4] OpenGL perspective matrix
## Returns
(Tensor): shape [..., 3, 3] OpenCV intrinsics
"""
assert torch.allclose(perspective[:, [0, 1, 3], 3], 0), "The matrix is not a perspective projection matrix"
ret = torch.tensor([[0.5, 0., 0.5], [0., -0.5, 0.5], [0., 0., 1.]], dtype=perspective.dtype, device=perspective.device) \
@ perspective[:, [0, 1, 3], :3] \
@ torch.diag(torch.tensor([1, -1, -1], dtype=perspective.dtype, device=perspective.device))
return ret / ret[:, 2, 2, None, None]
@totensor(None, _others='intrinsics')
@batched(2, 0, 0)
def intrinsics_to_perspective(
intrinsics: Tensor,
near: Union[float, Tensor],
far: Union[float, Tensor],
) -> Tensor:
"""
OpenCV intrinsics to OpenGL perspective matrix
NOTE: not work for tile-shifting intrinsics currently
## Parameters
intrinsics (Tensor): [..., 3, 3] OpenCV intrinsics matrix
near (float | Tensor): [...] near plane to clip
far (float | Tensor): [...] far plane to clip
## Returns
(Tensor): [..., 4, 4] OpenGL perspective matrix
"""
device, dtype = intrinsics.device, intrinsics.dtype
batch_shape = intrinsics.shape[:-2]
m = torch.tensor([[2, 0, -1], [0, -2, 1], [0, 0, 1]], dtype=dtype, device=device) @ intrinsics @ torch.diag(torch.tensor([1, -1, -1], dtype=dtype, device=device))
perspective = torch.cat([
torch.cat([m[..., :2, :], torch.zeros((*batch_shape, 2, 1), dtype=dtype, device=device)], dim=-1),
torch.cat([torch.zeros((*batch_shape, 1, 2), dtype=dtype, device=device), ((near / far + 1) / (near / far - 1))[..., None, None], (2. * near / (near / far - 1))[..., None, None]], dim=-1),
torch.tensor([0., 0., -1, 0], dtype=dtype, device=device).expand(*batch_shape, 1, 4)
], dim=-2)
return perspective
def extrinsics_to_view(extrinsics: Tensor) -> Tensor:
"""
OpenCV camera extrinsics to OpenGL view matrix
## Parameters
extrinsics (Tensor): [..., 4, 4] OpenCV camera extrinsics matrix
## Returns
(Tensor): [..., 4, 4] OpenGL view matrix
"""
return extrinsics * torch.tensor([1, -1, -1, 1], dtype=extrinsics.dtype, device=extrinsics.device)[:, None]
def view_to_extrinsics(view: Tensor) -> Tensor:
"""
OpenGL view matrix to OpenCV camera extrinsics
## Parameters
view (Tensor): [..., 4, 4] OpenGL view matrix
## Returns
(Tensor): [..., 4, 4] OpenCV camera extrinsics matrix
"""
return view * torch.tensor([1, -1, -1, 1], dtype=view.dtype, device=view.device)[:, None]
@totensor(None, 'intrinsics')
@batched(2, 1)
def normalize_intrinsics(
intrinsics: Tensor,
size: Union[Tuple[Number, Number], Tensor],
pixel_convention: Literal['integer-corner', 'integer-center'] = 'integer-center',
) -> Tensor:
"""
Normalize camera intrinsics to uv space
## Parameters
- `intrinsics` (Tensor): `(..., 3, 3)` camera intrinsics to normalize
- `size` (tuple | Tensor): A tuple `(height, width)` of the image size,
or an array of shape `(..., 2)` corresponding to the multiple image size(s)
- `pixel_convention`: `str`, optional `'integer-center'` or `'integer-corner'`, whether integer coordinates correspond to pixel centers or corners. Defaults to 'integer-center'.
- For more definitions, please refer to `pixel_coord_map()`
## Returns
(Tensor): [..., 3, 3] normalized camera intrinsics
"""
if isinstance(size, tuple):
size = torch.tensor(size, dtype=intrinsics.dtype, device=intrinsics.device)
size = size.expand(*intrinsics.shape[:-2], 2)
height, width = size.unbind(-1)
zeros = torch.zeros_like(width)
ones = torch.ones_like(width)
if pixel_convention == 'integer-center':
transform = torch.stack([
1 / width, zeros, 0.5 / width,
zeros, 1 / height, 0.5 / height,
zeros, zeros, ones
]).reshape(*zeros.shape, 3, 3)
elif pixel_convention == 'integer-corner':
transform = torch.stack([
1 / width, zeros, zeros,
zeros, 1 / height, zeros,
zeros, zeros, ones
]).reshape(*zeros.shape, 3, 3)
return transform @ intrinsics
@totensor(None, 'intrinsics')
@batched(2, 1)
def denormalize_intrinsics(
intrinsics: Tensor,
size: Union[Tuple[Number, Number], Tensor],
pixel_convention: Literal['integer-center', 'integer-corner'] = 'integer-center',
) -> Tensor:
"""
Denormalize camera intrinsics(s) from uv space to pixel space
## Parameters
- `intrinsics` (Tensor): `(..., 3, 3)` camera intrinsics
- `size` (tuple | Tensor): A tuple `(height, width)` of the image size,
or an array of shape `(..., 2)` corresponding to the multiple image size(s)
- `pixel_convention`: `str`, optional `'integer-center'` or `'integer-corner'`, whether integer coordinates correspond to pixel centers or corners. Defaults to 'integer-center'.
- For more definitions, please refer to `pixel_coord_map()`
## Returns
(Tensor): [..., 3, 3] denormalized camera intrinsics in pixel space
"""
if isinstance(size, tuple):
size = torch.tensor(size, dtype=intrinsics.dtype, device=intrinsics.device)
size = size.expand(*intrinsics.shape[:-2], 2)
height, width = size.unbind(-1)
zeros = torch.zeros_like(width)
ones = torch.ones_like(width)
if pixel_convention == 'integer-center':
transform = torch.stack([
width, zeros, -0.5 * ones,
zeros, height, -0.5 * ones,
zeros, zeros, ones
], dim=-1).reshape(*zeros.shape, 3, 3)
elif pixel_convention == 'integer-corner':
transform = torch.stack([
width, zeros, zeros,
zeros, height, zeros,
zeros, zeros, ones
], dim=-1).reshape(*zeros.shape, 3, 3)
return transform @ intrinsics
@totensor(None, _others='intrinsics')
@batched(2, 1, _others=0)
def crop_intrinsics(
intrinsics: Tensor,
size: Union[Tuple[Number, Number], Tensor],
cropped_top: Union[Number, Tensor],
cropped_left: Union[Number, Tensor],
cropped_height: Union[Number, Tensor],
cropped_width: Union[Number, Tensor],
) -> Tensor:
"""
Evaluate the new intrinsics after cropping the image
## Parameters
intrinsics (Tensor): (..., 3, 3) camera intrinsics(s) to crop
height (int | Tensor): (...) image height(s)
width (int | Tensor): (...) image width(s)
cropped_top (int | Tensor): (...) top pixel index of the cropped image(s)
cropped_left (int | Tensor): (...) left pixel index of the cropped image(s)
cropped_height (int | Tensor): (...) height of the cropped image(s)
cropped_width (int | Tensor): (...) width of the cropped image(s)
## Returns
(Tensor): (..., 3, 3) cropped camera intrinsics
"""
height, width = size.unbind(-1)
zeros = torch.zeros_like(height)
ones = torch.ones_like(height)
transform = torch.stack([
width / cropped_width, zeros, -cropped_left / cropped_width,
zeros, height / cropped_height, -cropped_top / cropped_height,
zeros, zeros, ones
]).reshape(*zeros.shape, 3, 3)
return transform @ intrinsics
def pixel_to_uv(
pixel: Tensor,
size: Union[Tuple[Number, Number], Tensor],
pixel_convention: Literal['integer-corner', 'integer-center'] = 'integer-center',
) -> Tensor:
"""
## Parameters
- `pixel` (Tensor): `(..., 2)` pixel coordinrates
- `size` (tuple | Tensor): A tuple `(height, width)` of the image size,
or an array of shape `(..., 2)` corresponding to the multiple image size(s)
- `pixel_convention`: `str`, optional `'integer-center'` or `'integer-corner'`, whether integer coordinates correspond to pixel centers or corners. Defaults to 'integer-center'.
- For more definitions, please refer to `pixel_coord_map()`
## Returns
(Tensor): `(..., 2)` uv coordinrates
"""
if not torch.is_floating_point(pixel):
pixel = pixel.float()
if pixel_convention == 'integer-center':
pixel = pixel + 0.5
uv = pixel / torch.as_tensor(size, device=pixel.device).flip(-1)
return uv
def uv_to_pixel(
uv: Tensor,
size: Union[Tuple[Number, Number], Tensor],
pixel_convention: Literal['integer-corner', 'integer-center'] = 'integer-center',
) -> Tensor:
"""
Convert UV space coordinates to pixel space coordinates.
## Parameters
- `uv` (Tensor): `(..., 2)` uv coordinrates.
- `size` (tuple | Tensor): A tuple `(height, width)` of the image size,
or an array of shape `(..., 2)` corresponding to the multiple image size(s)
- `pixel_convention`: `str`, optional `'integer-center'` or `'integer-corner'`, whether integer coordinates correspond to pixel centers or corners. Defaults to 'integer-center'.
- For more definitions, please refer to `pixel_coord_map()`
## Returns
(Tensor): `(..., 2)` pixel coordinrates
"""
pixel = uv * torch.as_tensor(size, device=uv.device).flip(-1)
if pixel_convention == 'integer-center':
pixel = pixel - 0.5
return pixel
def pixel_to_ndc(
pixel: Tensor,
size: Union[Tuple[Number, Number], Tensor],
pixel_convention: Literal['integer-corner', 'integer-center'] = 'integer-center',
) -> Tensor:
"""
Convert pixel coordinates to NDC (Normalized Device Coordinates).
## Parameters
- `pixel` (Tensor): `(..., 2)` pixel coordinrates.
- `size` (tuple | Tensor): A tuple `(height, width)` of the image size,
or an array of shape `(..., 2)` corresponding to the multiple image size(s)
- `pixel_convention`: `str`, optional `'integer-center'` or `'integer-corner'`, whether integer coordinates correspond to pixel centers or corners. Defaults to 'integer-center'.
- For more definitions, please refer to `pixel_coord_map()`
## Returns
(Tensor): `(..., 2)` ndc coordinrates, the range is (-1, 1)
"""
if not torch.is_floating_point(pixel):
pixel = pixel.float()
if pixel_convention == 'integer-center':
pixel = pixel + 0.5
ndc = pixel / (torch.as_tensor(size, device=pixel.device).flip(-1) * torch.tensor([2, -2], dtype=pixel.dtype, device=pixel.device)) \
+ torch.tensor([-1, 1], dtype=pixel.dtype, device=pixel.device)
return ndc
def depth_linear_to_buffer(
depth: Tensor,
near: Union[float, Tensor],
far: Union[float, Tensor]
) -> Tensor:
"""
Project linear depth to depth value in screen space
## Parameters
depth (Tensor): [...] depth value
near (float | Tensor): [...] near plane to clip
far (float | Tensor): [...] far plane to clip
## Returns
(Tensor): [..., 1] depth value in screen space, value ranging in [0, 1]
"""
return (1 - near / depth) / (1 - near / far)
def depth_buffer_to_linear(
depth: Tensor,
near: Union[float, Tensor],
far: Union[float, Tensor]
) -> Tensor:
"""
Linearize depth value to linear depth
## Parameters
depth (Tensor): [...] screen depth value, ranging in [0, 1]
near (float | Tensor): [...] near plane to clip
far (float | Tensor): [...] far plane to clip
## Returns
(Tensor): [...] linear depth
"""
return near / (1 - (1 - near / far) * depth)
def project_gl(
points: Tensor,
projection: Tensor,
view: Tensor = None,
) -> Tuple[Tensor, Tensor]:
"""
Project 3D points to 2D following the OpenGL convention (except for row major matrices)
## Parameters
points (Tensor): [..., N, 3] or [..., N, 4] 3D points to project, if the last
dimension is 4, the points are assumed to be in homogeneous coordinates
view (Tensor): [..., 4, 4] view matrix
projection (Tensor): [..., 4, 4] projection matrix
## Returns
scr_coord (Tensor): [..., N, 3] screen space coordinates, value ranging in [0, 1].
The origin (0., 0., 0.) is corresponding to the left & bottom & nearest
linear_depth (Tensor): [..., N] linear depth
"""
if points.shape[-1] == 3:
points = torch.cat([points, torch.ones((*points.shape[:-1], 1), dtype=points.dtype, device=points.device)], dim=-1)
transform = projection if view is None else projection @ view
clip_coord = points @ transform.mT
ndc_coord = clip_coord[..., :3] / clip_coord[..., 3:]
scr_coord = ndc_coord * 0.5 + 0.5
linear_depth = clip_coord[..., 3]
return scr_coord, linear_depth
def project_cv(
points: Tensor,
intrinsics: Tensor,
extrinsics: Optional[Tensor] = None,
) -> Tuple[Tensor, Tensor]:
"""
Project 3D points to 2D following the OpenCV convention
## Parameters
points (Tensor): [..., N, 3] 3D points
intrinsics (Tensor): [..., 3, 3] intrinsics matrix
extrinsics (Tensor): [..., 4, 4] extrinsics matrix
## Returns
uv_coord (Tensor): [..., N, 2] uv coordinates, value ranging in [0, 1].
The origin (0., 0.) is corresponding to the left & top
linear_depth (Tensor): [..., N] linear depth
"""
intrinsics = torch.cat([
torch.cat([intrinsics, torch.zeros((*intrinsics.shape[:-2], 3, 1), dtype=intrinsics.dtype, device=intrinsics.device)], dim=-1),
torch.tensor([[0, 0, 0, 1]], dtype=intrinsics.dtype, device=intrinsics.device).expand(*intrinsics.shape[:-2], 1, 4)
], dim=-2)
transform = intrinsics @ extrinsics if extrinsics is not None else intrinsics
points = torch.cat([points, torch.ones((*points.shape[:-1], 1), dtype=points.dtype, device=points.device)], dim=-1)
points = points @ transform.mT
uv_coord = points[..., :2] / points[..., 2:3]
linear_depth = points[..., 2]
return uv_coord, linear_depth
def unproject_gl(
uv: Tensor,
depth: Tensor,
projection: Tensor,
view: Optional[Tensor] = None,
) -> Tensor:
"""
Unproject screen space coordinates to 3D view space following the OpenGL convention (except for row major matrices)
## Parameters
uv (Tensor): (..., N, 2) screen space XY coordinates, value ranging in [0, 1].
The origin (0., 0.) is corresponding to the left & bottom
depth (Tensor): (..., N) linear depth values
projection (Tensor): (..., 4, 4) projection matrix
view (Tensor): (..., 4, 4) view matrix
## Returns
points (Tensor): (..., N, 3) 3d points
"""
ndc_xy = uv * 2 - 1
view_z = -depth
clip_xy = torch.linalg.inv(projection[..., :2, :2] - ndc_xy[..., :, None] * projection[..., 3:, :2]) \
@ ((ndc_xy[..., :, None] * projection[..., 3:, 2:] - projection[..., :2, 2:]) \
@ torch.cat([view_z[..., None, None], torch.ones_like(view_z[..., None, None])], axis=-2))
points = torch.cat([clip_xy.squeeze(-1), view_z[..., None], torch.ones_like(view_z)[..., None]], axis=-1)
if view is not None:
points = points @ torch.linalg.inv(view).mT
return points[..., :3]
def unproject_cv(
uv: Tensor,
depth: Tensor,
intrinsics: Tensor,
extrinsics: Tensor = None,
) -> Tensor:
"""
Unproject uv coordinates to 3D view space following the OpenCV convention
## Parameters
uv (Tensor): [..., N, 2] uv coordinates, value ranging in [0, 1].
The origin (0., 0.) is corresponding to the left & top
depth (Tensor): [..., N] depth value
extrinsics (Tensor): [..., 4, 4] extrinsics matrix
intrinsics (Tensor): [..., 3, 3] intrinsics matrix
## Returns
points (Tensor): [..., N, 3] 3d points
"""
intrinsics = torch.cat([
torch.cat([intrinsics, torch.zeros((*intrinsics.shape[:-2], 3, 1), dtype=intrinsics.dtype, device=intrinsics.device)], dim=-1),
torch.tensor([[0, 0, 0, 1]], dtype=intrinsics.dtype, device=intrinsics.device).expand(*intrinsics.shape[:-2], 1, 4)
], dim=-2)
transform = intrinsics @ extrinsics if extrinsics is not None else intrinsics
points = torch.cat([uv, torch.ones((*uv.shape[:-1], 1), dtype=uv.dtype, device=uv.device)], dim=-1) * depth[..., None]
points = torch.cat([points, torch.ones((*points.shape[:-1], 1), dtype=uv.dtype, device=uv.device)], dim=-1)
points = points @ torch.linalg.inv(transform).mT
points = points[..., :3]
return points
def project(
points: Tensor,
*,
intrinsics: Optional[Tensor] = None,
extrinsics: Optional[Tensor] = None,
view: Optional[Tensor] = None,
projection: Optional[Tensor] = None
) -> Tuple[Tensor, Tensor]:
"""
Calculate projection.
- For OpenCV convention, use `intrinsics` and `extrinsics` matrices.
- For OpenGL convention, use `view` and `projection` matrices.
## Parameters
- `points`: (..., N, 3) 3D world-space points
- `intrinsics`: (..., 3, 3) intrinsics matrix
- `extrinsics`: (..., 4, 4) extrinsics matrix
- `view`: (..., 4, 4) view matrix
- `projection`: (..., 4, 4) projection matrix
## Returns
- `uv`: (..., N, 2) 2D coordinates.
- For OpenCV convention, it is the normalized image coordinate where (0, 0) is the top left corner.
- For OpenGL convention, it is the screen space XY coordinate where (0, 0) is the bottom left corner.
- `depth`: (..., N) linear depth values, where `depth > 0` is visible.
- For OpenCV convention, it is the Z coordinate in camera space.
- For OpenGL convention, it is the -Z coordinate in camera space.
"""
assert (intrinsics is not None or extrinsics is not None) ^ (view is not None or projection is not None), \
"Either camera intrinsics (and extrinsics) or projection (and view) matrices must be provided."
if intrinsics is not None:
return project_cv(points, intrinsics, extrinsics)
elif projection is not None:
return project_gl(points, projection, view)
else:
raise ValueError("Invalid combination of input parameters.")
def unproject(
uv: Tensor,
depth: Optional[Tensor],
*,
intrinsics: Optional[Tensor] = None,
extrinsics: Optional[Tensor] = None,
projection: Optional[Tensor] = None,
view: Optional[Tensor] = None,
) -> Tensor:
"""
Calculate inverse projection.
- For OpenCV convention, use `intrinsics` and `extrinsics` matrices.
- For OpenGL convention, use `view` and `projection` matrices.
## Parameters
- `uv`: (..., N, 2) 2D coordinates.
- For OpenCV convention, it is the normalized image coordinate where (0, 0) is the top left corner.
- For OpenGL convention, it is the screen space XY coordinate where (0, 0) is the bottom left corner.
- `depth`: (..., N) linear depth values, where `depth > 0` is visible.
- For OpenCV convention, it is the Z coordinate in camera space.
- For OpenGL convention, it is the -Z coordinate in camera space.
- `intrinsics`: (..., 3, 3) intrinsics matrix
- `extrinsics`: (..., 4, 4) extrinsics matrix
- `view`: (..., 4, 4) view matrix
- `projection`: (..., 4, 4) projection matrix
## Returns
- `points`: (..., N, 3) 3D world-space points
"""
assert (intrinsics is not None or extrinsics is not None) ^ (view is not None or projection is not None), \
"Either camera intrinsics (and extrinsics) or projection (and view) matrices must be provided."
if intrinsics is not None:
return unproject_cv(uv, depth, intrinsics, extrinsics)
elif projection is not None:
return unproject_gl(uv, depth, projection, view)
else:
raise ValueError("Invalid combination of input parameters.")
def euler_axis_angle_rotation(axis: str, angle: Tensor) -> Tensor:
"""
Return the rotation matrices for one of the rotations about an axis
of which Euler angles describe, for each value of the angle given.
## Parameters
axis: Axis label "X" or "Y or "Z".
angle: any shape tensor of Euler angles in radians
## Returns
Rotation matrices as tensor of shape (..., 3, 3).
"""
cos = torch.cos(angle)
sin = torch.sin(angle)
one = torch.ones_like(angle)
zero = torch.zeros_like(angle)
if axis == "X":
R_flat = (one, zero, zero, zero, cos, -sin, zero, sin, cos)
elif axis == "Y":
R_flat = (cos, zero, sin, zero, one, zero, -sin, zero, cos)
elif axis == "Z":
R_flat = (cos, -sin, zero, sin, cos, zero, zero, zero, one)
else:
raise ValueError("letter must be either X, Y or Z.")
return torch.stack(R_flat, -1).reshape(angle.shape + (3, 3))
def euler_angles_to_matrix(euler_angles: Tensor, convention: str = 'XYZ') -> Tensor:
"""
Convert rotations given as Euler angles in radians to rotation matrices.
## Parameters
euler_angles: Euler angles in radians as tensor of shape (..., 3), XYZ
convention: permutation of "X", "Y" or "Z", representing the order of Euler rotations to apply.
## Returns
Rotation matrices as tensor of shape (..., 3, 3).
"""
if euler_angles.dim() == 0 or euler_angles.shape[-1] != 3:
raise ValueError("Invalid input euler angles.")
if len(convention) != 3:
raise ValueError("Convention must have 3 letters.")
if convention[1] in (convention[0], convention[2]):
raise ValueError(f"Invalid convention {convention}.")
for letter in convention:
if letter not in ("X", "Y", "Z"):
raise ValueError(f"Invalid letter {letter} in convention string.")
matrices = [
euler_axis_angle_rotation(c, euler_angles[..., 'XYZ'.index(c)])
for c in convention
]
# return functools.reduce(torch.matmul, matrices)
return matrices[2] @ matrices[1] @ matrices[0]
def skew_symmetric(v: Tensor):
"Skew symmetric matrix from a 3D vector"
assert v.shape[-1] == 3, "v must be 3D"
x, y, z = v.unbind(dim=-1)
zeros = torch.zeros_like(x)
return torch.stack([
zeros, -z, y,
z, zeros, -x,
-y, x, zeros,
], dim=-1).reshape(*v.shape[:-1], 3, 3)
def rotation_matrix_from_vectors(v1: Tensor, v2: Tensor):
"Rotation matrix that rotates v1 to v2"
I = torch.eye(3).to(v1)
v1 = F.normalize(v1, dim=-1)
v2 = F.normalize(v2, dim=-1)
v = torch.cross(v1, v2, dim=-1)
c = torch.sum(v1 * v2, dim=-1)
K = skew_symmetric(v)
R = I + K + (1 / (1 + c))[None, None] * (K @ K)
return R
def _angle_from_tan(
axis: str, other_axis: str, data, horizontal: bool, tait_bryan: bool
) -> Tensor:
"""
Extract the first or third Euler angle from the two members of
the matrix which are positive constant times its sine and cosine.
## Parameters
axis: Axis label "X" or "Y or "Z" for the angle we are finding.
other_axis: Axis label "X" or "Y or "Z" for the middle axis in the
convention.
data: Rotation matrices as tensor of shape (..., 3, 3).
horizontal: Whether we are looking for the angle for the third axis,
which means the relevant entries are in the same row of the
rotation matrix. If not, they are in the same column.
tait_bryan: Whether the first and third axes in the convention differ.
## Returns
Euler Angles in radians for each matrix in data as a tensor
of shape (...).
"""
i1, i2 = {"X": (2, 1), "Y": (0, 2), "Z": (1, 0)}[axis]
if horizontal:
i2, i1 = i1, i2
even = (axis + other_axis) in ["XY", "YZ", "ZX"]
if horizontal == even:
return torch.atan2(data[..., i1], data[..., i2])
if tait_bryan:
return torch.atan2(-data[..., i2], data[..., i1])
return torch.atan2(data[..., i2], -data[..., i1])
def matrix_to_euler_angles(matrix: Tensor, convention: str) -> Tensor:
"""
Convert rotations given as rotation matrices to Euler angles in radians.
NOTE: The composition order eg. `XYZ` means `Rz * Ry * Rx` (like blender), instead of `Rx * Ry * Rz` (like pytorch3d)
## Parameters
matrix: Rotation matrices as tensor of shape (..., 3, 3).
convention: Convention string of three uppercase letters.
## Returns
Euler angles in radians as tensor of shape (..., 3), in the order of XYZ (like blender), instead of convention (like pytorch3d)
"""
if not all(c in 'XYZ' for c in convention) or not all(c in convention for c in 'XYZ'):
raise ValueError(f"Invalid convention {convention}.")
if not matrix.shape[-2:] == (3, 3):
raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.")
i0 = 'XYZ'.index(convention[0])
i2 = 'XYZ'.index(convention[2])
tait_bryan = i0 != i2
if tait_bryan:
central_angle = torch.asin(matrix[..., i2, i0] * (-1.0 if i2 - i0 in [-1, 2] else 1.0))
else:
central_angle = torch.acos(matrix[..., i2, i2])
# Angles in composition order
o = [
_angle_from_tan(
convention[0], convention[1], matrix[..., i2, :], True, tait_bryan
),
central_angle,
_angle_from_tan(
convention[2], convention[1], matrix[..., i0], False, tait_bryan
),
]
return torch.stack([o[convention.index(c)] for c in 'XYZ'], -1)
def axis_angle_to_matrix(axis_angle: Tensor, eps: float = 1e-12) -> Tensor:
"""Convert axis-angle representation (rotation vector) to rotation matrix, whose direction is the axis of rotation and length is the angle of rotation
## Parameters
axis_angle (Tensor): shape (..., 3), axis-angle vcetors
## Returns
Tensor: shape (..., 3, 3) The rotation matrices for the given axis-angle parameters
"""
batch_shape = axis_angle.shape[:-1]
device, dtype = axis_angle.device, axis_angle.dtype
angle = torch.norm(axis_angle + eps, dim=-1, keepdim=True)
axis = axis_angle / angle
cos = torch.cos(angle)[..., None, :]
sin = torch.sin(angle)[..., None, :]
rx, ry, rz = axis.unbind(dim=-1)
zeros = torch.zeros(batch_shape, dtype=dtype, device=device)
K = torch.stack([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=-1).view((*batch_shape, 3, 3))
ident = torch.eye(3, dtype=dtype, device=device)
rot_mat = ident + sin * K + (1 - cos) * torch.matmul(K, K)
return rot_mat
def matrix_to_axis_angle(rot_mat: Tensor, eps: float = 1e-12) -> Tensor:
"""Convert a batch of 3x3 rotation matrices to axis-angle representation (rotation vector)
## Parameters
rot_mat (Tensor): shape (..., 3, 3), the rotation matrices to convert
## Returns
Tensor: shape (..., 3), the axis-angle vectors corresponding to the given rotation matrices
"""
quat = matrix_to_quaternion(rot_mat)
axis_angle = quaternion_to_axis_angle(quat, eps=eps)
return axis_angle
def quaternion_to_axis_angle(quaternion: Tensor, eps: float = 1e-12) -> Tensor:
"""Convert a batch of quaternions (w, x, y, z) to axis-angle representation (rotation vector)
## Parameters
quaternion (Tensor): shape (..., 4), the quaternions to convert
## Returns
Tensor: shape (..., 3), the axis-angle vectors corresponding to the given quaternions
"""
assert quaternion.shape[-1] == 4
norm = torch.norm(quaternion[..., 1:], dim=-1, keepdim=True)
axis = quaternion[..., 1:] / norm.clamp(min=eps)
angle = 2 * torch.atan2(norm, quaternion[..., 0:1])
return angle * axis
def axis_angle_to_quaternion(axis_angle: Tensor, eps: float = 1e-12) -> Tensor: