π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(geometry): speed up depth_to_normals (~3Γ) and denormalize_points_with_intrinsics (~2Γ) (#3656)
Dmytro Mishkin78496b7beb2b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7331ec3c1..7f4512086 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -103,6 +103,21 @@ The `device` and `dtype` fixtures are injected automatically. Use `self.assert_c- **Docstrings**: Follow existing codebase style; all public APIs need docstrings- Every source file must start with the Apache 2.0 license header (managed by `add-license-header`)+## Benchmarks++Scripts under `benchmarks/` measure the speed and/or quality of existing kornia functions, modules, or models. Each benchmark must:++- Report **CPU and CUDA timings** in a table.+- Include **quality metrics** where applicable (see `benchmarks/feature/` for an example with local-feature matching scores).+- Record the **date, hardware description, and git commit hash** being evaluated at the top of the output or in a results file.+- Benchmark **only the public kornia API** β no custom reimplementations or alternative snippets inside the script.++### Workflow for performance PRs++1. Check out `main` (or the relevant release tag) and run the benchmark to establish a baseline.+2. Apply your changes on a new branch and run the same benchmark again.+3. Include both result tables in the PR description so reviewers can compare before and after.+## Pre-commit HooksInstall hooks with `pre-commit install`. CI enforces ruff formatting, linting, and docformatter.diff --git a/benchmarks/geometry/depth_to_normals.py b/benchmarks/geometry/depth_to_normals.pynew file mode 100644index 000000000..c07da133c--- /dev/null+++ b/benchmarks/geometry/depth_to_normals.py@@ -0,0 +1,115 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+"""Benchmark for kornia.geometry.depth.depth_to_normals across image sizes.++Usage:+ python benchmarks/geometry/depth_to_normals.py+ python benchmarks/geometry/depth_to_normals.py --cuda+"""++from __future__ import annotations++import argparse+import datetime+import platform+import shutil+import subprocess+import time++import torch++from kornia.geometry.depth import depth_to_normals++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# Helpers+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def _sync(device: str) -> None:+ if device == "cuda":+ torch.cuda.synchronize()+++def bench(fn, *args, warmup: int = 5, reps: int = 20, device: str = "cpu", label: str = "") -> float:+ for _ in range(warmup):+ fn(*args)+ _sync(device)+ t0 = time.perf_counter()+ for _ in range(reps):+ fn(*args)+ _sync(device)+ ms = (time.perf_counter() - t0) / reps * 1000+ print(f" {label:<64s}: {ms:8.3f} ms")+ return ms+++def _print_env() -> None:+ date = datetime.datetime.now(tz=datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC")+ git = shutil.which("git") or "git"+ try:+ commit = subprocess.check_output([git, "rev-parse", "--short", "HEAD"], text=True).strip()+ except Exception:+ commit = "unknown"+ cpu = platform.processor() or platform.machine()+ print(f" date : {date}")+ print(f" commit : {commit}")+ print(f" cpu : {cpu}")+ if torch.cuda.is_available():+ print(f" gpu : {torch.cuda.get_device_name(0)}")+++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# Benchmark+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def run(device: str) -> None:+ print(f"\n{'=' * 72}")+ print(f" DEVICE : {device.upper()}")+ print(f"{'=' * 72}")++ K_base = torch.eye(3, device=device, dtype=torch.float32)+ K_base[0, 0] = K_base[1, 1] = 500.0+ K_base[0, 2] = K_base[1, 2] = 320.0++ configs = [+ ("B=1 H=64 W=64 ", 1, 64, 64),+ ("B=1 H=256 W=256 ", 1, 256, 256),+ ("B=4 H=480 W=640 ", 4, 480, 640),+ ("B=1 H=720 W=1280", 1, 720, 1280),+ ]++ print(f"\n {'config':<20s} {'depth_to_normals':>20s}")+ print(f" {'-' * 20} {'-' * 20}")+ for label, B, H, W in configs:+ K = K_base.unsqueeze(0).expand(B, -1, -1).contiguous()+ depth = torch.rand(B, 1, H, W, device=device, dtype=torch.float32).add_(0.1)+ bench(depth_to_normals, depth, K, device=device, label=label)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--cuda", action="store_true")+ args = parser.parse_args()++ _print_env()+ run("cpu")+ if args.cuda:+ if torch.cuda.is_available():+ run("cuda")+ else:+ print("\nWarning: --cuda requested but CUDA is not available.")diff --git a/benchmarks/geometry/pointcloud.py b/benchmarks/geometry/pointcloud.pynew file mode 100644index 000000000..f5930f754--- /dev/null+++ b/benchmarks/geometry/pointcloud.py@@ -0,0 +1,282 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+"""Benchmark for kornia.geometry point cloud operations on CPU and CUDA.++Covers:+ - transform_points+ - project_points / unproject_points+ - convert_points_to/from_homogeneous+ - depth_to_3d, depth_to_3d_v2 (uncached vs cached grid)+ - depth_to_normals+ - warp_frame_depth++Usage:+ python benchmarks/geometry/pointcloud.py # CPU only+ python benchmarks/geometry/pointcloud.py --cuda # CPU + CUDA+ python benchmarks/geometry/pointcloud.py --compile # include torch.compile variants+ python benchmarks/geometry/pointcloud.py --cuda --compile+"""++from __future__ import annotations++import argparse+import datetime+import functools+import platform+import shutil+import subprocess+import time++import torch++from kornia.geometry.camera import project_points, unproject_points+from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous+from kornia.geometry.depth import depth_to_3d, depth_to_3d_v2, depth_to_normals, unproject_meshgrid, warp_frame_depth+from kornia.geometry.linalg import transform_points++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# Helpers+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def _sync(device: str) -> None:+ if device == "cuda":+ torch.cuda.synchronize()+++def bench(fn, *args, warmup: int = 5, reps: int = 20, device: str = "cpu", label: str = "") -> float:+ """Return mean wall-clock time in milliseconds."""+ for _ in range(warmup):+ fn(*args)+ _sync(device)+ t0 = time.perf_counter()+ for _ in range(reps):+ fn(*args)+ _sync(device)+ ms = (time.perf_counter() - t0) / reps * 1000+ print(f" {label:<66s}: {ms:8.3f} ms")+ return ms+++def _print_env() -> None:+ date = datetime.datetime.now(tz=datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC")+ git = shutil.which("git") or "git"+ try:+ commit = subprocess.check_output([git, "rev-parse", "--short", "HEAD"], text=True).strip()+ except Exception:+ commit = "unknown"+ cpu = platform.processor() or platform.machine()+ print(f" date : {date}")+ print(f" commit : {commit}")+ print(f" cpu : {cpu}")+ if torch.cuda.is_available():+ print(f" gpu : {torch.cuda.get_device_name(0)}")+++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# transform_points+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def bench_transform_points(device: str, dtype: torch.dtype = torch.float32, compile_: bool = False) -> None:+ print(f"\n--- transform_points device={device} dtype={dtype} ---")++ fn = transform_points+ fn_c = torch.compile(fn) if compile_ else None++ configs = [+ ("B=1 N=1K single transform", 1, 1_000, True),+ ("B=8 N=10K single transform", 8, 10_000, True),+ ("B=32 N=100K single transform", 32, 100_000, True),+ ("B=1 N=1K per-sample transform", 1, 1_000, False),+ ("B=8 N=10K per-sample transform", 8, 10_000, False),+ ("B=32 N=100K per-sample transform", 32, 100_000, False),+ ]++ for label, B, N, single_T in configs:+ pts = torch.randn(B, N, 3, device=device, dtype=dtype)+ T = torch.eye(4, device=device, dtype=dtype).unsqueeze(0)+ if not single_T:+ T = T.expand(B, -1, -1).contiguous()++ bench(fn, T, pts, device=device, label=label)+ if compile_:+ bench(fn_c, T, pts, device=device, label=f"{label} (compiled)")+++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# project / unproject+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def bench_project_unproject(device: str, dtype: torch.dtype = torch.float32, compile_: bool = False) -> None:+ print(f"\n--- project_points / unproject_points device={device} dtype={dtype} ---")++ K_base = torch.eye(3, device=device, dtype=dtype)+ K_base[0, 0] = K_base[1, 1] = 500.0+ K_base[0, 2] = K_base[1, 2] = 320.0++ proj_fn = project_points+ unproj_fn = unproject_points+ if compile_:+ proj_fn = torch.compile(proj_fn)+ unproj_fn = torch.compile(unproj_fn)++ configs = [+ ("B=1 N=1K ", 1, 1_000),+ ("B=8 N=10K ", 8, 10_000),+ ("B=32 N=100K", 32, 100_000),+ ]++ for label, B, N in configs:+ K_b = K_base.unsqueeze(0).expand(B, -1, -1)+ pts3 = torch.rand(B, N, 3, device=device, dtype=dtype).add_(0.5)+ pts2 = torch.rand(B, N, 2, device=device, dtype=dtype).mul_(640.0)+ depth = torch.ones(B, N, 1, device=device, dtype=dtype)++ bench(proj_fn, pts3, K_b, device=device, label=f"{label} project_points")+ bench(unproj_fn, pts2, depth, K_b, device=device, label=f"{label} unproject_points")+++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# homogeneous conversions+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def bench_homogeneous_conversions(device: str, dtype: torch.dtype = torch.float32) -> None:+ print(f"\n--- homogeneous conversions device={device} dtype={dtype} ---")++ for label, shape, fn in [+ ("N=1M 3-D β homogeneous", (1_000_000, 3), convert_points_to_homogeneous),+ ("N=1M 4-D β euclidean", (1_000_000, 4), convert_points_from_homogeneous),+ ("B=32 N=100K 3-D β homogeneous", (32, 100_000, 3), convert_points_to_homogeneous),+ ("B=32 N=100K 4-D β euclidean", (32, 100_000, 4), convert_points_from_homogeneous),+ ]:+ x = torch.randn(*shape, device=device, dtype=dtype)+ bench(fn, x, device=device, label=label)+++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# depth_to_3d / depth_to_3d_v2 / depth_to_normals+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def bench_depth_functions(device: str, dtype: torch.dtype = torch.float32, compile_: bool = False) -> None:+ print(f"\n--- depth_to_3d / depth_to_3d_v2 / depth_to_normals device={device} dtype={dtype} ---")++ K_base = torch.eye(3, device=device, dtype=dtype)+ K_base[0, 0] = K_base[1, 1] = 500.0+ K_base[0, 2] = K_base[1, 2] = 320.0++ configs = [+ ("B=1 H=64 W=64 ", 1, 64, 64),+ ("B=1 H=256 W=256 ", 1, 256, 256),+ ("B=4 H=480 W=640 ", 4, 480, 640),+ ("B=1 H=720 W=1280", 1, 720, 1280),+ ]++ for label, B, H, W in configs:+ K_b = K_base.unsqueeze(0).expand(B, -1, -1).contiguous()+ depth4 = torch.rand(B, 1, H, W, device=device, dtype=dtype).add_(0.1)+ depth3 = depth4.squeeze(1)++ bench(depth_to_3d, depth4, K_b, device=device, label=f"{label} depth_to_3d")+ bench(depth_to_3d_v2, depth3, K_b, device=device, label=f"{label} depth_to_3d_v2 (no cache)")++ grid = unproject_meshgrid(H, W, K_b, device=device, dtype=dtype)+ bench(+ functools.partial(depth_to_3d_v2, xyz_grid=grid),+ depth3,+ K_b,+ device=device,+ label=f"{label} depth_to_3d_v2 (cached grid)",+ )++ bench(depth_to_normals, depth4, K_b, device=device, label=f"{label} depth_to_normals")++ if compile_:+ fn_c = torch.compile(depth_to_3d_v2)+ bench(+ functools.partial(fn_c, xyz_grid=grid),+ depth3,+ K_b,+ device=device,+ label=f"{label} depth_to_3d_v2 (cached + compiled)",+ )+++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# warp_frame_depth+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def bench_warp_frame_depth(device: str, dtype: torch.dtype = torch.float32) -> None:+ print(f"\n--- warp_frame_depth device={device} dtype={dtype} ---")++ K_base = torch.eye(3, device=device, dtype=dtype)+ K_base[0, 0] = K_base[1, 1] = 500.0+ K_base[0, 2] = K_base[1, 2] = 320.0++ configs = [+ ("B=1 C=3 H=256 W=256 ", 1, 3, 256, 256),+ ("B=4 C=3 H=480 W=640 ", 4, 3, 480, 640),+ ("B=1 C=3 H=720 W=1280", 1, 3, 720, 1280),+ ]++ for label, B, C, H, W in configs:+ K_b = K_base.unsqueeze(0).expand(B, -1, -1).contiguous()+ depth = torch.rand(B, 1, H, W, device=device, dtype=dtype).add_(0.1)+ image = torch.rand(B, C, H, W, device=device, dtype=dtype)+ T = torch.eye(4, device=device, dtype=dtype).unsqueeze(0).expand(B, -1, -1).contiguous()++ bench(warp_frame_depth, image, depth, T, K_b, device=device, label=label)+++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# Entry point+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def run_all(device: str, compile_: bool = False) -> None:+ sep = "=" * 72+ print(f"\n{sep}")+ print(f" DEVICE : {device.upper()}")+ print(f" compile: {compile_}")+ print(sep)+ bench_transform_points(device, compile_=compile_)+ bench_project_unproject(device, compile_=compile_)+ bench_homogeneous_conversions(device)+ bench_depth_functions(device, compile_=compile_)+ bench_warp_frame_depth(device)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(+ description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter,+ )+ parser.add_argument("--cuda", action="store_true", help="also run on CUDA")+ parser.add_argument("--compile", action="store_true", dest="compile_", help="include torch.compile variants")+ args = parser.parse_args()++ _print_env()+ run_all("cpu", compile_=args.compile_)+ if args.cuda:+ if torch.cuda.is_available():+ run_all("cuda", compile_=args.compile_)+ else:+ print("\nWarning: --cuda requested but CUDA is not available.")diff --git a/benchmarks/geometry/project_distort.py b/benchmarks/geometry/project_distort.pynew file mode 100644index 000000000..188a129b2--- /dev/null+++ b/benchmarks/geometry/project_distort.py@@ -0,0 +1,158 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+"""Benchmark for project/unproject_points and calibration distortion functions.++Usage:+ python benchmarks/geometry/project_distort.py+ python benchmarks/geometry/project_distort.py --cuda+"""++from __future__ import annotations++import argparse+import datetime+import platform+import shutil+import subprocess+import time++import torch++from kornia.geometry.calibration.distort import distort_points+from kornia.geometry.calibration.undistort import undistort_points+from kornia.geometry.camera import project_points, unproject_points+from kornia.geometry.conversions import denormalize_points_with_intrinsics, normalize_points_with_intrinsics++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# Helpers+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def _sync(device: str) -> None:+ if device == "cuda":+ torch.cuda.synchronize()+++def bench(fn, *args, warmup: int = 10, reps: int = 50, device: str = "cpu", label: str = "") -> float:+ for _ in range(warmup):+ fn(*args)+ _sync(device)+ t0 = time.perf_counter()+ for _ in range(reps):+ fn(*args)+ _sync(device)+ ms = (time.perf_counter() - t0) / reps * 1000+ print(f" {label:<60s}: {ms:8.3f} ms")+ return ms+++def _print_env() -> None:+ date = datetime.datetime.now(tz=datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC")+ git = shutil.which("git") or "git"+ try:+ commit = subprocess.check_output([git, "rev-parse", "--short", "HEAD"], text=True).strip()+ except Exception:+ commit = "unknown"+ cpu = platform.processor() or platform.machine()+ print(f" date : {date}")+ print(f" commit : {commit}")+ print(f" cpu : {cpu}")+ if torch.cuda.is_available():+ print(f" gpu : {torch.cuda.get_device_name(0)}")+++# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+# Benchmarks+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+++def bench_project_unproject(device: str) -> None:+ print(f"\n--- project_points / unproject_points device={device} ---")++ K_base = torch.eye(3, device=device)+ K_base[0, 0] = K_base[1, 1] = 500.0+ K_base[0, 2] = K_base[1, 2] = 320.0++ configs = [+ ("B=1 N=1K ", 1, 1_000),+ ("B=8 N=10K ", 8, 10_000),+ ("B=32 N=100K", 32, 100_000),+ ]++ for label, B, N in configs:+ K_b = K_base.unsqueeze(0).expand(B, -1, -1)+ pts3 = torch.rand(B, N, 3, device=device).add_(0.5)+ pts2 = torch.rand(B, N, 2, device=device).mul_(640.0)+ pts2_norm = normalize_points_with_intrinsics(pts2, K_b)+ depth = torch.ones(B, N, 1, device=device)++ print(f"\n {label}")+ bench(project_points, pts3, K_b, device=device, label="project_points")+ bench(unproject_points, pts2, depth, K_b, device=device, label="unproject_points")+ bench(normalize_points_with_intrinsics, pts2, K_b, device=device, label="normalize_points_with_intrinsics")+ bench(+ denormalize_points_with_intrinsics,+ pts2_norm,+ K_b,+ device=device,+ label="denormalize_points_with_intrinsics",+ )+++def bench_distort_undistort(device: str) -> None:+ print(f"\n--- distort_points / undistort_points device={device} ---")++ K_base = torch.eye(3, device=device)+ K_base[0, 0] = K_base[1, 1] = 500.0+ K_base[0, 2] = K_base[1, 2] = 320.0+ dist_base = torch.tensor([0.1, -0.05, 0.001, 0.001, 0.02, 0.01, -0.005, 0.002], device=device)++ configs = [+ ("B=1 N=1K ", 1, 1_000),+ ("B=1 N=100K", 1, 100_000),+ ("B=32 N=10K ", 32, 10_000),+ ]++ for label, B, N in configs:+ K_b = K_base.unsqueeze(0).expand(B, -1, -1).contiguous()+ dist_b = dist_base.unsqueeze(0).expand(B, -1).contiguous()+ pts2 = torch.rand(B, N, 2, device=device).mul_(640.0)++ print(f"\n {label}")+ bench(distort_points, pts2, K_b, dist_b, device=device, label="distort_points")+ bench(undistort_points, pts2, K_b, dist_b, device=device, label="undistort_points (5 iters)")+++def run(device: str) -> None:+ sep = "=" * 72+ print(f"\n{sep}\n DEVICE: {device.upper()}\n{sep}")+ bench_project_unproject(device)+ bench_distort_undistort(device)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--cuda", action="store_true")+ args = parser.parse_args()++ _print_env()+ run("cpu")+ if args.cuda:+ if torch.cuda.is_available():+ run("cuda")+ else:+ print("\nWarning: --cuda requested but CUDA is not available.")diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 861728a83..1480f9017 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -1299,24 +1299,11 @@ def denormalize_points_with_intrinsics(point_2d_norm: torch.Tensor, camera_matri# u = fx * X + cx# v = fy * Y + cy- # unpack coordinates- x_coord: torch.Tensor = point_2d_norm[..., 0]- y_coord: torch.Tensor = point_2d_norm[..., 1]-- # unpack intrinsics- fx: torch.Tensor = camera_matrix[..., 0, 0]- fy: torch.Tensor = camera_matrix[..., 1, 1]- cx: torch.Tensor = camera_matrix[..., 0, 2]- cy: torch.Tensor = camera_matrix[..., 1, 2]-- if len(cx.shape) < len(x_coord.shape): # broadcast intrinsics- cx, cy, fx, fy = cx.unsqueeze(-1), cy.unsqueeze(-1), fx.unsqueeze(-1), fy.unsqueeze(-1)-- # apply intrinsics ans return- u_coord: torch.Tensor = x_coord * fx + cx- v_coord: torch.Tensor = y_coord * fy + cy-- return torch.stack([u_coord, v_coord], dim=-1)+ fxfy = camera_matrix[..., :2, :2].diagonal(dim1=-2, dim2=-1) # (*, 2)+ cxcy = camera_matrix[..., :2, 2] # (*, 2)+ if len(cxcy.shape) < len(point_2d_norm.shape):+ fxfy, cxcy = fxfy.unsqueeze(-2), cxcy.unsqueeze(-2)+ return point_2d_norm * fxfy + cxcydef Rt_to_matrix4x4(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex 18cf7f714..4d368ce4f 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -134,8 +134,10 @@ def depth_to_3d_v2(# create base grid if not providedheight, width = depth.shape[-2:]- points_xyz: torch.Tensor = xyz_grid or unproject_meshgrid(- height, width, camera_matrix, normalize_points, depth.device, depth.dtype+ points_xyz: torch.Tensor = (+ xyz_grid+ if xyz_grid is not None+ else unproject_meshgrid(height, width, camera_matrix, normalize_points, depth.device, depth.dtype))KORNIA_CHECK_SHAPE(points_xyz, ["*", "H", "W", "3"])@@ -214,17 +216,20 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalizeKORNIA_CHECK_SHAPE(depth, ["B", "1", "H", "W"])KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])- # compute the 3d points from depth- xyz: torch.Tensor = depth_to_3d(depth, camera_matrix, normalize_points) # Bx3xHxW+ # compute the 3d points from depth; permute to channel-first for spatial_gradient+ xyz: torch.Tensor = depth_to_3d_v2(depth.squeeze(1), camera_matrix, normalize_points).permute(0, 3, 1, 2) # Bx3xHxW# compute the pointcloud spatial gradientsgradients: torch.Tensor = spatial_gradient(xyz) # Bx3x2xHxW- # compute normals- a, b = gradients[:, :, 0], gradients[:, :, 1] # Bx3xHxW+ # Rearrange to (B, H, W, 3) before cross product so the 3 XYZ components are+ # contiguous in memory. Cross product along dim=1 on a (B,3,H,W) tensor strides+ # H*W elements between components, causing severe cache thrashing on CPU.+ a: torch.Tensor = gradients[:, :, 0].permute(0, 2, 3, 1).contiguous() # BxHxWx3+ b: torch.Tensor = gradients[:, :, 1].permute(0, 2, 3, 1).contiguous() # BxHxWx3- normals: torch.Tensor = torch.linalg.cross(a, b, dim=1)- return F.normalize(normals, dim=1, p=2)+ normals: torch.Tensor = torch.linalg.cross(a, b, dim=-1) # BxHxWx3+ return F.normalize(normals, dim=-1, p=2).permute(0, 3, 1, 2) # Bx3xHxWdef depth_from_plane_equation(@@ -300,11 +305,8 @@ def warp_frame_depth(KORNIA_CHECK_SHAPE(src_trans_dst, ["B", "4", "4"])KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])- # unproject source points to camera frame- points_3d_dst: torch.Tensor = depth_to_3d(depth_dst, camera_matrix, normalize_points) # Bx3xHxW-- # transform points from source to destination- points_3d_dst = points_3d_dst.permute(0, 2, 3, 1) # BxHxWx3+ # unproject source points to camera frame as (B, H, W, 3) directly β avoids two permutes+ points_3d_dst: torch.Tensor = depth_to_3d_v2(depth_dst.squeeze(1), camera_matrix, normalize_points) # BxHxWx3# apply transformation to the 3d pointspoints_3d_src = transform_points(src_trans_dst[:, None], points_3d_dst) # BxHxWx3diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex c6ff9f1ea..111297c25 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -220,7 +220,6 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Tepoints_1_h = convert_points_to_homogeneous(points_1) # BxNxD+1# transform coordinatespoints_0_h = torch.bmm(points_1_h, trans_01.permute(0, 2, 1))- points_0_h = torch.squeeze(points_0_h, dim=-1)# to euclideanpoints_0 = convert_points_from_homogeneous(points_0_h) # BxNxD# reshape to the input shapediff --git a/pyproject.toml b/pyproject.tomlindex 1cadd31d5..81d2a4eff 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -206,8 +206,9 @@ max-statements = 64 # Recommended: 50"RUF012","S101","S311",+ "S603","D",-] # allow assert, random, ignore BLE, mutable class attr+] # allow assert, random, subprocess calls, ignore BLE, mutable class attr"docs/*" = ["PLR0912","PLR0915",diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex d936c48fe..327900d13 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -60,6 +60,16 @@ class TestDepthTo3d(BaseTester):# Align the output format of depth_to_3d with depth_to_3d_v2 by reordering dimensions.self.assert_close(points3d.permute(0, 2, 3, 1), points3d_v2)+ def test_depth_to_3d_v2_cached_grid(self, device, dtype):+ # Passing a pre-computed xyz_grid must not raise "Boolean value of Tensor+ # is ambiguous" (regression for the `xyz_grid or ...` truthiness bug).+ depth = torch.rand(2, 3, 4, device=device, dtype=dtype).add_(0.1)+ camera_matrix = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).expand(2, -1, -1).contiguous()+ grid = kornia.geometry.unproject_meshgrid(3, 4, camera_matrix, device=device, dtype=dtype)+ out_cached = kornia.geometry.depth.depth_to_3d_v2(depth, camera_matrix, xyz_grid=grid)+ out_uncached = kornia.geometry.depth.depth_to_3d_v2(depth, camera_matrix)+ self.assert_close(out_cached, out_uncached)+def test_unproject_meshgrid(self, device, dtype):# TODO: implement me with batchcamera_matrix = torch.eye(3, device=device, dtype=dtype).repeat(2, 1, 1)