Algorithm Search⌘K

Data structureintro

Range image

Also called depth image, 2.5D image.

An image whose pixels store the distance to the scene along each ray, which gives a point cloud with grid neighbors.

Time
Θ(n + W H) buildΘ(1) query
Space
Θ(W H) extra
Where
H = image height in pixels; W = image width in pixels; n = the number of input points of a build
Properties
deterministicexactnot static
Origin
Paul J. Besl, 1988

A range image is a 2D grid of numbers in which each cell holds the distance from a sensor to the first surface along one ray. It is a digital image where the value of a pixel is a distance, not a brightness. Depth cameras, laser scanners and stereo matching produce range images. Each valid cell gives one 3D point, so a range image is a point cloud whose points come with a grid: the four cells around a cell are its neighbors, often also on the surface. This makes neighbor search and normal estimation cost O(1)O(1) per point, without a k-d tree. The value is either the depth ZZ along the optical axis, as in a depth image, or the Euclidean range ∥X∥\|X\| to the sensor; the two differ by a known factor per pixel. The name 2.5D says that the image holds one surface per ray, the one seen from the sensor, not a full 3D model.

In plain words

Take a photograph, but in each pixel write down how far away the thing in that pixel is, in meters, instead of its color. That is a range image. A blank pixel means the sensor saw nothing there, for example the sky or a black surface.

Because you know where the camera was and which way each pixel looks, you can turn every pixel back into a point in space: go out along the pixel's ray by the stored distance. The pixels next to each other in the grid are usually next to each other on the object too, so the grid already tells you the neighbors of each point. The exception is the edge of an object, where the next pixel jumps to the background far behind.

The abstract type

A range image is a W×HW \times H grid of cells with a camera model. Each cell is empty or holds one depth. It supports:

  • BUILD(P)(P) makes the image of a point cloud PP seen by the camera: each cell gets the depth of the nearest point that projects into it.
  • BACK-PROJECT(u,v)(u, v) returns the 3D point of the cell (u,v)(u, v), or nothing if the cell is empty.
  • RANGE(u,v)(u, v) returns the distance ∥X∥\|X\| of that point to the camera center.
  • NEIGHBORS(u,v,τ)(u, v, \tau) returns the valid 4-neighbors of a cell whose depth differs from its depth by at most τ\tau.
  • NORMAL(u,v,τ)(u, v, \tau) returns a unit surface normal at the cell from its neighbors, turned toward the camera.
  • TO-CLOUD lists the points of all valid cells, row by row, an organized point cloud.

A cell can also be written directly, which is how a sensor fills the image.

Representation

This page uses the pinhole camera with the conventions of the area: the camera frame has XX to the right, YY down and ZZ forward, along the optical axis. (The graphics page of the pinhole camera looks along −w-w instead.) The intrinsic matrix is K=[[fx,0,cx],[0,fy,cy],[0,0,1]]K = [[f_x, 0, c_x], [0, f_y, c_y], [0, 0, 1]], the pixel (u,v)(u, v) has column uu and row vv, and the grid is stored as img[v][u]\mathrm{img}[v][u]. The center of pixel (u,v)(u, v) is the image point (u,v)(u, v), and its ray is

r(u,v)=(a,b,1),a=u−cxfx,b=v−cyfy.r(u, v) = (a, b, 1), \qquad a = \frac{u - c_x}{f_x}, \quad b = \frac{v - c_y}{f_y}.

A cell stores the depth ZZ. The point of the cell is X=Z r(u,v)X = Z\, r(u, v), and its range is ∥X∥=Z1+a2+b2\|X\| = Z \sqrt{1 + a^2 + b^2}. A range image that stores ∥X∥\|X\| converts to depth by dividing by the same factor, which depends only on the pixel. Empty cells hold a marker: here None, in files often 0 or NaN.

A lidar that spins about a vertical axis gives a different grid: one row per laser beam, one column per azimuth angle, and the range in each cell. The ray of a cell then comes from the two angles, not from KK, but the rest of this page is the same.

Operations

  1. BUILD(P, W, H, K) ▷ a z-buffer: keep the nearest point per pixel
  2. 1img ← a W × H grid of empty cells
  3. 2for each point X = (X₁, X₂, X₃) in P do
  4. 3if X₃ ≤ 0 then skip X ▷ behind the camera
  5. 4u ← ⌊f_x X₁/X₃ + c_x + 1/2⌋, v ← ⌊f_y X₂/X₃ + c_y + 1/2⌋
  6. 5if (u, v) is outside the grid then skip X
  7. 6if img[v][u] is empty or X₃ < img[v][u] then
  8. 7img[v][u] ← X₃
  9. 8return img

BUILD is the z-buffer of computer graphics, applied to points. Line L4 rounds the projection to the nearest pixel center, so the pixel (u,v)(u, v) owns the square [u−12,u+12)×[v−12,v+12)[u - \tfrac12, u + \tfrac12) \times [v - \tfrac12, v + \tfrac12). Lines L6 and L7 keep the nearest point, the one the sensor would see.

  1. BACK-PROJECT(img, u, v)
  2. 1Z ← img[v][u]; if Z is empty then return nothing
  3. 2return Z · ((u - c_x)/f_x, (v - c_y)/f_y, 1)
  4. NEIGHBORS(img, u, v, τ)
  5. 3for each (u', v') in (u ± 1, v) and (u, v ± 1) do
  6. 4if (u', v') is outside the grid then skip it
  7. 5if img[v'][u'] is not empty and |img[v'][u'] - img[v][u]| ≤ τ then
  8. 6report (u', v')
  9. NORMAL(img, u, v, τ) ▷ X is BACK-PROJECT(img, u, v)
  10. 7Δu ← right point - left point, Δv ← lower point - upper point ▷ from NEIGHBORS; one-sided if a side is missing, give up if both are
  11. 8n ← Δu × Δv
  12. 9n ← n / ‖n‖
  13. 10if n · X > 0 then n ← -n ▷ turn n toward the camera
  14. 11return n

The test at line L13 is what separates a range image from a plain image grid. Two adjacent cells on either side of the edge of an object hold depths that differ a lot, and their points are not neighbors on any surface. The threshold τ\tau cuts these links. A good τ\tau grows with the depth, because the gap between the points of two adjacent pixels on a slanted surface grows with ZZ.

Line L16 takes the cross product of two tangent directions, which gives a normal in O(1)O(1) time per cell. For less noise, fit a plane to a larger window of cells as in point cloud normal estimation; the window is still found in O(1)O(1) time per cell.

Example

Use a 3×23 \times 2 image with fx=fy=2f_x = f_y = 2, cx=1c_x = 1, cy=0.5c_y = 0.5. BUILD gets five points.

point projection pixel result
(0,−0.5,2)(0, -0.5, 2) (1,0)(1, 0) (1,0)(1, 0) stored, Z=2Z = 2
(0,−1,4)(0, -1, 4) (1,0)(1, 0) (1,0)(1, 0) hidden: 4>24 > 2
(−1,0.5,2)(-1, 0.5, 2) (0,1)(0, 1) (0,1)(0, 1) stored, Z=2Z = 2
(1,0.25,1)(1, 0.25, 1) (3,1)(3, 1) (3,1)(3, 1) outside the grid
(0.2,0,−1)(0.2, 0, -1) none none behind the camera

The grid is then

u=0u = 0 u=1u = 1 u=2u = 2
v=0v = 0 empty 2 empty
v=1v = 1 2 empty empty

BACK-PROJECT of (1,0)(1, 0) uses the ray (0,−0.25,1)(0, -0.25, 1) and returns 2⋅(0,−0.25,1)=(0,−0.5,2)2 \cdot (0, -0.25, 1) = (0, -0.5, 2), the first point again. Its range is 21+0.0625=2.06162\sqrt{1 + 0.0625} = 2.0616, a little more than its depth, because the pixel is off the optical axis. The second point is lost: a range image holds one surface per ray.

Correctness

Line L4 gives the pixel (u,v)(u, v) exactly when the projection lies in the square of that pixel, by the definition of the floor. An induction over the points then shows that after BUILD each cell holds the least depth among the points with positive depth that project into its square. BACK-PROJECT returns the point of that depth on the ray through the pixel center; it projects back to (u,v)(u, v) with the same depth, so a cloud with one point on each pixel ray is rebuilt exactly. NORMAL returns the exact plane normal, turned toward the camera, whenever the neighbors it uses lie on one plane. The full proof is below.

Proof: BUILD stores in each cell the least depth of the points seen through that pixel, BACK-PROJECT inverts the projection, and the grid normal is exact on planesfull

Fix the image size W×HW \times H and the intrinsic parameters fx,fy>0f_x, f_y > 0, cx,cyc_x, c_y. For a point X=(X1,X2,X3)X = (X_1, X_2, X_3) with X3>0X_3 > 0 the projection is π(X)=(fxX1/X3+cx, fyX2/X3+cy)\pi(X) = (f_x X_1 / X_3 + c_x,\ f_y X_2 / X_3 + c_y). The pixel (u,v)(u, v) owns the half-open square S(u,v)=[u−12,u+12)×[v−12,v+12)S(u, v) = [u - \tfrac12, u + \tfrac12) \times [v - \tfrac12, v + \tfrac12) of the image plane. For a pixel let A(u,v)A(u, v) be the set of input points with X3>0X_3 > 0 and π(X)∈S(u,v)\pi(X) \in S(u, v).

Lemma 1 (the pixel of a point). Line L4 gives (u,v)(u, v) exactly when π(X)∈S(u,v)\pi(X) \in S(u, v).

Proof. For a real xx and an integer uu, ⌊x+12⌋=u\lfloor x + \tfrac12 \rfloor = u holds exactly when u≤x+12<u+1u \le x + \tfrac12 < u + 1, that is, when u−12≤x<u+12u - \tfrac12 \le x < u + \tfrac12. Apply this to both coordinates. □\square

Theorem 1 (BUILD). After BUILD, the cell (u,v)(u, v) holds min⁡{X3:X∈A(u,v)}\min \{ X_3 : X \in A(u, v) \} if A(u,v)A(u, v) is not empty, and is empty otherwise.

Proof. Every cell starts empty at line L1. Line L3 drops the points with X3≤0X_3 \le 0, and line L5 drops the points whose pixel is outside the grid; by Lemma 1, such a point is in no set A(u,v)A(u, v) of the grid. Every other point is in exactly one set A(u,v)A(u, v), the one of the pixel of line L4, and it is compared only with that cell.

We show by induction over the loop of line L2 that after the first tt points each cell holds the minimum depth of the points of A(u,v)A(u, v) among the first tt, or is empty if there are none. This is true for t=0t = 0. Point t+1t + 1 changes at most the cell (u,v)(u, v) of line L4. If the cell was empty, line L7 stores X3X_3, the minimum of a set of one depth. If it held zz, line L6 replaces zz by X3X_3 exactly when X3<zX_3 < z, so the cell holds min⁡(z,X3)\min(z, X_3). Other cells keep their sets and their values. At t=nt = n this is the claim. □\square

Theorem 2 (BACK-PROJECT). Let the cell (u,v)(u, v) hold the depth z>0z > 0, and let X=z (a,b,1)X = z\,(a, b, 1) with a=(u−cx)/fxa = (u - c_x)/f_x and b=(v−cy)/fyb = (v - c_y)/f_y, as at line L10. Then X3=zX_3 = z, π(X)=(u,v)\pi(X) = (u, v), and ∥X∥=z1+a2+b2\|X\| = z\sqrt{1 + a^2 + b^2}. Of all the points with depth zz whose projection is in S(u,v)S(u, v), XX is the one on the ray through the pixel center.

Proof. X3=zX_3 = z by construction, and fxX1/X3+cx=fxa+cx=uf_x X_1 / X_3 + c_x = f_x a + c_x = u, and in the same way the second coordinate is vv. The norm is z∥(a,b,1)∥z \|(a, b, 1)\|. A point of depth zz is fixed by its projection, because X1=z(x−cx)/fxX_1 = z (x - c_x)/f_x and X2=z(y−cy)/fyX_2 = z (y - c_y)/f_y; the projection (u,v)(u, v) gives XX. □\square

So a cloud whose points project exactly onto pixel centers, one point per pixel, is rebuilt exactly by BUILD and BACK-PROJECT. For other points the round trip moves each kept point along its depth plane to the ray of its pixel center, by at most 12z/fx\tfrac12 z / f_x in X1X_1 and 12z/fy\tfrac12 z / f_y in X2X_2.

Theorem 3 (NEIGHBORS). Lines L11 to L14 return the pixels (u±1,v)(u \pm 1, v) and (u,v±1)(u, v \pm 1) that are in the grid, hold a depth z′z', and satisfy ∣z′−z∣≤τ|z' - z| \le \tau.

Proof. Line L11 lists the four offsets, line L12 removes those outside the grid, and line L13 tests the remaining two conditions. □\square

Theorem 4 (normals on a plane). Suppose the valid cells around (u,v)(u, v) used at line L15 all back-project to points of one plane {X:m⋅X=d}\{X : m \cdot X = d\} with ∥m∥=1\|m\| = 1, and that the two differences Δu,Δv\Delta_u, \Delta_v of line L15 are not parallel. Then lines L16 to L18 return mm or −m-m, and the sign is the one with n⋅X≤0n \cdot X \le 0 at the back-projected point XX of (u,v)(u, v), the side of the plane that faces the camera.

Proof. Each difference is X′−X′′X' - X'' with m⋅X′=m⋅X′′=dm \cdot X' = m \cdot X'' = d, so m⋅Δu=m⋅Δv=0m \cdot \Delta_u = m \cdot \Delta_v = 0. The cross product of two vectors that are both orthogonal to mm and not parallel is a nonzero multiple of mm, so after the division by its length at line L17 it is ±m\pm m. Line L18 flips it when n⋅X>0n \cdot X > 0, so the result has n⋅X≤0n \cdot X \le 0. The camera center is the origin, and n⋅(0−X)≥0n \cdot (0 - X) \ge 0 says that nn points from XX toward the camera side. □\square

On a curved surface the same lines give the normal of the plane through the back-projected neighbors, which tends to the surface normal as the pixel spacing on the surface goes to zero. All loops are over finite ranges, so every operation terminates. ■\blacksquare

Complexity

The model is the real RAM with the floor function.

operation time notes
BUILD of nn points Θ(n+WH)\Theta(n + WH) Θ(WH)\Theta(WH) to clear the grid, O(1)O(1) per point
BACK-PROJECT, RANGE Θ(1)\Theta(1) one ray and one product
NEIGHBORS, NORMAL Θ(1)\Theta(1) four cells
TO-CLOUD Θ(WH)\Theta(WH) one pass over the grid
space Θ(WH)\Theta(WH) one number per cell

Compare an unorganized cloud of nn points, where each neighbor query needs a search structure, such as a k-d tree with an O(nlog⁡n)O(n \log n) build and about O(log⁡n)O(\log n) per query on well-spread points.

Variants

  • Depth image and range image. Depth cameras usually store ZZ, and scanners usually store ∥X∥\|X\|. Both are called range images. Check which one a file holds before back-projection.
  • Spherical range image. A rotating lidar has one row per beam and one column per azimuth step. Many lidar methods, such as LOAM, use this grid for fast neighbors along a scan line.
  • Disparity image. Stereo gives a disparity dd per pixel, with Z=fB/dZ = f B / d for the baseline BB. It is stored as an image and turned into depth by depth from disparity.
  • Multi-return and multi-layer images. Some scanners record several returns per ray, from glass, leaves or rain. A layered depth image keeps several depths per pixel, which is no longer 2.5D.
  • Mesh from the grid. Join each 2×22 \times 2 block of valid cells into two triangles, and drop triangles across depth jumps. This gives a mesh of the visible surface in Θ(WH)\Theta(WH) time.
  • Fusion. TSDF fusion merges many depth images into one volume, following Curless and Levoy (1996).

When to use it

Keep data as a range image as long as possible when it comes from one sensor position: neighbors, normals, edges and meshes are cheap on the grid, and it takes less space than a list of points. Use the grid to find depth edges, which are the jumps of line L13. Convert to an unorganized point cloud when you merge views from several positions, since the points of two views no longer share a grid. Do not use a single range image when you need the parts of the scene behind the first surface.

Pitfalls

  • Depth where range is stored. Using a range value as ZZ at line L10 puts off-axis points too far away and bends planes into bowls. Divide a range by 1+a2+b2\sqrt{1 + a^2 + b^2} first.
  • Pixel corner or pixel center. Some programs put the pixel center at (u+12,v+12)(u + \tfrac12, v + \tfrac12). Mixing the conventions at lines L4 and L10 shifts every point by half a pixel. Use the same convention in both.
  • Zero as a depth. Many files store 0 for an empty cell. Back-projecting it at line L10 gives points at the camera center, which spoil means and fits. Test for the marker first.
  • No jump test. Leaving out the test ∣Z′−Z∣≤τ|Z' - Z| \le \tau at line L13 links the foreground to the background at every object edge. Normals there point sideways, and a mesh gets long, thin triangles across empty space.
  • A fixed jump threshold. A τ\tau that is right at 1 m cuts real surfaces at 10 m, because the spacing grows with ZZ. Scale τ\tau with the depth, or test the angle between the ray and the line between the two points.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

range_image.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/range-image/. The authors are listed in prov/M707AA.jsonl.
"""A range image (depth image) of a pinhole camera.

Conventions: the camera frame has X to the right, Y down and Z forward. The
intrinsic matrix is K = [[fx, 0, cx], [0, fy, cy], [0, 0, 1]] (no skew). The
image is indexed img[v][u] with u the column and v the row. Pixel (u, v) has
its center at the point (u, v) of the image plane. A cell stores the depth Z of
the point seen through the pixel center, or None if the pixel has no point.

The range of a point is its distance ||X|| to the camera center. Depth and
range of a cell differ by the fixed factor sqrt(1 + a^2 + b^2) with
a = (u - cx)/fx and b = (v - cy)/fy, the length of the ray (a, b, 1).
"""

from __future__ import annotations

import math
from typing import List, Optional, Sequence, Tuple

Point = Tuple[float, float, float]


class RangeImage:
    """A W x H grid of depths with a pinhole camera."""

    def __init__(self, width: int, height: int, fx: float, fy: float,
                 cx: float, cy: float) -> None:
        if width <= 0 or height <= 0 or fx <= 0 or fy <= 0:
            raise ValueError("need a positive size and positive focal lengths")
        self.W, self.H = width, height
        self.fx, self.fy, self.cx, self.cy = fx, fy, cx, cy
        self.depth: List[List[Optional[float]]] = [[None] * width for _ in range(height)]

    # -- build ------------------------------------------------------------

    @classmethod
    def from_points(cls, points: Sequence[Sequence[float]], width: int, height: int,
                    fx: float, fy: float, cx: float, cy: float) -> "RangeImage":
        """Project the points and keep, per pixel, the smallest depth (a z-buffer).

        A point goes to the pixel whose center is nearest to its projection.
        Points with Z <= 0 or outside the image are dropped."""
        img = cls(width, height, fx, fy, cx, cy)  # @line L1
        for X, Y, Z in points:  # @line L2
            if Z <= 0:  # @line L3
                continue
            u = math.floor(fx * X / Z + cx + 0.5)  # @line L4
            v = math.floor(fy * Y / Z + cy + 0.5)
            if not (0 <= u < width and 0 <= v < height):  # @line L5
                continue
            old = img.depth[v][u]
            if old is None or Z < old:  # @line L6
                img.depth[v][u] = Z  # @line L7
        return img  # @line L8

    # -- queries ----------------------------------------------------------

    def ray(self, u: int, v: int) -> Point:
        """The ray (a, b, 1) through the center of pixel (u, v)."""
        return ((u - self.cx) / self.fx, (v - self.cy) / self.fy, 1.0)

    def point(self, u: int, v: int) -> Optional[Point]:
        """Back-project the cell (u, v) to a 3D point, or None if it is empty."""
        z = self.depth[v][u]  # @line L9
        if z is None:
            return None
        a, b, _ = self.ray(u, v)
        return (z * a, z * b, z)  # @line L10

    def range_at(self, u: int, v: int) -> Optional[float]:
        """The range ||X|| of the cell (u, v), or None."""
        z = self.depth[v][u]
        if z is None:
            return None
        a, b, _ = self.ray(u, v)
        return z * math.sqrt(1.0 + a * a + b * b)

    def to_point_cloud(self) -> List[Tuple[int, int, Point]]:
        """All valid cells as (u, v, point), row by row: an organized cloud."""
        out = []
        for v in range(self.H):
            for u in range(self.W):
                p = self.point(u, v)
                if p is not None:
                    out.append((u, v, p))
        return out

    def neighbors(self, u: int, v: int, max_jump: float) -> List[Tuple[int, int]]:
        """The 4-neighbors of (u, v) that are valid and whose depth differs
        from the depth at (u, v) by at most max_jump."""
        z = self.depth[v][u]
        if z is None:
            return []
        out = []
        for du, dv in ((1, 0), (-1, 0), (0, 1), (0, -1)):  # @line L11
            uu, vv = u + du, v + dv
            if not (0 <= uu < self.W and 0 <= vv < self.H):  # @line L12
                continue
            zz = self.depth[vv][uu]
            if zz is not None and abs(zz - z) <= max_jump:  # @line L13
                out.append((uu, vv))  # @line L14
        return out

    def normal(self, u: int, v: int, max_jump: float) -> Optional[Point]:
        """A unit normal at (u, v) from the cross product of the horizontal and
        vertical neighbor differences, turned toward the camera. None if a
        neighbor is missing or across a depth jump."""
        nb = set(self.neighbors(u, v, max_jump))
        p = self.point(u, v)
        if p is None:
            return None
        # Use the central difference if both sides are there, else one side.
        def diff(a: Tuple[int, int], b: Tuple[int, int]) -> Optional[Point]:
            pa = self.point(*a) if a in nb or a == (u, v) else None
            pb = self.point(*b) if b in nb or b == (u, v) else None
            if pa is None or pb is None:
                return None
            return (pa[0] - pb[0], pa[1] - pb[1], pa[2] - pb[2])
        du = diff((u + 1, v), (u - 1, v)) or diff((u + 1, v), (u, v)) or diff((u, v), (u - 1, v))  # @line L15
        dv = diff((u, v + 1), (u, v - 1)) or diff((u, v + 1), (u, v)) or diff((u, v), (u, v - 1))
        if du is None or dv is None:
            return None
        n = (du[1] * dv[2] - du[2] * dv[1],  # @line L16
             du[2] * dv[0] - du[0] * dv[2],
             du[0] * dv[1] - du[1] * dv[0])
        length = math.sqrt(n[0] ** 2 + n[1] ** 2 + n[2] ** 2)
        if length == 0.0:
            return None
        n = (n[0] / length, n[1] / length, n[2] / length)  # @line L17
        if n[0] * p[0] + n[1] * p[1] + n[2] * p[2] > 0:  # @line L18
            n = (-n[0], -n[1], -n[2])
        return n  # @line L19
test_range_image.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/range-image/. The authors are listed in prov/M707AA.jsonl.

import math
import random

import pytest

from range_image import RangeImage

EXAMPLE = [(0.0, -0.5, 2.0), (0.0, -1.0, 4.0), (-1.0, 0.5, 2.0), (1.0, 0.25, 1.0), (0.2, 0.0, -1.0)]


def test_example() -> None:
    img = RangeImage.from_points(EXAMPLE, 3, 2, 2.0, 2.0, 1.0, 0.5)
    assert img.depth == [[None, 2.0, None], [2.0, None, None]]
    assert img.point(1, 0) == (0.0, -0.5, 2.0)
    assert img.point(0, 1) == (-1.0, 0.5, 2.0)
    assert img.point(2, 1) is None
    assert abs(img.range_at(1, 0) - 2.0 * math.sqrt(1.0625)) < 1e-15
    assert [(u, v) for u, v, _ in img.to_point_cloud()] == [(1, 0), (0, 1)]


def brute_force_zbuffer(points, W, H, fx, fy, cx, cy):
    """For each pixel, scan all points and keep the least depth among those
    whose projection lies in the pixel square [u - 1/2, u + 1/2) x [v - 1/2, v + 1/2)."""
    out = [[None] * W for _ in range(H)]
    for v in range(H):
        for u in range(W):
            best = None
            for X, Y, Z in points:
                if Z <= 0:
                    continue
                x, y = fx * X / Z + cx, fy * Y / Z + cy
                if u - 0.5 <= x < u + 0.5 and v - 0.5 <= y < v + 0.5:
                    if best is None or Z < best:
                        best = Z
            out[v][u] = best
    return out


def test_zbuffer_matches_brute_force() -> None:
    rng = random.Random(11)
    for _ in range(15):
        W, H = rng.randint(1, 8), rng.randint(1, 6)
        fx, fy = rng.uniform(2, 6), rng.uniform(2, 6)
        cx, cy = (W - 1) / 2, (H - 1) / 2
        pts = [(rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-0.5, 4)) for _ in range(60)]
        img = RangeImage.from_points(pts, W, H, fx, fy, cx, cy)
        assert img.depth == brute_force_zbuffer(pts, W, H, fx, fy, cx, cy)


def test_round_trip_and_range() -> None:
    rng = random.Random(12)
    W, H = 9, 7
    img = RangeImage(W, H, 5.0, 4.0, 4.0, 3.0)
    for v in range(H):
        for u in range(W):
            img.depth[v][u] = None if rng.random() < 0.2 else rng.uniform(0.5, 5.0)
    cloud = img.to_point_cloud()
    again = RangeImage.from_points([p for _, _, p in cloud], W, H, 5.0, 4.0, 4.0, 3.0)
    for v in range(H):
        for u in range(W):
            a, b = img.depth[v][u], again.depth[v][u]
            assert (a is None and b is None) or abs(a - b) <= 1e-12
    for u, v, p in cloud:
        assert abs(img.range_at(u, v) - math.sqrt(sum(c * c for c in p))) <= 1e-12


def test_neighbors_stop_at_depth_jumps() -> None:
    img = RangeImage(4, 3, 2.0, 2.0, 1.5, 1.0)
    for v in range(3):
        for u in range(4):
            img.depth[v][u] = 1.0 if u < 2 else 3.0
    img.depth[0][0] = None
    assert sorted(img.neighbors(1, 1, 0.5)) == [(0, 1), (1, 0), (1, 2)]
    assert sorted(img.neighbors(2, 1, 0.5)) == [(2, 0), (2, 2), (3, 1)]
    assert sorted(img.neighbors(1, 1, 5.0)) == [(0, 1), (1, 0), (1, 2), (2, 1)]
    assert img.neighbors(0, 0, 5.0) == []
    assert img.normal(1, 1, 0.5) is not None  # one-sided difference to the left
    img.depth[1][0] = None
    assert img.normal(1, 1, 0.5) is None  # no valid horizontal neighbor


def test_normal_of_a_plane() -> None:
    rng = random.Random(13)
    for _ in range(10):
        n = [rng.gauss(0, 0.3), rng.gauss(0, 0.3), -1.0]
        ln = math.sqrt(sum(c * c for c in n))
        n = [c / ln for c in n]
        d = -rng.uniform(1.0, 3.0) * abs(n[2])  # plane n . X = d, in front of the camera
        W, H, fx, fy, cx, cy = 6, 5, 4.0, 4.0, 2.5, 2.0
        img = RangeImage(W, H, fx, fy, cx, cy)
        for v in range(H):
            for u in range(W):
                a, b, c = img.ray(u, v)
                img.depth[v][u] = d / (n[0] * a + n[1] * b + n[2] * c)
        for v in range(H):
            for u in range(W):
                m = img.normal(u, v, 100.0)
                assert m is not None
                assert all(abs(m[i] - n[i]) < 1e-9 for i in range(3))  # n faces the camera
                p = img.point(u, v)
                assert m[0] * p[0] + m[1] * p[1] + m[2] * p[2] < 0


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        RangeImage(0, 3, 1.0, 1.0, 0.0, 0.0)

History

Range images came with the first range sensors for robots and industrial inspection. Besl (1988) surveyed the active optical sensors that produce them and classified them by principle: radar, which measures the time of flight, triangulation, moire, holographic interferometry, focusing and diffraction. Curless and Levoy (1996) merged dozens of range images of one object into a single model with a cumulative signed distance function, the base of later depth fusion. Low-cost depth cameras, from structured light and then from time of flight, made depth images at video rate a common input of computer vision and robotics after 2010.

References

  1. Paul J. Besl, Active, optical range imaging sensors, Machine Vision and Applications 1(2), 1988, 127-152, The range image as the output of a sensor, and the survey of the measuring principles
  2. Brian Curless and Marc Levoy, A volumetric method for building complex models from range images, SIGGRAPH 96, 303-312, Range images as the input of a model, merged into a cumulative weighted signed distance function
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 13, 3D reconstruction (range data and its merging)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.query
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/M707AA/text.yaml