Mini Project: A Shape Detector, End to End
This project builds a complete object detector and, more importantly, the evidence around it: a data set with annotations in a standard format, a baseline, a learned model chosen on the right validation data, a final score measured once, and an error analysis that says what to fix next. The objects are the course's synthetic squares, circles and triangles, so every step runs in your browser in seconds and the ground truth is exact. The story is a common one in real projects: the labelled data comes from one setting, the deployed camera sees another, and the model that wins on the first is not the one that survives the second.
The brief
| Task | detect squares, circles and triangles: class, box and score for every object in a 64 x 64 image |
| Training data | 300 images from the "lab rig": shapes always upright (make_scene, as in the rest of the course) |
| Validation and test | val (100) and test (200) images from the same rig |
| Deployment | the field camera is mounted at an angle, so squares and triangles appear rotated; a small labelled field_val set (60 images) and a field_test set (200 images) were collected there |
| Metric | AP@0.5 per class and their mean (mAP), as defined in detection metrics |
| Rules | thresholds and models are chosen on validation sets only; each test set is scored once, at the end; everything seeded |
The detector has the two-stage shape of Faster R-CNN, built from classical parts: proposals (candidate boxes) from the image, then a classifier that labels each proposal and gives it a score.
Step 1: the data and its annotations
The generator is the course's make_scene with one addition, a rotate option that turns squares and triangles by a random angle before they are drawn (circles look the same at every angle). Because it draws from the generator in a different order, its scenes are not the same as in other lessons. Each split gets its own images from one seeded stream, so no image is in two splits. The annotations are written in COCO format: boxes as [x, y, w, h], category ids from 1.
import numpy as np, cv2
CLASSES = ["square", "circle", "triangle"]
def make_scene(rng, size=64, max_objects=3, rotate=False):
"""The course's shape scenes, with an option to rotate squares and triangles by a random angle."""
img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
n = int(rng.integers(1, max_objects + 1))
boxes, labels, masks = [], [], []
for _ in range(100):
if len(boxes) == n:
break
s = int(rng.integers(12, 25)); cx, cy = rng.uniform(0.75 * s, size - 0.75 * s, 2)
c = int(rng.integers(0, 3)); a = rng.uniform(0, 2 * np.pi) if rotate else 0.0
m = np.zeros((size, size), np.uint8)
if c == 1:
cv2.circle(m, (int(cx), int(cy)), s // 2, 1, -1)
else:
v = np.array([[-1, -1], [1, -1], [1, 1], [-1, 1]] if c == 0 else [[0, -1], [-1, 1], [1, 1]]) * s / 2
rot = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])
cv2.fillPoly(m, [np.round(v @ rot.T + [cx, cy]).astype(np.int32)], 1)
ys, xs = np.nonzero(m)
b = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]
if any(b[0] < o[2] + 2 and o[0] < b[2] + 2 and b[1] < o[3] + 2 and o[1] < b[3] + 2 for o in boxes):
continue
img[m > 0] = rng.integers(0, 256, 3)
boxes.append(b); labels.append(c); masks.append(m > 0)
return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)
rng = np.random.default_rng(0)
train = [make_scene(rng) for _ in range(300)] # upright, from the lab rig
val = [make_scene(rng) for _ in range(100)]
test = [make_scene(rng) for _ in range(200)]
field_val = [make_scene(rng, rotate=True) for _ in range(60)] # rotated, from the deployed camera
field_test = [make_scene(rng, rotate=True) for _ in range(200)]
import json
def to_coco(scenes):
coco = {"images": [], "annotations": [], "categories": [{"id": k + 1, "name": n} for k, n in enumerate(CLASSES)]}
for i, (img, boxes, labels, masks) in enumerate(scenes):
coco["images"].append({"id": i, "file_name": f"{i:05d}.png", "width": img.shape[1], "height": img.shape[0]})
for (x1, y1, x2, y2), l, m in zip(boxes.tolist(), labels.tolist(), masks):
coco["annotations"].append({"id": len(coco["annotations"]) + 1, "image_id": i, "category_id": l + 1,
"bbox": [x1, y1, x2 - x1, y2 - y1], "area": int(m.sum()), "iscrowd": 0})
return coco
for name, ds in [("train", train), ("val", val), ("test", test), ("field_val", field_val), ("field_test", field_test)]:
labels = np.concatenate([s[2] for s in ds])
print(f"{name:10s} {len(ds):3d} images {len(labels):3d} objects per class {np.bincount(labels, minlength=3).tolist()}")
coco = to_coco(train)
print(json.dumps(coco["annotations"][0]))
sides = np.array([a["bbox"][2:] for a in coco["annotations"]])
print("box side in pixels: min", sides.min(), "median", np.median(sides), "max", sides.max())train 300 images 611 objects per class [185, 232, 194]
val 100 images 206 objects per class [62, 77, 67]
test 200 images 402 objects per class [125, 142, 135]
field_val 60 images 127 objects per class [42, 39, 46]
field_test 200 images 386 objects per class [93, 148, 145]
{"id": 1, "image_id": 0, "category_id": 3, "bbox": [13, 24, 25, 25], "area": 325, "iscrowd": 0}
box side in pixels: min 13 median 17.0 max 25
About 2 objects per image, roughly balanced classes, and small objects: a median box side of 17 pixels. The field sets have the same mix. Note the first annotation: bbox [13, 24, 25, 25] is the COCO form of the course's [13, 24, 38, 49], and area is the mask's pixel count (325), not the box area (625). That distinction matters for COCO's small/medium/large breakdown and for segmentation.
Step 2: proposals and a rule-based baseline
Proposals come from the observation that the background is a noisy grey: compute every pixel's colour distance from the image's median colour, keep pixels farther than a threshold, remove specks with a opening, and turn each connected blob of at least 30 pixels into a box. The threshold is chosen on val by proposal recall, the share of objects that some proposal hits with IoU at least 0.5. No classifier can find an object that has no proposal, so this is an upper bound on the final recall.
The baseline classifier is a rule on one number, the blob's extent: blob pixels divided by box area. An upright square fills its box, a circle fills about of it, a triangle about half. The thresholds are set halfway between the class means measured on training proposals, not on ideal shapes, because the opening rounds off corners and changes the numbers.
import numpy as np, cv2
CLASSES = ["square", "circle", "triangle"]
def make_scene(rng, size=64, max_objects=3, rotate=False):
"""The course's shape scenes, with an option to rotate squares and triangles by a random angle."""
img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
n = int(rng.integers(1, max_objects + 1))
boxes, labels, masks = [], [], []
for _ in range(100):
if len(boxes) == n:
break
s = int(rng.integers(12, 25)); cx, cy = rng.uniform(0.75 * s, size - 0.75 * s, 2)
c = int(rng.integers(0, 3)); a = rng.uniform(0, 2 * np.pi) if rotate else 0.0
m = np.zeros((size, size), np.uint8)
if c == 1:
cv2.circle(m, (int(cx), int(cy)), s // 2, 1, -1)
else:
v = np.array([[-1, -1], [1, -1], [1, 1], [-1, 1]] if c == 0 else [[0, -1], [-1, 1], [1, 1]]) * s / 2
rot = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])
cv2.fillPoly(m, [np.round(v @ rot.T + [cx, cy]).astype(np.int32)], 1)
ys, xs = np.nonzero(m)
b = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]
if any(b[0] < o[2] + 2 and o[0] < b[2] + 2 and b[1] < o[3] + 2 and o[1] < b[3] + 2 for o in boxes):
continue
img[m > 0] = rng.integers(0, 256, 3)
boxes.append(b); labels.append(c); masks.append(m > 0)
return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
i = ix * iy
return i / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i)
def proposals(img, thr=30, min_area=30):
"""Foreground = colour far from the median (background) colour; one proposal per connected blob."""
bg = np.median(img.reshape(-1, 3), axis=0)
fg = (np.sqrt(((img.astype(float) - bg) ** 2).sum(axis=2)) > thr).astype(np.uint8)
fg = cv2.morphologyEx(fg, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
n, lab, stats, _ = cv2.connectedComponentsWithStats(fg, connectivity=8)
return [([int(x), int(y), int(x + w), int(y + h)], lab[y:y + h, x:x + w] == k)
for k, (x, y, w, h, a) in enumerate(stats) if k > 0 and a >= min_area]
def average_precision(dets, gts, cls, thr=0.5):
"""VOC all-point AP for one class. dets: (image, class, score, box); gts: (image, class, box)."""
g = [(i, b) for i, c, b in gts if c == cls]
used, tp = [False] * len(g), []
for i, _, s, b in sorted([d for d in dets if d[1] == cls], key=lambda d: -d[2]):
best, j = max([(iou(b, gb), j) for j, (gi, gb) in enumerate(g) if gi == i], default=(0.0, -1))
tp.append(best >= thr and not used[j])
if tp[-1]:
used[j] = True
tp = np.array(tp, float)
if len(tp) == 0:
return 0.0
prec, rec = np.cumsum(tp) / np.arange(1, len(tp) + 1), np.cumsum(tp) / len(g)
env = np.maximum.accumulate(prec[::-1])[::-1]
return float(np.sum(np.diff(np.r_[0, rec]) * env))
rng = np.random.default_rng(0)
train = [make_scene(rng) for _ in range(300)] # upright, from the lab rig
val = [make_scene(rng) for _ in range(100)]
test = [make_scene(rng) for _ in range(200)]
field_val = [make_scene(rng, rotate=True) for _ in range(60)] # rotated, from the deployed camera
field_test = [make_scene(rng, rotate=True) for _ in range(200)]
for thr in [30, 45, 60, 80]:
found = total = n_prop = 0
for img, boxes, labels, masks in val:
P = proposals(img, thr)
n_prop += len(P)
found += sum(any(iou(b.tolist(), p) >= 0.5 for p, _ in P) for b in boxes); total += len(boxes)
print(f"threshold {thr}: proposal recall on val {found / total:.3f}, proposals per image {n_prop / len(val):.2f}")
def evaluate(ds, classify):
"""Run proposals + classifier on every image; AP@0.5 per class and the mean (mAP)."""
dets, gts = [], []
for i, (img, boxes, labels, masks) in enumerate(ds):
gts += [(i, int(l), b.tolist()) for b, l in zip(boxes, labels)]
for box, crop in proposals(img):
c, score = classify(crop)
dets.append((i, c, score, box))
aps = [average_precision(dets, gts, c) for c in range(3)]
return " ".join(f"{n} {a:.3f}" for n, a in zip(CLASSES, aps)) + f" | mAP {np.mean(aps):.3f}"
def matched(ds):
"""Proposal crops with the class of the object they hit (IoU >= 0.5), or 3 = background."""
out = []
for img, boxes, labels, masks in ds:
for box, crop in proposals(img):
best = max(((iou(box, b.tolist()), int(l)) for b, l in zip(boxes, labels)), default=(0.0, 3))
out.append((crop, best[1] if best[0] >= 0.5 else 3))
return out
fill = {c: [] for c in range(4)}
for crop, c in matched(train):
fill[c].append(crop.mean()) # extent: blob pixels / box area
print("extent of training proposals:", {CLASSES[c] if c < 3 else "background": round(float(np.mean(v)), 3) for c, v in fill.items() if v})
lo, hi = (np.mean(fill[2]) + np.mean(fill[1])) / 2, (np.mean(fill[1]) + np.mean(fill[0])) / 2
print(f"rule: extent > {hi:.3f} square, > {lo:.3f} circle, else triangle")
proto = [np.mean(fill[0]), np.mean(fill[1]), np.mean(fill[2])]
def rule(crop):
e = crop.mean()
c = 0 if e > hi else 1 if e > lo else 2
return c, 1.0 - abs(e - proto[c]) # closer to the class's typical extent = more confident
print("rules, test :", evaluate(test, rule))
print("rules, field_test :", evaluate(field_test, rule))threshold 30: proposal recall on val 1.000, proposals per image 2.06
threshold 45: proposal recall on val 0.995, proposals per image 2.05
threshold 60: proposal recall on val 0.961, proposals per image 1.98
threshold 80: proposal recall on val 0.898, proposals per image 1.85
extent of training proposals: {'square': 0.997, 'circle': 0.868, 'triangle': 0.648}
rule: extent > 0.933 square, > 0.758 circle, else triangle
rules, test : square 0.992 circle 0.978 triangle 0.985 | mAP 0.985
rules, field_test : square 0.065 circle 0.959 triangle 0.811 | mAP 0.612
The proposal recall is 1.000 at threshold 30 with 2.06 proposals per image, and falls to 0.898 at 80, so 30 it is. The measured extents (0.997, 0.868, 0.648) are well above the ideal and for circles and triangles: small rasterised shapes are blockier than their geometry. With these thresholds the rules reach mAP 0.985 on the upright test set. A baseline that good would tempt anyone to ship it.
On field_test it collapses to 0.612, and the square AP to 0.065. A square turned by 45 degrees fills only half of its axis-aligned box, exactly like a triangle, so the rule calls it a triangle. Nothing in val or test could have warned you: they come from the lab rig. This is distribution shift in its simplest form, and the reason the brief includes a labelled sample of field data.
Step 3: learned classifiers, chosen on field data
Three candidates, each a logistic regression trained on the training proposals (labelled with the class of the object they hit):
- Pixels: the blob mask resized to , 256 numbers.
- Pixels with rotation augmentation: the same, plus three randomly rotated copies of every training blob (augmentation that keeps the label, because a rotated square is still a square).
- Shape features that do not change when a shape turns: the fill of the minimum-area (rotated) rectangle, the circularity (1 for a disc), and the number of corners of a simplified polygon (contours).
The choice between them is made on field_val, the only validation data that looks like deployment. Then the chosen model is scored once on each test set.
import numpy as np, cv2
CLASSES = ["square", "circle", "triangle"]
def make_scene(rng, size=64, max_objects=3, rotate=False):
"""The course's shape scenes, with an option to rotate squares and triangles by a random angle."""
img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
n = int(rng.integers(1, max_objects + 1))
boxes, labels, masks = [], [], []
for _ in range(100):
if len(boxes) == n:
break
s = int(rng.integers(12, 25)); cx, cy = rng.uniform(0.75 * s, size - 0.75 * s, 2)
c = int(rng.integers(0, 3)); a = rng.uniform(0, 2 * np.pi) if rotate else 0.0
m = np.zeros((size, size), np.uint8)
if c == 1:
cv2.circle(m, (int(cx), int(cy)), s // 2, 1, -1)
else:
v = np.array([[-1, -1], [1, -1], [1, 1], [-1, 1]] if c == 0 else [[0, -1], [-1, 1], [1, 1]]) * s / 2
rot = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])
cv2.fillPoly(m, [np.round(v @ rot.T + [cx, cy]).astype(np.int32)], 1)
ys, xs = np.nonzero(m)
b = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]
if any(b[0] < o[2] + 2 and o[0] < b[2] + 2 and b[1] < o[3] + 2 and o[1] < b[3] + 2 for o in boxes):
continue
img[m > 0] = rng.integers(0, 256, 3)
boxes.append(b); labels.append(c); masks.append(m > 0)
return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
i = ix * iy
return i / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i)
def proposals(img, thr=30, min_area=30):
"""Foreground = colour far from the median (background) colour; one proposal per connected blob."""
bg = np.median(img.reshape(-1, 3), axis=0)
fg = (np.sqrt(((img.astype(float) - bg) ** 2).sum(axis=2)) > thr).astype(np.uint8)
fg = cv2.morphologyEx(fg, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
n, lab, stats, _ = cv2.connectedComponentsWithStats(fg, connectivity=8)
return [([int(x), int(y), int(x + w), int(y + h)], lab[y:y + h, x:x + w] == k)
for k, (x, y, w, h, a) in enumerate(stats) if k > 0 and a >= min_area]
def average_precision(dets, gts, cls, thr=0.5):
"""VOC all-point AP for one class. dets: (image, class, score, box); gts: (image, class, box)."""
g = [(i, b) for i, c, b in gts if c == cls]
used, tp = [False] * len(g), []
for i, _, s, b in sorted([d for d in dets if d[1] == cls], key=lambda d: -d[2]):
best, j = max([(iou(b, gb), j) for j, (gi, gb) in enumerate(g) if gi == i], default=(0.0, -1))
tp.append(best >= thr and not used[j])
if tp[-1]:
used[j] = True
tp = np.array(tp, float)
if len(tp) == 0:
return 0.0
prec, rec = np.cumsum(tp) / np.arange(1, len(tp) + 1), np.cumsum(tp) / len(g)
env = np.maximum.accumulate(prec[::-1])[::-1]
return float(np.sum(np.diff(np.r_[0, rec]) * env))
rng = np.random.default_rng(0)
train = [make_scene(rng) for _ in range(300)] # upright, from the lab rig
val = [make_scene(rng) for _ in range(100)]
test = [make_scene(rng) for _ in range(200)]
field_val = [make_scene(rng, rotate=True) for _ in range(60)] # rotated, from the deployed camera
field_test = [make_scene(rng, rotate=True) for _ in range(200)]
def evaluate(ds, classify):
"""Run proposals + classifier on every image; AP@0.5 per class and the mean (mAP)."""
dets, gts = [], []
for i, (img, boxes, labels, masks) in enumerate(ds):
gts += [(i, int(l), b.tolist()) for b, l in zip(boxes, labels)]
for box, crop in proposals(img):
c, score = classify(crop)
dets.append((i, c, score, box))
aps = [average_precision(dets, gts, c) for c in range(3)]
return " ".join(f"{n} {a:.3f}" for n, a in zip(CLASSES, aps)) + f" | mAP {np.mean(aps):.3f}"
def matched(ds):
"""Proposal crops with the class of the object they hit (IoU >= 0.5), or 3 = background."""
out = []
for img, boxes, labels, masks in ds:
for box, crop in proposals(img):
best = max(((iou(box, b.tolist()), int(l)) for b, l in zip(boxes, labels)), default=(0.0, 3))
out.append((crop, best[1] if best[0] >= 0.5 else 3))
return out
from sklearn.linear_model import LogisticRegression
def pixels(crop): # the blob's mask resized to 16 x 16
return cv2.resize(crop.astype(np.float32), (16, 16), interpolation=cv2.INTER_AREA).ravel()
def rotate_crop(crop, degrees): # augmentation: rotate a blob mask, crop to its new box
h, w = crop.shape
d = int(np.ceil(np.hypot(h, w))) + 2
pad = np.zeros((d, d), np.float32)
pad[(d - h) // 2:(d - h) // 2 + h, (d - w) // 2:(d - w) // 2 + w] = crop
r = cv2.warpAffine(pad, cv2.getRotationMatrix2D((d / 2, d / 2), degrees, 1.0), (d, d), flags=cv2.INTER_NEAREST) > 0.5
ys, xs = np.nonzero(r)
return r[ys.min():ys.max() + 1, xs.min():xs.max() + 1]
def shape(crop): # features that do not change when the shape turns
m = np.pad(crop.astype(np.uint8), 1)
cnt = max(cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0], key=cv2.contourArea)
area, perimeter = float(m.sum()), cv2.arcLength(cnt, True)
w, h = cv2.minAreaRect(cnt)[1]
corners = len(cv2.approxPolyDP(cnt, 0.04 * perimeter, True))
return [area / max(w * h, 1.0), 4 * np.pi * area / perimeter ** 2, min(corners, 8) / 8]
def fit(featurize, augment):
rng = np.random.default_rng(1)
X, y = [], []
for crop, c in matched(train):
for k in range(4 if augment else 1): # augment: 3 extra randomly rotated copies
X.append(featurize(crop if k == 0 else rotate_crop(crop, rng.uniform(0, 360)))); y.append(c)
clf = LogisticRegression(C=1.0, max_iter=5000).fit(np.array(X), np.array(y))
def classify(crop):
p = clf.predict_proba([featurize(crop)])[0]
k = int(np.argmax(p))
return int(clf.classes_[k]), float(p[k])
return classify, len(y)
models = {"pixels": fit(pixels, False), "pixels + rotation aug.": fit(pixels, True), "shape features": fit(shape, False)}
print("chosen on field_val (60 rotated images):")
for name, (classify, n) in models.items():
print(f" {name:22s} ({n:4d} training crops) {evaluate(field_val, classify)}")
best = models["shape features"][0] # the choice, made on field_val only
print("final, scored once:")
print(" test (upright):", evaluate(test, best))
print(" field_test (rotated):", evaluate(field_test, best))chosen on field_val (60 rotated images):
pixels ( 604 training crops) square 0.071 circle 0.967 triangle 0.261 | mAP 0.433
pixels + rotation aug. (2416 training crops) square 0.551 circle 0.982 triangle 0.848 | mAP 0.794
shape features ( 604 training crops) square 0.905 circle 0.997 triangle 0.957 | mAP 0.953
final, scored once:
test (upright): square 1.000 circle 0.986 triangle 0.985 | mAP 0.990
field_test (rotated): square 0.839 circle 0.969 triangle 0.958 | mAP 0.922
The pixel model inherits the rules' blind spot (square AP 0.071): it has never seen a rotated square. Augmentation helps a lot (mAP 0.433 to 0.794) with four times the training crops, but the shape features win clearly on field_val (0.953) with only three numbers per blob, because the invariance is built into the features instead of learned from examples. Scored once, the chosen model gets mAP 0.990 on the upright test and 0.922 on field_test. The gap between field_val (0.953) and field_test (0.922) is a reminder that 60 validation images give a noisy estimate, and that a model chosen as the best of three on a small set looks a little better there than it is.
Step 4: error analysis
A single mAP says how good the detector is, not what to fix. Split the remaining errors by stage: proposals that got the wrong class, and objects that never got a proposal.
import numpy as np, cv2
CLASSES = ["square", "circle", "triangle"]
def make_scene(rng, size=64, max_objects=3, rotate=False):
"""The course's shape scenes, with an option to rotate squares and triangles by a random angle."""
img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
n = int(rng.integers(1, max_objects + 1))
boxes, labels, masks = [], [], []
for _ in range(100):
if len(boxes) == n:
break
s = int(rng.integers(12, 25)); cx, cy = rng.uniform(0.75 * s, size - 0.75 * s, 2)
c = int(rng.integers(0, 3)); a = rng.uniform(0, 2 * np.pi) if rotate else 0.0
m = np.zeros((size, size), np.uint8)
if c == 1:
cv2.circle(m, (int(cx), int(cy)), s // 2, 1, -1)
else:
v = np.array([[-1, -1], [1, -1], [1, 1], [-1, 1]] if c == 0 else [[0, -1], [-1, 1], [1, 1]]) * s / 2
rot = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])
cv2.fillPoly(m, [np.round(v @ rot.T + [cx, cy]).astype(np.int32)], 1)
ys, xs = np.nonzero(m)
b = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]
if any(b[0] < o[2] + 2 and o[0] < b[2] + 2 and b[1] < o[3] + 2 and o[1] < b[3] + 2 for o in boxes):
continue
img[m > 0] = rng.integers(0, 256, 3)
boxes.append(b); labels.append(c); masks.append(m > 0)
return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
i = ix * iy
return i / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i)
def proposals(img, thr=30, min_area=30):
"""Foreground = colour far from the median (background) colour; one proposal per connected blob."""
bg = np.median(img.reshape(-1, 3), axis=0)
fg = (np.sqrt(((img.astype(float) - bg) ** 2).sum(axis=2)) > thr).astype(np.uint8)
fg = cv2.morphologyEx(fg, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
n, lab, stats, _ = cv2.connectedComponentsWithStats(fg, connectivity=8)
return [([int(x), int(y), int(x + w), int(y + h)], lab[y:y + h, x:x + w] == k)
for k, (x, y, w, h, a) in enumerate(stats) if k > 0 and a >= min_area]
rng = np.random.default_rng(0)
train = [make_scene(rng) for _ in range(300)] # upright, from the lab rig
val = [make_scene(rng) for _ in range(100)]
test = [make_scene(rng) for _ in range(200)]
field_val = [make_scene(rng, rotate=True) for _ in range(60)] # rotated, from the deployed camera
field_test = [make_scene(rng, rotate=True) for _ in range(200)]
def matched(ds):
"""Proposal crops with the class of the object they hit (IoU >= 0.5), or 3 = background."""
out = []
for img, boxes, labels, masks in ds:
for box, crop in proposals(img):
best = max(((iou(box, b.tolist()), int(l)) for b, l in zip(boxes, labels)), default=(0.0, 3))
out.append((crop, best[1] if best[0] >= 0.5 else 3))
return out
from sklearn.linear_model import LogisticRegression
def shape(crop): # features that do not change when the shape turns
m = np.pad(crop.astype(np.uint8), 1)
cnt = max(cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0], key=cv2.contourArea)
area, perimeter = float(m.sum()), cv2.arcLength(cnt, True)
w, h = cv2.minAreaRect(cnt)[1]
corners = len(cv2.approxPolyDP(cnt, 0.04 * perimeter, True))
return [area / max(w * h, 1.0), 4 * np.pi * area / perimeter ** 2, min(corners, 8) / 8]
def fit(featurize):
X, y = [], []
for crop, c in matched(train):
X.append(featurize(crop)); y.append(c)
clf = LogisticRegression(C=1.0, max_iter=5000).fit(np.array(X), np.array(y))
def classify(crop):
p = clf.predict_proba([featurize(crop)])[0]
k = int(np.argmax(p))
return int(clf.classes_[k]), float(p[k])
return classify, len(y)
classify = fit(shape)[0]
confusion = np.zeros((4, 4), int) # rows: true (3 = background), columns: predicted
square_feats = {"right": [], "wrong": []}
for crop, c in matched(field_test):
p = classify(crop)[0]
confusion[c, p] += 1
if c == 0:
square_feats["right" if p == 0 else "wrong"].append(shape(crop) + [crop.shape[1]])
print("proposals on field_test, true class (rows) vs predicted (columns):")
for c, row in enumerate(confusion[:3]):
print(f" {CLASSES[c]:8s} {row[:3].tolist()}")
print(" background proposals:", int(confusion[3].sum()))
for k, v in square_feats.items():
print(f" squares classified {k}: mean [rect fill, circularity, corners/8, width] =", np.mean(v, axis=0).round(2).tolist())
missed = {"low contrast": 0, "other": 0}
sizes = []
for img, boxes, labels, masks in field_test:
P = proposals(img)
bg = np.median(img.reshape(-1, 3), axis=0)
for b, m in zip(boxes, masks):
if not any(iou(b.tolist(), p) >= 0.5 for p, _ in P):
contrast = np.sqrt(((img[m].astype(float).mean(axis=0) - bg) ** 2).sum())
missed["low contrast" if contrast < 30 else "other"] += 1
sizes.append(int(b[2] - b[0]))
print("objects with no proposal:", missed, "| their widths:", sorted(sizes))proposals on field_test, true class (rows) vs predicted (columns):
square [78, 2, 12]
circle [0, 144, 0]
triangle [0, 4, 139]
background proposals: 0
squares classified right: mean [rect fill, circularity, corners/8, width] = [1.0, 0.84, 0.5, 20.45]
squares classified wrong: mean [rect fill, circularity, corners/8, width] = [0.94, 0.84, 0.51, 22.29]
objects with no proposal: {'low contrast': 7, 'other': 0} | their widths: [13, 15, 17, 20, 23, 23, 27]
Circles are perfect and triangles nearly so (4 called circles). The main error is 12 squares called triangles. The diagnostic line shows why: misclassified squares have a rotated-rectangle fill of 0.94 instead of 1.00. At these sizes a rotated square is drawn with stair-stepped edges, and the opening cuts its corners, so it no longer fills its rotated rectangle; the classifier was trained only on upright squares, which fill it perfectly. All 7 missed objects are low-contrast ones whose colour is within 30 of the background, of every size: no classifier change can recover them, only a better proposal stage. No proposal was background noise, so false alarms are not the problem here.
That gives a ranked to-do list: (1) teach the classifier rotated squares (field data or better augmentation), (2) a proposal stage that sees low-contrast objects (texture, edges, or a learned detector), (3) only then anything else.
Your turn
- Train the shape-feature model with the rotation augmentation of candidate 2 (
fit(shape, True)). Does it fix the squares?
Answer
Run with the same code, it gives field_val mAP 0.883 (square 0.881, circle 0.985, triangle 0.783) and field_test mAP 0.909 (square 0.882, triangle 0.883). The squares improve a little on field_test but the triangles get worse, and on field_val, where the decision is made, it loses to the plain shape features (0.953). By the rules of the brief you keep the plain model. A likely reason: rotating an already rasterised blob mask with nearest-neighbour sampling produces jagged edges that differ from shapes drawn at an angle, so the augmented examples are not quite the field data. Augmentation is a model of the real variation, and a wrong model can hurt.
- Lower the proposal threshold to 20 to catch the low-contrast objects. Predict what happens to proposal recall and to the number of proposals per image, then measure it on
val.
Hint
Background pixels are in each channel, so their colour distance from the median has a root-mean-square of . At a threshold near 20, a large share of background pixels pass; the opening removes isolated ones, but clusters merge with objects and enlarge their boxes. Measure both the recall and the mean IoU of the matched proposals.
- Replace the classical proposal stage by the learned grid detector of a tiny detector (a recorded example) and compare the AP on
field_test. Which errors of Step 4 should it fix, and which may it add? - Export the training set in YOLO format (one
.txtper image,class cx cy w hnormalised) and check the round trip back to pixel boxes on 10 images. - Compute the COCO-style AP@[.5:.95] of the final model (detection metrics). Which class loses most at strict IoU thresholds, and why would boxes from an opened mask be slightly too small?
Write-up template
Fill it in for your final model; the first column is this lesson's run.
| This run | Yours | |
|---|---|---|
| Data (train / val / test / field_val / field_test images) | 300 / 100 / 200 / 60 / 200 | |
| Proposal stage, threshold chosen on | colour distance > 30, val (recall 1.000) |
|
| Baseline, mAP test / field_test | extent rules: 0.985 / 0.612 | |
Candidates compared on field_val |
pixels 0.433, pixels + aug. 0.794, shape features 0.953 | |
| Final model, mAP test / field_test (scored once) | shape features: 0.990 / 0.922 | |
| Largest error | 12 of 92 rotated squares called triangles | |
| Second error | 7 low-contrast objects with no proposal | |
| Next step | rotated squares in training; proposals for low contrast | |
| Limits of this evaluation | synthetic shapes; 60-image field_val is noisy; one seed |
A good write-up also states what was not tested: real photographs, other rotations than the generator's, overlapping objects, other image sizes. On a synthetic task like this one, the method is the result; the numbers are not evidence about any real camera.
Test yourself
The rule-based detector scores mAP 0.985 on the upright test set and 0.612 on rotated field images. What should have been done differently?
- Tune the rules on the field test set
- Choose and check models on a validation set drawn from the deployment conditions (field_val), not only on lab data
- Report only the test score
- Use a larger upright training set
Why is proposal recall an upper bound on the detector's final recall?
- Because the classifier is linear
- An object without any proposal at IoU 0.5 or more can never become a true positive, whatever the classifier does
- Because AP ignores recall
- Because proposals have no scores
Shape features (rotated-rectangle fill, circularity, corner count) beat 256 resized pixels with rotation augmentation. What is the main reason?
- Logistic regression works better with three features in general
- The features are invariant to rotation by construction, so the classifier does not have to learn the invariance from examples
- Pixels cannot represent squares
- Augmentation always hurts
In the error analysis, all 7 missed objects have a colour within 30 of the background. What does that tell you?
- The classifier needs more training
- The fix belongs in the proposal stage; no change to the classifier can recover objects that are never proposed
- The AP formula is wrong
- The objects are mislabelled