目标检测:找到物体,再判断框得对不对
Object detection
从像素写出一个小检测器,追踪重复预测如何影响匹配,并推导三种 AP 口径为什么给出不同结果。
object-detection两个物体,三个很有把握的答案
设想一张暗色图像里有两个亮矩形。检测器给出三个框:第一个框住左边的矩形,第二个又框住它,第三个框住右边的矩形。每个框都与真实物体重合。检测器是否做出了三次正确预测?
若把三个都算对,就会奖励重复报答案的系统。目标检测既要定位,也要记账:这个预测指向哪个物体?那个物体是否已经记过一次功?因此,不能只看每张裁剪图像是不是像一个合理的物体,就完成检测评测。
图像分类给出图像层面的答案。检测器输出数量可变的一组类别、位置和分数;空场景输出零个检测也是有效结果。框描述物体范围,不像分割掩码那样逐像素指出前景。这些任务区别在 VOC 任务定义中有明确说明。
我们先用亮度和连通区域写一个简单检测器,让像素到框的流程完整跑通,无须先学会训练神经网络。然后主动加一个重复预测,追踪它对评测的影响。这里的场景、标注和分数都是教学例子,不是基准成绩。
从几何、匹配到排序
坐标约定也是算法的一部分
采用连续角点坐标,顺序为左、上、右、下,简称 xyxy。图像原点在左上角,x 向右增加,y 向下增加。框覆盖半开矩形,不含右侧和下侧边界。因此 (1, 1, 3, 3) 覆盖四个单位像素,宽高都为 2。我们要求宽高严格为正。
另一些系统使用中心点加宽高,或左上角加宽高。后一种格式转成 xyxy 时,应把宽加到左坐标、高加到上坐标。给每个宽度都加 1 会改变本例几何;只有另一个离散且含端点的坐标约定明确需要时才这样做。VOC 文件格式把左上角像素记为 (1, 1),所以本例从零开始的场景坐标不能原样当作提交文件。VOC 第 4.3 节
对框 A 和 B,先分别求水平、垂直区间的交集。交集长度若为负,表示没有重叠,应截为零。并集面积中减去一次交集,是为了避免重复计算共享部分:
交并比(intersection over union,IoU)对有效、有限面积的框介于 0 和 1 之间。两框相同得到 1;只沿边接触得到 0。两个宽高均为 2 的框水平错开 1,交集面积为 2,并集面积为 6,IoU 就是 1/3。IoU 衡量几何重叠,不是类别预测正确的概率。
先决定谁记功,再画曲线
本例评测器处理任意多张图像中的一个类别。预测按分数从高到低排列,同分时保留输入顺序。对每个预测,在同一图像里找 IoU 最高的真实框;只有重叠严格大于指定阈值、且该真实框尚未匹配时,才记为真正例(TP),否则记为假正例(FP)。真实框的 IoU 相同时按标注顺序选择。重复预测不会被转给重叠第二高的真实框。
这是明确的教学约定,并非所有评测器都如此匹配。VOC 文档要求重叠超过 50%,处罚重复检测,并忽略 difficult 物体;本例省略了 difficult 处理。固定版本的 COCO 实现在搜索时跳过已匹配的普通真实框,并另有 crowd 和 ignore 规则;其阈值比较也接受恰好相等的情况。拥挤场景中的匹配结果可能因此改变。VOC 第 4.4 节、COCO 匹配代码
教学例中的排序分数为 0.9、0.8、0.7,TP 标记依次为 1、0、1。真实物体数 G=2,在每个排名 k 处计算累计精确率和召回率:
| 排名 | 发生了什么 | 精确率 | 召回率 |
|---|---|---|---|
| 1 | 找到第一个物体 | 1 | 1/2 |
| 2 | 重复报告第一个物体 | 1/2 | 1/2 |
| 3 | 找到第二个物体 | 2/3 | 1 |
重复预测增加了精确率的分母,却没找到新物体。降低分数阈值会保留更多预测,但只有其中某个预测匹配了新物体,召回率才会提高。分数阈值负责筛选预测,IoU 阈值负责判断重叠,两者控制的事情不同。
为什么写 AP 时还要写定义
召回水平 r 处的插值精确率,取实测曲线在该召回或更高召回处的最大精确率;如果根本达不到 r,则取零。沿召回率积分这个包络,就得到全点平均精确率:
本例前半段召回的包络高度是 1,后半段是 2/3,面积为 1/2 + (1/2)(2/3) = 5/6。这不是把三次原始精确率取算术平均。VOC2010 把原来的固定 11 点采样改成了这种全点积分。VOC 第 3.4.1 节
若改在召回率 0、0.1、……、1 处采样,会得到六个 1 和五个 2/3,平均为 28/33。若改为 101 个等距召回点,则有 51 个 1 和 50 个 2/3,平均为 253/303。下面的函数支持这三种计算,让差别可以直接观察。
固定版本的 COCO 代码使用 101 个召回采样点、从 0.50 到 0.95 的十个 IoU 阈值,并处理类别、面积范围和检测数量限制。其常规检测默认值包括每张图最多 1、10、100 个检测,用于不同的汇总。仅在本例中选择 101 点,并不等于实现了 COCO AP。“mAP”同样需要说明对哪些类别、阈值和有效情形取平均。COCO 累积评测及检测参数
跑通一个完整的小基线
下面是只依赖 Python 标准库的完整程序。检测器访问亮像素,按四邻接分组,再取每组坐标的最小值和最大值。分数是该连通区域的平均亮度,对这个构造场景有用,但不是经过校准的物体概率。
真实标签直接写成场景设计中的坐标,与检测输出独立。若从预测框反过来生成标签,测试就会陷入自证。额外的重复预测是在检测后主动加入的;基线本身返回两个框。
"""Original teaching detector/evaluator; continuous xyxy, one category, no ignored GT."""
import math
def box(value):
b = tuple(float(x) for x in value)
if len(b) != 4 or not all(math.isfinite(x) for x in b):
raise ValueError('box needs four finite coordinates')
if not (0 < b[2] - b[0] < math.inf and 0 < b[3] - b[1] < math.inf):
raise ValueError('box must have finite positive width and height')
return b
def iou(first, second):
a, b = box(first), box(second)
lengths = (a[2]-a[0], a[3]-a[1], b[2]-b[0], b[3]-b[1])
scale = max(lengths)
aw, ah, bw, bh = (v / scale for v in lengths)
iw = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) / scale
ih = max(0.0, min(a[3], b[3]) - max(a[1], b[1])) / scale
intersection = iw * ih
union = aw * ah + bw * bh - intersection
if union <= 0 or not math.isfinite(union):
raise ValueError('box areas exceed supported numerical range')
return intersection / union
def components(image, threshold=0.5, min_area=1):
"""Four-neighbor bright components; score is mean brightness, not probability."""
if not math.isfinite(threshold) or not 0 <= threshold <= 1:
raise ValueError('threshold must be in [0,1]')
if type(min_area) is not int or min_area < 1:
raise ValueError('min_area must be a positive integer')
height = len(image)
width = len(image[0]) if height else 0
if any(len(row) != width for row in image):
raise ValueError('image must be rectangular')
if any(not math.isfinite(v) or not 0 <= v <= 1 for row in image for v in row):
raise ValueError('pixels must be finite values in [0,1]')
seen, detections = set(), []
for y in range(height):
for x in range(width):
if image[y][x] <= threshold or (y, x) in seen:
continue
stack, pixels = [(y, x)], []
seen.add((y, x))
while stack:
py, px = stack.pop()
pixels.append((py, px))
for ny, nx in ((py-1, px), (py+1, px), (py, px-1), (py, px+1)):
if (0 <= ny < height and 0 <= nx < width and
image[ny][nx] > threshold and (ny, nx) not in seen):
seen.add((ny, nx))
stack.append((ny, nx))
if len(pixels) >= min_area:
ys, xs = zip(*pixels)
bounds = (min(xs), min(ys), max(xs)+1, max(ys)+1)
score = math.fsum(image[py][px] for py, px in pixels) / len(pixels)
detections.append((bounds, score))
return detections
def ap_from_flags(flags, positives, samples=None):
"""Flags are TP/FP in descending score order. Return None if no positive GT."""
flags = list(flags)
if type(positives) is not int or positives < 0:
raise ValueError('positives must be a nonnegative integer')
if any(type(f) is not int or f not in (0, 1) for f in flags) or sum(flags) > positives:
raise ValueError('invalid TP flags')
if samples is not None and (type(samples) is not int or samples < 2):
raise ValueError('samples must be at least two, or None')
if positives == 0:
return None
tp, recalls, precision = 0, [], []
for rank, flag in enumerate(flags, 1):
tp += flag
recalls.append(tp / positives)
precision.append(tp / rank)
envelope = precision[:]
for k in range(len(envelope)-2, -1, -1):
envelope[k] = max(envelope[k], envelope[k+1])
if samples is not None:
return math.fsum(max((p for r, p in zip(recalls, envelope)
if r >= j/(samples-1)), default=0.0)
for j in range(samples)) / samples
previous, areas = 0.0, []
for recall, p in zip(recalls, envelope):
areas.append((recall-previous)*p)
previous = recall
return math.fsum(areas)
def evaluate(truth, predictions, threshold=0.5):
"""Single class across images. Best GT first; duplicates never get reassigned."""
if not math.isfinite(threshold) or not 0 <= threshold <= 1:
raise ValueError('IoU threshold must be in [0,1]')
truth = {image: [box(b) for b in boxes] for image, boxes in truth.items()}
validated = []
for index, (image, bounds, score) in enumerate(predictions):
if not math.isfinite(score):
raise ValueError('scores must be finite')
validated.append((index, image, box(bounds), score))
used, flags = set(), []
for _, image, bounds, _ in sorted(validated, key=lambda p: (-p[3], p[0])):
overlaps = [iou(bounds, gt) for gt in truth.get(image, [])]
best = max(range(len(overlaps)), key=overlaps.__getitem__) if overlaps else None
match = (image, best)
hit = best is not None and overlaps[best] > threshold and match not in used
flags.append(int(hit))
if hit:
used.add(match)
positives = sum(map(len, truth.values()))
return {'flags': flags, 'AP': ap_from_flags(flags, positives)}
if __name__ == '__main__':
image = [[0.0]*12 for _ in range(8)]
for y in range(1, 3):
for x in range(1, 3):
image[y][x] = 0.9
for y in range(4, 6):
for x in range(8, 10):
image[y][x] = 0.7
found = components(image)
# Labels come from the scene design, independently of the detector output.
truth = {'demo': [(1, 1, 3, 3), (8, 4, 10, 6)]}
predictions = [('demo', b, s) for b, s in found]
predictions.append(('demo', (1, 1, 3, 3), 0.8))
result = evaluate(truth, predictions)
print('boxes:', [b for b, _ in found])
print('TP flags:', result['flags'])
print('all-point AP:', round(result['AP'], 6))
print('11-point AP:', round(ap_from_flags(result['flags'], 2, 11), 6))
print('101-point AP:', round(ap_from_flags(result['flags'], 2, 101), 6))
预期输出:
boxes: [(1, 1, 3, 3), (8, 4, 10, 6)]
TP flags: [1, 0, 1]
all-point AP: 0.833333
11-point AP: 0.848485
101-point AP: 0.834983
对 H×W 个像素,连通区域遍历的时间和最坏存储量均为 O(HW)。有 D 个预测时,分数排序耗时 O(D log D);若每张图的真实框不超过 G 个,直接匹配最多需要 O(DG) 次重叠计算。匹配完成后的全点包络耗时 O(D)。本例为便于阅读,采样版直接遍历,S 个召回点需要 O(SD);生产评测器可以利用有序查找。
IoU 函数先缩放长度再计算面积乘积,因此比直接相乘更能处理整体很大的坐标。它拒绝无效尺寸和部分无法表示的情况,但不是任意精度几何。常规图像坐标不会接近这些极端值。
走出构造场景后,哪里会出错?
在两个亮矩形之间加一条亮桥,基线可能把它们合并。让物体暗于阈值,它就会消失;亮背景杂物则会被当作物体。两个矩形上全对,并不能说明系统会认猫、处理遮挡,或区分相邻实例。
学习型检测器还要决定如何表示候选、预测类别,以及利用训练数据细化坐标。接下来的区域方法、YOLO、SSD和 DETR分别讨论这些建模问题,与本章的指标问题相衔接。非极大值抑制专门讨论候选筛选;筛选无法找回根本没被提出的物体。
AP 汇总的是排序。若对全部分数施加严格递增变换,排序不变;在筛选和数量限制也没有变化时,本例 AP 就不变。但这不保证概率校准仍相同。单个 AP 也无法说明哪些类别、物体尺寸或场景条件容易失败。选择部署阈值前,应检查这些分组和真实错例。
没有真实正例时,程序返回 None,因为召回率没有分母;有真实正例却没有预测时,AP 为 0。汇总时要区分二者,不能悄悄把所有未定义类别都算成零。正式基准应使用指定官方评测器;比较实验时,固定分数阈值、数据划分和匹配口径。参数选择使用训练集与验证集,不应反复查看测试标签来调参。
先预测,再手算和测试
1. 框平移一个像素
两个框为 (0, 0, 2, 2) 和 (1, 0, 3, 2)。计算 IoU。把第一个当作真实框,第二个能否通过 0.5 的重叠阈值?
答案:交集面积为 2,并集面积为 6,IoU 为 1/3,不能通过。置信分数再高,也不会改变几何重叠。
2. 把重复框排到最后
只把重复预测的分数从 0.8 改为 0.6。TP 标记和全点 AP 会变成什么?
答案:标记变成 1、1、0。两次召回增加时精确率都为 1,所以 AP 变成 1。最后那个重复框仍是 FP,最终精确率仍为 2/3。这说明 AP 需要结合实际工作阈值和误检阅读,不能把它当成完整的错误清单。
3. 接触不等于连通
对 [[1, 0], [0, 1]] 运行检测器,会出现几个连通区域?如果允许对角邻居,会发生什么?
答案:四邻接得到两个区域,各自是一个像素的框。八邻接会把两个对角像素连成一组,框为 (0, 0, 2, 2),其中还包含两个暗像素。因此,框的覆盖面积不一定等于前景面积。
4. 101 点 AP 是否就是 COCO 复现?
本例输出 0.834983,能把它标成“COCO AP”吗?还缺哪些信息?
答案:不能。这里只改变召回采样。本例只有一个类别和一个 IoU 阈值,匹配语义也不同,还缺少 crowd/ignore 处理、面积范围和每图数量限制,并且使用的是合成数据。复现需要指定数据集、评测协议,以及官方实现或经过验证的等价实现。
把评测口径和数值放在一起保存
- VOC2010 开发包文档,第 3.4.1、4.1–4.4 节提供 AP 变更、检测输出格式及评测规则。本次读取了数学图片的替代文本,没有运行完整 MATLAB 开发包。
- 固定提交 6c3b394 的 COCO 评测器用于核对匹配、累积评测和默认检测参数。这是 2019 年的固定版本,不代表所有后续竞赛;已核看 BSD-2-Clause 许可,未复制或执行上游代码。
本章程序、场景和数值推演均为原创教学材料。可从精确率与召回率主题理解阈值取舍,以及模型评测理解实验设计。以后记录检测指标时,把坐标、匹配和平均方式一起保存,数值才有可比的含义。
先判断,再看解释
两个真实物体,按分数排序的TP标记为[1,0,1],全点插值AP是多少?
学习目标
- 转换框坐标,在不混用像素约定的前提下推导IoU。
- 追踪重复框和分数排序如何影响匹配、精确率、召回率和AP。
- 运行并检验完整非AI检测基线,区分不同基准协议。
先修与延伸
查看知识关联图 →参考文献
- PASCAL VOC2010 Development Kit — detection and average precision
Mark Everingham; John Winn · 2010 - COCO API detection evaluator — fixed commit 6c3b394 (2019-12-25)
Piotr Dollar; Tsung-Yi Lin; COCO API contributors · 2019
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary documentation and pinned official source; original pixel detector, independent geometry/AP references, boundary tests and bilingual reasoning. Not independent human review or a VOC/COCO benchmark reproduction.
- 核对独立标注的像素连通区域,以像素集合穷举整数框IoU,以召回等级定义穷举短TP序列AP,核对重复匹配、精确分数及无效/空输入。九项计算检查及一项双语结构检查。
- 逐节核读中英文坐标约定、匹配、包络推导、例子、复杂度、限制和四组答案;Python与展示公式完全相同。
- 最终链接检查发现precision-recall只有目录尚无正文,双语链接改指目录,且本章已解释所需定义,因此移除该假定先修。手机目视检查后把IoU公式等价拆成区间端点以适配屏宽。保留冻结原稿,程序、数值推演和习题答案不变。
核对的来源位置:
- PASCAL VOC2010 Development Kit — detection and average precision · VOC2010 HTML sections 3.4.1 and 4.1–4.4; formula image alt text read, no devkit execution.
- COCO API detection evaluator — fixed commit 6c3b394 (2019-12-25) · Commit 6c3b394c07aed33fd83784a8bf8798059a1e9ae4, cocoeval.py lines 265–298, 360–410 and 500–513; license.txt and commit date checked.
相关主题