Fast layered depth of field
A depth of field filter built on box sums: the image is cut into a few depth layers, each layer is blurred with a disc-like kernel made of prefix sums, and the bright lights are drawn as real sprites. It runs in real time on a GPU, and the same pipeline exists in plain C++ for the CPU.
filter · 128 spp inputray-traced lens · 2048 spp
- The circle of confusion
- Why layers
- The pipeline
- Slabs in inverse depth
- Filling behind near objects
- A disc from box sums
- Lights as sprites
- Layered compositing
- Try it
- Against a real lens
- Speed and error
- CoC from a depth map
- Code
- References
The circle of confusion
A lens brings a single depth, zf, into focus. A point at any other depth z spreads over a disc on the sensor, called its circle of confusion (CoC).
For a thin lens [Potmesil:1981], the signed radius of this disc, in pixels, is
\(\displaystyle c(z) = a\,\frac{z - z_f}{z} = a\left(1 - \frac{z_f}{z}\right)\)
a: the CoC radius at infinity, set by the aperture
The radius is negative in front of the focus and positive behind it, and |c| is the blur. The renderer provides the colour and the depth of every pixel, and the filter either computes the CoC from the depth with this formula or uses a CoC map supplied by the caller. Note that c is affine in 1/z: this property will decide where to cut the layers.
Why layers
A depth of field filter works either as a gather or as a scatter. A gather blurs each pixel with its own radius, which is cheap but wrong at silhouettes: a blurred background pixel next to a sharp object includes the object in its average, which draws a glow around the object. A scatter does what a lens does and spreads each pixel over its own circle of confusion, but it costs one splat per pixel. Real-time engines approximate the scatter with gathers [Jimenez:2014], often in two layers, one in front of the focus and one behind it.
The layered pipeline of this note sits between the two, in the spirit of [Kraus:2007]. It cuts the image into a few depth slabs, blurs each slab with a gather, and stacks the results front to back. Inside a slab the radius varies slowly, so a gather is accurate; between slabs, the stacking order does what a scatter would. Only a few pixels really need a scatter, the bright lights, and those are drawn as sprites.
The pipeline
- Clean the silhouettes. An antialiased edge pixel mixes the colours of two surfaces but stores a single depth. When it lies next to a much nearer, blurred neighbour, it takes that neighbour's depth, so that the near colour is no longer spread with the far blur. When the neighbour is in focus, the pixel stays where it is, but it lends no colour to the background hidden behind the edge.
- Cut into depth slabs. The image is cut into three slabs of equal width in inverse depth. Then, on 2×2 blocks, each slab looks for its nearest block within the largest blur radius, which gives the colour hidden behind nearer slabs, and the reach of near objects over what lies behind them.
- Pull out the lights. Pixels that are brighter than a threshold and have a large enough CoC are taken out of the slabs and merged into one sprite per block, within a budget of covered pixels.
- Blur each slab. At half resolution, prefix sums give each pixel three box windows scaled to its own radius, which stack into a disc-like kernel. The blur runs along the rows, then along the columns, and its cost does not depend on the radius.
- Draw the sprites. Each sprite is drawn as an antialiased disc, or as a polygon with 3 to 12 blades.
- Stack front to back. The final frame composites, from the nearest slab to the farthest, each upsampled slab with its sprites, and the in-focus pixels, kept sharp at full resolution.
The first item says all there is to say about the silhouettes; the next sections detail the other stages.
Slabs in inverse depth
Since the CoC is affine in u = 1/z, slabs of equal width in u span equal ranges of CoC. For K slabs between the nearest and the farthest finite depths of the frame, the K − 1 bounds are
\(\displaystyle u_b = u_{\text{far}} + \left(u_{\text{near}} - u_{\text{far}}\right)\frac{b}{K}, \qquad b = 1, \dots, K - 1\)
slab 0 is the nearest; the sky joins the farthest
Each slab then spans a CoC range of a zf (unear − ufar) / K, the same for all slabs. This is what keeps a single gather per slab close to what a lens does. The default is three slabs.
Filling behind near objects
A blurred near object is half transparent at its edges, and through them the lens sees part of what the object hides. A slab cut from a single view has no colour there, only a hole. Each slab is therefore extended under the nearer slabs. On 2×2 blocks, every block covered by a nearer slab takes the colour of the nearest block that belongs to the slab. This block is found with one pass along the rows and two sweeps along the columns, within a reach equal to the largest CoC radius. A filled block then counts as covered:
\(\displaystyle \text{coverage} = \frac{n + m}{4}\)
n: pixels of the slab in the block; m: its pixels in nearer slabs
Each slab thus becomes a complete layer behind the objects in front of it, and the blur of those objects reveals a plausible background instead of black. Beyond the reach, the hole remains, and the final composite renormalizes.
A disc from box sums
Given the running sum S of a line, a box window of any radius costs only two reads [Crow:1984]: the window [x − r, x + r) sums to S(x + r) − S(x − r). A disc is not separable, but a staircase of three rectangles comes close to one. Strip s covers
\(\displaystyle w_{s+1} R < |dx| \le w_s R, \qquad |dy| \le h_s R\)
w = (0.970, 0.769, 0.499, 0), h = the widths reversed
The pass along the rows computes the mean of each strip along x, from two windows of the row's running sum. The pass along the columns then averages each strip over its height, and weights the strips by their areas. When the end of a window falls between two samples, the running sum is interpolated linearly, so the radius varies continuously rather than in whole pixels. Every output pixel uses its own radius, and the filter works at half resolution on premultiplied colour and coverage. It is a gather, with a cost per pixel that does not depend on the radius.
Lights as sprites
When a bright light is gathered by its neighbours, it turns into a soft smear, whereas through a lens it becomes a disc with a hard edge: the bokeh. The pixels that are brighter than a threshold and have a CoC above 3 pixels are therefore taken out of the slabs. In each 2×2 block, they are merged into one sprite, which carries their summed colour, sits at their luminance centroid, and takes their mean CoC as its radius. The brightest sprites are kept while they cover at most four pixels per image pixel. Each one is drawn as an antialiased disc or polygon, with its colour divided over its shape so that no light is lost, and it stays in the slab of its brightest pixel.
Layered compositing
At every full-resolution pixel, each slab k now provides a colour Ck and a coverage αk, upsampled from half resolution, plus the colour Ek of its sprites. The colour is premultiplied: a blurred edge that covers half a pixel carries half its colour and α = ½. The slabs are stacked front to back with the over operator [Porter:1984]: each slab adds its colour, seen through the slabs in front of it.
\(\displaystyle \text{colour} = \sum_{k=0}^{K-1} T_k\,(C_k + E_k), \qquad T_k = \prod_{j<k} (1 - \alpha_j)\)
The transmittance Tk is the share of the pixel that the slabs in front of slab k leave visible: it starts at one on the nearest slab, and each slab lowers it by its coverage. For example, with three slabs that cover 0.6, 0.5 and 1 of a pixel, the near slab gives 60 % of its colour, the middle one half of the remaining 40 %, and the far one the last 20 %.
Where the nearest slab is opaque, nothing behind it shows. Where its blurred edge is half transparent, the next slab shows through, with the colour filled in behind the object: this is what the fill was for. The sprites are added rather than composited, because a light emits: its disc adds to the colour of its own slab, and the slabs in front cover it through T.
The slabs are stored at half resolution, which on its own would soften the details in focus. To avoid this, the sharp full-resolution pixel p is blended into its own slab as an opaque layer, with a weight s that falls from one, below half a pixel of CoC, to zero, above one and a half pixels:
\(\displaystyle \begin{aligned} s &= 1 - \operatorname{smoothstep}(0.5,\ 1.5,\ |c|) \\ C_k + E_k &\leftarrow (1 - s)(C_k + E_k) + s\,p \\ \alpha_k &\leftarrow (1 - s)\,\alpha_k + s \end{aligned}\)
Because a sharp pixel is opaque, the blurred slabs behind an in-focus object stop exactly at its silhouette, while a blurred slab in front of it still covers it in part. This is the occlusion that a single gather gets wrong. Finally, the colour is divided by the total coverage 1 − TK, which stays below one where the fill did not reach.
Try it
The demo below runs the scene of the top image at half resolution, through a JavaScript port of the filter with one function per stage. Drag the divider to compare the input, on the left, with the result, on the right, and click the image to focus on the surface under the cursor. The input side can also show the CoC map (blue in front of the focus, orange behind) or the slabs. The bokeh controls change the shape of the light sprites.
Against a real lens
The figure at the top compares the filter with a thin lens ray traced at 2048 samples per pixel, for three focus depths and the same aperture. The input of the filter is a pinhole frame of 128 samples per pixel. Its noise remains wherever the filter keeps the image sharp, and it counts in the error below.
The discs keep their size, colour and edge at every focus. What differs is occlusion inside the lens: when a blurred object partly hides a light, the ray tracer cuts its disc into a crescent, while a post-process, which sees a single view, draws the whole disc.
Speed and error
| Method | GPU 1080p | GPU 4K | CPU 1080p | PSNR, focus 3 · 8 · 16 |
|---|---|---|---|---|
| Near/far gather, with sprites | 0.37 ms | 1.64 ms | – | 34.7 · 28.7 · 27.8 dB |
| Layered | 0.54 ms | 2.97 ms | ≈ 23 ms | 37.1 · 35.4 · 32.3 dB |
GPU: RX 9070 XT. CPU: 8 cores, AVX2, float. PSNR is measured against the ray-traced lens of the previous section, with both images clipped to [0, 1].
The near/far gather, common in game engines, splits the scene into only two layers, one in front of the focus and one behind it. The layered pipeline costs more, and in exchange it gets silhouettes and near occluders right.
The CPU version is the same pipeline in plain C++, without intrinsics: the compiler vectorizes every row loop eight floats wide, and OpenMP spreads the rows over the cores. With eight threads it is bound by memory, so the speed came from moving fewer bytes: the staircase writes its output already transposed, and the slab colours are never copied.
CoC from a depth map
The filter only needs the signed CoC of every pixel. In a renderer, the depth buffer gives z once it is linearized: with near and far planes n and f, a stored depth d in [0, 1] corresponds to z = n f / (f − d (f − n)), or to z = n / d with a reversed, infinite projection. The blur at infinity follows from the camera parameters:
\(\displaystyle a = \frac{F^2}{2N\,(z_f - F)}\cdot\frac{W}{S}\)
F: focal length, N: f-number, S: sensor width, W: image width in pixels
For a photograph, a monocular depth network can stand in for the depth buffer. Most of these networks predict inverse depth, and only up to an unknown scale and shift: v = s u + t with u = 1/z. Since the CoC is affine in u, that is enough. With vf the value at the pixel to focus on and v∞ the value at infinity (the sky, or the smallest value of the map), the scale and the shift cancel:
\(\displaystyle c = a\,\frac{v_f - v}{v_f - v_\infty}\)
a, the blur at infinity, is then a free choice
Code
The whole filter is one call, which computes the CoC from the depth with the thin-lens formula:
DofParams params;
params.focus = 3.f; // focus depth, scene units
params.aperture = 26.f; // CoC radius at infinity, pixels
params.max_coc = 32.f; // clamp of the CoC
depth_of_field(rgb, depth, nullptr, out, w, h, 3, params); // CoC from the depth
To use your own CoC map, for instance one derived from a depth estimate, pass it instead of
nullptr. The sprite_blades parameter switches the bokeh to polygons.
References
- F. C. Crow, Summed-Area Tables for Texture Mapping, Computer Graphics 18(3) (SIGGRAPH), 1984.
- J. Jimenez, Next Generation Post Processing in Call of Duty: Advanced Warfare, Advances in Real-Time Rendering in Games, SIGGRAPH 2014 course.
- M. Kraus, M. Strengert, Depth-of-Field Rendering by Pyramidal Image Processing, Computer Graphics Forum 26(3) (Eurographics), 2007.
- T. Porter, T. Duff, Compositing Digital Images, Computer Graphics 18(3) (SIGGRAPH), 1984.
- M. Potmesil, I. Chakravarty, A Lens and Aperture Camera Model for Synthetic Image Generation, Computer Graphics 15(3) (SIGGRAPH), 1981.