Choose a language and read the cells in order. These are small teaching examples; the visual lesson runs separately.
Follow the calculation
Same inputs · Same operation · Same result
3 teaching cells · Python standard library · Read-only
1. Prepare the candidate and the four adjustments
The candidate is the search window over the watermelon, as top-left corner plus width and height in picture pixels (origin top-left, y downward). The four adjustments are the trained box head's output for this window, copied at full precision; the reference box is not an input to them.
import json import math x, y, w, h = 48, 24, 80, 80 # candidate: search window 13 t = [-0.2061745477183015, 0.16483249426655214, -0.34782754792939563, -0.396589869704336] # tx, ty, tw, th from the box head2. Decode the predicted box, then measure IoU
Move the centre by tx widths and ty heights, multiply the sides by e to the tw and th, and convert back to corners. Only then compare with the reference, supplied separately: intersection sides are clamped at zero, union = area A + area B − intersection, and an empty union gives 0. Round only the report.
cx, cy = x + w / 2 + t[0] * w, y + h / 2 + t[1] * h pw, ph = w * math.exp(t[2]), h * math.exp(t[3]) pred = [cx - pw / 2, cy - ph / 2, cx + pw / 2, cy + ph / 2] # x1, y1, x2, y2 ref = [49, 52, 103, 103] # reference corners, supplied separately def iou(a, b): iw = max(0, min(a[2], b[2]) - max(a[0], b[0])) ih = max(0, min(a[3], b[3]) - max(a[1], b[1])) inter = iw * ih union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter return inter, union, (inter / union if union > 0 else 0) inter, union, value = iou(pred, ref) result = { "predicted": [round(v, 4) for v in pred], "intersection": round(inter, 4), "union": round(union, 4), "iou": round(value, 4), "window_iou": round(iou([x, y, x + w, y + h], ref)[2], 4), }3. Inspect the result
Print the result as JSON so both languages use the same output format.
print(json.dumps(result))
Expected result
Running the three cells in order produces this result in either language.
{
"predicted": [
43.2572,
50.2822,
99.7549,
104.091
],
"intersection": 2588.498,
"union": 3205.5721,
"iou": 0.8075,
"window_iou": 0.4303
}