Algorithmadvanced
Shape from focus
Also called depth from focus, sum-modified-Laplacian shape from focus.
Take images at many focus settings and give each pixel the depth of the setting at which a local sharpness measure is largest, refined by a Gaussian fit.
- Time
- Θ(N W H) worst · average · best
- Space
- O(N W H) extra
- Where
- H = the image height in pixels; N = the number of images in the focal stack; W = the image width in pixels
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Shree K. Nayar, Yasuo Nakagawa, 1994
Shape from focus finds the depth of each pixel from a stack of images that one camera takes while it moves its plane of focus through the scene. A lens shows a point sharply only when the point is at the distance in focus; nearer and farther points are blurred. So for each pixel the method measures the local sharpness in every image, picks the image where it is largest, and gives the pixel the depth that is in focus in that image. A fit through the sharpness of the best image and its two neighbors gives a depth between the images. Unlike stereo, it needs one camera and no matching; unlike photometric stereo, it needs texture, not control of the light. Depth from defocus is the related method that uses only two or three images and models the amount of blur.
In plain words
Look at a textured object through a microscope and turn the focus knob slowly. Each part of the surface becomes sharp at one setting of the knob and blurred at the others. If you take a photo at every step of the knob and remember, for every pixel, the step where its small neighborhood looked sharpest, you know how far that part of the surface is from the lens. The sharpness is measured by how strongly the brightness changes between neighboring pixels, since blur smooths these changes away. A smooth curve through the sharpness values of three steps finds the depth between two steps.
The problem
Input.
- A focal stack: gray images of size from a fixed camera. Image is in focus at the depth . The images are aligned; a real lens also changes the magnification slightly with focus, which must be corrected first.
- A step for the modified Laplacian, a window radius and a threshold .
Model. The scene has texture at the scale of the window, and the depth is nearly constant over one window. A point at depth appears in image blurred by an amount that grows with .
Output. A depth for each pixel. The best image of each pixel also gives an all-in-focus image of the scene.
The focus measure. The modified Laplacian of Nayar and Nakagawa is
It takes absolute values of the two second differences separately, so they cannot cancel as they do in the plain Laplacian on a saddle. The sum-modified-Laplacian is the sum of the values over the window.
The algorithm
SHAPE-FROM-FOCUS(I_0..I_{N-1}, d_0, Δ, s, r, T_1)- 1
for k ← 0 to N - 1 do - 2
F_k ← the window sum of the values ML ≥ T_1 of the modified Laplacian of I_k - 3
for each pixel p do - 4
m ← the least k with the largest F_k(p) - 5
if 0 < m < N - 1 then δ ← the peak offset of the Gaussian through F_{m-1}(p), F_m(p), F_{m+1}(p), else δ ← 0 - 6
depth[p] ← d_0 + Δ (m + δ) - 7
return depth
Line L2, the window. The window sum takes per pixel with an integral image, for any . Nayar and Nakagawa sum over a small window, because one pixel has too little texture to measure focus.
Line L5, the Gaussian fit. If the focus measure near its peak has the shape , then is a parabola in , and the peak is
The code skips the fit when a value is not positive or the denominator is not negative.
Line L6, from frame to depth. The depth that frame has in focus comes from the calibration of the lens, for example the thin lens law with the distance of the sensor. In a microscope that moves the stage in equal steps, it is simply .
Example
One modified Laplacian. A pixel of value 10 with left and right neighbors 4 and 6 and upper and lower neighbors 7 and 9 has for .
One Gaussian fit. If the best frame has and its neighbors have and , then , and . The denominator is , the numerator is , and . The peak lies 0.22 of a step past frame , toward the larger neighbor.
A slanted plane. The test file blurs a random texture into 9 frames. The true depth grows from frame 2 at the left edge to frame 6 at the right, and the blur in frame is a Gaussian with standard deviation pixels. With a window, the best frame of every one of the 576 pixels is within one frame of the true depth, and the mean error of the best frame is 0.244 frames, which is close to the 0.25 of rounding to whole frames. After the Gaussian fit, the mean error is 0.057 frames and the largest is 0.21.
Correctness
The full proof is in proofs/correctness.md.
- The fit is exact for Gaussian profiles. If the three values follow a Gaussian in , their logarithms lie on a parabola, and the formula returns its vertex exactly.
- The fit stays near the best frame. If is the largest of the three values, the step is at most in size, whatever the shape of the profile.
- Gain and offset. Replacing every image by with multiplies the modified Laplacian by , so the choice and the fit do not change when .
- Why the Laplacian measures focus. For a periodic texture blurred by a Gaussian, the energy of the Laplacian is up to a constant, by Parseval's theorem, which strictly decreases as the blur grows.
That the sum-modified-Laplacian peaks at the true depth is a heuristic, which Nayar and Nakagawa support by experiments. It uses absolute values, a small window and a threshold, and real blur is not an exact Gaussian.
Proof: Shape from focus picks the frame of largest focus, and its Gaussian fit is exact for Gaussian focus profilesfull
We use the pseudocode of the page. The stack has frames at focus positions for . is the focus measure of frame at pixel from line L2.
Lemma 1 (window sums). The integral image gives the sum of over the rows and columns as .
Proof. The code builds , which is the definition. Inclusion and exclusion of the four corner rectangles gives the formula.
So line L2 computes over the window of cut at the border, as Nayar and Nakagawa define the sum-modified-Laplacian.
Lemma 2 (selection). Line L4 sets to the least index with .
Theorem 1 (the Gaussian fit). Let and suppose that the three values near the peak follow a Gaussian,
with and . Then line L5 finds , so line L6 returns , the position of the peak.
Proof. Let be the logarithms of . Then , a parabola in . A direct computation gives
So the code accepts the fit, and
Lemma 3 (the step stays in the interval). If , , all three are positive and the fit is accepted, then .
Proof. Let and . Then , which is negative because the fit was accepted, and . So , and .
So the refined position lies within half a frame of the best frame, and a fit that is not exact still cannot move the result past a neighboring frame.
Lemma 4 (gain and offset). If every frame is replaced by with , then is multiplied by . With , every is multiplied by , and the choice of and the offset do not change.
Proof. The weights in each term of sum to 0, so cancels and comes out of the absolute values. Scaling all by keeps the argmax, and adds to in Theorem 1, which cancels in both differences. With the threshold must be scaled by too.
Theorem 2 (blur lowers the energy of the Laplacian). Let be a periodic image on the plane whose Laplacian is square integrable over one period, and let for the Gaussian of standard deviation . Then over one period is strictly decreasing in , unless is constant.
Proof. Write as a Fourier series with coefficients . The Laplacian multiplies the coefficient at frequency by , and the Gaussian multiplies it by . By Parseval's theorem,
for a constant . The term with is 0. Every other term is nonnegative and nonincreasing in , and strictly decreasing if . If is not constant, some with is not zero.
For a scene at one depth whose blur grows with the distance from focus, Theorem 2 says that the squared Laplacian, summed over the image, is largest in the sharpest frame. This is the reason for Laplacian-based focus measures.
What is not proved. The modified Laplacian uses absolute values instead of squares, the window is small, the threshold drops small values, and real blur is not an exact Gaussian. Theorem 2 covers none of these, so the claim that SML peaks at the right frame is a heuristic that Nayar and Nakagawa support by experiments. The test file shows one way it can fail: a blur kernel cut off at a radius of 3 pixels behaves like a box filter at large , and the measure is then not monotone far from focus, though it still peaks at the sharp frame. Theorem 1 also assumes a Gaussian focus profile; for other shapes the fit is only an approximation, bounded by Lemma 3.
Complexity
The model is the real RAM. Line L2 costs per frame: the modified Laplacian is per pixel, and the window sums are per pixel with the integral image. Lines L3 to L6 cost per pixel for the maximum. The total is in every case. The code keeps all focus measures, . A version that reads the stack as it is taken needs only the best value, its index and the values of its two neighbors per pixel, .
Properties
- One camera, no matching. All images show the same pixel grid, so there is no correspondence problem.
- Needs texture. On a surface with no texture, every frame has the same low focus measure, and the depth is noise.
- Resolution in depth. The step and the depth of field of the lens set the resolution. The Gaussian fit gives a fraction of a step.
- Local. Each pixel is decided on its own, so depth edges and noise are not smoothed.
- Not exact. The method estimates depth; the result depends on the texture and the lens.
Variants and improvements
- Other focus measures. Krotkov compared several measures and used the Tenengrad, the sum of squared Sobel gradient magnitudes above a threshold. Others use the variance of the gray values, the energy of the Laplacian of Gaussian, or energies of wavelet bands.
- Autofocus. For a single region, the best focus can be searched instead of sampled, for example by Fibonacci search over the lens position, which Krotkov used.
- Depth from defocus. It models the blur as a function of depth and finds the depth from two or three images, so it needs far fewer images but a calibrated blur model.
- Regularization. A smoothness term between neighboring pixels, solved by graph cuts or a variational method, fills in the depth of textureless regions.
- All-in-focus images. Taking each pixel from its best frame gives an image that is sharp everywhere, as in focus stacking for macro photography and microscopy.
When to use it
Use shape from focus for small textured objects under a microscope or a macro lens, where the depth of field is shallow and a motorized stage or focus drive is available. It needs many images of a static scene, so it is slow to capture, but the setup is one camera with no second view and no projector. For large scenes, the depth of field of normal lenses is too deep to give a useful depth resolution; use stereo or structured light scanning there.
Pitfalls
- Magnification changes. Moving the focus also changes the scale of the image slightly. Without alignment, the window of a pixel covers different points in different frames.
- No texture. Flat regions give a flat focus profile, and the argmax picks a random frame. Mark pixels whose largest is below a threshold as unknown.
- Window too large. A window that crosses a depth edge mixes two profiles and gives a depth between them.
- Threshold and gain. A fixed depends on the brightness of the image. Scale it with the gain, or use .
- Truncated blur. A blur kernel that is cut off, or the blur of a real lens with its aperture shape, is not a Gaussian. Far from focus, the focus measure can then rise again. The test file shows this with a kernel cut at 3 pixels; the peak stays at the right frame.
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/shape-from-focus/. The authors are listed in prov/09NTD3.jsonl.
"""Shape from focus with the sum-modified-Laplacian (Nayar and Nakagawa).
A focal stack is a list of N gray images img[v][u] taken at focus positions
d_0 + k * delta for k = 0..N-1. For each pixel the method picks the frame with
the largest focus measure and refines the position with a Gaussian fit to the
measure at the best frame and its two neighbors. Borders are handled by
clamping the coordinates to the image.
"""
import math
def modified_laplacian(img, step=1):
"""ML(u, v) = |2I - I(u-s, v) - I(u+s, v)| + |2I - I(u, v-s) - I(u, v+s)|."""
height, width = len(img), len(img[0])
out = []
for v in range(height):
row = []
up, down = img[max(v - step, 0)], img[min(v + step, height - 1)]
for u in range(width):
c = 2.0 * img[v][u]
left, right = img[v][max(u - step, 0)], img[v][min(u + step, width - 1)]
row.append(abs(c - left - right) + abs(c - up[u] - down[u]))
out.append(row)
return out
def window_sum(values, radius):
"""Sum over the (2r+1) x (2r+1) window of each pixel, cut at the border (integral image)."""
height, width = len(values), len(values[0])
S = [[0.0] * (width + 1) for _ in range(height + 1)]
for v in range(height):
acc = 0.0
for u in range(width):
acc += values[v][u]
S[v + 1][u + 1] = S[v][u + 1] + acc
out = []
for v in range(height):
v0, v1 = max(v - radius, 0), min(v + radius + 1, height)
row = []
for u in range(width):
u0, u1 = max(u - radius, 0), min(u + radius + 1, width)
row.append(S[v1][u1] - S[v0][u1] - S[v1][u0] + S[v0][u0])
out.append(row)
return out
def sum_modified_laplacian(img, step=1, radius=2, t1=0.0):
"""SML: the window sum of the ML values that are at least t1."""
ml = modified_laplacian(img, step)
return window_sum([[x if x >= t1 else 0.0 for x in row] for row in ml], radius)
def gaussian_peak_offset(f_prev, f_mid, f_next):
"""Offset in frames of the peak of the Gaussian through three equally spaced samples,
or None if the samples have no interior maximum or are not positive."""
if min(f_prev, f_mid, f_next) <= 0.0:
return None
a, b, c = math.log(f_prev), math.log(f_mid), math.log(f_next)
den = a - 2.0 * b + c
if den >= 0.0:
return None
return 0.5 * (a - c) / den
def shape_from_focus(stack, d0=0.0, delta=1.0, step=1, radius=2, t1=0.0):
"""Depth (focus position) per pixel, and the index of the best frame."""
n = len(stack)
focus = []
for k in range(n): # @line L1
focus.append(sum_modified_laplacian(stack[k], step, radius, t1)) # @line L2
height, width = len(stack[0]), len(stack[0][0])
depth = [[0.0] * width for _ in range(height)]
best = [[0] * width for _ in range(height)]
for v in range(height): # @line L3
for u in range(width):
m = max(range(n), key=lambda k: focus[k][v][u]) # @line L4
offset = 0.0
if 0 < m < n - 1: # @line L5
o = gaussian_peak_offset(focus[m - 1][v][u], focus[m][v][u], focus[m + 1][v][u])
if o is not None:
offset = o
best[v][u] = m
depth[v][u] = d0 + delta * (m + offset) # @line L6
return depth, best # @line L7
def defocus_stack(texture, depth_index, frames, blur_per_frame, radius=3):
"""A synthetic focal stack: frame k blurs the texture at pixel (u, v) with a
Gaussian of standard deviation blur_per_frame * |k - depth_index[v][u]|.
The texture repeats at the border (periodic)."""
height, width = len(texture), len(texture[0])
stack = []
for k in range(frames):
img = []
for v in range(height):
row = []
for u in range(width):
sigma = blur_per_frame * abs(k - depth_index[v][u])
if sigma < 1e-9:
row.append(float(texture[v][u]))
continue
total, wsum = 0.0, 0.0
for dv in range(-radius, radius + 1):
for du in range(-radius, radius + 1):
w = math.exp(-(du * du + dv * dv) / (2.0 * sigma * sigma))
total += w * texture[(v + dv) % height][(u + du) % width]
wsum += w
row.append(total / wsum)
img.append(row)
stack.append(img)
return stack
test_shape_from_focus.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shape-from-focus/. The authors are listed in prov/09NTD3.jsonl.
import math
import random
import unittest
from shape_from_focus import (defocus_stack, gaussian_peak_offset, modified_laplacian,
shape_from_focus, sum_modified_laplacian, window_sum)
class ShapeFromFocusTest(unittest.TestCase):
def test_modified_laplacian_by_hand(self):
img = [[0, 7, 0], [4, 10, 6], [0, 9, 0]]
self.assertEqual(modified_laplacian(img)[1][1], 14.0)
flat = [[5.0] * 4 for _ in range(4)]
self.assertEqual(modified_laplacian(flat), [[0.0] * 4 for _ in range(4)])
def test_window_sum_matches_direct_sum(self):
rng = random.Random(1)
vals = [[rng.random() for _ in range(7)] for _ in range(5)]
got = window_sum(vals, 2)
for v in range(5):
for u in range(7):
want = sum(vals[y][x] for y in range(max(v - 2, 0), min(v + 3, 5))
for x in range(max(u - 2, 0), min(u + 3, 7)))
self.assertAlmostEqual(got[v][u], want, places=9)
def test_gaussian_fit_is_exact_for_gaussian_profiles(self):
rng = random.Random(2)
for _ in range(50):
center, width, height = rng.uniform(1.0, 7.0), rng.uniform(0.7, 3.0), rng.uniform(1.0, 50.0)
F = [height * math.exp(-(k - center) ** 2 / (2.0 * width * width)) for k in range(9)]
m = max(range(9), key=lambda k: F[k])
self.assertAlmostEqual(m + gaussian_peak_offset(F[m - 1], F[m], F[m + 1]), center, places=9)
self.assertAlmostEqual(gaussian_peak_offset(40.0, 100.0, 70.0), 0.2198, places=4)
self.assertIsNone(gaussian_peak_offset(10.0, 5.0, 10.0))
self.assertIsNone(gaussian_peak_offset(0.0, 5.0, 1.0))
def test_gain_and_offset_do_not_change_the_choice(self):
rng = random.Random(3)
tex = [[rng.randint(0, 255) for _ in range(16)] for _ in range(16)]
d = [[1.0 + 0.4 * u for u in range(16)] for _ in range(16)]
stack = defocus_stack(tex, d, 9, 0.8)
_, best = shape_from_focus(stack)
brighter = [[[3.0 * x + 40.0 for x in row] for row in img] for img in stack]
_, best2 = shape_from_focus(brighter)
self.assertEqual(best, best2)
a = sum_modified_laplacian(stack[0])
b = sum_modified_laplacian(brighter[0])
self.assertAlmostEqual(b[5][5], 3.0 * a[5][5], places=6)
def test_recovers_a_slanted_plane(self):
rng = random.Random(1)
size = 24
tex = [[rng.randint(0, 255) for _ in range(size)] for _ in range(size)]
truth = [[2.0 + 4.0 * u / (size - 1) for u in range(size)] for _ in range(size)]
stack = defocus_stack(tex, truth, 9, 0.8)
depth, best = shape_from_focus(stack, radius=2)
frame_err = [abs(best[v][u] - truth[v][u]) for v in range(size) for u in range(size)]
fit_err = [abs(depth[v][u] - truth[v][u]) for v in range(size) for u in range(size)]
self.assertLessEqual(max(frame_err), 1.0)
self.assertLess(sum(fit_err) / len(fit_err), 0.1)
self.assertLess(sum(fit_err), 0.5 * sum(frame_err))
def test_focus_measure_peaks_at_the_sharp_frame(self):
rng = random.Random(4)
tex = [[rng.randint(0, 255) for _ in range(12)] for _ in range(12)]
d = [[4.0] * 12 for _ in range(12)]
stack = defocus_stack(tex, d, 9, 0.8)
totals = [sum(map(sum, sum_modified_laplacian(img))) for img in stack]
self.assertEqual(max(range(9), key=lambda k: totals[k]), 4)
# Near focus the measure falls on both sides. Far from focus the cut-off
# kernel is no longer a Gaussian and the fall need not be monotone.
for k in (2, 3):
self.assertLess(totals[k], totals[k + 1])
self.assertGreater(totals[8 - k - 1], totals[8 - k])
if __name__ == "__main__":
unittest.main()
History
Krotkov (1988) studied how to bring a camera into focus automatically: he compared focus measures, found the gradient-based Tenengrad to be among the best, and searched for the lens position of best focus with a Fibonacci search. Nayar and Nakagawa (1994) turned focus into a dense depth method: they introduced the modified Laplacian and the sum-modified-Laplacian, took images while the object moved through the focus in steps, and found the depth of each pixel by a Gaussian fit to its focus measure. Later work added other focus measures, depth from defocus with few images, and regularized versions.
References
- Shree K. Nayar and Yasuo Nakagawa, Shape from focus, IEEE Transactions on Pattern Analysis and Machine Intelligence 16(8), 1994, pages 824 to 831, the modified Laplacian and the sum-modified-Laplacian focus measure, the depth from the frame of largest focus, and the Gaussian interpolation over three frames
- Eric Krotkov, Focusing, International Journal of Computer Vision 1(3), 1988, pages 223 to 237, the comparison of focus measures, including the Tenengrad gradient measure, and the Fibonacci search for the best focus
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 13.1.3, Shape from focus
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 09NTD3 Edit this page History Report an error Markdown