Procedural Stroke Rendering: Simulating Brush Painting with Code
This article explores the technical path of procedural stroke rendering, shifting from pixel-based output to action-based sequences. It details a three-layer architecture consisting of canvas, brush, and motion layers, followed by a minimal Python implementation using the stamp method. The article further discusses an error feedback mechanism for iterative corrections, compares this approach with diffusion models, and provides practical engineering recommendations.
1. Background: From Generating Pixels to Generating Processes
Mainstream image generation methods predominantly use pixels as their output unit. Diffusion models start from random noise and gradually produce a complete image through multi-step denoising, adjusting the entire canvas simultaneously. While this approach is highly mature in terms of image quality and style diversity, the intermediate process is difficult to explain, and local modifications are not straightforward.
An alternative approach treats painting as a sequence of actions. Instead of outputting a finished image directly, the system outputs a set of parameterized stroke commands, such as start point, path, brush width, color, and opacity. The image is formed sequentially as these commands are executed. The output of this method is a readable process record, where every single stroke can be inspected, replayed, deleted, or replaced.
Procedural painting holds practical value in several scenarios:
- Teaching demonstrations: Showing how strokes overlap to form shading and contours helps learners understand painting principles.
- Digital painting tools: Breaking down a painting into a replayable sequence of strokes supports step-by-step editing and style reuse.
- Robot painting: Stroke commands can be directly mapped to the motion trajectories of an actuator.
- Graphics research: It allows for the independent validation of brush models, pigment mixing, and texture algorithms.
2. Core Architecture: Canvas, Brush, and Motion Layers
An executable procedural painting system is typically divided into three layers.
1. Canvas Layer
The canvas is a 2D pixel grid where each pixel stores a color value. The example in this article uses an RGB triplet to represent color. The canvas layer is responsible for storing state and providing read and write interfaces.
2. Brush Layer
The brush layer defines the effect of a single “brush down” action. Common parameters include:
- Radius: Determines the coverage area of the brush.
- Hardness: The steepness of the edge transition. A high-hardness brush has a clear boundary, while a low-hardness brush has soft edges.
- Opacity: The proportion of the base color covered by a single stroke.
- Texture: Overlays noise on the color to simulate dry brush or rough paper effects.
In actual painting, the wetness of the paint affects color mixing. Wet paint spreads quickly with blurred boundaries, while dry paint retains more visible brush marks. Engineering-wise, this effect can be approximated using a combination of opacity and diffusion radius.
3. Motion Layer
The motion layer is responsible for generating the stroke path. The path is defined by several control points, interpolated with a fixed step length between adjacent points, with slight random perturbations added to each sampling point. Human hand movement is not perfectly smooth; slight jitter makes the lines closer to manual brushwork. Excessive jitter will cause the line to lose its sense of direction, so it needs to be adjusted according to the canvas size.
The relationship between the three layers is clear: the motion layer determines where the brush tip is, the brush layer determines what the brush tip leaves behind, and the canvas layer records the result.
3. Basic Implementation: The Stamp Method and Stroke Interpolation
The following code implements a minimal runnable example using pure Python standard syntax. It adopts the “stamp method”: stamping a circular imprint with edge falloff at each sampling point along the path, and stacking multiple imprints to form a line.
import mathimport randomW, H = 64, 64canvas = [[(255, 255, 255)] * W for _ in range(H)]def blend(dst, src, alpha):"""Blends the source color onto the destination color according to opacity."""return tuple(int(d * (1 - alpha) + s * alpha) for d, s in zip(dst, src))def stamp(canvas, x, y, radius, color, opacity):"""Stamps a circular imprint at (x, y), with edge falloff based on distance."""r0 = int(math.ceil(radius))cx, cy = int(round(x)), int(round(y))for dy in range(-r0, r0 + 1):for dx in range(-r0, r0 + 1):px, py = cx + dx, cy + dyif not (0 <= px < W and 0 <= py < H):continuedist = math.hypot(dx, dy)if dist <= radius:falloff = 1 - dist / (radius + 1e-6)alpha = opacity * falloffcanvas[py][px] = blend(canvas[py][px], color, alpha)def stroke(canvas, points, radius, color, opacity, jitter=0.0):"""Interpolates strokes along a polyline path and adds random perturbations to each sampling point."""for (x0, y0), (x1, y1) in zip(points, points[1:]):length = math.hypot(x1 - x0, y1 - y0)steps = max(1, int(length))for i in range(steps + 1):t = i / stepsx = x0 + (x1 - x0) * t + random.uniform(-jitter, jitter)y = y0 + (y1 - y0) * t + random.uniform(-jitter, jitter)stamp(canvas, x, y, radius, color, opacity)def draw_demo():random.seed(7)# A thicker, darker main linestroke(canvas, [(8, 48), (30, 16), (56, 44)],radius=3, color=(40, 60, 120), opacity=0.6, jitter=0.4)# A thinner, warm-colored auxiliary linestroke(canvas, [(20, 30), (44, 30)],radius=1.5, color=(200, 80, 60), opacity=0.8, jitter=0.2)return canvasif __name__ == "__main__":draw_demo()
This code illustrates several key points. First, the stroke is parameterized; changing the radius, color, or jitter amplitude yields different effects. Second, applying the brush is an overlay operation, where later strokes cover previous pixels, consistent with the behavior of real paint. Third, the random number uses a fixed seed to ensure that the same parameters yield the same result every run, which is convenient for debugging and reproduction.
4. Error Feedback: Observing the Canvas and Adding Strokes
Executing stroke commands once rarely succeeds on the first try. A practical system requires a closed loop: the system observes the current canvas, compares it with the target, identifies the position with the largest deviation, and adds new strokes.
The following code provides a minimal skeleton for this closed loop. The target can be a reference image or a semantic score provided by another module. Here, a reference pixel matrix is used as an example.
def error(canvas, target):"""Calculates the average pixel error between the canvas and the target, ranging roughly from 0 to 255."""total = 0for row_c, row_t in zip(canvas, target):for c, t in zip(row_c, row_t):total += sum(abs(a - b) for a, b in zip(c, t))return total / (W * H * 3)def worst_point(canvas, target):"""Finds the pixel coordinate with the maximum error."""best, best_err = (0, 0), -1for y in range(H):for x in range(W):e = sum(abs(a - b) for a, b in zip(canvas[y][x], target[y][x]))if e > best_err:best, best_err = (x, y), ereturn bestdef correct(canvas, target, threshold=5.0, max_rounds=5):"""Adds a stroke at the point of maximum error each round until the error falls below the threshold or the round limit is reached."""for _ in range(max_rounds):if error(canvas, target) < threshold:breakx, y = worst_point(canvas, target)color = target[y][x]stroke(canvas, [(x - 2, y), (x + 2, y)],radius=1.5, color=color, opacity=0.9, jitter=0.2)return canvas
An important design choice here: corrective strokes can only be stacked, not undone. This corresponds to the constraints of real painting and keeps the cause-and-effect of each step clear. The trade-off is limited correction capability; if an early stroke deviates too much, it is difficult to fully recover later. Therefore, in practice, large strokes are usually used first to establish the composition, and small strokes are used later for details, minimizing error early on.
The choice of error function also affects the results. Average pixel error is simple and intuitive, but it is not sensitive to contours and color blocks. To better align with human visual perception, blurring or edge extraction can be applied before comparison, or metrics like structural similarity can be introduced.
5. Comparison with the Diffusion Model Approach
Both approaches have their applicable scopes, compared below across several dimensions.
| Dimension | Diffusion Model Approach | Procedural Stroke Approach |
|---|---|---|
| Output unit | Entire pixel image | Ordered stroke commands |
| Process explainability | Weak, intermediate states are hard to map to specific operations | Strong, every stroke has parameter records |
| Local editing | Usually requires regeneration or local inpainting | Simply delete or replace the corresponding strokes, provided undo is allowed |
| Style source | Relies on training data distribution | Relies on brush model and rule design |
| Implementation threshold | Requires large-scale training resources | Can start with small-scale rules |
| Current maturity | High maturity in image quality and diversity | Still in the exploratory stage, limited detail realism |
It is worth noting that the two are not mutually exclusive. A common combination is to use a generative model to provide the target image or semantic constraints, and then let the stroke system execute the painting. This preserves process controllability while leveraging high-quality target representations.
6. Engineering Practice Recommendations
1. Separate Parameters from Rendering Logic
Store brush parameters, path data, and rendering functions separately. Path data can be serialized into structured files for easy replay, review, and version control.
2. Record Complete Stroke Logs
Every stroke should at least record path points, radius, color, opacity, random seed, and execution order. Logs are essential for debugging and reproduction.
