*(Preserves the user's WIP "A simple algorithm" — same intent, fleshed.)*
• **the core idea**: a region is **in focus** when it carries **local high-frequency detail** — sharp edges, texture. So measure, per pixel and per frame, how much high-frequency content sits in a small window, and at each output pixel **pick the frame with the most**. [`fig-focalstack-sharpness`]
• **the sharpness measure**: take the **band-pass / high-frequency** component of frame $k$ (a Laplacian, a high-pass, or a band of a pyramid), and accumulate its **energy** in a window $w(p)$:
$$s_k(p)=\sum_{q\in w(p)} \lVert \nabla I_k(q)\rVert^2 \quad(\text{local high-frequency / Laplacian power}).$$
• **why you must *square* before averaging** (the subtle step from the slides): the raw high-frequency signal **swings positive and negative** — around an edge it goes $+\to 0\to-$. Its local average is **~zero by construction** (low frequencies were removed), so you cannot smooth it directly. **Square it** (or take $|\cdot|$) → all-positive → now the local (Gaussian) average correctly reads "there *is* detail here." [`fig-focalstack-why-square`]
• **the selection**: the all-in-focus image is the per-pixel argmax,
$$k^\*(p)=\arg\max_k s_k(p),\qquad I(p)=I_{k^\*(p)}(p).$$
(Aside: $k^\*(p)$ is itself a coarse **depth map** — "which focal plane was sharpest here" — i.e. **shape-from-focus**, Nayar–Nakagawa 1994. Cross-ref depth estimation.)
• **softening it — weighted composite**: a hard per-pixel argmax is noisy and shows seams. Two fixes from the slides, both about **giving more weight to the best frame while staying spatially coherent**:
• **weighted sum** (then **normalize!**): $I(p)=\dfrac{\sum_k w_k(p)\,I_k(p)}{\sum_k w_k(p)}$ with $w_k(p)=s_k(p)$ — smooth, but a blurry frame still leaks in.
• **sharpen the weights with an exponent**: $w_k(p)=s_k(p)^{\gamma}$, $\gamma\approx4$ — pushes toward argmax (the winner dominates) while keeping a smooth blend; "subtle but sharper" than $\gamma=1$. [`fig-focalstack-argmax-composite`]
• **and smooth the selection map**: beyond weighting, **spatially regularize the choice** (smooth $s_k$, or smooth/MRF the label field) so neighbors tend to come from the same frame — avoiding salt-and-pepper switching between frames. This "spatial coherence in the choice of pixels" is exactly what the advanced method makes principled. [`fig-focalstack-argmax-composite`, weight-visualization inset]