π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Adds conversions between graphics and vision coordinate frames (#1823)
Dmytro Mishkin17a0032820aa
diff --git a/docs/source/geometry.conversions.rst b/docs/source/geometry.conversions.rstindex e524f4fcd..332937798 100644--- a/docs/source/geometry.conversions.rst+++ b/docs/source/geometry.conversions.rst@@ -50,3 +50,16 @@ Angle Axis.. autofunction:: angle_axis_to_quaternion.. autofunction:: angle_axis_to_rotation_matrix++Pose (extrinsics)+----------++.. autofunction:: Rt_to_matrix4x4+.. autofunction:: matrix4x4_to_Rt+.. autofunction:: worldtocam_to_camtoworld_Rt+.. autofunction:: camtoworld_to_worldtocam_Rt+.. autofunction:: camtoworld_graphics_to_vision_4x4+.. autofunction:: camtoworld_vision_to_graphics_4x4+.. autofunction:: camtoworld_graphics_to_vision_Rt+.. autofunction:: camtoworld_vision_to_graphics_Rt+.. autofunction:: ARKitQTVecs_to_ColmapQTVecsdiff --git a/docs/source/references.bib b/docs/source/references.bibindex 11fbed519..4d4be8ced 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -211,7 +211,7 @@}@article{MODS2015,- aitle = {MODS: Fast and robust method for two-view matching },+ title = {MODS: Fast and robust method for two-view matching },author = {Dmytro Mishkin and Jiri Matas and Michal Perdoch},journal = {Computer Vision and Image Understanding },year = {2015},diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 89e0dd2a1..3798b58f0 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -4,8 +4,10 @@ from typing import Optional, Tupleimport torchimport torch.nn.functional as F+from torch import Tensor, tensorfrom kornia.constants import pi+from kornia.testing import KORNIA_CHECK_SHAPEfrom kornia.utils.helpers import _torch_inverse_cast__all__ = [@@ -36,6 +38,15 @@ __all__ = ["normalize_homography3d","normal_transform_pixel","normal_transform_pixel3d",+ "worldtocam_to_camtoworld_Rt",+ "camtoworld_to_worldtocam_Rt",+ "Rt_to_matrix4x4",+ "matrix4x4_to_Rt",+ "camtoworld_graphics_to_vision_4x4",+ "camtoworld_vision_to_graphics_4x4",+ "camtoworld_graphics_to_vision_Rt",+ "camtoworld_vision_to_graphics_Rt",+ "ARKitQTVecs_to_ColmapQTVecs",]@@ -1175,3 +1186,257 @@ def normalize_homography3d(# compute chain transformationsdst_norm_trans_src_norm: torch.Tensor = dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)return dst_norm_trans_src_norm+++def Rt_to_matrix4x4(R: Tensor, t: Tensor) -> Tensor:+ r"""Combines 3x3 rotation matrix R and 1x3 translation vector t into 4x4 extrinsics.++ Args:+ R: Rotation matrix, :math:`(B, 3, 3).`+ t: Translation matrix :math:`(B, 3, 1)`.++ Returns:+ the extrinsics :math:`(B, 4, 4)`.++ Example:+ >>> R, t = torch.eye(3)[None], torch.ones(3).reshape(1, 3, 1)+ >>> Rt_to_matrix4x4(R, t)+ tensor([[[1., 0., 0., 1.],+ [0., 1., 0., 1.],+ [0., 0., 1., 1.],+ [0., 0., 0., 1.]]])+ """+ KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])+ KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])+ Rt = torch.cat([R, t], dim=2)+ return convert_affinematrix_to_homography3d(Rt)+++def matrix4x4_to_Rt(extrinsics: Tensor) -> Tuple[Tensor, Tensor]:+ r"""Converts 4x4 extrinsics into 3x3 rotation matrix R and 1x3 translation vector ts.++ Args:+ extrinsics: pose matrix :math:`(B, 4, 4)`.++ Returns:+ R: Rotation matrix, :math:`(B, 3, 3).`+ t: Translation matrix :math:`(B, 3, 1)`.++ Example:+ >>> ext = torch.eye(4)[None]+ >>> matrix4x4_to_Rt(ext)+ (tensor([[[1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.]]]), tensor([[[0.],+ [0.],+ [0.]]]))+ """+ KORNIA_CHECK_SHAPE(extrinsics, ["B", "4", "4"])+ R, t = extrinsics[:, :3, :3], extrinsics[:, :3, 3:]+ return R, t+++def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: Tensor) -> Tensor:+ r"""Converts graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.), , i.e. flips y+ and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards]. Vision convention: [+x, +y, +z] ==++ [right, down, forwards]++ Args:+ extrinsics: pose matrix :math:`(B, 4, 4)`.++ Returns:+ extrinsics: pose matrix :math:`(B, 4, 4)`.++ Example:+ >>> ext = torch.eye(4)[None]+ >>> camtoworld_graphics_to_vision_4x4(ext)+ tensor([[[ 1., 0., 0., 0.],+ [ 0., -1., 0., 0.],+ [ 0., 0., -1., 0.],+ [ 0., 0., 0., 1.]]])+ """+ KORNIA_CHECK_SHAPE(extrinsics_graphics, ["B", "4", "4"])+ invert_yz = tensor(+ [[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1.0]]],+ dtype=extrinsics_graphics.dtype,+ device=extrinsics_graphics.device,+ )+ return extrinsics_graphics @ invert_yz+++def camtoworld_graphics_to_vision_Rt(R: Tensor, t: Tensor) -> Tuple[Tensor, Tensor]:+ r"""Converts graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.), , i.e. flips y+ and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards]. Vision convention: [+x, +y, +z] ==++ [right, down, forwards]++ Args:+ R: Rotation matrix, :math:`(B, 3, 3).`+ t: Translation matrix :math:`(B, 3, 1)`.++ Returns:+ R: Rotation matrix, :math:`(B, 3, 3).`+ t: Translation matrix :math:`(B, 3, 1)`.++ Example:+ >>> R, t = torch.eye(3)[None], torch.ones(3).reshape(1, 3, 1)+ >>> camtoworld_graphics_to_vision_Rt(R, t)+ (tensor([[[ 1., 0., 0.],+ [ 0., -1., 0.],+ [ 0., 0., -1.]]]), tensor([[[1.],+ [1.],+ [1.]]]))+ """+ KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])+ KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])+ mat4x4 = camtoworld_graphics_to_vision_4x4(Rt_to_matrix4x4(R, t))+ return matrix4x4_to_Rt(mat4x4)+++def camtoworld_vision_to_graphics_4x4(extrinsics_vision: Tensor) -> Tensor:+ r"""Converts vision coordinate frame (e.g. OpenCV) to graphics coordinate frame (e.g. OpenGK.), i.e. flips y and+ z axis Graphics convention: [+x, +y, +z] == [right, up, backwards]. Vision convention: [+x, +y, +z] == [right,+ down, forwards]++ Args:+ extrinsics: pose matrix :math:`(B, 4, 4)`.++ Returns:+ extrinsics: pose matrix :math:`(B, 4, 4)`.++ Example:+ >>> ext = torch.eye(4)[None]+ >>> camtoworld_vision_to_graphics_4x4(ext)+ tensor([[[ 1., 0., 0., 0.],+ [ 0., -1., 0., 0.],+ [ 0., 0., -1., 0.],+ [ 0., 0., 0., 1.]]])+ """+ KORNIA_CHECK_SHAPE(extrinsics_vision, ["B", "4", "4"])+ invert_yz = torch.tensor(+ [[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1.0]]],+ dtype=extrinsics_vision.dtype,+ device=extrinsics_vision.device,+ )+ return extrinsics_vision @ invert_yz+++def camtoworld_vision_to_graphics_Rt(R: Tensor, t: Tensor) -> Tuple[Tensor, Tensor]:+ r"""Converts graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.), , i.e. flips y+ and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards]. Vision convention: [+x, +y, +z] ==++ [right, down, forwards]++ Args:+ R: Rotation matrix, :math:`(B, 3, 3).`+ t: Translation matrix :math:`(B, 3, 1)`.++ Returns:+ R: Rotation matrix, :math:`(B, 3, 3).`+ t: Translation matrix :math:`(B, 3, 1)`.++ Example:+ >>> R, t = torch.eye(3)[None], torch.ones(3).reshape(1, 3, 1)+ >>> camtoworld_vision_to_graphics_Rt(R, t)+ (tensor([[[ 1., 0., 0.],+ [ 0., -1., 0.],+ [ 0., 0., -1.]]]), tensor([[[1.],+ [1.],+ [1.]]]))+ """+ KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])+ KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])+ mat4x4 = camtoworld_vision_to_graphics_4x4(Rt_to_matrix4x4(R, t))+ return matrix4x4_to_Rt(mat4x4)+++def camtoworld_to_worldtocam_Rt(R: Tensor, t: Tensor) -> Tuple[Tensor, Tensor]:+ r"""Converts camtoworld, i.e. projection from camera coordinate system to world coordinate system, to worldtocam+ frame i.e. projection from world to the camera coordinate system (used in Colmap).+ See+ long-url: https://colmap.github.io/format.html#output-format++ Args:+ R: Rotation matrix, :math:`(B, 3, 3).`+ t: Translation matrix :math:`(B, 3, 1)`.++ Returns:+ Rinv: Rotation matrix, :math:`(B, 3, 3).`+ tinv: Translation matrix :math:`(B, 3, 1)`.++ Example:+ >>> R, t = torch.eye(3)[None], torch.ones(3).reshape(1, 3, 1)+ >>> camtoworld_to_worldtocam_Rt(R, t)+ (tensor([[[1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.]]]), tensor([[[-1.],+ [-1.],+ [-1.]]]))+ """+ KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])+ KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])++ R_inv = R.transpose(1, 2)+ new_t: Tensor = -R_inv @ t++ return (R_inv, new_t)+++def worldtocam_to_camtoworld_Rt(R: Tensor, t: Tensor) -> Tuple[Tensor, Tensor]:+ r"""Converts worldtocam frame i.e. projection from world to the camera coordinate system (used in Colmap) to+ camtoworld, i.e. projection from camera coordinate system to world coordinate system.++ Args:+ R: Rotation matrix, :math:`(B, 3, 3).`+ t: Translation matrix :math:`(B, 3, 1)`.++ Returns:+ Rinv: Rotation matrix, :math:`(B, 3, 3).`+ tinv: Translation matrix :math:`(B, 3, 1)`.++ Example:+ >>> R, t = torch.eye(3)[None], torch.ones(3).reshape(1, 3, 1)+ >>> worldtocam_to_camtoworld_Rt(R, t)+ (tensor([[[1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.]]]), tensor([[[-1.],+ [-1.],+ [-1.]]]))+ """+ KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])+ KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])++ R_inv = R.transpose(1, 2)+ new_t: Tensor = -R_inv @ t++ return (R_inv, new_t)+++def ARKitQTVecs_to_ColmapQTVecs(qvec: Tensor, tvec: Tensor) -> Tuple[Tensor, Tensor]:+ r"""Converts output of Apple ARKit screen pose (in quaternion representation) to the camera-to-world+ transformation, expected by Colmap, also in quaternion representation.++ Args:+ qvec: ARKit rotation quaternion :math:`(B, 4)`, [x, y, z, w] format.+ tvec: translation vector :math:`(B, 3, 1)`, [x, y, z]++ Returns:+ qvec: Colmap rotation quaternion :math:`(B, 4)`, [w, x, y, z] format.+ tvec: translation vector :math:`(B, 3, 1)`, [x, y, z]++ Example:+ >>> q, t = torch.tensor([0, 1, 0, 1.])[None], torch.ones(3).reshape(1, 3, 1)+ >>> ARKitQTVecs_to_ColmapQTVecs(q, t)+ (tensor([[0.7071, 0.0000, 0.7071, 0.0000]]), tensor([[[-1.0000],+ [-1.0000],+ [ 1.0000]]]))+ """+ # ToDo: integrate QuaterniaonAPI++ Rcg = quaternion_to_rotation_matrix(qvec, order=QuaternionCoeffOrder.WXYZ)+ Rcv, Tcv = camtoworld_graphics_to_vision_Rt(Rcg, tvec)+ R_colmap, t_colmap = camtoworld_to_worldtocam_Rt(Rcv, Tcv)+ t_colmap = t_colmap.reshape(-1, 3, 1)+ q_colmap = rotation_matrix_to_quaternion(R_colmap.contiguous(), order=QuaternionCoeffOrder.WXYZ)+ return q_colmap, t_colmapdiff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.pyindex 27913c7b3..fe0734a68 100644--- a/test/geometry/test_conversions.py+++ b/test/geometry/test_conversions.py@@ -6,7 +6,18 @@ import torchfrom torch.autograd import gradcheckimport kornia-from kornia.geometry.conversions import QuaternionCoeffOrder+from kornia.geometry.conversions import (+ ARKitQTVecs_to_ColmapQTVecs,+ QuaternionCoeffOrder,+ Rt_to_matrix4x4,+ camtoworld_graphics_to_vision_4x4,+ camtoworld_graphics_to_vision_Rt,+ camtoworld_to_worldtocam_Rt,+ camtoworld_vision_to_graphics_4x4,+ camtoworld_vision_to_graphics_Rt,+ matrix4x4_to_Rt,+ worldtocam_to_camtoworld_Rt,+)from kornia.testing import assert_close, create_eye_batch, tensor_to_gradcheck_var@@ -1368,3 +1379,108 @@ class TestDenormalizePixelCoordinates:expected = op(grid, height, width)assert_close(actual, expected)+++class TestRt2Extrinsics:+ @pytest.mark.parametrize("batch_size", [1, 2, 3])+ def test_everything(self, batch_size, device, dtype):+ # generate input data+ R = torch.rand(batch_size, 3, 3, dtype=dtype, device=device)+ t = torch.rand(batch_size, 3, 1, dtype=dtype, device=device)++ Rt = Rt_to_matrix4x4(R, t)+ assert Rt.shape == (batch_size, 4, 4)++ R2, t2 = matrix4x4_to_Rt(Rt)+ assert R2.shape == (batch_size, 3, 3)+ assert t2.shape == (batch_size, 3, 1)++ assert_close(R, R2, rtol=1e-4, atol=1e-5)+ assert_close(t, t2, rtol=1e-4, atol=1e-5)+ assert gradcheck(+ kornia.geometry.conversions.Rt_to_matrix4x4,+ (tensor_to_gradcheck_var(R), tensor_to_gradcheck_var(t)),+ raise_exception=True,+ )+++class TestCamtoworldGraphicsToVision:+ @pytest.mark.parametrize("batch_size", [1, 2, 3])+ def test_everything(self, batch_size, device, dtype):+ # generate input data+ t_vis = torch.tensor([2, 3, 4], device=device, dtype=dtype).view(1, 3, 1).repeat(batch_size, 1, 1)+ angles = torch.tensor([0, kornia.pi / 2.0, 0.0], device=device, dtype=dtype)[None]+ R_vis = kornia.geometry.angle_axis_to_rotation_matrix(angles).repeat(batch_size, 1, 1)+ K_vis = Rt_to_matrix4x4(R_vis, t_vis)+ K_graf = camtoworld_vision_to_graphics_4x4(K_vis)++ expected = torch.tensor(+ [[0, 0, -1, 2], [0, -1, 0, 3], [-1, 0, 0, 4], [0, 0, 0, 1]], device=device, dtype=dtype+ )[None].repeat(batch_size, 1, 1)++ assert_close(K_graf, expected, rtol=1e-4, atol=1e-5)+ R_graf, t_graf = camtoworld_vision_to_graphics_Rt(R_vis, t_vis)+ expected_R = torch.tensor([[0, 0, -1], [0, -1, 0], [-1, 0, 0]], device=device, dtype=dtype)[None].repeat(+ batch_size, 1, 1+ )+ expected_t = torch.tensor([2, 3, 4], device=device, dtype=dtype).reshape(1, 3, 1).repeat(batch_size, 1, 1)++ assert_close(t_graf, expected_t, rtol=1e-4, atol=1e-5)+ assert_close(R_graf, expected_R, rtol=1e-4, atol=1e-5)++ Kvis_back = camtoworld_graphics_to_vision_4x4(K_graf)+ assert_close(Kvis_back, K_vis, rtol=1e-4, atol=1e-5)++ R_vis_back, t_vis_back = camtoworld_graphics_to_vision_Rt(R_graf, t_graf)+ assert_close(R_vis_back, R_vis, rtol=1e-4, atol=1e-5)+ assert_close(t_vis_back, t_vis, rtol=1e-4, atol=1e-5)+ assert gradcheck(camtoworld_graphics_to_vision_4x4, (tensor_to_gradcheck_var(K_vis)), raise_exception=True)+ assert gradcheck(camtoworld_vision_to_graphics_4x4, (tensor_to_gradcheck_var(K_vis)), raise_exception=True)+++class TestCamtoworldRtToPoseRt:+ @pytest.mark.parametrize("batch_size", [1, 2, 3])+ def test_everything(self, batch_size, device, dtype):+ # generate input data+ t = torch.tensor([2, 3, 4], device=device, dtype=dtype).view(1, 3, 1).repeat(batch_size, 1, 1)+ angles = torch.tensor([0, kornia.pi / 2.0, 0.0], device=device, dtype=dtype)[None]+ R = kornia.geometry.angle_axis_to_rotation_matrix(angles).repeat(batch_size, 1, 1)++ Rp, tp = camtoworld_to_worldtocam_Rt(R, t)++ expected_Rp = torch.tensor([[0, 0, -1], [0, 1, 0], [1, 0, 0]], device=device, dtype=dtype)[None].repeat(+ batch_size, 1, 1+ )+ expected_tp = torch.tensor([4, -3, -2], device=device, dtype=dtype).view(1, 3, 1).repeat(batch_size, 1, 1)+ assert_close(Rp, expected_Rp, rtol=1e-4, atol=1e-5)+ assert_close(tp, expected_tp, rtol=1e-4, atol=1e-5)++ Rback, tback = worldtocam_to_camtoworld_Rt(Rp, tp)+ assert_close(Rback, R, rtol=1e-4, atol=1e-5)+ assert_close(tback, t, rtol=1e-4, atol=1e-5)++ assert gradcheck(+ camtoworld_to_worldtocam_Rt, (tensor_to_gradcheck_var(R), tensor_to_gradcheck_var(t)), raise_exception=True+ )+ assert gradcheck(+ worldtocam_to_camtoworld_Rt, (tensor_to_gradcheck_var(R), tensor_to_gradcheck_var(t)), raise_exception=True+ )+++class TestCARKitToColmap:+ def test_everything(self, device, dtype):+ # generate input data+ t = torch.tensor([1, 0, 0], device=device, dtype=dtype).view(1, 3, 1)+ ang_deg = torch.tensor([45, 60.0, 0.0], device=device, dtype=dtype)[None]+ ang_rad = kornia.geometry.conversions.deg2rad(ang_deg)+ qvec = kornia.geometry.angle_axis_to_quaternion(ang_rad, order=QuaternionCoeffOrder.WXYZ)++ q_colmap, t_colmap = ARKitQTVecs_to_ColmapQTVecs(qvec, t)++ angles_colmap = kornia.geometry.conversions.quaternion_to_angle_axis(q_colmap, order=QuaternionCoeffOrder.WXYZ)+ angles_colmap = kornia.geometry.conversions.rad2deg(angles_colmap)+ expected_angles = torch.tensor([[116.8870620728, 0.0, -71.7524719238]], device=device, dtype=dtype)+ expected_t = torch.tensor([[[-0.5256], [0.3558], [0.7727]]], device=device, dtype=dtype)++ assert_close(angles_colmap, expected_angles, rtol=1e-4, atol=1e-5)+ assert_close(t_colmap, expected_t, rtol=1e-4, atol=1e-5)