Algorithmcore
Photometric stereo
Also called Woodham photometric stereo, calibrated Lambertian photometric stereo.
Recover a surface normal and albedo at each pixel from three or more images under known distant lights, by least squares on the Lambertian model.
- Time
- Θ(N W H) worst · average · best
- Space
- Θ(W H) extra
- Where
- H = the image height in pixels; N = the number of images; W = the image width in pixels
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Robert J. Woodham, 1980
Photometric stereo finds the direction a surface faces, and how much light it reflects, at every pixel of a fixed camera. The camera and the object do not move; only the light changes, and each image is taken with one known, distant light. For a matte (Lambertian) surface, each image gives one linear equation for the vector , the albedo times the unit normal. Three lights in general position give three equations and fix , and more lights give a least squares solution. Unlike two-view stereo, no pixel matching is needed, since every image shows the same point at the same pixel. Unlike shape from shading, which has one image and is ill-posed, the problem at each pixel is a small linear system with a unique solution.
In plain words
Hold a matte object under a lamp. A part that faces the lamp is bright, and a part that turns away is darker. One photo cannot tell you if a patch is dark because it turns away or because its paint is dark. Now take three photos with the lamp in three different places, without moving the camera or the object. Each patch now has three brightness values, and only one direction and one paint shade explain all three. Solving a small set of equations at every pixel gives the direction the surface faces there and how bright its paint is. Joining the directions gives the shape.
The problem
Frame. This page uses the height-field frame of Horn: and lie in the image plane, and points toward the viewer. This differs from the camera frame of the area, where points away from the camera. A surface with slopes and has the unit normal .
Input.
- images of size from one fixed camera, with a linear response.
- A light vector for each image: its direction points toward a distant light, and its length is the strength of the light.
- A threshold below which a reading counts as shadow.
Model. At each pixel, (Lambertian reflectance with attached shadows), with the albedo and the unit normal . The camera is orthographic, or far enough that the viewing direction is about the same at all pixels. There are no cast shadows, interreflections or highlights in the readings that are kept.
Output. The albedo and the normal at each pixel, or "unknown" where fewer than three lights in general position light the point.
The algorithm
PHOTOMETRIC-STEREO(I_1..I_N, s_1..s_N, threshold)- 1
for each pixel p do - 2
A ← {k : I_k(p) > threshold} ▷ drop shadowed readings - 3
if |A| < 3 then mark p unknown; continue - 4
M ← Σ_{k ∈ A} s_k s_k^T; b ← Σ_{k ∈ A} I_k(p) s_k - 5
solve M g = b; if M is singular then mark p unknown; continue - 6
ρ(p) ← |g|; n(p) ← g / |g| - 7
return ρ, n
Line L4, the normal equations. With the light matrix whose rows are for , and . These are the normal equations of the overdetermined system . For exactly three lights, has the same solution as .
Line L5, the solve. The code uses Gaussian elimination with partial pivoting on the system. If all pixels use all lights, is the same for every pixel, so one inverse, or one pseudo-inverse of , serves the whole image.
Line L6, albedo and normal. The length of is the albedo because has length 1. The slopes follow as and .
Integration. The algorithm gives normals, not depths. A height map comes from integrating the slope field . Noise makes the field slightly non-integrable, so methods find the surface whose slopes are closest to it: Frankot and Chellappa project the field onto integrable surfaces with the fast Fourier transform, and least squares methods solve a Poisson equation .
Example
Three lights. Take , and , all of length 1, and the readings at one pixel. The equations are
so . Then and . The slopes are and : the surface goes down toward and, less steeply, toward .
A sphere with shadows. The test file renders a cap of a unit sphere with random albedo under five lights, four of them at about 50 degrees from the view direction. Near the edge of the cap some lights do not reach the surface, and 68 of the 845 readings are 0. Dropping these readings recovers every albedo and normal to 9 decimal places, since every pixel still has three lit readings. Keeping them gives albedo errors larger than 0.01, because a 0 reading does not fit the linear model.
Correctness
The full proof is in proofs/correctness.md.
- Shadows. With threshold 0, a reading is kept if and only if , and then it equals .
- Exact recovery. is invertible if and only if the kept lights span 3D space, which needs at least three lights that are not in one plane through the origin. Then , so line L5 returns itself.
- Least squares. With noise, is the unique minimizer of . For independent noise with equal variance it is the best linear unbiased estimate of by the Gauss-Markov theorem.
- Necessity. If the lit lights lie in one plane through the origin, a vector orthogonal to that plane can be added to without changing any reading.
Proof: Photometric stereo recovers the albedo and normal exactly when the lit lights span space, and the least squares estimate otherwisefull
We use the pseudocode of the page and exact real arithmetic. At one pixel the surface has albedo and unit normal , and we write . Image has a known light vector . The image formation model is the Lambertian model with attached shadows,
Lemma 1 (the shadow test). With threshold 0, line L2 keeps reading if and only if , and then .
Proof. If then . Otherwise , which is not greater than the threshold.
Lemma 2 (normal equations). Let be the set of kept readings and . Then is invertible if and only if the vectors , , span .
Proof. For any , , so is positive semidefinite, and implies , which holds if and only if is orthogonal to every with . Such an exists if and only if the do not span .
Theorem 1 (exact recovery). If the lights with span , the algorithm returns and exactly at the pixel.
Proof. By Lemma 1, , and for . Spanning needs at least three vectors, so line L3 does not skip the pixel. Line L4 computes . By Lemma 2, is invertible, so line L5 returns . Then , and line L6 returns and .
Theorem 2 (least squares). If is invertible, line L5 returns the unique minimizer of , for any readings.
Proof. is a convex quadratic with gradient and Hessian , which is positive definite by Lemma 2. Its only stationary point is , and it is the minimum.
If the readings are plus independent noise with mean 0 and equal variance, this is the ordinary least squares estimate, which the Gauss-Markov theorem shows to be the best linear unbiased estimate of . The albedo and the normal are nonlinear functions of , so the theorem does not make them unbiased.
Theorem 3 (the condition is needed). Suppose the lit lights do not span and for every . Then other vectors give exactly the same images.
Proof. Take orthogonal to every with , and let . For , . For , , and for small enough too, so the reading stays 0. So and give the same value in every image.
Lemma 3 (unknown lights). Let be any invertible matrix. The pair , gives the same images, attached shadows included.
Proof. , so both values agree.
So if the lights are not known, images alone determine only up to an invertible matrix. If comes from a smooth height field, with and . For the generalized bas-relief matrix
we get , which is proportional to . This is the normal of the height field . So the transformed normals again come from a surface, and the images cannot tell the two surfaces apart. Belhumeur, Kriegman and Yuille show that these are the only such matrices that keep every surface integrable, and that cast shadows are also preserved; we do not prove those parts here.
Complexity
The model is the real RAM. Each pixel reads its values and builds and in , then solves a system in . The total is in every case, and the output takes . When every pixel uses all lights, the pseudo-inverse of is computed once, and each pixel costs multiplications.
Properties
- Local. Each pixel is solved on its own. There is no smoothness term and no matching.
- Exact under the model. Noise-free Lambertian readings from three or more lit, non-coplanar lights give the exact albedo and normal.
- Gives normals, not depth. The depth comes from integration and is known only up to an additive constant.
- High detail. The normals have the full resolution of the camera, which shows fine surface detail that triangulation methods miss.
- Needs the light vectors. The light directions and strengths must be calibrated, for example with a mirror sphere and a matte sphere.
Variants and improvements
- Unknown lights. The images, stacked as a matrix of rows and columns, have rank 3 under the model. The singular value decomposition factors it into normals and lights up to an invertible matrix. Requiring an integrable surface reduces this to the generalized bas-relief ambiguity of Belhumeur, Kriegman and Yuille: , which gives the same images, shadows included.
- Robust estimation. Highlights and cast shadows are outliers to the linear model. Dropping the brightest and darkest readings, or a robust fit over many lights, handles them.
- Non-Lambertian surfaces. Methods with a general BRDF, or with a table of reference objects of the same material, replace the dot product with a measured response.
- Color. With color images and white light, the normal is shared by the three channels, and each channel has its own albedo.
- Near lights and perspective. Lights close to the object change direction and strength across the surface, which makes the problem nonlinear but still solvable.
When to use it
Use photometric stereo when you control the lighting and want fine surface detail of a mostly matte object, for example in industrial inspection, scanning of coins, documents, skin or relief. It needs a fixed camera and object while the light moves, so it does not suit moving scenes without special multiplexed lights. For absolute depth, combine it with a triangulation method, such as structured light scanning, whose depths fix the low frequencies that integration gets wrong.
Pitfalls
- Nonlinear camera response. The model needs readings proportional to the light. Gamma-corrected images must be made linear first.
- Shadows and highlights. A 0 reading or a specular peak used as a Lambertian reading pulls the normal toward or away from that light. Drop them, as line L2 does for shadows.
- Lights in one plane. If all light directions lie in one plane through the surface point, for example lamps placed along one straight line, is singular. Three lamps at the same height around the camera are fine.
- Integration drift. Small biases in the normals add up over the integration and bend the surface, so the low-frequency shape can be wrong while the detail is right.
- Mixed frames. Normals in the height-field frame have toward the viewer. In the camera frame of the area, a surface that faces the camera has a negative component. Convert before you combine with other methods.
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/photometric-stereo/. The authors are listed in prov/QKJF6P.jsonl.
"""Lambertian photometric stereo with known distant lights (Woodham).
Vectors are in the height-field frame: x right, y in the image plane, z toward
the viewer. Image k has a light s_k (a 3-vector whose length is the light
strength), and a Lambertian point with albedo rho and unit normal n has the
brightness I_k = max(0, rho n . s_k). The unknown per pixel is g = rho n.
Images are lists of rows, img[v][u].
"""
import math
def solve3(M, b):
"""Solve the 3 x 3 system M x = b by Gaussian elimination with partial pivoting.
Returns None if M is singular (relative to its size)."""
A = [list(M[r]) + [b[r]] for r in range(3)]
scale = max(abs(A[r][c]) for r in range(3) for c in range(3))
if scale == 0.0:
return None
for c in range(3):
piv = max(range(c, 3), key=lambda r: abs(A[r][c]))
if abs(A[piv][c]) <= 1e-12 * scale:
return None
A[c], A[piv] = A[piv], A[c]
for r in range(c + 1, 3):
m = A[r][c] / A[c][c]
for k in range(c, 4):
A[r][k] -= m * A[c][k]
x = [0.0, 0.0, 0.0]
for r in (2, 1, 0):
x[r] = (A[r][3] - sum(A[r][k] * x[k] for k in range(r + 1, 3))) / A[r][r]
return x
def photometric_stereo(images, lights, threshold=0.0):
"""Per pixel least squares for g = rho n. Readings with I <= threshold are
treated as shadow and dropped. Returns (albedo, normals) as images; a pixel
with fewer than three usable readings, or with lights that do not span 3D,
gets None in both."""
height, width = len(images[0]), len(images[0][0])
albedo = [[None] * width for _ in range(height)]
normals = [[None] * width for _ in range(height)]
for v in range(height): # @line L1
for u in range(width):
use = [k for k in range(len(images)) if images[k][v][u] > threshold] # @line L2
if len(use) < 3: # @line L3
continue
M = [[sum(lights[k][r] * lights[k][c] for k in use) for c in range(3)] for r in range(3)] # @line L4
b = [sum(images[k][v][u] * lights[k][r] for k in use) for r in range(3)]
g = solve3(M, b) # @line L5
if g is None:
continue
rho = math.sqrt(g[0] ** 2 + g[1] ** 2 + g[2] ** 2) # @line L6
if rho == 0.0:
continue
albedo[v][u] = rho
normals[v][u] = [g[0] / rho, g[1] / rho, g[2] / rho]
return albedo, normals # @line L7
def render(albedo, normals, lights):
"""Lambertian images with attached shadows: I = max(0, rho n . s)."""
images = []
for s in lights:
img = []
for arow, nrow in zip(albedo, normals):
img.append([max(0.0, a * (n[0] * s[0] + n[1] * s[1] + n[2] * s[2]))
for a, n in zip(arow, nrow)])
images.append(img)
return images
def gradients(normal):
"""Surface slopes p = dz/dx and q = dz/dy from a normal (-p, -q, 1) / |.|."""
nx, ny, nz = normal
return -nx / nz, -ny / nz
test_photometric_stereo.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/photometric-stereo/. The authors are listed in prov/QKJF6P.jsonl.
import math
import random
import unittest
from photometric_stereo import gradients, photometric_stereo, render, solve3
def unit(x, y, z):
n = math.sqrt(x * x + y * y + z * z)
return [x / n, y / n, z / n]
def sphere_cap(size, extent, rng):
"""Normals and albedo of the cap z = sqrt(1 - x^2 - y^2) seen from +z."""
albedo, normals = [], []
for v in range(size):
y = -extent + 2.0 * extent * v / (size - 1)
arow, nrow = [], []
for u in range(size):
x = -extent + 2.0 * extent * u / (size - 1)
nrow.append([x, y, math.sqrt(1.0 - x * x - y * y)])
arow.append(rng.uniform(0.3, 1.0))
albedo.append(arow)
normals.append(nrow)
return albedo, normals
def mat_vec(M, x):
return [sum(M[r][c] * x[c] for c in range(3)) for r in range(3)]
class PhotometricStereoTest(unittest.TestCase):
def test_worked_example(self):
lights = [[0.0, 0.0, 1.0], [0.6, 0.0, 0.8], [0.0, 0.6, 0.8]]
images = [[[0.6]], [[0.84]], [[0.66]]]
albedo, normals = photometric_stereo(images, lights)
self.assertAlmostEqual(albedo[0][0], 0.9, places=12)
for got, want in zip(normals[0][0], (2.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0)):
self.assertAlmostEqual(got, want, places=12)
p, q = gradients(normals[0][0])
self.assertAlmostEqual(p, -1.0, places=12)
self.assertAlmostEqual(q, -0.5, places=12)
def test_exact_recovery_without_shadows(self):
rng = random.Random(1)
albedo, normals = sphere_cap(15, 0.6, rng)
lights = [unit(0.0, 0.0, 1.0), unit(0.3, 0.1, 1.0), unit(-0.2, 0.3, 1.0),
unit(0.1, -0.35, 1.0), [0.4, 0.4, 1.5]]
images = render(albedo, normals, lights)
self.assertTrue(all(x > 0.0 for img in images for row in img for x in row))
est_a, est_n = photometric_stereo(images, lights)
for v in range(15):
for u in range(15):
self.assertAlmostEqual(est_a[v][u], albedo[v][u], places=9)
for a, b in zip(est_n[v][u], normals[v][u]):
self.assertAlmostEqual(a, b, places=9)
def test_three_lights_invert_the_light_matrix(self):
rng = random.Random(2)
lights = [unit(0.5, 0.0, 1.0), unit(-0.3, 0.4, 1.0), unit(0.0, -0.5, 1.0)]
for _ in range(20):
g = [rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3), rng.uniform(0.5, 1.0)]
I = [sum(s[r] * g[r] for r in range(3)) for s in lights]
if min(I) <= 0.0:
continue
albedo, normals = photometric_stereo([[[x]] for x in I], lights)
got = [albedo[0][0] * c for c in normals[0][0]]
want = solve3(lights, I)
for a, b, c in zip(got, want, g):
self.assertAlmostEqual(a, b, places=12)
self.assertAlmostEqual(a, c, places=12)
def test_shadowed_readings_are_dropped(self):
rng = random.Random(3)
albedo, normals = sphere_cap(13, 0.68, rng)
lights = [unit(0.0, 0.0, 1.0), unit(1.2, 0.0, 1.0), unit(-1.2, 0.0, 1.0),
unit(0.0, 1.2, 1.0), unit(0.0, -1.2, 1.0)]
images = render(albedo, normals, lights)
shadowed = sum(1 for img in images for row in img for x in row if x == 0.0)
self.assertGreater(shadowed, 0)
est_a, est_n = photometric_stereo(images, lights, threshold=0.0)
naive_a, _ = photometric_stereo(images, lights, threshold=-1.0)
worst_naive = 0.0
for v in range(13):
for u in range(13):
self.assertAlmostEqual(est_a[v][u], albedo[v][u], places=9)
worst_naive = max(worst_naive, abs(naive_a[v][u] - albedo[v][u]))
self.assertGreater(worst_naive, 0.01)
def test_coplanar_lights_give_no_answer(self):
lights = [unit(1.0, 0.0, 1.0), unit(-1.0, 0.0, 1.0), unit(0.0, 0.0, 1.0)]
albedo, normals = photometric_stereo([[[0.5]], [[0.4]], [[0.7]]], lights)
self.assertIsNone(albedo[0][0])
self.assertIsNone(normals[0][0])
def test_generalized_bas_relief_gives_the_same_images(self):
rng = random.Random(4)
albedo, normals = sphere_cap(9, 0.68, rng)
lights = [unit(0.0, 0.0, 1.0), unit(0.9, 0.2, 1.0), unit(-0.7, 0.6, 1.0), unit(0.1, -0.9, 1.0)]
mu, nu, lam = 0.4, -0.3, 1.7
G = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [mu, nu, lam]]
G_inv_T = [[1.0, 0.0, -mu / lam], [0.0, 1.0, -nu / lam], [0.0, 0.0, 1.0 / lam]]
new_lights = [mat_vec(G, s) for s in lights]
new_albedo, new_normals = [], []
for arow, nrow in zip(albedo, normals):
ar, nr = [], []
for a, n in zip(arow, nrow):
b = mat_vec(G_inv_T, [a * c for c in n])
r = math.sqrt(sum(c * c for c in b))
ar.append(r)
nr.append([c / r for c in b])
new_albedo.append(ar)
new_normals.append(nr)
first = render(albedo, normals, lights)
second = render(new_albedo, new_normals, new_lights)
for img_a, img_b in zip(first, second):
for row_a, row_b in zip(img_a, img_b):
for x, y in zip(row_a, row_b):
self.assertAlmostEqual(x, y, places=12)
self.assertTrue(any(x == 0.0 for img in first for row in img for x in row))
est_a, _ = photometric_stereo(second, new_lights)
self.assertAlmostEqual(est_a[4][4], new_albedo[4][4], places=9)
self.assertGreater(abs(new_albedo[4][4] - albedo[4][4]), 0.1)
if __name__ == "__main__":
unittest.main()
History
Woodham (1980) introduced photometric stereo: with the camera fixed and the light moved between images, each image constrains the orientation of the surface through the reflectance map of its light, and together the images fix the orientation at each pixel. Horn's book Robot Vision (1986) treats it next to shape from shading. Frankot and Chellappa (1988) gave a fast way to integrate the normals into a surface. Belhumeur, Kriegman and Yuille (1999) showed that with unknown lights the shape can only be found up to the generalized bas-relief transformation, which explains why relief sculptures look right under many lights.
References
- Robert J. Woodham, Photometric method for determining surface orientation from multiple images, Optical Engineering 19(1), 1980, pages 139 to 144, the whole paper (the reflectance map for several light sources and the solution for the surface orientation and albedo)
- Peter N. Belhumeur, David J. Kriegman and Alan L. Yuille, The bas-relief ambiguity, International Journal of Computer Vision 35(1), 1999, pages 33 to 44, the generalized bas-relief transformation and the proof that it preserves shading and shadows
- Robert T. Frankot and Rama Chellappa, A method for enforcing integrability in shape from shading algorithms, IEEE Transactions on Pattern Analysis and Machine Intelligence 10(4), 1988, pages 439 to 451, the projection of a gradient field onto integrable surfaces in the Fourier domain
- Berthold K. P. Horn, Robot Vision, MIT Press, 1986, the chapters on reflectance maps and photometric stereo
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 13.1.1, Shape from shading and photometric stereo
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 | W2 basic |
|
Tag QKJF6P Edit this page History Report an error Markdown