File size: 36,109 Bytes
36c95ba |
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 1001 1002 1003 |
import enum
import warnings
from typing import Tuple
import torch
import torch.nn.functional as F
from kornia.constants import pi
__all__ = [
"rad2deg",
"deg2rad",
"pol2cart",
"cart2pol",
"convert_points_from_homogeneous",
"convert_points_to_homogeneous",
"convert_affinematrix_to_homography",
"convert_affinematrix_to_homography3d",
"angle_axis_to_rotation_matrix",
"angle_axis_to_quaternion",
"rotation_matrix_to_angle_axis",
"rotation_matrix_to_quaternion",
"quaternion_to_angle_axis",
"quaternion_to_rotation_matrix",
"quaternion_log_to_exp",
"quaternion_exp_to_log",
"denormalize_pixel_coordinates",
"normalize_pixel_coordinates",
"normalize_quaternion",
"denormalize_pixel_coordinates3d",
"normalize_pixel_coordinates3d",
"angle_to_rotation_matrix",
]
class QuaternionCoeffOrder(enum.Enum):
XYZW = 'xyzw'
WXYZ = 'wxyz'
def rad2deg(tensor: torch.Tensor) -> torch.Tensor:
r"""Function that converts angles from radians to degrees.
Args:
tensor: Tensor of arbitrary shape.
Returns:
Tensor with same shape as input.
Example:
>>> input = torch.tensor(3.1415926535)
>>> rad2deg(input)
tensor(180.)
"""
if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
return 180.0 * tensor / pi.to(tensor.device).type(tensor.dtype)
def deg2rad(tensor: torch.Tensor) -> torch.Tensor:
r"""Function that converts angles from degrees to radians.
Args:
tensor: Tensor of arbitrary shape.
Returns:
tensor with same shape as input.
Examples:
>>> input = torch.tensor(180.)
>>> deg2rad(input)
tensor(3.1416)
"""
if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.0
def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Function that converts polar coordinates to cartesian coordinates.
Args:
rho: Tensor of arbitrary shape.
phi: Tensor of same arbitrary shape.
Returns:
Tensor with same shape as input.
Example:
>>> rho = torch.rand(1, 3, 3)
>>> phi = torch.rand(1, 3, 3)
>>> x, y = pol2cart(rho, phi)
"""
if not (isinstance(rho, torch.Tensor) & isinstance(phi, torch.Tensor)):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(rho)}, {type(phi)}")
x = rho * torch.cos(phi)
y = rho * torch.sin(phi)
return x, y
def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1.0e-8) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function that converts cartesian coordinates to polar coordinates.
Args:
rho: Tensor of arbitrary shape.
phi: Tensor of same arbitrary shape.
eps: To avoid division by zero.
Returns:
Tensor with same shape as input.
Example:
>>> x = torch.rand(1, 3, 3)
>>> y = torch.rand(1, 3, 3)
>>> rho, phi = cart2pol(x, y)
"""
if not (isinstance(x, torch.Tensor) & isinstance(y, torch.Tensor)):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}, {type(y)}")
rho = torch.sqrt(x ** 2 + y ** 2 + eps)
phi = torch.atan2(y, x)
return rho, phi
def convert_points_from_homogeneous(points: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Function that converts points from homogeneous to Euclidean space.
Args:
points: the points to be transformed of shape :math:`(B, N, D)`.
eps: to avoid division by zero.
Returns:
the points in Euclidean space :math:`(B, N, D-1)`.
Examples:
>>> input = torch.tensor([[0., 0., 1.]])
>>> convert_points_from_homogeneous(input)
tensor([[0., 0.]])
"""
if not isinstance(points, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(points)}")
if len(points.shape) < 2:
raise ValueError(f"Input must be at least a 2D tensor. Got {points.shape}")
# we check for points at max_val
z_vec: torch.Tensor = points[..., -1:]
# set the results of division by zeror/near-zero to 1.0
# follow the convention of opencv:
# https://github.com/opencv/opencv/pull/14411/files
mask: torch.Tensor = torch.abs(z_vec) > eps
scale = torch.where(mask, 1.0 / (z_vec + eps), torch.ones_like(z_vec))
return scale * points[..., :-1]
def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:
r"""Function that converts points from Euclidean to homogeneous space.
Args:
points: the points to be transformed with shape :math:`(B, N, D)`.
Returns:
the points in homogeneous coordinates :math:`(B, N, D+1)`.
Examples:
>>> input = torch.tensor([[0., 0.]])
>>> convert_points_to_homogeneous(input)
tensor([[0., 0., 1.]])
"""
if not isinstance(points, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(points)}")
if len(points.shape) < 2:
raise ValueError(f"Input must be at least a 2D tensor. Got {points.shape}")
return torch.nn.functional.pad(points, [0, 1], "constant", 1.0)
def _convert_affinematrix_to_homography_impl(A: torch.Tensor) -> torch.Tensor:
H: torch.Tensor = torch.nn.functional.pad(A, [0, 0, 0, 1], "constant", value=0.0)
H[..., -1, -1] += 1.0
return H
def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:
r"""Function that converts batch of affine matrices.
Args:
A: the affine matrix with shape :math:`(B,2,3)`.
Returns:
the homography matrix with shape of :math:`(B,3,3)`.
Examples:
>>> A = torch.tensor([[[1., 0., 0.],
... [0., 1., 0.]]])
>>> convert_affinematrix_to_homography(A)
tensor([[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]])
"""
if not isinstance(A, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(A)}")
if not (len(A.shape) == 3 and A.shape[-2:] == (2, 3)):
raise ValueError(f"Input matrix must be a Bx2x3 tensor. Got {A.shape}")
return _convert_affinematrix_to_homography_impl(A)
def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:
r"""Function that converts batch of 3d affine matrices.
Args:
A: the affine matrix with shape :math:`(B,3,4)`.
Returns:
the homography matrix with shape of :math:`(B,4,4)`.
Examples:
>>> A = torch.tensor([[[1., 0., 0., 0.],
... [0., 1., 0., 0.],
... [0., 0., 1., 0.]]])
>>> convert_affinematrix_to_homography3d(A)
tensor([[[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]]])
"""
if not isinstance(A, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(A)}")
if not (len(A.shape) == 3 and A.shape[-2:] == (3, 4)):
raise ValueError(f"Input matrix must be a Bx3x4 tensor. Got {A.shape}")
return _convert_affinematrix_to_homography_impl(A)
def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:
r"""Convert 3d vector of axis-angle rotation to 3x3 rotation matrix.
Args:
angle_axis: tensor of 3d vector of axis-angle rotations in radians with shape :math:`(N, 3)`.
Returns:
tensor of rotation matrices of shape :math:`(N, 3, 3)`.
Example:
>>> input = torch.tensor([[0., 0., 0.]])
>>> angle_axis_to_rotation_matrix(input)
tensor([[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]])
>>> input = torch.tensor([[1.5708, 0., 0.]])
>>> angle_axis_to_rotation_matrix(input)
tensor([[[ 1.0000e+00, 0.0000e+00, 0.0000e+00],
[ 0.0000e+00, -3.6200e-06, -1.0000e+00],
[ 0.0000e+00, 1.0000e+00, -3.6200e-06]]])
"""
if not isinstance(angle_axis, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(angle_axis)}")
if not angle_axis.shape[-1] == 3:
raise ValueError(f"Input size must be a (*, 3) tensor. Got {angle_axis.shape}")
def _compute_rotation_matrix(angle_axis, theta2, eps=1e-6):
# We want to be careful to only evaluate the square root if the
# norm of the angle_axis vector is greater than zero. Otherwise
# we get a division by zero.
k_one = 1.0
theta = torch.sqrt(theta2)
wxyz = angle_axis / (theta + eps)
wx, wy, wz = torch.chunk(wxyz, 3, dim=1)
cos_theta = torch.cos(theta)
sin_theta = torch.sin(theta)
r00 = cos_theta + wx * wx * (k_one - cos_theta)
r10 = wz * sin_theta + wx * wy * (k_one - cos_theta)
r20 = -wy * sin_theta + wx * wz * (k_one - cos_theta)
r01 = wx * wy * (k_one - cos_theta) - wz * sin_theta
r11 = cos_theta + wy * wy * (k_one - cos_theta)
r21 = wx * sin_theta + wy * wz * (k_one - cos_theta)
r02 = wy * sin_theta + wx * wz * (k_one - cos_theta)
r12 = -wx * sin_theta + wy * wz * (k_one - cos_theta)
r22 = cos_theta + wz * wz * (k_one - cos_theta)
rotation_matrix = torch.cat([r00, r01, r02, r10, r11, r12, r20, r21, r22], dim=1)
return rotation_matrix.view(-1, 3, 3)
def _compute_rotation_matrix_taylor(angle_axis):
rx, ry, rz = torch.chunk(angle_axis, 3, dim=1)
k_one = torch.ones_like(rx)
rotation_matrix = torch.cat([k_one, -rz, ry, rz, k_one, -rx, -ry, rx, k_one], dim=1)
return rotation_matrix.view(-1, 3, 3)
# stolen from ceres/rotation.h
_angle_axis = torch.unsqueeze(angle_axis, dim=1)
theta2 = torch.matmul(_angle_axis, _angle_axis.transpose(1, 2))
theta2 = torch.squeeze(theta2, dim=1)
# compute rotation matrices
rotation_matrix_normal = _compute_rotation_matrix(angle_axis, theta2)
rotation_matrix_taylor = _compute_rotation_matrix_taylor(angle_axis)
# create mask to handle both cases
eps = 1e-6
mask = (theta2 > eps).view(-1, 1, 1).to(theta2.device)
mask_pos = (mask).type_as(theta2)
mask_neg = (~mask).type_as(theta2)
# create output pose matrix
batch_size = angle_axis.shape[0]
rotation_matrix = torch.eye(3).to(angle_axis.device).type_as(angle_axis)
rotation_matrix = rotation_matrix.view(1, 3, 3).repeat(batch_size, 1, 1)
# fill output matrix with masked values
rotation_matrix[..., :3, :3] = mask_pos * rotation_matrix_normal + mask_neg * rotation_matrix_taylor
return rotation_matrix # Nx3x3
def rotation_matrix_to_angle_axis(rotation_matrix: torch.Tensor) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to Rodrigues vector in radians.
Args:
rotation_matrix: rotation matrix of shape :math:`(N, 3, 3)`.
Returns:
Rodrigues vector transformation of shape :math:`(N, 3)`.
Example:
>>> input = torch.tensor([[1., 0., 0.],
... [0., 1., 0.],
... [0., 0., 1.]])
>>> rotation_matrix_to_angle_axis(input)
tensor([0., 0., 0.])
>>> input = torch.tensor([[1., 0., 0.],
... [0., 0., -1.],
... [0., 1., 0.]])
>>> rotation_matrix_to_angle_axis(input)
tensor([1.5708, 0.0000, 0.0000])
"""
if not isinstance(rotation_matrix, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(rotation_matrix)}")
if not rotation_matrix.shape[-2:] == (3, 3):
raise ValueError(f"Input size must be a (*, 3, 3) tensor. Got {rotation_matrix.shape}")
quaternion: torch.Tensor = rotation_matrix_to_quaternion(rotation_matrix, order=QuaternionCoeffOrder.WXYZ)
return quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
def rotation_matrix_to_quaternion(
rotation_matrix: torch.Tensor, eps: float = 1.0e-8, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to 4d quaternion vector.
The quaternion vector has components in (w, x, y, z) or (x, y, z, w) format.
.. note::
The (x, y, z, w) order is going to be deprecated in favor of efficiency.
Args:
rotation_matrix: the rotation matrix to convert with shape :math:`(*, 3, 3)`.
eps: small value to avoid zero division.
order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
the rotation in quaternion with shape :math:`(*, 4)`.
Example:
>>> input = torch.tensor([[1., 0., 0.],
... [0., 1., 0.],
... [0., 0., 1.]])
>>> rotation_matrix_to_quaternion(input, eps=torch.finfo(input.dtype).eps,
... order=QuaternionCoeffOrder.WXYZ)
tensor([1., 0., 0., 0.])
"""
if not isinstance(rotation_matrix, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(rotation_matrix)}")
if not rotation_matrix.shape[-2:] == (3, 3):
raise ValueError(f"Input size must be a (*, 3, 3) tensor. Got {rotation_matrix.shape}")
if not torch.jit.is_scripting():
if order.name not in QuaternionCoeffOrder.__members__.keys():
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
warnings.warn(
"`XYZW` quaternion coefficient order is deprecated and"
" will be removed after > 0.6. "
"Please use `QuaternionCoeffOrder.WXYZ` instead."
)
def safe_zero_division(numerator: torch.Tensor, denominator: torch.Tensor) -> torch.Tensor:
eps: float = torch.finfo(numerator.dtype).tiny # type: ignore
return numerator / torch.clamp(denominator, min=eps)
rotation_matrix_vec: torch.Tensor = rotation_matrix.view(*rotation_matrix.shape[:-2], 9)
m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.chunk(rotation_matrix_vec, chunks=9, dim=-1)
trace: torch.Tensor = m00 + m11 + m22
def trace_positive_cond():
sq = torch.sqrt(trace + 1.0) * 2.0 # sq = 4 * qw.
qw = 0.25 * sq
qx = safe_zero_division(m21 - m12, sq)
qy = safe_zero_division(m02 - m20, sq)
qz = safe_zero_division(m10 - m01, sq)
if order == QuaternionCoeffOrder.XYZW:
return torch.cat((qx, qy, qz, qw), dim=-1)
return torch.cat((qw, qx, qy, qz), dim=-1)
def cond_1():
sq = torch.sqrt(1.0 + m00 - m11 - m22 + eps) * 2.0 # sq = 4 * qx.
qw = safe_zero_division(m21 - m12, sq)
qx = 0.25 * sq
qy = safe_zero_division(m01 + m10, sq)
qz = safe_zero_division(m02 + m20, sq)
if order == QuaternionCoeffOrder.XYZW:
return torch.cat((qx, qy, qz, qw), dim=-1)
return torch.cat((qw, qx, qy, qz), dim=-1)
def cond_2():
sq = torch.sqrt(1.0 + m11 - m00 - m22 + eps) * 2.0 # sq = 4 * qy.
qw = safe_zero_division(m02 - m20, sq)
qx = safe_zero_division(m01 + m10, sq)
qy = 0.25 * sq
qz = safe_zero_division(m12 + m21, sq)
if order == QuaternionCoeffOrder.XYZW:
return torch.cat((qx, qy, qz, qw), dim=-1)
return torch.cat((qw, qx, qy, qz), dim=-1)
def cond_3():
sq = torch.sqrt(1.0 + m22 - m00 - m11 + eps) * 2.0 # sq = 4 * qz.
qw = safe_zero_division(m10 - m01, sq)
qx = safe_zero_division(m02 + m20, sq)
qy = safe_zero_division(m12 + m21, sq)
qz = 0.25 * sq
if order == QuaternionCoeffOrder.XYZW:
return torch.cat((qx, qy, qz, qw), dim=-1)
return torch.cat((qw, qx, qy, qz), dim=-1)
where_2 = torch.where(m11 > m22, cond_2(), cond_3())
where_1 = torch.where((m00 > m11) & (m00 > m22), cond_1(), where_2)
quaternion: torch.Tensor = torch.where(trace > 0.0, trace_positive_cond(), where_1)
return quaternion
def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.0e-12) -> torch.Tensor:
r"""Normalize a quaternion.
The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
Args:
quaternion: a tensor containing a quaternion to be normalized.
The tensor can be of shape :math:`(*, 4)`.
eps: small value to avoid division by zero.
Return:
the normalized quaternion of shape :math:`(*, 4)`.
Example:
>>> quaternion = torch.tensor((1., 0., 1., 0.))
>>> normalize_quaternion(quaternion)
tensor([0.7071, 0.0000, 0.7071, 0.0000])
"""
if not isinstance(quaternion, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
raise ValueError(f"Input must be a tensor of shape (*, 4). Got {quaternion.shape}")
return F.normalize(quaternion, p=2.0, dim=-1, eps=eps)
# based on:
# https://github.com/matthew-brett/transforms3d/blob/8965c48401d9e8e66b6a8c37c65f2fc200a076fa/transforms3d/quaternions.py#L101
# https://github.com/tensorflow/graphics/blob/master/tensorflow_graphics/geometry/transformation/rotation_matrix_3d.py#L247
def quaternion_to_rotation_matrix(
quaternion: torch.Tensor, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
) -> torch.Tensor:
r"""Convert a quaternion to a rotation matrix.
The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
Args:
quaternion: a tensor containing a quaternion to be converted.
The tensor can be of shape :math:`(*, 4)`.
order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
the rotation matrix of shape :math:`(*, 3, 3)`.
Example:
>>> quaternion = torch.tensor((0., 0., 0., 1.))
>>> quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
tensor([[-1., 0., 0.],
[ 0., -1., 0.],
[ 0., 0., 1.]])
"""
if not isinstance(quaternion, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
raise ValueError(f"Input must be a tensor of shape (*, 4). Got {quaternion.shape}")
if not torch.jit.is_scripting():
if order.name not in QuaternionCoeffOrder.__members__.keys():
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
warnings.warn(
"`XYZW` quaternion coefficient order is deprecated and"
" will be removed after > 0.6. "
"Please use `QuaternionCoeffOrder.WXYZ` instead."
)
# normalize the input quaternion
quaternion_norm: torch.Tensor = normalize_quaternion(quaternion)
# unpack the normalized quaternion components
if order == QuaternionCoeffOrder.XYZW:
x, y, z, w = torch.chunk(quaternion_norm, chunks=4, dim=-1)
else:
w, x, y, z = torch.chunk(quaternion_norm, chunks=4, dim=-1)
# compute the actual conversion
tx: torch.Tensor = 2.0 * x
ty: torch.Tensor = 2.0 * y
tz: torch.Tensor = 2.0 * z
twx: torch.Tensor = tx * w
twy: torch.Tensor = ty * w
twz: torch.Tensor = tz * w
txx: torch.Tensor = tx * x
txy: torch.Tensor = ty * x
txz: torch.Tensor = tz * x
tyy: torch.Tensor = ty * y
tyz: torch.Tensor = tz * y
tzz: torch.Tensor = tz * z
one: torch.Tensor = torch.tensor(1.0)
matrix: torch.Tensor = torch.stack(
(
one - (tyy + tzz),
txy - twz,
txz + twy,
txy + twz,
one - (txx + tzz),
tyz - twx,
txz - twy,
tyz + twx,
one - (txx + tyy),
),
dim=-1,
).view(-1, 3, 3)
if len(quaternion.shape) == 1:
matrix = torch.squeeze(matrix, dim=0)
return matrix
def quaternion_to_angle_axis(
quaternion: torch.Tensor, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
) -> torch.Tensor:
"""Convert quaternion vector to angle axis of rotation in radians.
The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
Args:
quaternion: tensor with quaternions.
order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
tensor with angle axis of rotation.
Shape:
- Input: :math:`(*, 4)` where `*` means, any number of dimensions
- Output: :math:`(*, 3)`
Example:
>>> quaternion = torch.tensor((1., 0., 0., 0.))
>>> quaternion_to_angle_axis(quaternion)
tensor([3.1416, 0.0000, 0.0000])
"""
if not torch.is_tensor(quaternion):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
raise ValueError(f"Input must be a tensor of shape Nx4 or 4. Got {quaternion.shape}")
if not torch.jit.is_scripting():
if order.name not in QuaternionCoeffOrder.__members__.keys():
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
warnings.warn(
"`XYZW` quaternion coefficient order is deprecated and"
" will be removed after > 0.6. "
"Please use `QuaternionCoeffOrder.WXYZ` instead."
)
# unpack input and compute conversion
q1: torch.Tensor = torch.tensor([])
q2: torch.Tensor = torch.tensor([])
q3: torch.Tensor = torch.tensor([])
cos_theta: torch.Tensor = torch.tensor([])
if order == QuaternionCoeffOrder.XYZW:
q1 = quaternion[..., 0]
q2 = quaternion[..., 1]
q3 = quaternion[..., 2]
cos_theta = quaternion[..., 3]
else:
cos_theta = quaternion[..., 0]
q1 = quaternion[..., 1]
q2 = quaternion[..., 2]
q3 = quaternion[..., 3]
sin_squared_theta: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3
sin_theta: torch.Tensor = torch.sqrt(sin_squared_theta)
two_theta: torch.Tensor = 2.0 * torch.where(
cos_theta < 0.0, torch.atan2(-sin_theta, -cos_theta), torch.atan2(sin_theta, cos_theta)
)
k_pos: torch.Tensor = two_theta / sin_theta
k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta)
k: torch.Tensor = torch.where(sin_squared_theta > 0.0, k_pos, k_neg)
angle_axis: torch.Tensor = torch.zeros_like(quaternion)[..., :3]
angle_axis[..., 0] += q1 * k
angle_axis[..., 1] += q2 * k
angle_axis[..., 2] += q3 * k
return angle_axis
def quaternion_log_to_exp(
quaternion: torch.Tensor, eps: float = 1.0e-8, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
) -> torch.Tensor:
r"""Apply exponential map to log quaternion.
The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
Args:
quaternion: a tensor containing a quaternion to be converted.
The tensor can be of shape :math:`(*, 3)`.
eps: a small number for clamping.
order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
the quaternion exponential map of shape :math:`(*, 4)`.
Example:
>>> quaternion = torch.tensor((0., 0., 0.))
>>> quaternion_log_to_exp(quaternion, eps=torch.finfo(quaternion.dtype).eps,
... order=QuaternionCoeffOrder.WXYZ)
tensor([1., 0., 0., 0.])
"""
if not isinstance(quaternion, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 3:
raise ValueError(f"Input must be a tensor of shape (*, 3). Got {quaternion.shape}")
if not torch.jit.is_scripting():
if order.name not in QuaternionCoeffOrder.__members__.keys():
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
warnings.warn(
"`XYZW` quaternion coefficient order is deprecated and"
" will be removed after > 0.6. "
"Please use `QuaternionCoeffOrder.WXYZ` instead."
)
# compute quaternion norm
norm_q: torch.Tensor = torch.norm(quaternion, p=2, dim=-1, keepdim=True).clamp(min=eps)
# compute scalar and vector
quaternion_vector: torch.Tensor = quaternion * torch.sin(norm_q) / norm_q
quaternion_scalar: torch.Tensor = torch.cos(norm_q)
# compose quaternion and return
quaternion_exp: torch.Tensor = torch.tensor([])
if order == QuaternionCoeffOrder.XYZW:
quaternion_exp = torch.cat((quaternion_vector, quaternion_scalar), dim=-1)
else:
quaternion_exp = torch.cat((quaternion_scalar, quaternion_vector), dim=-1)
return quaternion_exp
def quaternion_exp_to_log(
quaternion: torch.Tensor, eps: float = 1.0e-8, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
) -> torch.Tensor:
r"""Apply the log map to a quaternion.
The quaternion should be in (x, y, z, w) format.
Args:
quaternion: a tensor containing a quaternion to be converted.
The tensor can be of shape :math:`(*, 4)`.
eps: a small number for clamping.
order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
the quaternion log map of shape :math:`(*, 3)`.
Example:
>>> quaternion = torch.tensor((1., 0., 0., 0.))
>>> quaternion_exp_to_log(quaternion, eps=torch.finfo(quaternion.dtype).eps,
... order=QuaternionCoeffOrder.WXYZ)
tensor([0., 0., 0.])
"""
if not isinstance(quaternion, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
raise ValueError(f"Input must be a tensor of shape (*, 4). Got {quaternion.shape}")
if not torch.jit.is_scripting():
if order.name not in QuaternionCoeffOrder.__members__.keys():
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
warnings.warn(
"`XYZW` quaternion coefficient order is deprecated and"
" will be removed after > 0.6. "
"Please use `QuaternionCoeffOrder.WXYZ` instead."
)
# unpack quaternion vector and scalar
quaternion_vector: torch.Tensor = torch.tensor([])
quaternion_scalar: torch.Tensor = torch.tensor([])
if order == QuaternionCoeffOrder.XYZW:
quaternion_vector = quaternion[..., 0:3]
quaternion_scalar = quaternion[..., 3:4]
else:
quaternion_scalar = quaternion[..., 0:1]
quaternion_vector = quaternion[..., 1:4]
# compute quaternion norm
norm_q: torch.Tensor = torch.norm(quaternion_vector, p=2, dim=-1, keepdim=True).clamp(min=eps)
# apply log map
quaternion_log: torch.Tensor = (
quaternion_vector * torch.acos(torch.clamp(quaternion_scalar, min=-1.0, max=1.0)) / norm_q
)
return quaternion_log
# based on:
# https://github.com/facebookresearch/QuaterNet/blob/master/common/quaternion.py#L138
def angle_axis_to_quaternion(
angle_axis: torch.Tensor, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
) -> torch.Tensor:
r"""Convert an angle axis to a quaternion.
The quaternion vector has components in (x, y, z, w) or (w, x, y, z) format.
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
Args:
angle_axis: tensor with angle axis in radians.
order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
tensor with quaternion.
Shape:
- Input: :math:`(*, 3)` where `*` means, any number of dimensions
- Output: :math:`(*, 4)`
Example:
>>> angle_axis = torch.tensor((0., 1., 0.))
>>> angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
tensor([0.8776, 0.0000, 0.4794, 0.0000])
"""
if not torch.is_tensor(angle_axis):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(angle_axis)}")
if not angle_axis.shape[-1] == 3:
raise ValueError(f"Input must be a tensor of shape Nx3 or 3. Got {angle_axis.shape}")
if not torch.jit.is_scripting():
if order.name not in QuaternionCoeffOrder.__members__.keys():
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
warnings.warn(
"`XYZW` quaternion coefficient order is deprecated and"
" will be removed after > 0.6. "
"Please use `QuaternionCoeffOrder.WXYZ` instead."
)
# unpack input and compute conversion
a0: torch.Tensor = angle_axis[..., 0:1]
a1: torch.Tensor = angle_axis[..., 1:2]
a2: torch.Tensor = angle_axis[..., 2:3]
theta_squared: torch.Tensor = a0 * a0 + a1 * a1 + a2 * a2
theta: torch.Tensor = torch.sqrt(theta_squared)
half_theta: torch.Tensor = theta * 0.5
mask: torch.Tensor = theta_squared > 0.0
ones: torch.Tensor = torch.ones_like(half_theta)
k_neg: torch.Tensor = 0.5 * ones
k_pos: torch.Tensor = torch.sin(half_theta) / theta
k: torch.Tensor = torch.where(mask, k_pos, k_neg)
w: torch.Tensor = torch.where(mask, torch.cos(half_theta), ones)
quaternion: torch.Tensor = torch.zeros(
size=(*angle_axis.shape[:-1], 4), dtype=angle_axis.dtype, device=angle_axis.device
)
if order == QuaternionCoeffOrder.XYZW:
quaternion[..., 0:1] = a0 * k
quaternion[..., 1:2] = a1 * k
quaternion[..., 2:3] = a2 * k
quaternion[..., 3:4] = w
else:
quaternion[..., 1:2] = a0 * k
quaternion[..., 2:3] = a1 * k
quaternion[..., 3:4] = a2 * k
quaternion[..., 0:1] = w
return quaternion
# based on:
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L65-L71
def normalize_pixel_coordinates(
pixel_coordinates: torch.Tensor, height: int, width: int, eps: float = 1e-8
) -> torch.Tensor:
r"""Normalize pixel coordinates between -1 and 1.
Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).
Args:
pixel_coordinates: the grid with pixel coordinates. Shape can be :math:`(*, 2)`.
width: the maximum width in the x-axis.
height: the maximum height in the y-axis.
eps: safe division by zero.
Return:
the normalized pixel coordinates with shape :math:`(*, 2)`.
Examples:
>>> coords = torch.tensor([[50., 100.]])
>>> normalize_pixel_coordinates(coords, 100, 50)
tensor([[1.0408, 1.0202]])
"""
if pixel_coordinates.shape[-1] != 2:
raise ValueError("Input pixel_coordinates must be of shape (*, 2). " "Got {}".format(pixel_coordinates.shape))
# compute normalization factor
hw: torch.Tensor = torch.stack(
[
torch.tensor(width, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),
torch.tensor(height, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),
]
)
factor: torch.Tensor = torch.tensor(2.0, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype) / (
hw - 1
).clamp(eps)
return factor * pixel_coordinates - 1
def denormalize_pixel_coordinates(
pixel_coordinates: torch.Tensor, height: int, width: int, eps: float = 1e-8
) -> torch.Tensor:
r"""Denormalize pixel coordinates.
The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1).
Args:
pixel_coordinates: the normalized grid coordinates. Shape can be :math:`(*, 2)`.
width: the maximum width in the x-axis.
height: the maximum height in the y-axis.
eps: safe division by zero.
Return:
the denormalized pixel coordinates with shape :math:`(*, 2)`.
Examples:
>>> coords = torch.tensor([[-1., -1.]])
>>> denormalize_pixel_coordinates(coords, 100, 50)
tensor([[0., 0.]])
"""
if pixel_coordinates.shape[-1] != 2:
raise ValueError("Input pixel_coordinates must be of shape (*, 2). " "Got {}".format(pixel_coordinates.shape))
# compute normalization factor
hw: torch.Tensor = (
torch.stack([torch.tensor(width), torch.tensor(height)])
.to(pixel_coordinates.device)
.to(pixel_coordinates.dtype)
)
factor: torch.Tensor = torch.tensor(2.0) / (hw - 1).clamp(eps)
return torch.tensor(1.0) / factor * (pixel_coordinates + 1)
def normalize_pixel_coordinates3d(
pixel_coordinates: torch.Tensor, depth: int, height: int, width: int, eps: float = 1e-8
) -> torch.Tensor:
r"""Normalize pixel coordinates between -1 and 1.
Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).
Args:
pixel_coordinates: the grid with pixel coordinates. Shape can be :math:`(*, 3)`.
depth: the maximum depth in the z-axis.
height: the maximum height in the y-axis.
width: the maximum width in the x-axis.
eps: safe division by zero.
Return:
the normalized pixel coordinates.
"""
if pixel_coordinates.shape[-1] != 3:
raise ValueError("Input pixel_coordinates must be of shape (*, 3). " "Got {}".format(pixel_coordinates.shape))
# compute normalization factor
dhw: torch.Tensor = (
torch.stack([torch.tensor(depth), torch.tensor(width), torch.tensor(height)])
.to(pixel_coordinates.device)
.to(pixel_coordinates.dtype)
)
factor: torch.Tensor = torch.tensor(2.0) / (dhw - 1).clamp(eps)
return factor * pixel_coordinates - 1
def denormalize_pixel_coordinates3d(
pixel_coordinates: torch.Tensor, depth: int, height: int, width: int, eps: float = 1e-8
) -> torch.Tensor:
r"""Denormalize pixel coordinates.
The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1).
Args:
pixel_coordinates: the normalized grid coordinates. Shape can be :math:`(*, 3)`.
depth: the maximum depth in the x-axis.
height: the maximum height in the y-axis.
width: the maximum width in the x-axis.
eps: safe division by zero.
Return:
the denormalized pixel coordinates.
"""
if pixel_coordinates.shape[-1] != 3:
raise ValueError("Input pixel_coordinates must be of shape (*, 3). " "Got {}".format(pixel_coordinates.shape))
# compute normalization factor
dhw: torch.Tensor = (
torch.stack([torch.tensor(depth), torch.tensor(width), torch.tensor(height)])
.to(pixel_coordinates.device)
.to(pixel_coordinates.dtype)
)
factor: torch.Tensor = torch.tensor(2.0) / (dhw - 1).clamp(eps)
return torch.tensor(1.0) / factor * (pixel_coordinates + 1)
def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:
r"""Create a rotation matrix out of angles in degrees.
Args:
angle: tensor of angles in degrees, any shape.
Returns:
tensor of *x2x2 rotation matrices.
Shape:
- Input: :math:`(*)`
- Output: :math:`(*, 2, 2)`
Example:
>>> input = torch.rand(1, 3) # Nx3
>>> output = angle_to_rotation_matrix(input) # Nx3x2x2
"""
ang_rad = deg2rad(angle)
cos_a: torch.Tensor = torch.cos(ang_rad)
sin_a: torch.Tensor = torch.sin(ang_rad)
return torch.stack([cos_a, sin_a, -sin_a, cos_a], dim=-1).view(*angle.shape, 2, 2)
|