Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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: NN gray images I0,…,IN−1I_0, \dots, I_{N-1} of size W×HW \times H from a fixed camera. Image kk is in focus at the depth d0+kΔd_0 + k \Delta. The images are aligned; a real lens also changes the magnification slightly with focus, which must be corrected first.
  • A step ss for the modified Laplacian, a window radius rr and a threshold T1T_1.

Model. The scene has texture at the scale of the window, and the depth is nearly constant over one window. A point at depth zz appears in image kk blurred by an amount that grows with ∣z−(d0+kΔ)∣|z - (d_0 + k \Delta)|.

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

ML(u,v)=∣2I(u,v)−I(u−s,v)−I(u+s,v)∣+∣2I(u,v)−I(u,v−s)−I(u,v+s)∣.\mathrm{ML}(u, v) = |2 I(u, v) - I(u - s, v) - I(u + s, v)| + |2 I(u, v) - I(u, v - s) - I(u, v + s)|.

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 FF is the sum of the values ML≥T1\mathrm{ML} \ge T_1 over the (2r+1)×(2r+1)(2r+1) \times (2r+1) window.

The algorithm

  1. SHAPE-FROM-FOCUS(I_0..I_{N-1}, d_0, Δ, s, r, T_1)
  2. 1for k ← 0 to N - 1 do
  3. 2F_k ← the window sum of the values ML ≥ T_1 of the modified Laplacian of I_k
  4. 3for each pixel p do
  5. 4m ← the least k with the largest F_k(p)
  6. 5if 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
  7. 6depth[p] ← d_0 + Δ (m + δ)
  8. 7return depth

Line L2, the window. The window sum takes O(1)O(1) per pixel with an integral image, for any rr. 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 Aexp⁡(−(k−c)2/(2s2))A \exp(-(k - c)^2 / (2 s^2)), then ln⁡F\ln F is a parabola in kk, and the peak is

δ=12⋅ln⁡Fm−1−ln⁡Fm+1ln⁡Fm−1−2ln⁡Fm+ln⁡Fm+1.\delta = \frac{1}{2} \cdot \frac{\ln F_{m-1} - \ln F_{m+1}}{\ln F_{m-1} - 2 \ln F_m + \ln F_{m+1}}.

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 kk has in focus comes from the calibration of the lens, for example the thin lens law 1/f=1/z+1/z′1/f = 1/z + 1/z' with the distance z′z' of the sensor. In a microscope that moves the stage in equal steps, it is simply d0+kΔd_0 + k \Delta.

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 ML=∣20−4−6∣+∣20−7−9∣=10+4=14\mathrm{ML} = |20 - 4 - 6| + |20 - 7 - 9| = 10 + 4 = 14 for s=1s = 1.

One Gaussian fit. If the best frame has Fm=100F_m = 100 and its neighbors have Fm−1=40F_{m-1} = 40 and Fm+1=70F_{m+1} = 70, then ln⁡40=3.689\ln 40 = 3.689, ln⁡100=4.605\ln 100 = 4.605 and ln⁡70=4.248\ln 70 = 4.248. The denominator is −1.273-1.273, the numerator is −0.560-0.560, and δ=0.5⋅0.560/1.273=0.220\delta = 0.5 \cdot 0.560 / 1.273 = 0.220. The peak lies 0.22 of a step past frame mm, toward the larger neighbor.

A slanted plane. The test file blurs a random 24×2424 \times 24 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 kk is a Gaussian with standard deviation 0.8 ∣k−d∣0.8\,|k - d| pixels. With a 5×55 \times 5 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.

  1. The fit is exact for Gaussian profiles. If the three values follow a Gaussian in kk, their logarithms lie on a parabola, and the formula returns its vertex exactly.
  2. The fit stays near the best frame. If FmF_m is the largest of the three values, the step δ\delta is at most 1/21/2 in size, whatever the shape of the profile.
  3. Gain and offset. Replacing every image by aI+ba I + b with a>0a > 0 multiplies the modified Laplacian by aa, so the choice and the fit do not change when T1=0T_1 = 0.
  4. Why the Laplacian measures focus. For a periodic texture blurred by a Gaussian, the energy of the Laplacian is ∑∣ω∣4∣T^(ω)∣2e−σ2∣ω∣2\sum |\omega|^4 |\hat T(\omega)|^2 e^{-\sigma^2 |\omega|^2} up to a constant, by Parseval's theorem, which strictly decreases as the blur σ\sigma 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 NN frames at focus positions d0+kΔd_0 + k \Delta for k=0,…,N−1k = 0, \dots, N - 1. Fk(p)F_k(p) is the focus measure of frame kk at pixel pp from line L2.

Lemma 1 (window sums). The integral image S[v][u]=∑v′<v, u′<ux(v′,u′)S[v][u] = \sum_{v' < v,\, u' < u} x(v', u') gives the sum of xx over the rows [v0,v1)[v_0, v_1) and columns [u0,u1)[u_0, u_1) as S[v1][u1]−S[v0][u1]−S[v1][u0]+S[v0][u0]S[v_1][u_1] - S[v_0][u_1] - S[v_1][u_0] + S[v_0][u_0].

Proof. The code builds S[v+1][u+1]=S[v][u+1]+∑u′≤ux(v,u′)S[v+1][u+1] = S[v][u+1] + \sum_{u' \le u} x(v, u'), which is the definition. Inclusion and exclusion of the four corner rectangles gives the formula. □\square

So line L2 computes Fk(p)=∑qMLk(q)[MLk(q)≥T1]F_k(p) = \sum_{q} \mathrm{ML}_k(q) [\mathrm{ML}_k(q) \ge T_1] over the window of pp cut at the border, as Nayar and Nakagawa define the sum-modified-Laplacian.

Lemma 2 (selection). Line L4 sets mm to the least index with Fm(p)=max⁡kFk(p)F_m(p) = \max_k F_k(p). □\square

Theorem 1 (the Gaussian fit). Let 0<m<N−10 < m < N - 1 and suppose that the three values near the peak follow a Gaussian,

Fk=Aexp⁡(−(k−c)22s2)for k∈{m−1,m,m+1},F_k = A \exp\left(-\frac{(k - c)^2}{2 s^2}\right) \quad \text{for } k \in \{m - 1, m, m + 1\},

with A>0A > 0 and s>0s > 0. Then line L5 finds m+δ=cm + \delta = c, so line L6 returns d0+cΔd_0 + c \Delta, the position of the peak.

Proof. Let a,b,ea, b, e be the logarithms of Fm−1,Fm,Fm+1F_{m-1}, F_m, F_{m+1}. Then ln⁡Fk=ln⁡A−(k−c)2/(2s2)\ln F_k = \ln A - (k - c)^2 / (2 s^2), a parabola in kk. A direct computation gives

a−2b+e=−1s2<0,a−e=2(m−c)s2.a - 2 b + e = -\frac{1}{s^2} < 0, \qquad a - e = \frac{2 (m - c)}{s^2}.

So the code accepts the fit, and

δ=12⋅a−ea−2b+e=12⋅2(m−c)/s2−1/s2=c−m.■\delta = \frac{1}{2} \cdot \frac{a - e}{a - 2 b + e} = \frac{1}{2} \cdot \frac{2 (m - c) / s^2}{-1 / s^2} = c - m. \qquad \blacksquare

Lemma 3 (the step stays in the interval). If Fm≥Fm−1F_m \ge F_{m-1}, Fm≥Fm+1F_m \ge F_{m+1}, all three are positive and the fit is accepted, then ∣δ∣≤1/2|\delta| \le 1/2.

Proof. Let x=b−a≥0x = b - a \ge 0 and y=b−e≥0y = b - e \ge 0. Then a−2b+e=−(x+y)a - 2 b + e = -(x + y), which is negative because the fit was accepted, and a−e=y−xa - e = y - x. So δ=(x−y)/(2(x+y))\delta = (x - y) / (2 (x + y)), and ∣x−y∣≤x+y|x - y| \le x + y. □\square

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 aI+ba I + b with a>0a > 0, then ML\mathrm{ML} is multiplied by aa. With T1=0T_1 = 0, every FkF_k is multiplied by aa, and the choice of mm and the offset δ\delta do not change.

Proof. The weights 2,−1,−12, -1, -1 in each term of ML\mathrm{ML} sum to 0, so bb cancels and aa comes out of the absolute values. Scaling all FkF_k by aa keeps the argmax, and adds ln⁡a\ln a to a,b,ea, b, e in Theorem 1, which cancels in both differences. With T1>0T_1 > 0 the threshold must be scaled by aa too. □\square

Theorem 2 (blur lowers the energy of the Laplacian). Let TT be a periodic image on the plane whose Laplacian is square integrable over one period, and let Bσ=Gσ∗TB_\sigma = G_\sigma * T for the Gaussian GσG_\sigma of standard deviation σ\sigma. Then E(σ)=∫∣ΔBσ∣2E(\sigma) = \int |\Delta B_\sigma|^2 over one period is strictly decreasing in σ≥0\sigma \ge 0, unless TT is constant.

Proof. Write TT as a Fourier series with coefficients T^(ω)\hat T(\omega). The Laplacian multiplies the coefficient at frequency ω\omega by −∣ω∣2-|\omega|^2, and the Gaussian multiplies it by exp⁡(−σ2∣ω∣2/2)\exp(-\sigma^2 |\omega|^2 / 2). By Parseval's theorem,

E(σ)=C∑ω∣ω∣4∣T^(ω)∣2exp⁡(−σ2∣ω∣2)E(\sigma) = C \sum_{\omega} |\omega|^4 |\hat T(\omega)|^2 \exp(-\sigma^2 |\omega|^2)

for a constant C>0C > 0. The term with ω=0\omega = 0 is 0. Every other term is nonnegative and nonincreasing in σ\sigma, and strictly decreasing if T^(ω)≠0\hat T(\omega) \ne 0. If TT is not constant, some T^(ω)\hat T(\omega) with ω≠0\omega \ne 0 is not zero. □\square

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 σ\sigma, 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 Θ(WH)\Theta(W H) per frame: the modified Laplacian is O(1)O(1) per pixel, and the window sums are O(1)O(1) per pixel with the integral image. Lines L3 to L6 cost Θ(N)\Theta(N) per pixel for the maximum. The total is Θ(NWH)\Theta(N W H) in every case. The code keeps all focus measures, O(NWH)O(N W H). 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, Θ(WH)\Theta(W H).

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 Δ\Delta 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 FF 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 T1T_1 and gain. A fixed T1T_1 depends on the brightness of the image. Scale it with the gain, or use T1=0T_1 = 0.
  • 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.

shape_from_focus.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • 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)
WritingW2 basic
  • a scene preset for the example