How to Draw Images Stroke by Stroke in Python Without an Image Generation Model
This article explains how to draw images without calling any image generation model: instead of outputting pixels, an AI programming assistant writes a Python program that paints on a virtual canvas one stroke at a time. It compares diffusion-based generation with this code-driven approach, then walks through the full pipeline—scene planning, brush physics simulation, append-only strokes that cannot be undone, and a render-observe-revise feedback loop. It also shows how explicit brush rules create a reproducible artistic style, how to engineer the canvas, stroke protocol and feedback mechanism, and how to manage cost by separating coarse-grained planning from fine-grained rendering. Practical guidance, limitations and an honest assessment of where this technique fits are included for developers interested in controllable, auditable and stylized generation.
Introduction: When Drawing Is No Longer Reserved for Image Models
In most mainstream image generation approaches, producing a picture depends on a diffusion model: the model starts from random noise and, over many denoising steps, gradually “sculpts” an image that matches the text prompt. This route is fast, end-to-end and visually refined. But its output is a “pixel result.” The drawing process in between is opaque, and users have little way to influence where a particular stroke should land.
In recent years, a very different idea has come into view: completely bypass image generation models and let an AI coding assistant write an executable Python program that paints an image stroke by stroke on a virtual canvas. The core of this idea is not to generate pixels but to generate actions — each step is a coordinate, a path and a set of brush parameters. The image only exists once the program finishes and leaves its result on the canvas.
At first glance this seems clumsy, yet it solves several problems that traditional approaches struggle with: the process is explainable, the parameters are adjustable, the style can be constrained and mistakes can be corrected. For developers it is a technical paradigm worth studying seriously, because it reframes “image generation” as a combination of program generation + physics simulation + feedback-driven iteration.
1. The Fundamental Difference: Generating Pixels vs. Generating Actions
To understand code-driven drawing, it helps to see clearly where it diverges from diffusion-based generation.
1.1 Diffusion Generation: Pixels Output in One Shot
A diffusion model is trained to learn “how to recover an image from noise.” During inference, the model iterates multiple times in latent or pixel space; each step slightly reduces noise and strengthens structure, eventually producing a complete image. Its characteristics include:
- End-to-end: you give a prompt and get a finished image directly.
- Strongly black-box: the intermediate process is hard to intervene in, and controlling a single local stroke is especially difficult.
- Style depends on the training distribution: fine details tend to inherit style biases from the training data.
1.2 Code-Driven Drawing: A Sequence of Brush Instructions
Code-driven drawing inverts the problem. What the model (or program) must output is not pixels but a sequence of executable drawing instructions, for example:
strokes = [{"color": "#30346a", "width": 90, "points": [(120, 80), (123, 82), (126, 81)]},{"color": "#4a5a8a", "width": 12, "points": [(200, 150), (215, 160)]},# ... possibly tens of thousands to over a million stroke instructions]
The canvas is a two-dimensional buffer. The program applies ink stroke by stroke following the instructions, and the strokes stack up into an image. The key differences from a diffusion model are:
| Dimension | Diffusion generation | Code-driven stroke painting |
|---|---|---|
| Output | Pixel image | Stroke instructions + render result |
| Process transparency | Low | High; every step can be logged and replayed |
| Intervenability | Weak | Strong; parameters can be adjusted at any time |
| Style control | Depends on prompt and model | Constrained through stroke rules and feedback |
| Compute profile | GPU inference | Runs on ordinary CPUs |
For developers, the greatest value of the second path is that the image is no longer just a “result” but a “process.” This means the entire drawing process can be recorded, reproduced, audited and corrected.
2. The Core Workflow: Plan, Draw, Observe, Revise
Based on public technical write-ups, systems of this kind usually contain four stages that form a closed loop.
2.1 Stage One: Scene Understanding and Stroke Planning
Before the first mark, the system needs to “think through what it is drawing.” This step is typically handled by a language model, which decomposes the scene into a set of executable drawing tasks, such as:
- What the main subject is (for example, “a shopping cart in a parking lot”);
- Which geometric shapes, color blocks and textures make it up;
- What to draw first and what to draw later (usually background → subject → details → highlights).
The output of this stage is not natural-language description but a structured drawing plan, for example:
{"canvas": {"width": 1920, "height": 1080, "background": "#d8d8d8"},"layers": [{"name": "ground", "strokes": 120000},{"name": "cart_body", "strokes": 380000},{"name": "details_and_highlights", "strokes": 200000}]}
2.2 Stage Two: Simulating the Physics of a Real Brush
“Making it look like a real brush” is not a slogan; it has to be quantified into parameters. Common simulation dimensions include:
- Brush width and shape: round, flat or fan-shaped tips affect the edges of lines.
- Paint wetness: wet paint produces softer edges, while dry paint leaves broken, streaky marks.
- Pen pressure: higher pressure makes lines thicker and colors darker.
- Path jitter: a human arm cannot draw perfectly straight lines, and deliberately adding tiny wobbles actually looks more realistic.
- Canvas texture: a rough canvas makes paint accumulate on the raised parts of the texture, creating a grainy feel.
A simplified brush simulation might look like this:
import math, randomdef draw_stroke(canvas, points, color, width, wetness=0.5, jitter=7):"""Draw a stroke with path jitter and wetness falloff on the canvas"""for i in range(1, len(points)):x0, y0 = points[i-1]x1, y1 = points[i]# Path jitter: simulate an unsteady armjx = random.uniform(-jitter, jitter) * 0.1jy = random.uniform(-jitter, jitter) * 0.1x1, y1 = x1 + jx, y1 + jy# Interpolate along the path to simulate continuous ink depositionsteps = int(math.hypot(x1-x0, y1-y0))for s in range(steps):t = s / max(steps, 1)px = x0 + (x1 - x0) * tpy = y0 + (y1 - y0) * t# Wetness falloff: the color fades as the stroke progressesalpha = wetness * (1 - 0.3 * t)canvas.blend(px, py, color, alpha, brush_width=width)
The key point of this code is that color is not painted by direct overwrite but layered on with a certain transparency, and the transparency decays as the path progresses. This is a direct expression of “the paint gradually running out.”
2.3 Stage Three: Irreversible Strokes Force the Model to Think Before It Draws
One design decision that is often emphasized is this: once a stroke lands on the canvas, it cannot be undone. The constraint looks harsh, but it is deliberate. The reasons are:
- If undo were allowed, the model would easily fall into repeated trial and error, and the generated stroke sequence would lose coherence.
- Irreversibility forces the model to do more thorough internal planning before committing a stroke.
- Real painting is itself an overwrite-based process — mistakes are usually fixed by covering them with new strokes, not by erasing.
This also means the program’s architecture needs to support “append-only, no delete” canvas operations.
2.4 Stage Four: Look at the Canvas and Iterate
Drawing is never finished in one pass. After each stage, the system takes a “look” at the current canvas and judges whether something is wrong. For example:
- The lines on a bird’s back are too thin → add thicker strokes over them;
- A patch of color is too dark → overlay a lighter color to neutralize it;
- Proportions are off → paint in new shapes to rebalance the composition.
From an engineering perspective, this step requires rendering the current canvas into image data that can be read back, then handing it to the model for a “visual check.” In other words, the system is actually running a “generate — render — observe — revise” loop.
3. Why This Approach Can Develop an Independent Style
A traditional generation model’s style usually comes from its training data, so it can inadvertently imitate an existing artist’s established style. Code-driven drawing is different: its style comes from the brush rules themselves.
When a system is asked to “design an artist with a fictional background and a stable creative style,” the model produces a self-consistent rule set, for example:
artist_persona:name: "A fictional painter who favors cool tones"traits:- Short, brisk strokes with deliberate blank space at corners- Shadows use low-saturation blue-purple rather than pure black- Highlight strokes are extremely fine and distributed along shape edgesconstraints:- A single stroke width does not exceed 15 pixels (detail layer)- Dry paint for the background, wet paint for the subject
Once this rule set is fixed, it becomes a reproducible style filter: the same scene rendered with different rule sets produces a completely different visual character. Moreover, because the rules are explicit, the style can be reviewed, inherited and combined — something diffusion models struggle to do.
More importantly, this approach naturally sidesteps the controversy of “style plagiarism”: it does not imitate any specific painter’s brushwork; it generates images under a self-consistent set of physics and aesthetic constraints.
4. The Engineering View: Turning Code-Driven Drawing into a Reusable Capability
To ship this kind of capability in a real project, several layers need to be considered.
4.1 Canvas and Rendering Engine
The canvas is the foundation of the whole system. A usable design should include:
- Layer management: draw background, subject and detail layers separately to make iteration easier.
- Pixel buffer: support efficient alpha blending rather than simple overwrite.
- Texture mapping: preset a roughness for the canvas that affects how paint settles.
- Render export: export the buffer to common image formats.
A sketch of the interface design:
class Canvas:def __init__(self, width, height, bg=(255, 255, 255)):self.width, self.height = width, heightself.buffer = [[bg for _ in range(width)] for _ in range(height)]self.layers = {}def create_layer(self, name):self.layers[name] = [[None for _ in range(self.width)] for _ in range(self.height)]def blend(self, x, y, color, alpha, brush_width):# Perform alpha blending in the neighborhood using brush_width as the radius...def export(self, path):# Write the buffer to an image file...
4.2 The Stroke Instruction Protocol
To let the model “issue instructions” reliably, a concise protocol needs to be defined. Instructions should not be too complex, or the model will make mistakes. A pragmatic approach is a JSON array where each instruction carries only the necessary fields:
{"stroke_id": 1,"brush": "round_soft","color": "#30346a","width": 90,"wetness": 0.6,"points": [[120, 80], [126, 82], [130, 79]]}
At the same time, the program should strictly validate instructions: are the coordinates out of bounds, is the color legal, does the stroke count exceed the budget? When validation fails, execution should be rejected outright rather than silently tolerated.
4.3 The Feedback Loop and the “Look at the Picture” Mechanism
The feedback loop is the soul of such a system. One workable implementation:
- Every N strokes (say, every 1,000 strokes), render a thumbnail.
- Submit the thumbnail together with current stroke statistics (for example, “too few strokes in the bird’s back area”) to the model.
- The model returns the next batch of stroke instructions, or returns revision suggestions such as “adjust the brush width” or “add highlights.”
- Loop until the stroke budget is reached or the image quality target is met.
Illustrative code:
while strokes_used < BUDGET:batch = model.plan_next_strokes(canvas.thumbnail(), context=stats)for s in batch:canvas.draw(s)strokes_used += 1stats = summarize(canvas) # Compute color distribution, regional density, etc.if stats.quality_ok:break
4.4 Performance and Cost Considerations
The overhead of this approach needs to be assessed objectively:
- Compute volume: hundreds of thousands to over a million strokes mean a large number of small drawing operations. An ordinary CPU can handle them, but the time may reach minutes or even longer.
- Model call volume: if the model is invoked at every stage for planning and checking, token consumption and latency rise significantly.
- Storage: the stroke instruction sequence is itself text — small in size, easy to compress and suitable for archiving and reproduction.
A common optimization direction, therefore, is to separate coarse-grained planning from fine-grained rendering: the model only produces a structured stroke plan (dozens to a few thousand strokes), and a local program expands it into hundreds of thousands of concrete strokes. This lowers model call costs while preserving reproducibility.
5. Practical Advice: How to Try It Yourself
If you want to validate this idea in your own project, you can proceed in the following order:
- Build a minimal canvas first: implement a two-dimensional buffer that supports alpha blending and export it as a PNG.
- Implement two or three brushes: a round soft brush, a flat dry brush and a fine-line brush, each corresponding to a different texture.
- Define the stroke protocol: start with the simplest
{color, width, points}and gradually add wetness and pressure. - Wire in a planner: first use a hand-written script to generate strokes and verify the rendering, then replace it with model-based planning.
- Add the observation loop: first implement “render a thumbnail + print statistics,” then connect the model for visual checking.
- Control the budget: set upper limits on stroke count and iteration rounds to avoid infinite loops.
- Record and reproduce: save every batch of stroke instructions so that any drawing can be fully replayed.
During the validation phase, it is advisable to start with a subject that has a clear structure and controllable stroke requirements — such as still lifes or simple geometric compositions — and then move on to complex scenes.
6. Limitations and an Objective Assessment
This approach is not a cure-all, and its boundaries need to be viewed rationally:
- There is a ceiling on photorealistic detail: limited by the brush model and rendering precision, extremely photorealistic results still require a large number of strokes.
- Long-range consistency is hard to guarantee: after hundreds of iterations, local drift easily appears in the image and additional structural constraints are needed.
- Debugging costs are high: when the result is unsatisfactory, it is not easy to pinpoint whether the planning is wrong or the rendering is wrong.
- It does not fit every scenario: for illustration that demands extremely rich texture, or posters that need precise text layout, code-driven drawing is not the best solution.
A more realistic positioning, then, is this: it is a complementary capability that offers explainable processes, constrainable style and reproducible results, well suited to stylized creation, teaching demonstrations and auditable generation pipelines — not a wholesale replacement for traditional image generation models.
Conclusion
The value of “no image model, just code painting stroke by stroke” does not lie in whether it can beat diffusion models on speed or realism. It lies in providing a new kind of controllability: every step of the drawing is an explicit program behavior that can be recorded, reviewed, intervened in and reproduced. It translates “generating an image” from a black-box problem into an engineering problem built from planning, simulation, feedback and iteration.
For developers, this is both an interesting technical experiment and an engineering topic worth digging into. If you are exploring controllable generation, stylized rendering or explainable AI, start with a “virtual brush” and verify for yourself how far this path can go.
