DEV Community

Cover image for Scanning Tread Wear Indicators: Two ONNX Detectors (Grid + Heatmap)
Silver Kernel
Silver Kernel

Posted on Edited on

Scanning Tread Wear Indicators: Two ONNX Detectors (Grid + Heatmap)

This is Part 3 of the Hawk Eye series. Part 1 covers depth post-processing in pure NumPy, and Part 2 covers passive rangefinding. "Hawk Eye" is the internal codename. The Gatekeeper and TWI detection layer described here is available on TyreCam AI (free scans are limited, and a free account unlocks more).

What TWI is

TWI stands for Tread Wear Indicator. These are small molded bridges at the bottom of the main tire grooves.

Their height is 1.6 mm (2/32 inch), which is the minimum legal tread depth in many regions. When the tread wears down to the bridge, the tire is at its limit.

For a photo-based depth estimate, a visible TWI gives us two things: a 1.6 mm reference point and a confidence signal. Finding these small marks in a photo automatically is the job of two trained neural networks. They are exported as ONNX models, a portable file format that runs without the training framework. This article explains how they work and why there are two.

Pipeline in one picture

Three terms appear in the picture. The ROI (region of interest) is the crop of the photo that contains the tread. Fusion is the step that combines several wear estimates into one result. The HUD (heads-up display) is the overlay drawn over the photo.

photo -> Gatekeeper --STOP--> return (strip on the photo)
              |
              v  ok / cracks
          tread ROI
              |
     +--------+--------+
     |                 |
     v                 v
 Grid 7x7         Heatmap U-Net
     |                 |
     +--------+--------+
              v
   merge -> TWI count -> fusion -> HUD
Enter fullscreen mode Exit fullscreen mode

The diagram leaves out the depth network (512x512 input). In the ROI call it runs first, one step after another. Everything runs on the CPU with ONNX Runtime (no GPU).

Grid and Heatmap are not stages one after another. They look at the same crop, and their results are merged. The only real cascade is Gatekeeper -> detectors.

Stage 0: the Gatekeeper

The Gatekeeper is a small classifier (MobileNetV4, timm mobilenetv4_conv_small). A classifier looks at a whole photo and picks one label from a fixed list. Here there are 7 labels: not_tire, ok, cracks, hernia, exposed_cord, puncture_cut, flat_tire.

Its purpose is simple: do not waste analysis on a bad photo. There are three outcomes:

  • ok: the analysis continues.
  • cracks: an amber warning plate appears and the analysis continues. This is a flag for the whole photo. It does not locate the crack.
  • Any other class: STOP. not_tire gets a yellow strip, and the others get a red "operation prohibited" strip. The analysis returns immediately.

The verdict is the class with the highest probability.

Gatekeeper STOP outcomes: flat tire, sidewall hernia, exposed cord, not a tire

Stage 1: two TWI detectors, and why two

Here are two analogies to make the difference clear.

Grid detector: "which square?" (analogy)

The ROI is resized to 224x224 pixels and cut into a 7x7 grid of cells, 32 px each. For every cell the network answers three questions: is there a TWI here, where exactly inside the cell, and how big is it. The output has shape (5, 7, 7): confidence (how sure the network is), dx, dy, width and height.

The backbone is ResNet18 (a standard image network) with a small head. A cell with confidence of at least 0.45 becomes a box. There is one box per cell and no NMS (non-maximum suppression, the step that removes duplicate boxes). The strength of Grid is that one pass gives ready boxes.

Heatmap detector: "where exactly?" (analogy)

This is a U-Net with a ResNet18 encoder. A U-Net is a network that outputs an image instead of a label. Here the output is a 224x224 map with a bright spot wherever a TWI center is likely.

For training, every labeled TWI center gets a Gaussian blob (a soft round spot) with sigma = 6 px. At the 0.35 threshold the blob is about 17 px wide in the training target.

Labels are made by hand: the author clicks the center of each TWI, and the box is created automatically.

TWI labeling tool: one click on each TWI center

The strength of Heatmap is a per-pixel answer, so the position is not limited to the cell structure. The cost is that we must pull the bright spots out of the map ourselves. That is the next section.

Why two. They are two different ways of looking at the same crop: boxes on a coarse grid, and a pixel-level map. When both point at the same place, the merge counts it once. Points found by only one detector are kept too.

How well do they work. On our test photos, both networks find TWI reliably. This is the author's visual check. Formal precision and recall were not measured, because there is no separate validation set.

Training in short: Grid uses the TWIGridLoss loss with lambda_coord=5.0 and lambda_noobj=0.5. Heatmap uses MSE loss. Both use only color jitter (random color changes on training photos) as augmentation, and both train with the Adam optimizer at learning rate 0.001.

Peak finding: from a bright map to points

The heatmap is a gray image, and we need the coordinates of its bright spots. A pixel counts as a peak if two things are true: its value is at least 0.35, and it is the maximum inside a 9x9 window around it.

# From labeler.py (reformatted, same logic).
def find_local_maxima(hm, threshold=0.35, k=7):
    h, w = hm.shape
    r = k // 2
    peaks = []
    for y in range(h):
        for x in range(w):
            v = hm[y, x]
            if v < threshold:
                continue
            win = hm[max(0, y - r):y + r + 1, max(0, x - r):x + r + 1]
            if v >= win.max():
                peaks.append((x, y, float(v)))
    return peaks
Enter fullscreen mode Exit fullscreen mode

The call site passes k=9. The peaks come out in 224x224 coordinates and are scaled back to the photo.

The merge: two detectors, one list

Take every Grid box and look for a Heatmap point within 20 px. There are three possible results:

  • consensus: a pair found by both (the center is the average of the two),
  • solo Grid: only Grid saw it,
  • solo Heatmap: only Heatmap saw it.
# Simplified: the same greedy logic as in labeler.py.
def merge_twi_detections(grid_boxes, heatmap_points, distance_threshold=20.0):
    consensus, solo_grid, used = [], [], set()
    for g in grid_boxes:
        for hi, h in enumerate(heatmap_points):
            if hi in used:
                continue
            if np.hypot(g[0] - h[0], g[1] - h[1]) <= distance_threshold:
                used.add(hi)
                consensus.append((int((g[0] + h[0]) / 2),
                                  int((g[1] + h[1]) / 2),
                                  min(1.0, (g[4] + h[2]) / 2.0 + 0.15)))
                break
        else:
            solo_grid.append(g)
    solo_hm = [h for hi, h in enumerate(heatmap_points) if hi not in used]
    return consensus, solo_grid, solo_hm
Enter fullscreen mode Exit fullscreen mode

The TWI count is n_twi = consensus + solo_grid + solo_hm, so a matched pair is counted once, not twice. This is the number shown on the HUD.

A matched pair also gets a +0.15 confidence bonus. The next function, extract_twi_coords, passes on only the coordinates, so the fusion works with the count.

The merge is greedy: each Grid box takes the first free Heatmap point within 20 px, so the result can depend on the order of the lists. Example with four points on one line: Grid G1 at x = 0 and G2 at x = 25, Heatmap H1 at x = 18 and H2 at x = -15 (list order H1, H2). G1 takes H1, G2 then finds nothing within 20 px. The result is 1 pair, although G1-H2 and G2-H1 would give 2. Matching the closest pairs first would avoid this; the app does not do it today.

The constants 0.45, 0.35, the window 9, 20 px and +0.15 are set in code, origin not recorded.

What TWI gives the depth estimate

TWI is the 1.6 mm reference point. The HUD shows a depth scale from 1.6 mm to 8.0 mm.

The fusion step combines several wear estimates (the 3D engine, the Wear network and others) into one result. When at least one TWI is found, the system trusts the 3D depth estimate more:

  • 3D engine (Tire3DEngine.delta_to_mm). Without TWI: mm = max(mm_3d, 0.75 * d_class). With TWI: mm = 0.85 * mm_3d + 0.15 * d_class. The result is clipped to 1.6-10 mm. Here mm_3d is the 3D depth estimate, and d_class is the class-based depth value from the Wear network (a separate network that classifies wear).
  • Fusion (SilverKernelUnifiedFusion.fuse). When n_twi >= 1, the multiplier m_twi = 1.25 raises the weight of the 3D estimate (capped at 0.85).

Today the fusion uses TWI as "at least one found". Using the count and the confidence more finely is a direction for future work.

We use TWI as a reference and a confidence signal; we do not claim it improves depth accuracy.

The HUD

The HUD is drawn in two layers:

  • PIL ImageDraw draws on the photo itself: Grid boxes in blue (#00C8FF) and Heatmap rings in pink (#FF00A0) with a yellow center.
  • QPainter in paintEvent (PyQt6 drawing) adds the HUD blocks and the cracks plate on top.

The HUD shows tread depth in mm and tread life in percent, a line with the number of matched, solo Grid and solo Heatmap detections, a depth scale from 1.6 mm to 8.0 mm, and a block with model agreement and rangefinder optics from Part 2.

It is not an animation and not real time: the HUD is drawn once per analysis. In the app this panel is called "Terminator Vision". It is a joke name for the overlay: boxes, rings and plates drawn over a photo.

Terminator Vision: the full HUD on one analyzed photo

One analyzed photo: depth 5.6 mm, tread life 63%, usable remainder 4.0 mm. The TWI line reads 1 matched, 2 solo Grid, 3 solo Heatmap.

Speed on CPU

Setup: Python 3.13.12, NumPy 2.5.4, Pillow 12.1.1, ONNX Runtime 1.31.0, Windows 11, Intel64 Family 6 Model 154 Stepping 4, 8 logical CPUs, no GPU. Laptop or desktop and power mode: not recorded.

One 480x640 photo was used, whole frame (not an ROI). Each step was timed by repeating it on the same photo, and the table shows the median time. Most steps ran 2000 timed repeats; the depth network ran 200, and the peak finder and the end-to-end run ran 400. We made two full runs. Times are in ms:

Step Run 1 Run 2
Gatekeeper 1.65 1.64
Grid 11.70 57.79
Heatmap 29.84 27.78
Peak finder (real heatmap) 15.51 12.64
Merge (3 Grid boxes, 3 Heatmap points) 0.049 0.041
End-to-end TWI run 185.6 198.9

In plain words:

  • The end-to-end TWI run takes about 0.19-0.2 s on the CPU described above, with no GPU.
  • The merge costs a fraction of a millisecond, and the peak finder 13-16 ms.
  • The depth network is the heaviest step, about 0.84-0.88 s per call. It is not part of the end-to-end TWI run.

One note: the same step can differ between runs (Grid: 11.70 ms in run 1, 57.79 ms in run 2), so treat these numbers as indicative.

Not measured: HUD paintEvent, fusion, the 3D engine, the rangefinder, multi-tire ROIs.

Limitations

  1. There is no separate validation set for the TWI detectors, so precision and recall were not measured.
  2. The constants 0.45, 0.35, 9, 20 px, +0.15 are set in code, origin not recorded.
  3. The 20 px merge threshold is fixed and does not depend on the ROI size.
  4. cracks marks the whole frame and has no localization.

Takeaways

  • Two different views of one crop (boxes and a pixel map) are merged into a single TWI list.
  • A heatmap needs a peak finder. Ours is a simple local-maximum rule.
  • A TWI gives a 1.6 mm reference and shifts the system toward the 3D estimate.
  • Greedy matching depends on list order: "first free within a threshold" is not "nearest".
  • Measure before you claim: we show our own timings, including the unstable ones.

In Part 4 we move inference (running the networks) and drawing off the GUI thread (the thread that keeps the window responsive). Today inference runs in the GUI thread, so the window is blocked while it runs.

Top comments (2)

Collapse
 
userxnom profile image
Abdullah Naseer •

The honesty in this one is what makes it worth reading, Silver Kernel — most posts would have buried 'no separate validation set, so precision and recall were not measured' and moved on, and you put it in the limitations list along with the constants having no recorded origin. That is exactly the kind of post other builders can actually learn from. Two things I would love to see next. First, the 20 px merge threshold is fixed while the ROI size varies — a 20 px match means something different on a close-up tire than on a distant one, so have you tried scaling it to a fraction of the ROI width and watching whether your consensus counts move? Second, on your own takeaway that greedy matching depends on list order: sorting the Grid boxes by confidence descending before the greedy pass would let the strongest box claim its nearest Heatmap point first, instead of whichever box happens to come first. Which of those two would you expect to move the numbers more — the scaled threshold, or the confidence-ordered merge?

Collapse
 
silver_kernel profile image
Silver Kernel •

Thanks, glad it was useful. Both ideas are reasonable, and I haven't tried either, so I can't say which would move the numbers more. I'd rather not guess without measuring. I'll keep them in mind for a possible follow-up.