计算机视觉 / 系统课时
定位误检样本
定位误检样本
本课解决“模型为什么把不存在的目标识别出来”这一问题。你将从验证集生成带置信度的预测结果,自动筛出无法与真实标注匹配的检测框,再依据背景相似、类别边界、阈值设置和样本偏差完成归因与复验。
学习目标
- 明确误检样本的判定标准,区分误检、漏检与类别混淆
- 生成可追溯的预测标签,并自动定位误检所在图片
- 根据误检特征选择阈值调整、补充样本或修订标注规范
误检判定与定位流程
在目标检测中,预测框若无法与同类别真实框形成足够大的交并比,就可视为误检。常用判定条件是同类别且 IoU 不低于 0.5;若位置匹配但类别不同,则预测类别产生一次误检,真实类别同时产生一次漏检。

定位时必须固定验证集、权重、输入尺寸和阈值,否则两次结果无法直接比较。先记录误检图片、预测类别、置信度和最佳 IoU,再判断它属于偶发错误还是稳定模式。
生成并筛选误检样本
先在验证集上执行推理,并保存每个预测框的类别、归一化坐标和置信度。下面示例假设验证集图片位于 datasets/helmet/images/val,真实标签位于对应的 datasets/helmet/labels/val。
python detect.py \
--weights runs/train/exp/weights/best.pt \
--source datasets/helmet/images/val \
--img 640 \
--conf-thres 0.25 \
--iou-thres 0.45 \
--save-txt \
--save-conf \
--project runs/error-analysis \
--name predictions \
--exist-ok预期输出:
Results saved to runs/error-analysis/predictions预测标签默认写入 runs/error-analysis/predictions/labels。每行格式为 class x_center y_center width height confidence,真实标签则没有最后的置信度字段。
将下面脚本保存为 tools/find_false_positives.py。它按置信度从高到低匹配同类别真实框,避免多个预测重复占用同一个真实框;未达到 IoU 阈值的预测会被输出为误检候选。
from __future__ import annotations
import argparse
from pathlib import Path
def xywh_to_xyxy(values: list[float]) -> tuple[float, float, float, float]:
x, y, w, h = values
return x - w / 2, y - h / 2, x + w / 2, y + h / 2
def read_labels(path: Path, with_confidence: bool) -> list[dict]:
if not path.exists():
return []
expected = 6 if with_confidence else 5
records = []
for line_no, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
parts = line.split()
if len(parts) != expected:
raise ValueError(f"{path}:{line_no} 字段数应为 {expected}")
cls_id = int(float(parts[0]))
box = xywh_to_xyxy([float(value) for value in parts[1:5]])
confidence = float(parts[5]) if with_confidence else 1.0
records.append({"class_id": cls_id, "box": box, "confidence": confidence})
return records
def box_iou(a: tuple[float, ...], b: tuple[float, ...]) -> float:
left, top = max(a[0], b[0]), max(a[1], b[1])
right, bottom = min(a[2], b[2]), min(a[3], b[3])
intersection = max(0.0, right - left) * max(0.0, bottom - top)
area_a = max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1])
area_b = max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1])
union = area_a + area_b - intersection
return intersection / union if union > 0 else 0.0
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--images", type=Path, required=True)
parser.add_argument("--ground-truth", type=Path, required=True)
parser.add_argument("--predictions", type=Path, required=True)
parser.add_argument("--iou-thres", type=float, default=0.5)
args = parser.parse_args()
suffixes = {".jpg", ".jpeg", ".png", ".bmp"}
print("image,pred_class,confidence,best_iou")
for image in sorted(p for p in args.images.iterdir() if p.suffix.lower() in suffixes):
targets = read_labels(args.ground_truth / f"{image.stem}.txt", False)
predictions = sorted(
read_labels(args.predictions / f"{image.stem}.txt", True),
key=lambda item: item["confidence"],
reverse=True,
)
matched: set[int] = set()
for prediction in predictions:
best_index, best_iou = -1, 0.0
for index, target in enumerate(targets):
if index in matched or target["class_id"] != prediction["class_id"]:
continue
score = box_iou(prediction["box"], target["box"])
if score > best_iou:
best_index, best_iou = index, score
if best_index >= 0 and best_iou >= args.iou_thres:
matched.add(best_index)
else:
print(
f"{image.name},{prediction['class_id']},"
f"{prediction['confidence']:.3f},{best_iou:.3f}"
)
if __name__ == "__main__":
main()预期结果:脚本输出 CSV 格式的误检候选,实际行数取决于模型和验证集。
python tools/find_false_positives.py \
--images datasets/helmet/images/val \
--ground-truth datasets/helmet/labels/val \
--predictions runs/error-analysis/predictions/labels \
--iou-thres 0.5预期输出:
image,pred_class,confidence,best_iou
<IMAGE_NAME>,<CLASS_ID>,<CONFIDENCE>,<BEST_IOU>若只想优先检查高风险误检,可先按置信度降序查看。高置信度误检通常比边缘低分框更能暴露标签冲突、背景偏差或类别定义问题。
从样本反推原因并修复
| 误检模式 | 主要证据 | 优先处理 |
|---|---|---|
| 相似背景被稳定识别为目标 | 多张图片在相同纹理或区域出现同类框 | 收集这些背景作为困难负样本,确保标签文件为空但图片参与训练 |
| 两个类别互相混淆 | 误检集中在外观相近类别,人工也难快速区分 | 明确类别边界,统一标注规则,必要时合并不可稳定区分的类别 |
| 大量低分框形成误检 | 误检置信度集中在较低区间 | 在验证集上选择更合适的置信度阈值,同时观察召回率下降幅度 |
| 特定场景误检明显增多 | 夜间、逆光、摄像头角度或地域背景集中出错 | 补充对应场景样本,并检查训练集与部署环境是否存在分布偏差 |
修复后必须使用同一验证集重新推理,比较误检数量、Precision、Recall 和 mAP。单纯提高置信度阈值只能改变部署取舍,不能修复错误的类别定义或训练数据偏差;阈值升高还可能把原本正确的低分框变成漏检。
本课总结
- 误检定位应基于固定验证集,并记录预测类别、置信度和最佳 IoU
- 自动匹配可以快速缩小检查范围,但最终归因仍需结合原图与标注规范
- 修复策略必须针对原因:背景问题补困难负样本,类别冲突修订定义,场景偏差补对应数据
下一课预告
下一课将分析漏检样本,重点检查小目标、遮挡、标注缺失和召回率不足,并建立与误检分析互相配合的评估流程。