Code as a Brush: How AI Paints Stroke by Stroke, and How to Build It

    This article explains an alternative to diffusion-based text-to-image generation: using a large language model to output drawing instructions instead of pixels, so the generated artifact becomes a program rather than an image. It covers how to build a minimal virtual painting engine with canvas, brush, and paint abstractions, how the model plans structured brushstrokes, how an observe-and-correct loop enables local fixes, how artist personas constrain style, and practical engineering guidance for production use.

    1. From One-Shot Images to Stroke-by-Stroke Painting

    In a conventional text-to-image pipeline, the dominant approach relies on diffusion models: the model starts from random noise, runs multiple denoising steps, gradually maps the text condition onto a pixel matrix, and outputs the entire image in one pass. This works end to end, is fast, and produces rich detail. But it has inherent limitations: the intermediate process is hard to explain, local edits usually require resampling the whole image, and the model has no explicit control over how the picture was drawn.

    A different approach turns this around: let a large language model act as the painter’s hand. Instead of emitting pixels, it emits drawing instructions. The model first plans the composition, then breaks the scene into hundreds, thousands, or even hundreds of thousands of stroke calls, which a rendering engine paints onto a virtual canvas one stroke at a time. The key shift is this: the generated object changes from an image to a program. What the model writes is not a picture but Python code that produces one.

    This paradigm shift yields three direct benefits:

    • Explainable process: every stroke carries structured parameters such as coordinates, color, brush width, and path points, which makes auditing and replay straightforward.
    • Locally correctable: when something is wrong, you do not repaint the whole image; you add new strokes to cover or deepen the area.
    • Controllable style: adjusting the brush model, paint wetness, canvas texture, and similar parameters lets you write the art style explicitly into the code.

    2. Building a Virtual Painting Engine: Moving the Physical World into Code

    To make a model “paint like a human,” it first needs a programmable brush system. A minimal usable engine needs at least three layers of abstraction: canvas, brush, and paint.

    2.1 Canvas and Canvas Texture

    A canvas is more than a pixel buffer. A real canvas has texture and absorbency, both of which affect how paint spreads. In code, this can be represented with multiple layers:

    1. class Canvas:
    2. def __init__(self, w, h):
    3. self.pixels = [[BG_COLOR] * w for _ in range(h)]
    4. self.texture = generate_texture_noise(w, h) # canvas texture
    5. self.wetness = [[0.0] * w for _ in range(h)] # paint wetness

    2.2 Brush Model: Width, Jitter, and Path Points

    One detail in the source material is worth borrowing: when the model drew its first line, it did not aim for perfectly straight. It deliberately added roughly 7 pixels of sway. The reason is that a human arm has physiological tremor, and a line that is too straight looks mechanical instead. This reflects an important principle of procedural painting — use noise to simulate realism.

    1. def stroke(canvas, color, width, points, jitter=7.0):
    2. for i in range(len(points) - 1):
    3. p1 = add_jitter(points[i], jitter)
    4. p2 = add_jitter(points[i+1], jitter)
    5. draw_line(canvas, p1, p2, color, width)

    The jitter parameter controls how much the stroke wavers, width controls brush thickness, and points controls the path. Each time the model outputs a stroke, it is essentially outputting some combination of these three kinds of parameters.

    2.3 Paint and Wetness: Letting Colors Transition Naturally

    Wet paint spreads slightly on the canvas and forms soft edges; dry paint leaves sharp ones. A simple diffusion approximation looks like this:

    1. def wet_blend(canvas, x, y, color, wetness):
    2. if canvas.wetness[y][x] > 0.6:
    3. blend_neighbor_pixels(canvas, x, y, color, alpha=0.3)
    4. paint_pixel(canvas, x, y, color)
    5. canvas.wetness[y][x] = min(1.0, wetness)

    Once a stroke lands, the wetness field decides whether the color bleeds into neighboring pixels. This mechanism turns the picture from a collage of flat color blocks into something with moisture in the application.

    3. Making the Model Plan Strokes: From Natural Language to Coordinate Instructions

    With the engine in place, the model needs to output instructions the engine can execute. In practice, the model can generate a structured stroke description that an interpreter converts into engine calls:

    1. brushstrokes = [
    2. {
    3. "color": "#30346a",
    4. "width": 90,
    5. "points": [(120, 80), (121, 83), (119, 86)],
    6. "wetness": 0.7
    7. },
    8. {
    9. "color": "#f0e6d2",
    10. "width": 12,
    11. "points": [(300, 420), (310, 425)],
    12. "wetness": 0.2
    13. }
    14. ]

    The model first establishes a global composition, then decides the stroke order: lay down large color fields first and layer details on top; paint the background before the subject. The “111 strokes to finish a sunrise with a small bird” example from the source shows that stroke count is not proportional to scene complexity — with sensible brush widths and path design, a small number of strokes can express a complete image.

    4. Error Checking and Iterative Correction: Finishing Is Not the End

    A diffusion model is essentially untouchable after its single generation pass, whereas code-based painting naturally supports “render, inspect, then add more strokes.” The typical flow is:

    1. The model outputs a batch of stroke instructions.
    2. The engine renders the current canvas.
    3. The canvas is sampled or described, and that feedback goes back to the model.
    4. Based on the feedback, the model decides whether to keep painting, deepen a region, or cover a mistake with new strokes.
    5. Repeat until it converges.

    This observe-and-correct loop lets the model handle local problems such as “the lines on the bird’s back are too thin and the structure looks scattered.” The fix is not to erase and repaint, but to add strokes that change the visual result — the digital expression of the covering technique used in real painting.

    1. for step in range(max_steps):
    2. canvas = engine.render(brushstrokes)
    3. feedback = inspect(canvas) # visual description or simple metrics
    4. if feedback.is_satisfied():
    5. break
    6. new_strokes = model.plan_next_stroke(feedback)
    7. brushstrokes.extend(new_strokes)

    5. Style as Persona: From Imitation to Original Expression

    Once the model has stable stroke control, you can add an “artist persona” mechanism: give the model a fictional background, preferences, and working habits, and let it choose palettes, brushes, and composition strategies under that setting. The value is that style moves from post-hoc parameter tuning to an upfront constraint, which reduces the homogenization that comes from directly imitating existing works.

    In engineering terms, this can be implemented with a system prompt or a persona configuration:

    1. artist_persona = {
    2. "background": "landscape painter who has sketched in port cities for years",
    3. "palette": ["#2c3e50", "#e67e22", "#ecf0f1"],
    4. "brush_preference": "broad strokes for the base, fine strokes for outlines",
    5. "avoid": ["overly sharp edges", "high-saturation color clashes"]
    6. }

    Injecting the persona constraints into the model’s context before each stroke-planning step keeps the output stylistically consistent.

    6. Engineering Recommendations

    To adopt this “code as a brush” approach in a real system, start from these directions:

    1. Engine first, model second: package basic capabilities such as brushes, canvas, and wetness into a stable API, and let the model handle only the strategy layer.
    2. Control the stroke budget: set a maximum stroke count and a rendering timeout to keep long chains from diverging.
    3. Add intermediate previews: generate a thumbnail every N strokes for the model to self-check and for humans to step in.
    4. Whitelist parameters: colors, widths, jitter, and similar values should be constrained to legal ranges so abnormal model output cannot crash the engine.
    5. Logging and replay: record every stroke instruction in full so runs can be reproduced, audited, and edited afterwards.
    6. Combine with general cloud capabilities: stroke instructions and rendered output can be stored in object storage, the task queue can be handled by a message queue, inference and rendering services can be deployed on a container platform, and log and monitoring services with alerting can track the status of long-running tasks.

    7. Conclusion

    “Painting stroke by stroke in code without calling an image model” is not meant to replace diffusion-based generation. It offers another perspective: reducing painting from one-shot pixel generation to controllable execution at the action level. Its value lies not in generation speed but in being explainable, correctable, and reproducible. For developers, understanding this technical route adds a programmable brush to the toolbox — when a project needs style consistency, local refinement, or process auditing, stroke-level modeling is a better fit than end-to-end generation.