
Recall first from Histogram and atomic operations
- An atomic addition preserves competing increments to one counter.
- Updates to the same address can limit throughput even when every update is correct.
- Shared-memory bins let each block combine counts before updating global memory.
Stencils and their input neighbourhoods
3 min readYou have built reduction, scan, and histogram. Now the pattern at the heart of image processing, and this lesson answers what a stencil is and why separable kernels like Gaussian and Sobel split into two passes.
Suppose a camera image has small fluctuations in brightness across an otherwise uniform surface. A blur computes a weighted average of nearby pixels so that an isolated fluctuation contributes less to the output. As the output position moves one column to the right, all the input positions move one column to the right with it. The offsets stay the same.
A stencil specifies a fixed set of input offsets used to compute each output. A full 3×3 stencil reads the centre pixel and its eight neighbours, including the diagonals. A five-point stencil reads the centre and the four neighbours directly above, below, left and right. The stencil describes which positions the computation uses. The operation at those positions could be a weighted sum, a minimum or another local calculation. A convolution is the weighted-sum case with a specific coefficient convention.
Adjacent outputs can read the same inputs. For example, two horizontally adjacent full 3×3 neighbourhoods share two columns of three pixels each. Both outputs can be computed independently from the same source image. Keep the source and destination in separate buffers for a pass. Writing an output into the source would let a nearby calculation read a value that already includes some filtering, making the result depend on the order of execution.
If an output tile covers 16 columns by 16 rows, the inputs needed by a full 3×3 stencil cover 18 columns by 18 rows for a tile in the image interior. An output on the tile's right edge needs the pixel one column farther right. An output at the bottom-right corner also needs the diagonal pixel one row farther down and one column farther right. Those extra inputs form the one-cell halo, sometimes called ghost cells when stored around a local tile. The five-point stencil also needs a one-cell halo along the four sides. Its offsets omit the four diagonal corners of the expanded rectangle.
A tile boundary inside the image and the outer edge of the image supply halo values differently. At the interior tile boundary, the needed value belongs to the source image, even if it falls in the next tile. Past the outer image edge, a boundary rule defines the value. This lesson uses zero extension, which treats coordinates outside the image as zero and keeps the output the same size as the input. The coefficients stay fixed at the image edge, so a blur with zero extension can darken a constant image near its border.
Convolution in two one-dimensional passes
4 min readLet I[y,x] denote the source pixel in row y, column x. For a square filter of radius r, let K[dy,dx] denote its coefficient at row offset dy and column offset dx. A direct implementation computes one output by looping over both offsets from -r to r, multiplying each input by its coefficient and accumulating the products.
O[y,x] = sum over dy,dx of K[dy,dx] * I[y-dy,x-dx]
The minus signs give mathematical convolution. Using I[y+dy,x+dx] with the same coefficient layout gives cross-correlation. A symmetric Gaussian kernel gives the same result under either convention. For Sobel, reversing both offset axes changes the sign of each derivative kernel's response. Pick a convention and use it consistently when comparing signed outputs.
A kernel is separable when each coefficient is the product of a vertical coefficient and a horizontal coefficient, so K[dy,dx] = v[dy] * h[dx]. Each row is then a scaled copy of the horizontal vector h. Substitute the product into the direct sum. For any fixed row offset dy, the vertical weight is independent of dx, so it can be multiplied by the result of the entire horizontal sum. That horizontal result is reusable wherever a vertical pass needs the same intermediate pixel.
T[y,x] = sum over dx of h[dx] * I[y,x-dx]
O[y,x] = sum over dy of v[dy] * T[y-dy,x]
First compute a full intermediate image T, shifting only along each row of I. Then shift along the rows of T at a fixed column to produce O. With zero extension, an intermediate row outside the image is all zero because its entire source row is outside the image. The vertical pass can therefore use a zero for those row indices. In the horizontal pass, out-of-range source columns also contribute zero. These rules make the two expressions agree with direct convolution at the corners as well as in the interior.
For a Gaussian example, use the five-tap vector [1, 4, 6, 4, 1] / 16 on both axes. This is a binomial approximation to a sampled Gaussian. The 2D filter is the outer product of the vector with itself. Its centre weight is (6/16) × (6/16) = 36/256. The centre row is [6, 24, 36, 24, 6] / 256. The 1D coefficients sum to one, so the product kernel does too. A constant input therefore keeps its value at positions whose entire neighbourhood lies inside the image. An axis-aligned Gaussian sampled on a rectangular grid is also separable when truncated to a rectangular support. Its exponential factors into a function of x times a function of y, and each vector can be normalised separately.
For an impulse of value one surrounded by zeros, the direct Gaussian output in the affected region equals the 2D coefficient pattern centred on the impulse. In the two-pass version, the horizontal pass produces a single row of five weighted values. The vertical pass spreads that row across five rows, scaling each copy by the corresponding vertical weight. This gives a concrete way to check whether the two implementations use the same offsets and normalisation.
Sobel uses a smoothing vector on one axis and a difference vector on the other. Using coefficient order -1, 0, +1, the outer product of vertical [1, 2, 1] and horizontal [-1, 0, 1] gives the Sobel kernel for changes along x. Swap the roles of the vectors to get the kernel for changes along y. Each directional response can be computed using two 1D passes. Blur attenuates local differences, while Sobel uses signed weights to estimate how brightness changes across a neighbourhood.
For a k×k filter, direct convolution has k² weighted terms per interior output. The two-pass implementation evaluates k terms per intermediate and k per final output. With a full-size intermediate, that is 2k terms per output over the whole image, before accounting for skipped boundary taps. The five-tap Gaussian uses 25 terms directly and 10 in two passes. An arbitrary coefficient matrix needs a valid factorisation before the same rewrite will preserve the filter.
Measuring the cost of the two passes
3 min readThe reduction from 25 terms to 10 gives an arithmetic ratio of 2.5 for the five-tap filter. Elapsed time also includes the intermediate. A direct pass reads source neighbourhoods and writes final pixels. The two-pass version additionally writes every intermediate pixel and later reads it during the vertical pass. Caches can satisfy some reads, so counting terms or array accesses alone cannot determine how many bytes reach main memory. On a GPU, two separate passes also require two kernel launches. The measured ratio depends on image size, implementation and hardware.
A CPU benchmark on Ubuntu can verify the algorithm and measure its speedup without a GPU. Use the same row-major floating-point source in both versions, with pixel values in [0, 1]. Allocate a direct output, a separable output and an intermediate. Build the direct coefficient table once from the same horizontal and vertical vectors. Use the same output dimensions, zero extension and compiler optimisation settings for both versions. Keep the intermediate in floating point so that converting it to integer pixels cannot change the second pass.
Check correctness before timing. An interior impulse should reproduce the coefficient pattern. A corner impulse exposes accidental wraparound or an inconsistent edge rule. A constant input should retain its value in the interior and can lose some contribution at the edges. On a varied input, compare every output pixel and report the maximum absolute difference. The two evaluation orders can round differently in floating point. For the five-tap filter with single-precision pixels in [0, 1], 1e-6 is a practical absolute tolerance for the lab.
On Ubuntu, clock_gettime() with CLOCK_MONOTONIC gives elapsed time unaffected by discontinuous wall-clock changes. With strict C17, define _POSIX_C_SOURCE as 200809L before any headers to expose the declaration in <time.h>. Check that each clock call returns zero. Convert the difference between the timestamps to seconds by adding the seconds-field difference to the nanoseconds-field difference divided by one billion. clock_gettime(2), feature_test_macros(7).
Allocate memory and prepare coefficients before timing. Warm up both versions, then measure repeated runs on the same input. Keep output validation or a reported checksum outside the timed interval and make the output observable so the compiler has to produce it. Use enough iterations to make elapsed time measurable, and time both passes together for each separable run. Compare median times using direct time / separable time. A ratio above one means the separable version ran faster on that setup. On a CUDA system, a device benchmark likewise needs to measure completion of one direct launch or both separable launches, since timing only the host calls can capture submission time while device work is still pending.
Going deeperExplore the mechanism
Several stencil passes can be fused into one GPU kernel to avoid writing the intermediate to global memory and reading it back in a later launch. Each block computes the intermediate values needed by its own output tile and keeps them in shared memory. For the five-tap horizontal-then-vertical Gaussian, the final tile needs intermediate values for two extra rows above and below. Computing those intermediate values in turn needs source pixels extending two columns to either side. The block must finish producing the shared intermediate values before its threads use them for the vertical pass.
Adjacent blocks may recompute intermediate values where their required regions overlap. Fusion exchanges the intermediate global-memory round-trip and a launch for additional local work, shared-memory storage and a block-wide synchronisation. For a longer chain, derive the input footprint by following each output's dependencies backward through the passes. Every block needs the complete set of source values for its own outputs.
The next lesson, Shared-memory halo loading and boundaries, shows how a block supplies the extra inputs around its tile and handles coordinates at the edge of the image.
Key takeaways
- A stencil uses the same set of relative input offsets at every output position.
- A tile needs a halo wherever its output neighbourhoods extend into adjacent input regions.
- A separable k×k kernel reduces the tap count from k² to 2k per output when applied as two one-dimensional passes.
- The measured speedup includes the cost of writing and reading the intermediate image.
Reflect
- Explain to a colleague, in two sentences: identify the input offsets of a 3×3 stencil and a five-point stencil.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageclock_gettime(2): reading a monotonic clock
- Man pagefeature_test_macros(7): exposing POSIX interfaces in C
Official documentation first. Links checked when the lesson was published.