27 min read · Machine vision

Suppose a factory sets out to train an AI to detect scratches on metal parts. The team collects 300 pictures of defects. But when they try it on the real line, the system flags normal surface texture as scratches on many parts. In another case, the test score is very high, but the results fall apart once it goes on the line. Both problems are usually not about the model. They are about the data: pictures that do not match real working conditions, labels that contradict each other, or the same picture leaking into both the training set and the test set.
This article does not teach model training. It teaches how to check a dataset before training (labeling means having a person state whether an image is good or defective, or where the defect is), using Python code that really runs and uses only numpy. Every image is generated in memory from a seed, so there are no image files. A manager can read the explanations and tables to get the picture. An engineer can run the code and follow along.
The real problem: a dataset that looks complete but teaches the AI wrong
A defect image set usually fails in three ways. First, it lacks good parts and borderline parts, so the model never sees what normal surface texture looks like. Second, two labelers use different criteria. Third, near-duplicate images (for example, three rapid-fire frames of the same part) are randomly split into different sets. Consider three hypothetical situations. None of them is a BT San customer project.
- A hypothetical metal parts factory: it collects only scratch images from the reject tray, with no good parts from lots with different lighting. The result is a model that learns that a brighter surface means defective.
- A hypothetical assembly line: two labelers disagree on whether a faint mark counts as a defect. Each follows their own feeling, and there is no unsure class, so the labels come out random at the borderline.
- A hypothetical factory that re-photographs the same part: the same part is shot again and registered under a new part ID. Splitting by part ID cannot tell it is the same picture, so one image lands in train and the other in test, and the test score is inflated.
All three can be caught with short code before you spend time on training. The example below covers the whole chain: writing the guideline as data, measuring agreement, building the list of images that need review, checking class ratios and per-lot coverage, finding near-duplicate images, and splitting without leakage.
What the documents say, and what this example does not claim
| Topic | What the document says | Effect on our example |
|---|---|---|
| Labeling guideline | Ultralytics recommends clear, standardized labeling criteria with instructions and example images, reviewed and improved regularly. | spec.py stores the guideline as data, and validate checks every label against it. |
| Agreement | Ultralytics says high inter-annotator agreement indicates a clear guideline that labelers apply consistently, but it gives no numeric threshold. | We report the kappa value but do not set how much is enough. That must be agreed with QC. |
| The kappa formula | scikit-learn defines kappa = (p_o - p_e) / (1 - p_e), with values between -1.0 and 1.0, where 0.0 means agreement no better than random chance. The example in the documentation gives 0.6875. | agreement.py writes the formula itself and uses the 0.6875 example as a test. |
| IoU | Label Studio describes IoU as the area shared by two boxes divided by their combined area, giving a value from 0.0 to 1.0. CVAT consensus uses Min overlap as the matching threshold, which corresponds to IoU for boxes. | match_boxes pairs boxes with an IoU of 0.5 or higher. The value 0.5 is our own choice. |
| Duplicate images | The Google ML Crash Course says to remove examples in the validation and test sets that duplicate the training set, because a fair test needs new examples, not repeated ones. | dedupe.py finds near-duplicate images, and split.py keeps each group in the same set. |
| Splitting by group | scikit-learn GroupKFold says each group appears in the test set exactly once across all folds. | Same idea, but we wrote our own simple train/val/test splitter and do not call scikit-learn. |
| Imbalanced data | The Google ML Crash Course calls the frequent class the majority and the rare class the minority, and recommends downsampling and upweighting. | balance.py only reports the ratios and gaps. It does not adjust weights. |
The example uses synthetic images, two hypothetical labelers, and numbers generated by us. The kappa and IoU values you see therefore cannot be compared with real factory data. What you can learn is how to measure and how to read the results.
Overview of the example
All the code is in the folder examples/defect-dataset-labeling-guide/. It uses Python 3 with numpy. Nothing else needs to be installed, and no network is used.
| File | Role |
|---|---|
| spec.py | The labeling guideline as data: classes, minimum size, definition of good |
| synth.py | Generates gray images from a seed (surface, scratches, dents, faint marks, lighting that differs by lot) |
| make_data.py and data/ | Builds the image list and the labels of A and B, with flaws deliberately planted in the data |
| agreement.py | Checks labels, kappa, IoU, and the list of images to review |
| balance.py | Class ratios and per-lot coverage |
| dedupe.py | Average hash and grouping of near-duplicate images |
| split.py | Splits train/val/test by group and checks for leakage |
| demo.py / test_dataset.py | A report covering every step, and a unittest suite |
Step 1: write the labeling guideline as data, with an unsure class
A guideline that lives in a Word document cannot be checked automatically. A guideline that is data lets code check every label. Three points should be written down clearly. The first is the minimum size of a defect that counts (in the example, a long side of at least 8 pixels). The second is what good means, including a statement that brightness that differs by lot is not a defect. The third is an unsure class that is a real class, which lets a labeler say they see something but cannot decide. These images go to an arbiter instead of being quietly guessed as good or defective.
"""Labelling spec as data: class list, minimum defect size, what counts as good."""
IMG_SIZE = 64 # synthetic images are 64x64 grayscale
CLASSES = ["good", "scratch", "dent", "unsure"]
DEFECT_CLASSES = ["scratch", "dent"] # these must carry a box
# A defect box whose longer side is under this many pixels is too small to call.
# The annotator must use "unsure" (or no box) instead of "scratch"/"dent".
MIN_DEFECT_PX = 8
# What counts as good (written down so both annotators use the same rule):
# - no visible mark at all, or only marks below MIN_DEFECT_PX that you cannot name
# - lighting changes and lot-to-lot brightness differences are NOT defects
# What counts as unsure: you can see something but cannot decide scratch / dent / texture.
# "unsure" is a first-class label: it goes to a reviewer, it is never silently
# turned into good or defect.
GUIDE = {
"good": "no visible mark; brightness differences between lots do not count",
"scratch": "thin bright line, longer side >= MIN_DEFECT_PX, box around the whole line",
"dent": "dark soft blob, longer side >= MIN_DEFECT_PX, box around the dark area",
"unsure": "something is visible but you cannot decide; box optional",
}
IOU_MATCH = 0.5 # boxes with IoU >= this count as the same defect
HASH_MAX_DIST = 6 # Hamming distance (of 64 bits) at or below this = near-duplicateThe values of MIN_DEFECT_PX and IOU_MATCH in this file are assumed values for the example. Real ones must come from the product standard or an agreement with QC, and the final arbiter should be the person responsible for the quality of the actual product.
Step 2: generate synthetic data with traps like the real thing
synth.py draws images from seeds. Each part's surface comes from part_seed, the frame noise comes from frame_seed, and gain is the lot's brightness. This means a re-shot of the same part gives a similar image that is not identical pixel for pixel. A faint, short mark is the unsure case.
"""Synthetic grayscale images drawn from seeds. Nothing is stored as an image file."""
import numpy as np
from spec import IMG_SIZE
def render(entry):
"""entry: dict with part_seed, frame_seed, gain, kind, box (box = [x0,y0,x1,y1] or None)."""
prng = np.random.default_rng(entry["part_seed"])
# base texture belongs to the part: 8x8 coarse blocks, so every part looks different
img = np.kron(prng.uniform(80, 170, (8, 8)), np.ones((8, 8)))
if entry["box"] is not None:
x0, y0, x1, y1 = entry["box"]
if entry["kind"] in ("scratch", "unsure"):
lift = 60 if entry["kind"] == "scratch" else 25 # unsure = faint mark
yy = (y0 + y1) // 2
img[yy:yy + 2, x0:x1] += lift
elif entry["kind"] == "dent":
ys, xs = np.mgrid[y0:y1, x0:x1]
cy, cx = (y0 + y1 - 1) / 2, (x0 + x1 - 1) / 2
r = ((ys - cy) / ((y1 - y0) / 2)) ** 2 + ((xs - cx) / ((x1 - x0) / 2)) ** 2
img[y0:y1, x0:x1] -= 45 * np.clip(1 - r, 0, 1)
frng = np.random.default_rng(entry["frame_seed"]) # per-frame sensor noise
img = img * entry["gain"] + frng.normal(0, 2.0, img.shape) # gain = lighting / lot shift
assert img.shape == (IMG_SIZE, IMG_SIZE)
return np.clip(img, 0, 255)make_data.py creates 49 images from 40 parts in total, in three lots with different lighting. Lot L3 deliberately has very few good parts so the coverage report can catch it, and the data contains the traps that real data usually has.
- Near-duplicate images: some parts have several frames with slightly different lighting
- The same part re-shot but registered with a new ID (p041 is p005 and p042 is p021)
- Bad labels: a class that is not in the guideline, a 3x3 box on a good part, a box that falls outside the image, and an image that B did not label
- B sets a different threshold for faint marks than A, so there is real disagreement to measure
def annotate(who):
out = {}
for im in images:
cls = im["kind"]
if who == "B": # annotator B has a different threshold for faint marks
r = rng.random()
if cls == "unsure" and r < 0.45:
cls = "good" if rng.random() < 0.5 else "scratch"
elif cls == "scratch" and r < 0.15:
cls = "unsure"
elif cls == "good" and r < 0.06:
cls = "unsure"
boxes = []
if im["box"] is not None and cls != "good":
boxes = [dict(cls=cls, xyxy=jitter(im["box"], 1 if who == "A" else 2))]
out[im["id"]] = dict(cls=cls, boxes=boxes)
return out
A, B = annotate("A"), annotate("B")
# deliberately bad entries (a real export has these):
B["p001_f0"] = dict(cls="crack", boxes=[]) # class not in the spec
B["p002_f0"] = dict(cls="scratch", boxes=[dict(cls="scratch", xyxy=[10, 10, 13, 13])]) # 3x3 box on a good part
A["p000_f0"] = dict(cls="dent", boxes=[dict(cls="dent", xyxy=[50, 50, 70, 66])]) # box leaves the image
del B["p010_f0"] # B never labelled this imageStep 3: check labels against the guideline, then measure agreement
Before measuring agreement, filter out malformed labels first, because a label that fails the guideline should not be counted as an opinion. validate checks four things: a class that is not in the guideline, a defect class with no box, a good part with a box, and a box that falls outside the image or is smaller than the guideline allows.
def validate(label):
"""Problems in ONE annotator's label for ONE image, judged against spec.py."""
probs = []
if label["cls"] not in CLASSES:
probs.append(f"unknown class '{label['cls']}'")
if label["cls"] in DEFECT_CLASSES and not label["boxes"]:
probs.append("defect class without a box")
if label["cls"] == "good" and label["boxes"]:
probs.append("good image carries boxes")
for b in label["boxes"]:
x0, y0, x1, y1 = b["xyxy"]
if not (0 <= x0 < x1 <= IMG_SIZE and 0 <= y0 < y1 <= IMG_SIZE):
probs.append(f"box {b['xyxy']} leaves the {IMG_SIZE}px image")
elif b["cls"] in DEFECT_CLASSES and max(x1 - x0, y1 - y0) < MIN_DEFECT_PX:
probs.append(f"{b['cls']} box {b['xyxy']} under {MIN_DEFECT_PX}px: use unsure")
return probsNext, measure Cohen's kappa for the image-level class. The idea is to take the share of cases where the two people answer the same (p_o) and subtract the share expected to match by chance (p_e), using the formula given in the scikit-learn documentation. This correction matters when classes are imbalanced. If 90 percent of parts are good, anyone who answers good for every image agrees 90 percent of the time without inspecting anything.
def cohen_kappa(a, b):
"""kappa = (po - pe) / (1 - pe); same formula as sklearn.metrics.cohen_kappa_score."""
n = len(a)
po = sum(x == y for x, y in zip(a, b)) / n
ca, cb = Counter(a), Counter(b)
pe = sum(ca[c] * cb[c] for c in set(ca) | set(cb)) / (n * n)
# simplified: if both annotators use a single identical class pe == 1; return 1.0.
return 1.0 if pe == 1 else (po - pe) / (1 - pe)Boxes are measured with IoU, which is the overlapping area divided by the combined area. Boxes are matched one to one, in order from highest IoU to lowest. A box whose IoU is below the threshold is treated as a different defect. This matches the way CVAT consensus uses an overlap threshold to pair boxes.
def iou(p, q):
"""Intersection over union of two [x0,y0,x1,y1] boxes (x1,y1 exclusive)."""
iw = min(p[2], q[2]) - max(p[0], q[0])
ih = min(p[3], q[3]) - max(p[1], q[1])
inter = max(0, iw) * max(0, ih)
union = (p[2] - p[0]) * (p[3] - p[1]) + (q[2] - q[0]) * (q[3] - q[1]) - inter
return inter / union if union else 0.0def match_boxes(ba, bb, thr=IOU_MATCH):
"""Greedy one-to-one matching by descending IoU. Returns (pairs, only_a, only_b)."""
# simplified: greedy, not Hungarian; fine with 0-2 boxes per image, use scipy for crowds.
cand = sorted(((iou(x["xyxy"], y["xyxy"]), i, j) for i, x in enumerate(ba)
for j, y in enumerate(bb)), reverse=True)
pairs, ua, ub = [], set(), set()
for v, i, j in cand:
if v >= thr and i not in ua and j not in ub:
pairs.append((i, j, v)); ua.add(i); ub.add(j)
return pairs, [i for i in range(len(ba)) if i not in ua], [j for j in range(len(bb)) if j not in ub]Be careful with the boxes of thin scratches, which are only a few pixels tall. Moving by one pixel drops IoU a lot. Disagreement at the box level is therefore usually higher than at the class level. Look at both together, not at a single number.
Step 4: the list of images to send back for review
The kappa value tells you how much the labelers agree, but not which images need fixing. The conflicts function therefore builds a list of images with the reason for each. There are four kinds: missing label, malformed label, different class, and boxes that do not overlap enough. The list is sorted so that class disagreements involving unsure come first, because that is where the guideline is probably still unclear.
def conflicts(A, B):
"""Images to send back for review: (image id, reason). 'unsure' on either side goes first."""
out = []
for iid in sorted(set(A) | set(B)):
a, b = A.get(iid), B.get(iid)
if a is None or b is None:
out.append((iid, "missing label from " + ("A" if a is None else "B")))
continue
va, vb = validate(a), validate(b)
if va or vb:
out.append((iid, "invalid: " + "; ".join([f"A {p}" for p in va] + [f"B {p}" for p in vb])))
elif a["cls"] != b["cls"]:
out.append((iid, f"class differs: A={a['cls']} B={b['cls']}"))
else:
pairs, ua, ub = match_boxes(a["boxes"], b["boxes"])
if ua or ub:
out.append((iid, f"boxes do not overlap enough (IoU < {IOU_MATCH})"))
return sorted(out, key=lambda r: (not (r[1].startswith("class differs") and "unsure" in r[1]), r[0]))Step 5: class ratios and per-lot coverage
The training set should come from images the labelers agree on. Images still on the review list must wait for the arbiter. balance.py therefore counts only images that are not on the list, then checks whether each lot has enough good parts and whether any class is missing. The result tells you where to go and collect more images.
def coverage(final, lot_of):
"""Rows (lot, counts per class, total, flag text)."""
rows = []
for lot in sorted(set(lot_of.values())):
c = Counter(cls for i, cls in final.items() if lot_of[i] == lot)
n = sum(c.values())
flags = []
if n and c["good"] / n < MIN_GOOD_SHARE:
flags.append(f"good only {c['good'] / n:.0%}")
flags += [f"no {k}" for k in CLASSES if c[k] == 0]
rows.append((lot, [c[k] for k in CLASSES], n, ", ".join(flags) or "ok"))
return rowsStep 6: find near-duplicate images with an average hash
An average hash shrinks the image to an 8x8 grid and sets each cell to 1 if it is brighter than the mean, giving a 64-bit number. Similar images differ in few bits, and images of different parts differ in many. Comparing each cell to the image's own mean means that making the whole image brighter or darker barely changes the hash, which suits the case where lighting differs by lot.
def ahash(img):
"""64x64 -> 8x8 block means -> bit = block mean above the overall mean. Returns a 64-bit int."""
small = img.reshape(8, 8, 8, 8).mean(axis=(1, 3))
bits = (small > small.mean()).ravel()
return int("".join("1" if b else "0" for b in bits), 2)def near_dup_groups(hashes, max_dist=HASH_MAX_DIST):
"""Union-find over image ids: any pair within max_dist ends up in one group id."""
# simplified: O(n^2) pair scan; production = LSH / BK-tree or embeddings for 100k+ images.
ids = list(hashes)
parent = {i: i for i in ids}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for k, a in enumerate(ids):
for b in ids[k + 1:]:
if hamming(hashes[a], hashes[b]) <= max_dist:
parent[find(a)] = find(b)
return {i: find(i) for i in ids}Grouping uses union-find because closeness is a chain. If A is close to B and B is close to C, all three must be in one group even if A and C are far apart. The limitation is that this kind of hash only catches images with a similar light-and-dark structure. Images shifted in angle or cropped very differently will slip through. A real system should use a sturdier perceptual hash, or compare using vectors from a model.
Step 7: split train/val/test by group
The idea is the same as scikit-learn's GroupKFold: every member of a group must be in the same set. The difference is that our groups are not part IDs. They come from the near-duplicate search, so this also catches the case of the same part registered under a new ID.
def group_split(group_of, fractions=(0.7, 0.15, 0.15), seed=7):
"""group_of: image id -> group id. Returns image id -> 'train'|'val'|'test'."""
names = ("train", "val", "test")
members = {}
for img, g in group_of.items():
members.setdefault(g, []).append(img)
groups = sorted(members, key=lambda g: (-len(members[g]), str(g)))
random.Random(seed).shuffle(groups) # shuffle, then big groups first keeps sizes near target
groups.sort(key=lambda g: -len(members[g]))
total, load, out = len(group_of), dict.fromkeys(names, 0), {}
for g in groups:
# simplified: fills the split furthest below its target; no per-class stratification.
# production: stratify rare classes across splits (e.g. StratifiedGroupKFold).
s = max(names, key=lambda n: fractions[names.index(n)] * total - load[n])
for img in members[g]:
out[img] = s
load[s] += len(members[g])
return outdef leaks(split_of, group_of):
"""Groups that appear in more than one split (must be empty)."""
seen = {}
for img, g in group_of.items():
seen.setdefault(g, set()).add(split_of[img])
return {g: s for g, s in seen.items() if len(s) > 1}This splitter does not split by class. In the real run, the test set got 0 scratch images. With real data that has few defects, you need a stratified split by group (for example, scikit-learn's StratifiedGroupKFold). You may also need to split by lot or production date to test whether the model holds up on a new lot. This is the author's conclusion, not something quoted from the cited documents.
A real run: the whole report at once
demo.py loads the data, runs the five steps, and prints a report. The results below come from a real run of python3 demo.py.
print("== 1. agreement")
both = [i for i in part_of if i in A and i in B]
print(f"images labelled by both: {len(both)} of {len(part_of)}")
print(f"image-class kappa: {cohen_kappa([A[i]['cls'] for i in both], [B[i]['cls'] for i in both]):.3f}")
ious = [v for i in both for _, _, v in match_boxes(A[i]["boxes"], B[i]["boxes"], 0.0)[0]]
print(f"box pairs: {len(ious)}, mean IoU {sum(ious) / len(ious):.3f}")
print("== 2. review list")
review = conflicts(A, B)
for iid, why in review:
print(f"{iid}: {why}")
print(f"{len(review)} images go back for review")== 1. agreement
images labelled by both: 48 of 49
image-class kappa: 0.745
box pairs: 20, mean IoU 0.600
== 2. review list
p006_f0: class differs: A=good B=unsure
p012_f1: class differs: A=scratch B=unsure
p037_f0: class differs: A=unsure B=good
p038_f0: class differs: A=unsure B=good
p000_f0: invalid: A box [50, 50, 70, 66] leaves the 64px image
p001_f0: invalid: B unknown class 'crack'
p002_f0: invalid: B scratch box [10, 10, 13, 13] under 8px: use unsure
p010_f0: missing label from B
p011_f0: boxes do not overlap enough (IoU < 0.5)
p013_f0: boxes do not overlap enough (IoU < 0.5)
p015_f0: invalid: B scratch box [47, 43, 54, 47] under 8px: use unsure
p029_f0: boxes do not overlap enough (IoU < 0.5)
p039_f0: boxes do not overlap enough (IoU < 0.5)
13 images go back for review
== 3. class balance and lot coverage (agreed labels only)
class counts: {'good': 22, 'scratch': 8, 'dent': 6}
lot good scratch dent unsure total flag
L1 9 1 1 0 11 no unsure
L2 11 2 2 0 15 no unsure
L3 2 5 3 0 10 good only 20%, no unsure
== 4. near-duplicates (aHash, Hamming <= 6)
['p003_f0', 'p003_f1', 'p003_f2'] max dist 0
['p005_f0', 'p041_f0'] max dist 0
['p012_f0', 'p012_f1'] max dist 0
['p020_f0', 'p020_f1'] max dist 0
['p021_f0', 'p042_f0'] max dist 0
['p033_f0', 'p033_f1', 'p033_f2'] max dist 1
['p036_f0', 'p036_f1'] max dist 1
distinct groups: 40 images: 49
== 5. grouped split
split by part id only, leaking groups: 1
split by near-dup group, leaking groups: 0
sizes: {'train': 34, 'val': 8, 'test': 7}
train: good=14, scratch=7, dent=4, unsure=0, (in review)=9
val: good=5, scratch=1, dent=1, unsure=0, (in review)=1
test: good=3, scratch=0, dent=1, unsure=0, (in review)=3Reading the results one by one.
- The image-level kappa is 0.745 over 48 images that both people labeled (B did not label one more image). This number is not a model result. It says the guideline still has borderline spots. Boxes were matched in 20 pairs with a mean IoU of 0.600, which is lower than it feels because thin scratch boxes are hard to match.
- The review list has 13 images: 4 with different classes (all 4 involve unsure on one side), 4 with malformed labels (p000 box outside the image, p001 class crack that is not in the guideline, p002 and p015 boxes smaller than 8 pixels), 1 with a missing label (p010), and 4 where the boxes do not overlap enough.
- p012_f1 is judged scratch by A but unsure by B, even though p012_f0, its near-duplicate, was agreed on by both. This is why you should also check near-duplicate images against the labels. Identical images should have identical labels.
- After removing the images waiting for review, 22 good, 8 scratch, 6 dent and 0 unsure images remain. The unsure class disappeared entirely because all of it was sent for review. If you trained now, the model would never see borderline cases. Lot L3 has only 20 percent good parts, so it was flagged.
- The average hash found 7 duplicate groups, covering both the rapid-fire frames and the two pairs that were registered under new IDs (p005 with p041, p021 with p042). The 49 images therefore reduce to 40 groups.
- Splitting by part ID alone leaves 1 group leaking across sets. Splitting by hash group leaves 0. The set sizes are 34, 8 and 7 images, and the test set got 0 scratch images, as the note above warns.
How to test that it is really correct
The test suite checks the things that fail silently: kappa, IoU, catching bad labels, and no leakage. Kappa is tested against the 0.6875 example printed in the scikit-learn documentation and against the extreme cases (complete agreement gives 1.0, chance-level agreement gives 0.0). IoU is tested with numbers that can be computed by hand: 50 divided by 150 equals one third, boxes that only touch at the edge give 0, and identical boxes give 1.
class Agreement(unittest.TestCase):
def test_kappa_matches_sklearn_doc_example(self):
y1 = ["negative", "positive", "negative", "neutral", "positive"]
y2 = ["negative", "positive", "negative", "neutral", "negative"]
self.assertAlmostEqual(cohen_kappa(y1, y2), 0.6875) # value printed in the sklearn docs
def test_kappa_extremes(self):
self.assertEqual(cohen_kappa(["a", "b", "a"], ["a", "b", "a"]), 1.0)
self.assertAlmostEqual(cohen_kappa(["a", "a", "b", "b"], ["a", "b", "a", "b"]), 0.0)
def test_iou(self):
self.assertAlmostEqual(iou([0, 0, 10, 10], [5, 0, 15, 10]), 50 / 150)
self.assertEqual(iou([0, 0, 4, 4], [4, 0, 8, 4]), 0.0) # touching edges: no overlap
self.assertEqual(iou([1, 1, 5, 5], [1, 1, 5, 5]), 1.0)
def test_match_is_one_to_one(self):
a = [dict(xyxy=[0, 0, 10, 10])]
b = [dict(xyxy=[0, 0, 10, 10]), dict(xyxy=[1, 0, 10, 10])]
pairs, only_a, only_b = match_boxes(a, b)
self.assertEqual(len(pairs), 1)
self.assertEqual(only_b, [1])
def test_bad_labels_are_caught(self):
self.assertTrue(validate(B["p001_f0"])) # unknown class
self.assertTrue(validate(B["p002_f0"])) # 3x3 "scratch"
self.assertTrue(validate(A["p000_f0"])) # box outside image
ids = [c[0] for c in conflicts(A, B)]
self.assertIn("p010_f0", ids) # missing from B
The leakage tests matter most. There are 3. The first proves that splitting by part ID alone really leaks (otherwise the example would be pointless). The second splits by hash group with 20 different seeds and must never leak, and every image must get a set. The third proves that a 10 percent lighting change does not push the hash beyond the threshold.
class NoLeak(unittest.TestCase):
def setUp(self):
self.part_of = {m["id"]: m["part"] for m in M}
self.hashes = {m["id"]: ahash(render(m)) for m in M}
self.dg = near_dup_groups(self.hashes)
def test_part_id_alone_leaks_re_photographed_parts(self):
# p041 is p005 photographed again under a new part id: grouping by part id misses it
split = group_split(self.part_of)
self.assertTrue(leaks(split, self.dg))
def test_hash_groups_never_leak(self):
for seed in range(20):
split = group_split(self.dg, seed=seed)
self.assertEqual(leaks(split, self.dg), {})
self.assertEqual(set(split), {m["id"] for m in M})
def test_lighting_shift_keeps_hash(self):
m = dict(M[0])
dark = dict(m, gain=m["gain"] * 0.9, frame_seed=5)
d = bin(ahash(render(m)) ^ ahash(render(dark))).count("1")
self.assertLessEqual(d, 6)
Run it with python3 -m unittest -v in the example folder. All 8 tests pass.
Taking it to real use: what the example skips
- Real images: replace synth.py with code that reads image files, and keep the metadata (lot, production date, camera, light) in the same table as the labels so you can report per lot. Every image needs a trustworthy lot and part ID.
- Labeling tools: use a tool such as CVAT or Label Studio, which has built-in agreement measurement and review, and use code like this as an extra gate on the exported files.
- More than two labelers: two-person kappa can be applied pair by pair, or you can use another metric for multiple labelers, and you must decide who the final arbiter is.
- Hashing: with hundreds of thousands of images, comparing every pair is slow. Use an index such as a BK-tree or LSH, or compare embeddings.
- Splitting: stratify by group, and hold out at least the most recent lot as the test set, and do not touch it until the final evaluation.
- Labels after arbitration: keep a history of who changed what and when so you can audit it later, and keep the guideline version with the dataset.
Hypothetical examples: applying it to three businesses
- A hypothetical plastic injection factory: inspecting burn marks and excess flash. Raw material lots in different colors reflect light differently. The per-lot report can show that the new color lot does not yet have enough good parts, before the model is trained.
- A hypothetical circuit board assembly factory: inspecting borderline solder joints. The unsure class and the review list let engineers and QC look only at the images where they disagree, not at all of them.
- A hypothetical processed food maker: products are photographed continuously on a conveyor, producing many near-duplicate frames. Grouping near-duplicate images before splitting prevents an inflated test score.
Common mistakes and a checklist
- Collecting only defect images from the reject bin and forgetting good images from every lot, every shift and every lighting condition
- Having no unsure class, which forces people to guess at the borderline, and then training on the guessed labels
- Reporting only image-level agreement and not looking at the box level. Labels with the same class but pointing at different places also teach the model wrong.
- Using the kappa value as the single deciding number without looking at where the labelers disagree. Read the review list alongside it.
- Splitting randomly at the image level, or by an unreliable part ID, so duplicate images leak across sets
- Reviewing labels but fixing only the training set, and leaving wrong test labels in place, so the measured score does not match reality
- Changing the guideline midway without recording the version, so images labeled before and after use different criteria and nobody knows
Checklist before sending a dataset to training
- The labeling guideline is written down, has example images, a minimum size, an unsure class and a version number.
- Good images come from every lot, every shift and every lighting condition, not only defects.
- Every label passes validate, and there are no classes outside the guideline.
- Two or more labelers have labeled a randomly sampled subset, kappa and IoU are reported, and the review list is fully closed.
- Images in unsure are decided by the person responsible for quality, or at least kept apart from the evaluation set.
- The per-lot report has no unresolved warning flags, or each one has a recorded reason for accepting it.
- Near-duplicate images are grouped, and no group spans the train/val/test sets.
- The test set is kept separate and is not used to tune the model or any threshold.
Cautions about the example: it uses synthetic images and hypothetical labelers, so it was not tested on real factory data. The average hash catches only images with a similar light-and-dark structure. The kappa and IoU values depend on this dataset only. Thresholds such as IoU 0.5 and the 8-pixel minimum size must be set again for the real part and image resolution. This example is for learning, not production code.
References
- Ultralytics docs: Data collection and annotation for computer vision (accessed 2026-11-21)
- Ultralytics docs: Performance metrics (IoU, mAP50, mAP50-95) (accessed 2026-11-21)
- scikit-learn: cohen_kappa_score (accessed 2026-11-21)
- scikit-learn: GroupKFold (accessed 2026-11-21)
- CVAT docs: Consensus (Min overlap, agreement score) (accessed 2026-11-21)
- Label Studio docs: Task agreement and annotator agreement (IoU for boxes, exact match) (accessed 2026-11-21)
- Google ML Crash Course: Dividing the original dataset (accessed 2026-11-21)
- Google ML Crash Course: Imbalanced datasets (accessed 2026-11-21)




