Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): reject degenerate spatial sizes in depth_to_normals (#4458)

Zhenhuan Wang0b7e0e0e269e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e7389b272..6cd9e116e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -379,6 +379,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `depth_to_normals` now raises `ShapeError` when `H < 2` or `W < 2`, since surface normals need two
+ tangent directions. Previously, singleton axes could yield zero or non-finite normals, and empty
+ spatial dimensions failed inside padding. Inputs with both dimensions at least 2 are unchanged. (#4458)
+
* `RandAugment`'s `m` guard is exclusive at both ends, but its docstring and its error message
both named the closed interval `[0, 30]`, so a user who asked for the maximum strength the
message advertised got an exception saying `30` was in range. Both now read `(0, 30)`; the
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index d90e28d6a..e13a2aa5d 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -26,6 +26,7 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.exceptions import ShapeError
from kornia.filters.sobel import spatial_gradient
from kornia.geometry.grid import create_meshgrid
@@ -263,9 +264,10 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poin
def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:
- """Compute the normal surface per pixel.
+ r"""Compute the normal surface per pixel.
Convention:
+ - both spatial dimensions must be at least 2: a surface normal requires two tangent directions.
- the normal is the cross product of the two spatial gradients of the unprojected point cloud, taken in
the order ``d/dx`` cross ``d/dy`` and then normalized to unit length, so a fronto-parallel plane gets
the normal ``(0, 0, 1)``: ``+z`` points **away** from the camera, along the viewing direction, and
@@ -278,7 +280,8 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize
layout, with the three normal components on the channel axis.
Args:
- depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.
+ depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`, with
+ :math:`H \geq 2` and :math:`W \geq 2`.
camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.
normalize_points: whether to normalize the pointcloud. This must be set to `True` when the depth is
represented as the Euclidean ray length from the camera position.
@@ -286,6 +289,9 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize
Return:
tensor with a normal surface vector per pixel of the same resolution as the input :math:`(B, 3, H, W)`.
+ Raises:
+ ShapeError: if either spatial dimension of ``depth`` is smaller than 2.
+
Example:
>>> depth = torch.rand(1, 1, 4, 4)
>>> K = torch.eye(3)[None]
@@ -298,6 +304,14 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize
KORNIA_CHECK_SHAPE(depth, ["B", "1", "H", "W"])
KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])
+ height, width = depth.shape[-2:]
+ if height < 2 or width < 2:
+ raise ShapeError(
+ f"depth_to_normals requires H >= 2 and W >= 2. Got H={height}, W={width}.",
+ actual_shape=list(depth.shape),
+ expected_shape=["B", "1", "H >= 2", "W >= 2"],
+ )
+
# 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
diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.py
index 956e0e09d..2a411b40f 100644
--- a/tests/geometry/test_depth.py
+++ b/tests/geometry/test_depth.py
@@ -294,17 +294,13 @@ class TestDepthTo3d(BaseTester):
def test_convention_depth_to_3d_v2_keeps_the_w_one_axis_4278(self, device, dtype):
# Regression for #4278 (repaired by #4298): a single column retains its width axis and agrees across
- # layouts, and the two public consumers of unproject_meshgrid that inherited the squeeze --
- # depth_to_normals and warp_frame_depth -- keep the axis too. At H = 1 the normals' VALUE is
- # device-dependent (all-zero on cpu, [-1, -1, -1] on mps, nan in float16), so only shapes are asserted
- # for those two.
+ # layouts. warp_frame_depth also keeps the axis. depth_to_normals requires both spatial dimensions
+ # to be at least 2; its separate convention pin covers that contract.
camera_matrix = _k_asymmetric(device, dtype)
depth = torch.full((1, 1, 3, 1), 2.0, device=device, dtype=dtype)
v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)
assert v2.shape == (1, 3, 1, 3)
assert torch.equal(depth_to_3d(depth, camera_matrix).permute(0, 2, 3, 1), v2)
- assert depth_to_normals(depth, camera_matrix).shape == (1, 3, 3, 1)
- assert depth_to_normals(depth.transpose(-1, -2).contiguous(), camera_matrix).shape == (1, 3, 1, 3)
assert warp_frame_depth(depth, depth, _eye4(device, dtype), camera_matrix).shape == (1, 1, 3, 1)
def test_convention_xyz_grid_bypasses_the_camera_matrix(self, device, dtype):
@@ -418,6 +414,52 @@ class TestUnprojectMeshgrid(BaseTester):
class TestDepthToNormals(BaseTester):
+ @pytest.mark.parametrize(("height", "width"), [(1, 3), (3, 1), (1, 1), (0, 3), (3, 0), (0, 0)])
+ @pytest.mark.parametrize("normalize_points", [False, True])
+ def test_convention_normals_require_two_spatial_axes_4398(self, height, width, normalize_points, device, dtype):
+ # A surface normal needs two tangent directions, including when depth represents ray length.
+ depth = torch.full((1, 1, height, width), 2.0, device=device, dtype=dtype)
+ camera_matrix = torch.eye(3, device=device, dtype=dtype)[None]
+
+ with pytest.raises(ShapeError, match="H >= 2 and W >= 2") as exc_info:
+ depth_to_normals(depth, camera_matrix, normalize_points)
+
+ assert exc_info.value.actual_shape == list(depth.shape)
+ assert f"H={height}, W={width}" in str(exc_info.value)
+
+ @pytest.mark.parametrize(("height", "width"), [(2, 2), (2, 3), (3, 2)])
+ @pytest.mark.parametrize("normalize_points", [False, True])
+ @pytest.mark.parametrize("camera_batch_size", [1, 2])
+ def test_minimum_spatial_size_plane(self, height, width, normalize_points, camera_batch_size, device, dtype):
+ camera_matrix = torch.tensor(
+ [[[1.0, 0.0, 1.0], [0.0, 2.0, 1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ ).expand(camera_batch_size, -1, -1)
+ depth = torch.tensor([2.0, 4.0], device=device, dtype=dtype).view(2, 1, 1, 1).expand(2, 1, height, width)
+ if normalize_points:
+ # Ray lengths for the same fronto-parallel planes z=2 and z=4, rather than constant ray lengths.
+ x = torch.arange(width, device=device, dtype=dtype) - 1.0
+ y = (torch.arange(height, device=device, dtype=dtype) - 1.0) / 2.0
+ depth = depth * (x[None, :] ** 2 + y[:, None] ** 2 + 1.0).sqrt()
+
+ normals = depth_to_normals(depth, camera_matrix, normalize_points)
+
+ assert normals.shape == (2, 3, height, width)
+ assert normals.device == depth.device
+ assert normals.dtype == dtype
+ assert torch.isfinite(normals).all()
+ expected = torch.zeros_like(normals)
+ expected[:, 2] = 1.0
+ self.assert_close(normals, expected)
+
+ @pytest.mark.parametrize("normalize_points", [False, True])
+ def test_dynamo_minimum_spatial_size(self, normalize_points, device, dtype, torch_optimizer):
+ depth = torch.full((1, 1, 2, 3), 2.0, device=device, dtype=dtype)
+ camera_matrix = torch.eye(3, device=device, dtype=dtype)[None]
+ expected = depth_to_normals(depth, camera_matrix, normalize_points)
+
+ compiled = torch_optimizer(depth_to_normals, fullgraph=True)
+ self.assert_close(compiled(depth, camera_matrix, normalize_points), expected)
+
def test_smoke(self, device, dtype):
depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)