BT San Technology

6 May 2026

收集缺陷图像训练 AI:除了不良品还要收集什么

27 分钟阅读 · 机器视觉

插图:戴手套的双手把工件分拣到托盘的格子里,将表面纹理正常的工件与真正有瑕疵的工件分开,笔记本电脑上显示已加框标注的图像
AI 生成的插图

假设一家工厂打算训练 AI 检测金属工件上的划痕,团队收集了整整 300 张不良品图片。可是在真实产线上一试,系统却把好几件表面纹理正常的工件误报成划痕。另一种情况是测试得分非常高,一上产线结果却下滑。这两种问题往往不出在模型,而出在数据:收集来的图片与实际工况不符,标注之间自相矛盾,或者同一张图片同时出现在训练集和测试集里。

本文不教训练模型,而是教你在训练前检查数据集(label 指由人来标明这张图是良品还是不良品,或不良在哪里),用的是可以真正运行的 Python 代码,只用 numpy。所有图像都由内存中的 seed 生成,没有图像文件。经理读说明和表格就能看懂,工程师可以直接跟着运行代码。

真实问题:看似齐全却教错了 AI 的数据集

缺陷图像集通常会犯三种错误。第一种是缺少良品和临界样本,模型从没见过正常纹理长什么样。第二种是两位标注员的标准不一致。第三种是近似重复的图像(例如对同一工件连拍的三帧)被随机分到了不同的集合。下面是三个假设情景,并非 BT San 任何客户的项目。

  • 假设的金属零件工厂:只收集了不良品托盘里的划痕图像,没有不同光照批次的良品图像。结果模型学到“表面变亮就是不良”。
  • 假设的产线装配场景:两位标注员对淡淡的痕迹算不算不良意见不同,各凭感觉判断,又没有 unsure 类别,因此在临界点上得到的标注是随机的。
  • 假设的重复拍摄工件的工厂:同一工件重新拍摄后登记成新的工件编号,按工件编号划分数据集时无法得知它们其实是同一张图,一张进了 train,另一张进了 test,测试得分因此虚高。

这三个问题都能在浪费训练时间之前用一小段代码查出来。下面的示例把整个流程做全了:把标注指南写成数据、衡量一致性、生成需要复核的图像清单、查看各批次的比例和覆盖情况、找出近似重复的图像,以及无泄漏地划分数据集。

文档怎么说,以及本示例不主张什么

主题文档的说法对我们示例的影响
标注指南Ultralytics 建议制定清晰且统一的标注标准,附上说明和示例图片,并定期复查和改进spec.py 把指南存成数据,validate 按指南检查每一条标注
一致性Ultralytics 指出,较高的 inter-annotator agreement 表明指南清晰、标注员的用法一致,但没有给出阈值数字我们报告 kappa 值,但不规定多少算够,需要自行与 QC 约定
kappa 公式scikit-learn 定义 kappa = (p_o - p_e) / (1 - p_e),取值在 -1.0 到 1.0 之间,0.0 表示一致程度不超过随机预期,文档中的示例给出 0.6875agreement.py 自行实现该公式,并以 0.6875 的示例作为测试
IoULabel Studio 把 IoU 解释为两个框重叠的面积除以合并后的总面积,取值 0.0 到 1.0。CVAT consensus 用 Min overlap 作为匹配阈值,对框而言相当于 IoUmatch_boxes 把 IoU 达到 0.5 以上的框配成一对,0.5 是我们自己选的值
重复图像Google ML Crash Course 要求删除 validation 和 test 集中与 training 集重复的样本,因为公平的测试需要新的样本,而不是重复的样本dedupe.py 找出近似重复的图像,然后 split.py 让同一组图像留在同一个集合
按组划分scikit-learn GroupKFold 指出,每个组在所有 fold 中只会在测试集出现一次思路相同,但我们自己写了简单的 train/val/test 划分器,没有调用 scikit-learn
数据不平衡Google ML Crash Course 把常见的类别称为 majority,罕见的类别称为 minority,并建议使用 downsampling 和 upweightingbalance.py 只报告比例和缺口,不调整权重
按所注明的文档整理,查阅日期为 2026-11-21。IoU 0.5 或 hash 距离 6 位这类数值阈值是本示例自行设定的,并非来自文档

本示例使用合成图像、两位假设的标注员和自行生成的数字,因此其中的 kappa 和 IoU 不能拿去与真实工厂数据比较。可以学到的是衡量方法和读结果的方法。

示例概览

全部代码位于 examples/defect-dataset-labeling-guide/ 文件夹,使用 Python 3 和 numpy,无需另外安装任何东西,不使用网络。

文件作用
spec.py把标注指南存成数据:类别、最小尺寸、良品的定义
synth.py由 seed 生成灰度图像(表面纹理、划痕、凹痕、淡痕、各批次不同的光照)
make_data.py 和 data/生成 A 和 B 两位标注员的图像清单和标注,并有意混入有问题的数据
agreement.py检查标注、kappa、IoU 以及需要复核的图像清单
balance.py类别比例和各批次的覆盖情况
dedupe.pyaverage hash 以及近似重复图像的分组
split.py按组划分 train/val/test,并检查泄漏
demo.py / test_dataset.py输出全部步骤的报告,以及 unittest 测试集

第 1 步:把标注指南写成数据,并包含 unsure 类别

Word 文档形式的指南无法自动检查,而数据形式的指南可以让代码检查每一条标注。需要写清楚的有三点。第一点是计入的 defect 的最小尺寸(示例中是长边至少 8 像素)。第二点是良品指什么,包括说明各批次亮度不同不算 defect。第三点是 unsure 类别,它是一个真实的类别,供标注员表示“看到了些什么,但无法判断”。这类图像会交给裁定人,而不是被悄悄猜成良品或不良品。

spec.py
"""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-duplicate
spec.py 类别、最小尺寸,以及良品和 unsure 的定义

这个文件中的 MIN_DEFECT_PX 和 IOU_MATCH 是示例的假设值,真实的数值必须来自产品标准或与 QC 的约定,最终的裁定人应是对实际产品质量负责的人。

第 2 步:生成带有“陷阱”的合成数据,使其像真实数据

synth.py 根据 seed 绘制图像。每个工件的表面来自 part_seed,帧的噪声来自 frame_seed,gain 是各批次的亮度,这样同一工件重新拍摄会得到相似但并非逐像素相同的图像。短而淡的痕迹就是 unsure 的情形。

synth.py
"""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)
synth.py 由 seed 生成的合成图像,没有图像文件

make_data.py 一共生成 40 个工件的 49 张图像,有三个光照不同的批次。批次 L3 有意只放很少的良品,好让覆盖情况报告能抓到,同时还加入了真实数据中常见的陷阱。

  • 近似重复的图像:有些工件有多帧,光照略有差异
  • 同一工件重新拍摄但登记了新编号(p041 就是 p005,p042 就是 p021)
  • 有问题的标注:指南中没有的类别、良品上的 3x3 框、超出图像范围的框,以及 B 没有标注的图像
  • B 对淡痕的判断标准与 A 不同,因此有真实的分歧可供衡量
make_data.py · 行 52–76
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 image
make_data.py 标注员 B 使用与 A 不同的标准,以及有意放入的问题数据

第 3 步:按指南检查标注,再衡量一致性

衡量一致性之前,先把格式有误的标注过滤掉,因为不符合指南的标注不应算作意见。validate 检查四件事:类别不在指南中、不良类别却没有框、良品却有框,以及框超出图像或小于指南规定。

agreement.py · 行 6–21
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 probs
agreement.py validate 对照 spec.py 检查一条标注

接着衡量图像级类别的 Cohen's kappa。思路是先看两人回答一致的比例(p_o),再扣除预计会因巧合而一致的部分(p_e),公式见 scikit-learn 文档。当类别不平衡时,这个扣除很重要,因为如果良品占 90%,任何人对所有图像都回答“良品”,也能有 90% 的一致,却什么都没检查。

agreement.py · 行 24–31
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)
agreement.py kappa 按公式 (p_o - p_e) / (1 - p_e)

框则用 IoU 衡量,即重叠面积除以合并面积,然后一对一地配对,按 IoU 从高到低排序。IoU 低于阈值的框视为不同的 defect,这与 CVAT consensus 用 overlap 阈值配对框的方式一致。

agreement.py · 行 34–40
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.0
agreement.py 两个框的 IoU
agreement.py · 行 43–52
def 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]
agreement.py 框的一对一配对

需要注意的是,薄划痕的框只有几个像素高,偏移一个像素 IoU 就会大幅下降,所以框级别的不一致往往比类别级别更高,应当一起看,而不是只看一个数字。

第 4 步:需要退回复核的图像清单

kappa 值能说明意见一致到什么程度,但不会告诉你哪些图像需要修改。因此 conflicts 函数生成附带原因的图像清单,共有四种:缺少标注、标注格式有误、类别不同,以及框重叠不够。清单排序时,涉及 unsure 的类别不同情形排在前面,因为这是指南最可能还不清晰的地方。

agreement.py · 行 55–72
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]))
agreement.py conflicts 生成需要复核的图像清单

第 5 步:类别比例和各批次的覆盖情况

用于训练的数据集应来自标注员意见一致的图像,仍在复核清单中的图像必须等裁定人处理。因此 balance.py 只统计不在清单中的图像,然后查看每个批次的良品是否足够,以及是否有类别缺失。结果会告诉你需要到哪里补采图像。

balance.py · 行 14–25
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 rows
balance.py 各批次的覆盖情况和警示标记

第 6 步:用 average hash 找出近似重复的图像

average hash 把图像缩小成 8x8 个格子,每个格子的亮度高于平均值就记为 1,得到一个 64 位的数。相似的图像只有很少几位不同,不同工件的图像则差异很大。与图像自身的平均值比较,使整幅图像变亮或变暗时 hash 值几乎不变,很适合各批次光照不同的情况。

dedupe.py · 行 6–10
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)
dedupe.py 64 位 average hash
dedupe.py · 行 17–33
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}
dedupe.py 用 union-find 合并 hash 相近的图像分组

分组用 union-find,因为“相近”是链式的:如果 A 与 B 相近、B 与 C 相近,那么三者必须归为同一组,即使 A 与 C 相距较远。局限是这种 hash 只能抓到明暗结构相似的图像,视角偏移或裁剪差异很大的图像会漏掉。实际使用时应换用更稳健的 perceptual hash,或用模型输出的向量来比较。

第 7 步:按组划分 train/val/test

思路与 scikit-learn 的 GroupKFold 相同:一个组的所有成员必须留在同一个集合。不同的是,我们的组不是工件编号,而是由近似重复图像分组得到的组,因此连重新登记了新编号的同一工件也能抓到。

split.py · 行 5–22
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 out
split.py 按组划分,优先补足离目标最远的集合
split.py · 行 25–30
def 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}
split.py 检查是否有组出现在多个集合中

这个划分器没有按类别划分,实际运行中 test 集得到 0 张 scratch 图像。真实数据中 defect 很少时,应做按组的 stratified 划分(例如 scikit-learn 的 StratifiedGroupKFold),也可能需要按批次或生产日期划分,以测试模型能否适应新批次。这是作者的结论,并非引自所参考的文档。

实际运行:一次输出全部报告

demo.py 加载数据,运行全部五个步骤,然后打印报告。下面的结果来自实际运行 python3 demo.py。

demo.py · 行 14–25
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")
demo.py 衡量一致性并打印复核清单的部分
output.txt
== 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)=3
2026-11-21 用 python3 demo.py 实际运行的输出(Python 3,numpy 2.3.5)

逐条解读结果

  1. 图像级 kappa 为 0.745,基于两人都标注了的 48 张图像(另有一张 B 没有标注)。这个数字不是模型的结果,而是说明指南里仍有临界情形。框配对得到 20 对,平均 IoU 为 0.600,比直觉低,因为划痕的框很薄。
  2. 复核清单有 13 张图像,其中类别不同 4 张(这 4 张都是某一方标了 unsure)、标注格式有误 4 张(p000 框超出图像,p001 出现指南中没有的 crack 类别,p002 和 p015 的框小于 8 像素)、缺少标注 1 张(p010)、框重叠不够 4 张。
  3. 有一张 p012_f1,A 判定为 scratch 而 B 判定为 unsure,而它的近似重复图像 p012_f0 两人却意见一致。这就是为什么应当把近似重复图像与标注对照检查:相同图像的标注应当相同。
  4. 去掉等待复核的图像后,剩下 good 22 张、scratch 8 张、dent 6 张、unsure 0 张。unsure 类别全部消失,因为都被送去复核了。如果现在训练,模型就从没见过临界情形。批次 L3 的良品只有 20%,因此被标上了警示标记。
  5. average hash 找到 7 组重复图像,涵盖连拍的帧以及两对被重新登记了编号的图像(p005 与 p041,p021 与 p042)。因此 49 张图像归并为 40 组。
  6. 只按工件编号划分有 1 组泄漏到不同集合,按 hash 分组划分则泄漏 0 组。各集合大小为 34、8 和 7 张图像,而 test 集得到 0 张 scratch 图像,正如上面的说明所提醒的。

怎么验证结果确实正确

测试集检查的是那些会悄悄出错的地方:kappa、IoU、对有问题标注的捕捉,以及不发生泄漏。kappa 用 scikit-learn 文档印出的 0.6875 示例来测试,并测试极端情形(完全一致得 1.0,一致程度等同随机得 0.0)。IoU 用可以手算的数字测试:50 除以 150 等于三分之一,仅边缘相贴的框得 0,相同的框得 1。

test_dataset.py · 行 12–40
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
test_dataset.py 测试 kappa、IoU、配对和有问题的标注

泄漏测试最重要,共有 3 项。第一项证明只按工件编号划分确实会泄漏(否则这个示例就没有意义)。第二项用 20 个不同的 seed 按 hash 分组划分,必须完全不泄漏,且每张图像都有所属集合。第三项证明光照改变 10% 不会让 hash 的距离超过阈值。

test_dataset.py · 行 42–64
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)
test_dataset.py 测试按组划分不会泄漏

在示例文件夹中运行 python3 -m unittest -v,8 项全部通过。

用于实际工作:示例跳过的部分

  • 真实图像:用读取图像文件取代 synth.py,并把元数据(批次、生产日期、相机、光照)与标注存在同一张表里,以便按批次出报告。所有图像都必须有可靠的批次和工件编号。
  • 标注工具:使用 CVAT 或 Label Studio 这类工具,它们自带一致性衡量和复核功能,再把这类代码当作对导出文件的额外检查关卡。
  • 多于两位标注员:双人 kappa 可以两两使用,或改用适用于多人的其他指标,并且要指定谁是最终裁定人。
  • hash:如果有十万张图像,逐对比较会很慢,应使用 BK-tree 或 LSH 这类索引,或者比较 embedding。
  • 数据集划分:按组做 stratified 划分,并把最新的至少一个批次留作 test 集,在最终评估之前不得触碰。
  • 裁定后的标注:保存谁在何时改了什么的记录,以便日后回溯检查,并把指南的版本与数据集一起保存。

假设示例:套用到三类业务

  • 假设的注塑工厂:检测烧焦痕迹和多余的飞边。原料批次颜色不同,导致反光不同,按批次出的报告可以在训练模型之前指出新颜色批次的良品还不够。
  • 假设的电路板组装工厂:检测临界的焊点痕迹。unsure 类别和复核清单让工程师与 QC 只需查看意见分歧的图像,不必全部看一遍。
  • 假设的食品加工厂:在传送带上连续拍摄产品,得到大量近似重复的帧。在划分数据集之前先合并近似重复图像的分组,可避免测试得分虚高。

常见错误和检查清单

  • 只收集不良品托盘里的不良品图像,却忘了每个批次、每个班次、每种光照下的良品图像。
  • 没有 unsure 类别,因而迫使人在临界点上猜,然后拿猜出来的标注去训练。
  • 只报告图像级的一致性,不看框级别。类别标注一致但指向不同位置,同样会教错模型。
  • 把 kappa 当作唯一的判断数字,而不看不一致出在哪里,应当结合复核清单一起看。
  • 按图像随机划分,或按不可靠的工件编号划分,导致重复图像泄漏到不同集合。
  • 复核标注后只改了训练集,把 test 集中错误的标注留在原处,因此测得的分数与实际不符。
  • 中途调整了指南却没有记录版本,导致之前和之后标注的图像使用了不同的标准,而没人知道。

把数据集送去训练前的检查清单

  1. 标注指南有书面文件,附有示例图像、最小尺寸、unsure 类别和版本号。
  2. 每个批次、每个班次、每种光照都有良品图像,而不仅仅是不良品。
  3. 每条标注都通过 validate,且没有指南之外的类别。
  4. 在随机抽取的子集上有两位或以上的标注员,报告 kappa 和 IoU,且复核清单已全部处理完毕。
  5. unsure 中的图像由质量负责人裁定,或者至少与评测集分开存放。
  6. 按批次的报告没有遗留的警示标记,或者有已确认的理由。
  7. 已合并近似重复的图像分组,且 train/val/test 没有跨集合的组。
  8. test 集单独保存,没有被用来调整任何模型或阈值。

本示例的注意事项:使用合成图像和假设的标注员,因此没有用真实工厂数据测试。average hash 只能抓到明暗结构相似的图像。得到的 kappa 和 IoU 只适用于这一组数据。IoU 0.5 和最小尺寸 8 像素这类阈值必须根据实际工件和图像分辨率重新设定。本示例用于学习,不是 production 代码。

参考资料

  1. Ultralytics docs: Data collection and annotation for computer vision (accessed 2026-11-21)
  2. Ultralytics docs: Performance metrics (IoU, mAP50, mAP50-95) (accessed 2026-11-21)
  3. scikit-learn: cohen_kappa_score (accessed 2026-11-21)
  4. scikit-learn: GroupKFold (accessed 2026-11-21)
  5. CVAT docs: Consensus (Min overlap, agreement score) (accessed 2026-11-21)
  6. Label Studio docs: Task agreement and annotator agreement (IoU for boxes, exact match) (accessed 2026-11-21)
  7. Google ML Crash Course: Dividing the original dataset (accessed 2026-11-21)
  8. Google ML Crash Course: Imbalanced datasets (accessed 2026-11-21)

在 LINE 上添加我们

请用手机上的 LINE 应用扫描

添加 LINE @Bankoos 的二维码

LINE ID: @Bankoos

在这台电脑上打开 LINE