Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Feat/codeflash-cache-non-zero-tensors-proj-matrix (#3229)

Meggison Oritsemisance4321a23556
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 965abe2bc..1242a3d74 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -31,7 +31,7 @@ from kornia.utils import create_meshgrid
from .camera import PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_points
from .conversions import normalize_pixel_coordinates, normalize_points_with_intrinsics
-from .linalg import compose_transformations, convert_points_to_homogeneous, inverse_transformation, transform_points
+from .linalg import convert_points_to_homogeneous, transform_points
"""Module containing operators to work on RGB-Depth images."""
@@ -369,13 +369,37 @@ class DepthWarper(Module):
)
if type(pinhole_src) is not PinholeCamera:
raise TypeError(f"Argument pinhole_src expected to be of class PinholeCamera. Got {type(pinhole_src)}")
- # Avoid intermediate vars when possible, avoid temporaries
- dst_trans_src = compose_transformations(
- self._pinhole_dst.extrinsics, inverse_transformation(pinhole_src.extrinsics)
- )
- # intrinsics (Nx3x3) @ extrinsics (Nx4x4) -- let PyTorch batch matmul
+ # Compute transformation matrix: dst_extrinsics @ inv(src_extrinsics)
+ batch_shape = pinhole_src.extrinsics.shape[:-2]
+ device = pinhole_src.extrinsics.device
+ dtype = pinhole_src.extrinsics.dtype
+
+ # Create 4x4 identity matrices efficiently
+ inv_extr = torch.eye(4, device=device, dtype=dtype).expand(*batch_shape, 4, 4).contiguous()
+ dst_trans_src = torch.eye(4, device=device, dtype=dtype).expand(*batch_shape, 4, 4).contiguous()
+
+ # Inline inverse transformation
+ src_rmat = pinhole_src.extrinsics[..., :3, :3]
+ src_tvec = pinhole_src.extrinsics[..., :3, 3:]
+ inv_rmat = torch.transpose(src_rmat, -1, -2)
+ inv_tvec = torch.matmul(-inv_rmat, src_tvec)
+
+ # Set rotation and translation parts
+ inv_extr[..., :3, :3] = inv_rmat
+ inv_extr[..., :3, 3:] = inv_tvec
+
+ # Compose with dst extrinsics
+ dst_rmat = self._pinhole_dst.extrinsics[..., :3, :3]
+ dst_tvec = self._pinhole_dst.extrinsics[..., :3, 3:]
+ composed_rmat = torch.matmul(dst_rmat, inv_rmat)
+ composed_tvec = torch.matmul(dst_rmat, inv_tvec) + dst_tvec
+
+ dst_trans_src[..., :3, :3] = composed_rmat
+ dst_trans_src[..., :3, 3:] = composed_tvec
+
+ # intrinsics (Nx3x3) @ extrinsics (Nx4x4)
dst_proj_src = torch.matmul(self._pinhole_dst.intrinsics, dst_trans_src)
- # Single assignment, avoid unnecessary double assign
+
self._pinhole_src = pinhole_src
self._dst_proj_src = dst_proj_src
return self