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
- Model
- Real RAM
- Properties
- deterministicexactnot static
- Evidence
- Proof sketchCode in 1 languages
- 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 per point, without a k-d tree. The value is either the depth along the optical axis, as in a depth image, or the Euclidean range 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 grid of cells with a camera model. Each cell is empty or holds one depth. It supports:
- BUILD makes the image of a point cloud seen by the camera: each cell gets the depth of the nearest point that projects into it.
- BACK-PROJECT returns the 3D point of the cell , or nothing if the cell is empty.
- RANGE returns the distance of that point to the camera center.
- NEIGHBORS returns the valid 4-neighbors of a cell whose depth differs from its depth by at most .
- NORMAL 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 to the right, down and forward, along the optical axis. (The graphics page of the pinhole camera looks along instead.) The intrinsic matrix is , the pixel has column and row , and the grid is stored as . The center of pixel is the image point , and its ray is
A cell stores the depth . The point of the cell is , and its range is . A range image that stores 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 , but the rest of this page is the same.
Operations
BUILD(P, W, H, K) ▷ a z-buffer: keep the nearest point per pixel- 1
img ← a W × H grid of empty cells - 2
for each point X = (X₁, X₂, X₃) in P do - 3
if X₃ ≤ 0 then skip X ▷ behind the camera - 4
u ← ⌊f_x X₁/X₃ + c_x + 1/2⌋, v ← ⌊f_y X₂/X₃ + c_y + 1/2⌋ - 5
if (u, v) is outside the grid then skip X - 6
if img[v][u] is empty or X₃ < img[v][u] then - 7
img[v][u] ← X₃ - 8
return 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 owns the square . Lines L6 and L7 keep the nearest point, the one the sensor would see.
BACK-PROJECT(img, u, v)- 1
Z ← img[v][u]; if Z is empty then return nothing - 2
return Z · ((u - c_x)/f_x, (v - c_y)/f_y, 1) NEIGHBORS(img, u, v, τ)- 3
for each (u', v') in (u ± 1, v) and (u, v ± 1) do - 4
if (u', v') is outside the grid then skip it - 5
if img[v'][u'] is not empty and |img[v'][u'] - img[v][u]| ≤ τ then - 6
report (u', v') NORMAL(img, u, v, τ) ▷ X is BACK-PROJECT(img, u, v)- 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 - 8
n ← Δu × Δv - 9
n ← n / ‖n‖ - 10
if n · X > 0 then n ← -n ▷ turn n toward the camera - 11
return 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 cuts these links. A good grows with the depth, because the gap between the points of two adjacent pixels on a slanted surface grows with .
Line L16 takes the cross product of two tangent directions, which gives a normal in 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 time per cell.
Example
Use a image with , , . BUILD gets five points.
| point | projection | pixel | result |
|---|---|---|---|
| stored, | |||
| hidden: | |||
| stored, | |||
| outside the grid | |||
| none | none | behind the camera |
The grid is then
| empty | 2 | empty | |
| 2 | empty | empty |
BACK-PROJECT of uses the ray and returns , the first point again. Its range is , 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 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 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 and the intrinsic parameters , . For a point with the projection is . The pixel owns the half-open square of the image plane. For a pixel let be the set of input points with and .
Lemma 1 (the pixel of a point). Line L4 gives exactly when .
Proof. For a real and an integer , holds exactly when , that is, when . Apply this to both coordinates.
Theorem 1 (BUILD). After BUILD, the cell holds if is not empty, and is empty otherwise.
Proof. Every cell starts empty at line L1. Line L3 drops the points with , and line L5 drops the points whose pixel is outside the grid; by Lemma 1, such a point is in no set of the grid. Every other point is in exactly one set , 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 points each cell holds the minimum depth of the points of among the first , or is empty if there are none. This is true for . Point changes at most the cell of line L4. If the cell was empty, line L7 stores , the minimum of a set of one depth. If it held , line L6 replaces by exactly when , so the cell holds . Other cells keep their sets and their values. At this is the claim.
Theorem 2 (BACK-PROJECT). Let the cell hold the depth , and let with and , as at line L10. Then , , and . Of all the points with depth whose projection is in , is the one on the ray through the pixel center.
Proof. by construction, and , and in the same way the second coordinate is . The norm is . A point of depth is fixed by its projection, because and ; the projection gives .
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 in and in .
Theorem 3 (NEIGHBORS). Lines L11 to L14 return the pixels and that are in the grid, hold a depth , and satisfy .
Proof. Line L11 lists the four offsets, line L12 removes those outside the grid, and line L13 tests the remaining two conditions.
Theorem 4 (normals on a plane). Suppose the valid cells around used at line L15 all back-project to points of one plane with , and that the two differences of line L15 are not parallel. Then lines L16 to L18 return or , and the sign is the one with at the back-projected point of , the side of the plane that faces the camera.
Proof. Each difference is with , so . The cross product of two vectors that are both orthogonal to and not parallel is a nonzero multiple of , so after the division by its length at line L17 it is . Line L18 flips it when , so the result has . The camera center is the origin, and says that points from toward the camera side.
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.
Complexity
The model is the real RAM with the floor function.
| operation | time | notes |
|---|---|---|
| BUILD of points | to clear the grid, per point | |
| BACK-PROJECT, RANGE | one ray and one product | |
| NEIGHBORS, NORMAL | four cells | |
| TO-CLOUD | one pass over the grid | |
| space | one number per cell |
Compare an unorganized cloud of points, where each neighbor query needs a search structure, such as a k-d tree with an build and about per query on well-spread points.
Variants
- Depth image and range image. Depth cameras usually store , and scanners usually store . 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 per pixel, with for the baseline . 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 block of valid cells into two triangles, and drop triangles across depth jumps. This gives a mesh of the visible surface in 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 at line L10 puts off-axis points too far away and bends planes into bowls. Divide a range by first.
- Pixel corner or pixel center. Some programs put the pixel center at . 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 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 that is right at 1 m cuts real surfaces at 10 m, because the spacing grows with . Scale 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag M707AA Edit this page History Report an error Markdown