How Vision-Language Models Turn Images into TikZ Drawing Code
This article explains why converting a figure into executable TikZ code is harder than image classification. It covers three core difficulties: determining the drawing order of overlapping objects, mapping pixel positions to drawing coordinates, and keeping line styles and fills consistent with the source image. It also outlines an evaluation framework and practical engineering steps, including a generate, validate, and repair workflow, LoRA fine-tuning for specific visual styles, and overlapping tile processing for high-resolution images.
Introduction: From Seeing Images to Drawing Them
Multimodal large language models already perform reasonably well on image captioning and object recognition. A harder task is converting a figure into drawing code that can be executed. TikZ is a declarative drawing language in the LaTeX ecosystem. It describes figures with coordinates, paths, line styles, and fill commands, and it depends strictly on the order in which commands are written to determine how layers overlap.
This article does not evaluate any unpublished model, and it does not cite performance figures that cannot be verified. Instead, it discusses the general challenges of this task and how developers can measure and improve model performance on their own.
1. Why This Task Is Harder Than Image Classification
The output of image classification is a single label. If the label is wrong, the error is limited to one wrong answer. Drawing code must satisfy three requirements at the same time.
The first is syntax. The code must compile. Brackets, command names, and argument formats all need to be correct.
The second is geometry. Every coordinate must fall in a reasonable position, and line lengths and proportions must match the original figure.
The third is layering. Paths written later cover paths written earlier, so the model must understand which objects are in front and which are behind.
These three types of errors often appear together in real output. A piece of code may compile, yet the figure has the wrong proportions and the occlusion relationships are reversed. For this reason, evaluation should count syntax, geometry, and layering errors separately. Checking only whether the figure can be drawn at all is not enough.
2. Three Core Difficulties
1. Occlusion and Drawing Order
TikZ draws commands one by one in the order they are written. If a background circle is written after a foreground square, the circle’s fill will cover the square. The model must determine the depth relationships among objects before it generates the code.
Computer graphics often handles this problem with the painter’s algorithm, which sorts objects from far to near and draws them in that order. For a single two-dimensional image, the model must infer the depth order from occlusion cues. Common cues include a line that stops where it meets another line (a T-junction), or the boundary of one region being cut off by another object.
There are two common types of error. In the first, the fill of a foreground object is covered by the outline of a background object. In the second, a hidden line that should be occluded is drawn on top of a foreground object. For evaluation, each sample can be annotated with its correct drawing order, and the proportion of samples with incorrect order can be counted.
2. Mapping Pixel Coordinates to Drawing Coordinates
Positions in an image are integer pixels, while TikZ coordinates use units specified by the user, such as cm or pt, and can be adjusted with scaling parameters. As a result, the coordinates the model outputs need one linear transformation.
One workable approach is to select two or three reference points in the image whose real distances are known, and then calculate the scale factor and offset from pixels to drawing units. Contours can then be processed on this basis.
Contours usually come from segmentation masks. A mask boundary contains many points. If the model outputs them directly, the code becomes long and full of noise. Douglas-Peucker polygon simplification can reduce the number of points first. After that, Bézier curves can be fitted to produce smooth curve segments. The fitting process requires an error tolerance, for example a deviation of no more than a few pixels. If the tolerance is too large, detail is lost. If it is too small, too many control points are generated.
3. Consistency of Line Style and Fill Attributes
Attributes in drawing code include solid and dashed lines, fill colors, and transparency. The model needs to understand what these attributes mean in the source image. For example, a dashed line in a schematic usually represents a hidden edge or an auxiliary line, but in an engineering drawing it may represent a dimension line or a centerline.
The same visual style can have different meanings in different drawings. For this reason, prompts should state line style rules explicitly, such as “occluded edges use dashed lines,” and the model’s compliance should be tested with annotated examples.
3. Evaluation Framework
Evaluation should cover three dimensions. Each dimension needs a definition, a method, and metrics. The following section describes only the framework. No measured results are provided.
Dimension 1: Structural Correctness
- Test method: Use geometric figures that contain crossings, nesting, and closed paths, such as polyhedron projections and ring structures.
- Metric definition: Compilation success rate equals the number of compilable samples divided by the total number of samples. The path closure rate and the rate of out-of-bounds coordinates should also be counted separately.
- Notes: Record the LaTeX distribution, the TikZ version, and the compilation command. The same code may produce different results under different versions.
Dimension 2: Semantic Consistency
- Test method: Provide images with explicit semantic requirements, such as “a shaded sphere on a grid background.”
- Metric definition: Attribute match rate equals the number of correct output attributes divided by the total number of annotated attributes. Attributes include line style, fill color, transparency, and clipping boundaries.
- Notes: At least two people should annotate attributes independently, and the method for handling disagreements should be recorded.
Dimension 3: Complex Hierarchical Reasoning
- Test method: Use diagrams with nested multi-component structures, and ask the model to output the stacking order and connection relationships of the components.
- Metric definition: Stacking order accuracy and the F1 score for connection relationships. Component complexity is grouped by the number of components, for example fewer than 5, 6 to 15, and more than 15.
- Notes: Grouped statistics show the complexity range where model performance starts to decline noticeably.
Evaluation Record Template
The table below records the basic information for each evaluation run. If no measured data is available, leave the “Measured result” column blank. Do not cite other people’s numbers.
| Item | Description | Recommended Record | Measured Result |
|---|---|---|---|
| Test set size | Total number of samples and the count for each figure type | For example, at least 30 samples per type | To be added |
| Tool versions | Compiler and TikZ versions | Record the distribution name, version number, and compilation command | To be added |
| Metric definitions | How each metric is calculated | Specify what the numerator and denominator represent | To be added |
| Pass threshold | Minimum value for a passing result | Determined by business requirements, with the reasoning stated | To be added |
| Failure cases | Typical errors, with images and code | Save the input, output, and compilation log | To be added |
| Scope of validity | The range over which the conclusions apply | Figure types, resolution, and the TikZ syntax subset | To be added |
To compare different models, use the comparison table below and run the tests on the same test set with the same tool versions.
| Metric | Model A | Model B | Test Conditions |
|---|---|---|---|
| Invalid instruction rate | To be added | To be added | Same test set, same compilation environment |
| Coordinate error (pixels) | To be added | To be added | Same reference point calibration method |
| Occlusion order error rate | To be added | To be added | Same depth annotations |
4. Engineering Recommendations
1. Build a Generate, Validate, and Repair Workflow
Model output should not be passed directly to users. A safer approach is to treat the model as a sketch generator and complete the following steps in an external program.
Step one: compile the code in a sandbox. Disable shell escape during compilation (for example, with -no-shell-escape). When shell escape is enabled, TikZ can run system commands, which creates a security risk.
Step two: check the code structure. Coordinates should be numeric, paths should have clear start and end points, and option names should be on an allowlist. A parser can build a syntax tree so that each node can be checked.
Step three: when compilation fails, return the compiler error message to the model and allow a limited number of repair attempts, for example up to two. If the number of repair attempts exceeds the limit, keep the last compilable version and send it for manual review.
2. Use LoRA to Adapt to Specific Figure Styles
If a business’s figures follow a fixed style, such as a particular icon library for architecture diagrams or a set of circuit symbols, prompt engineering is often not stable enough. Parameter-efficient fine-tuning with LoRA can be used instead.
The values below are only starting search ranges and should be tuned on a validation set. LoRA rank can start at 8 or 16, and the learning rate can be searched between 1e-4 and 2e-4. Training usually needs hundreds to thousands of examples, and an independent validation set must be held out. After fine-tuning, compare the model with the untuned baseline to confirm that it actually improves. The copyright and licensing status of the training data should also be confirmed in advance.
3. Tiling Strategy for High-Resolution Images
For high-resolution images with dense layouts, direct downsampling loses thin dashed lines and faint boundaries. A better approach is to split the image into overlapping tiles, with an overlap of 10% to 15%. The offset of each tile must be recorded so that local coordinates can be mapped back to full-image coordinates.
After tiling, check for duplicate elements. Shapes that lie on a tile boundary may be output twice, so they should be deduplicated by coordinates.
5. Open Questions
Two issues are worth continued observation.
The first is context consistency in long code. When drawing code runs to hundreds of lines, can the model reuse variable names correctly and keep the coordinate system consistent? Multi-page diagrams can be designed as test cases, and the variable reuse rate and the number of undefined variable occurrences can be counted.
The second is generalization to unseen symbols. Testing can include abstract symbols that do not appear in the training set. The question is whether the model simply reproduces known patterns or can make reasonable variations based on figure structure. The pass rate on new symbols can be measured, and failure cases can be saved for analysis.
6. Verification Notes
- TikZ syntax descriptions in this article are based on the official PGF/TikZ manual. When reading, check the documentation for the version you use.
- This article does not cite test figures for any specific model. All values are starting references or metrics to be measured.
- Test images should include their source and licensing status. When using public datasets, record the dataset name and version.
- Statistical results should report sample sizes. With small samples, conclusions are less reliable. Confidence intervals should be reported, or the results should be treated only as qualitative references.
- Evaluation conclusions apply only to the specific TikZ syntax subset, figure types, and resolution conditions tested. They cannot be generalized directly to other drawing languages or other image types.
