7 min read

The Model Handles Meaning, OpenCV Handles Geometry

Turning a diagram image into an editable diagram by letting a vision model read it, OpenCV measure it, and an editable JSON file sit between them.
Drafting table with transparent stool and wooden sawhorses
Photo by Brecht Corbeel on Unsplash

I wanted to take a picture of a diagram (a whiteboard photo, a screenshot from a slide deck) and get back an editable draw.io file. Real boxes I can drag, real text I can fix, real connectors that stay attached when I move things.

My first attempt was the obvious one: show the image to a vision model and ask it to draw the diagram. It got most of the way there quickly, and then I spent a long time on the last part. The model read the diagram well. It just couldn't place it accurately.

Fixing that came down to one idea: the model handles meaning, classic computer vision handles geometry, and a plain JSON file sits between them where I can read and edit it.

What the model is good at, and what it isn't

A vision model is very good at the semantic part of a diagram. It can tell you there are twelve boxes, that one says "Auth service" and another says "Postgres", that an arrow goes from the first to the second and has the label "reads". It understands that a dashed outline around four boxes is a group. That is the hard part of the problem, and it gets it right most of the time.

Ask it for exact pixel coordinates and it gets vague. The boxes come back roughly in the right place: same column, about the right size. They are rarely exact. They're off by ten or twenty pixels, sometimes overlapping, sometimes a little too narrow for their text. In an editable diagram that shows immediately: lines that should be straight are crooked and rows that should line up don't.

OpenCV has the opposite profile. Run edge detection and contour finding over the image and you get rectangles accurate to the pixel. But OpenCV has no idea what any of them mean. It can't tell a service box from a legend or a text background, and it can't say which rectangle the arrow is pointing at.

Each tool is strong where the other is weak, so I stopped asking either one to do the whole job.

The split

The pipeline has three stages, and only one of them involves a model.

  1. Extract meaning. The vision model gets the image plus its real pixel dimensions and returns JSON: nodes with a label, a type and an approximate bounding box, and edges that refer to nodes by id.
  2. Fix geometry. OpenCV finds every rectangle-like contour in the image. Each node the model returned is matched to the detected rectangle it overlaps most, and if the match is good enough the node takes that rectangle's exact coordinates. Text, type and connections still come from the model.
  3. Generate. Plain code turns the JSON into draw.io XML: one shape per node at its coordinates, one connector per edge bound to its source and target shapes.

The intermediate representation is deliberately boring:

{
  "canvas": {"width": 1600, "height": 900},
  "nodes": [
    {"id": "api", "label": "API", "type": "service",
     "bbox": {"x": 412, "y": 180, "w": 140, "h": 60}},
    {"id": "db", "label": "Database", "type": "database",
     "bbox": {"x": 690, "y": 182, "w": 130, "h": 64}}
  ],
  "edges": [
    {"source": "api", "target": "db", "label": "reads"}
  ]
}

Snapping

The snapping step is small. For each node, find the detected rectangle with the highest intersection-over-union (IoU), and accept it only above a threshold:

def iou(a, b):
    ix = max(0, min(a.x + a.w, b.x + b.w) - max(a.x, b.x))
    iy = max(0, min(a.y + a.h, b.y + b.h) - max(a.y, b.y))
    inter = ix * iy
    return inter / (a.w * a.h + b.w * b.h - inter) if inter else 0.0

def snap(nodes, rects, min_iou=0.3):
    used = set()
    for node in nodes:
        best = max(rects, key=lambda r: iou(node.bbox, r), default=None)
        if best and iou(node.bbox, best) >= min_iou and id(best) not in used:
            node.bbox = best      # geometry from pixels
            used.add(id(best))    # meaning stays from the model
    return nodes

A few details turned out to matter. The threshold is low on purpose: the model's guess only has to be in the right neighbourhood, and 0.3 is loose enough to catch a box that's off by a fair margin. Each detected rectangle can be claimed once, so two nodes can't collapse onto the same shape. And a node with no good match keeps the model's estimate instead of being dropped. A slightly crooked box is better than a missing one.

Detection needed some care too. A single threshold misses boxes with light borders or coloured fills, so I run three masks (adaptive threshold, Canny edges, Otsu), merge what they find and remove duplicates. I also stopped requiring exactly four corners. A rounded rectangle gives a contour with more vertices, so I accept anything that fills most of its bounding rectangle.

On the first real image I tried, a dense architecture diagram, OpenCV found 44 rectangles and 23 of the 35 nodes the model returned snapped to one. The other 12 kept the model's approximate boxes. Those are the cases you'd expect: icons and shapes that aren't closed rectangles, and a few boxes the model put far enough off that nothing overlapped them well enough. Getting about two-thirds pixel-exact is not perfect, but it changed the output from "roughly right everywhere" to "exactly right in most places, roughly right in the rest". An overlay of the detected boxes on the source image showed me which was which in seconds.

I built the back half first

The order I built things in mattered as much as the split.

Before writing any model call, I wrote a JSON file by hand for one sample image and built the generator against it. That meant 32 boxes and 22 lines, rendered and checked in draw.io, plus tests that round-trip the JSON to XML without a network call. Only after that did I write the extractor.

That turned the uncertain part into something I could measure. When I started prompting the model, I had a working generator and a known-good IR to diff against. If the output looked wrong, I could open the JSON and see in a minute whether the model had misread the image or my generator had drawn it badly. Without the IR, both would show up the same way: an ugly diagram, and no clue which half to blame.

The JSON in the middle is also where I fix things by hand. If the model misreads a label or misses an edge, I edit one line and rerun the generator. That takes milliseconds, costs nothing and gives the same result every time. I don't have to call the model again and hope it does better.

Trade-offs

  • More moving parts. A model-only pipeline is one call. This one has a detector with thresholds to tune, a matching step and a schema to keep in sync with the prompt.
  • The CV step only helps with what it can see. Hand-drawn whiteboard boxes with gaps in the strokes, or diagrams made mostly of icons, snap poorly. In those cases you fall back to the model's estimates.
  • Snapping can be confidently wrong. A low threshold catches more boxes but can sometimes grab a neighbouring rectangle. I treat the CV pass as best-effort and keep the overlay as a quick visual check.
  • The IR can lose information. Anything the schema has no field for, such as a line's routing or a custom shape, never reaches the output. The schema has to grow as the diagrams get richer.

Takeaway

When a task has a fuzzy part and a precise part, don't ask a model to do both. Give the model the meaning, give deterministic code the measurements, and put an editable file between them. Build and test the deterministic half first, so the model's output has a known-good target to compare against.