实例分割:这些像素到底属于哪个物体?
Instance segmentation
区分类别与物体身份,推导掩码匹配和AP,运行一个只多连上一个像素就失败的连通分量基线。
instance-segmentation只多一个像素,两个物体就变成了一个
设想一张小型合成图:两个明亮矩形各占12个像素。把图像阈值化,再把相连的前景像素归为一组,就能找出两个物体。现在把间隙里的一个像素调亮。前景预测只改变一个像素,两个连通分量却合成了一个。
前景交并比仍是24/25,也就是0.96。但把合并预测与任一独立物体比较,交集只有12、并集为25:实例IoU只有0.48。在0.5的匹配阈值下,两个物体都没有被成功检测。下方程序会从真实二值掩码算出这些数值。
语义分割询问每个像素属于哪一类。实例分割还要回答这些像素属于哪个具体物体。两个人同属一个类别,却必须保留不同的实例身份。Mask R-CNN把目标检测与逐检测区域的掩码结合起来;它是这项任务的一种方法,不是任务本身的定义。Mask R-CNN第3节
先把身份表示清楚,再选择分数
掩码不是框,类别不是身份
对高H、宽W的图像,可以用一组二值掩码、类别和置信度表示预测。数量N本身也是预测的一部分:
分数用于排序,并不会自动成为经过校准的“实例预测正确概率”。实例下标i只是本张图像里某个条目的身份。跨视频帧判断是不是同一个物体,是另一项跟踪任务。
整数标签图在每个像素存一个实例ID,常用0表示背景;它适合表示互不重叠的可见区域。多个独立掩码还可以表示重叠,但把它们压成一张整数图必须制定冲突规则,可能丢失信息。标注只覆盖可见部分,还是推断被遮挡部分,必须由数据集约定。本例只处理给定的二值像素。
框保留的几何信息少于掩码。在2×2网格中,主对角线和另一条对角线的前景像素完全不相交,却拥有相同的整图外接框。框IoU为1,掩码IoU为0。用框重叠评价掩码,测量的就不是物体的像素形状。
普通重叠与crowd重叠回答不同问题
对普通二值掩码P与G,数出前景交集和并集:
程序把空并集的值明确设为0,并在评测时拒绝空真值实例。这是教学实现的显式契约,不是说“没有任何像素的物体”是一种有意义的标注。空间尺寸不同的掩码也会被拒绝。
COCO对标为crowd的区域采用另一种重叠计算。一个检测可能只描述人群中的一部分,因此该真值区域的重叠分母改为检测区域的面积:
一个像素的检测完全包含在九像素crowd区域中,普通IoU为1/9,crowd重叠为1。这不表示它在每一种汇总中都成了普通真阳性:crowd匹配与忽略规则由评测器配合处理。掩码工具与匹配逻辑需要一起读。固定掩码API、C重叠实现
重复掩码不能把同一物体检测两次
在同一张图、同一类别内,先按置信度降序排列预测,并应用检测数量上限。依次处理每个预测,在尚可使用的真值中,选择达到阈值且重叠最好的一个。普通真值只能使用一次。同一物体的第二个预测会成为假阳性,除非它匹配到另一个尚未使用的真值。
这种贪心匹配不是DETR训练里的全局代价分配。评测顺序使置信度产生具体作用。本程序中,相同分数保留输入顺序;候选IoU相等时更新为后遇到的真值,使并列情况可复现。固定COCO实现还处理可重复匹配的crowd、普通匹配的优先级、面积与忽略规则;本例较窄的评测器不包含这些功能。其准备代码也不是原样保留任意传入的ignore字段:对这些任务,它会用iscrowd重设该值。固定评测器的准备与逐图匹配
精度、召回与说清设置的AP
排在前k个的检测中,令T(k)、F(k)分别为累计真阳性和假阳性,G为适用的真值实例数:
某个召回阈值上的插值精度,取所有达到或超过该召回率的位置中最好的精度。如果没有检测达到它,就取0。本例只考虑一个IoU阈值、一个类别、一张图,其AP定义为:
这里明确把空集合上的最大值定义为0。如果没有适用的真值,AP没有定义,程序返回None,不能解释成满分或零分。有真值而没有预测时,AP为0。101点插值遵循固定评测器的累积过程,但这个局部结果不是完整COCO AP:它只有一个选定IoU阈值,没有全数据集汇总、多阈值、面积范围和crowd/忽略处理。固定评测器的累积部分
两个真值物体,预测顺序为真阳性、重复假阳性、真阳性。召回率依次为0.5、0.5、1,精度为1、1/2、2/3。0到0.5共有51个召回阈值,超过0.5有50个,所以:
编码与计算成本
游程编码保存连续背景/前景段的长度。COCO要求列优先的二值掩码布局,游程列表从0值段开始,长度可以为0。对[[1,0,1],[0,1,0]],列优先游程是[0,1,2,2,1];逐行遍历会得到另一组计数。COCO压缩counts字符串又是另一种表示,不能与这里打印的Python列表混称。RLE契约和包装函数
简单形状通常容易压缩。前景与背景交替的图案,游程数量可能与像素数同阶;不能把有利的形状假设改写成适用于所有掩码的平方根复杂度上界。
令像素数P=HW,固定使用4或8邻域时,广度优先连通分量标记的时间、空间都是O(P)。显式生成N张完整掩码需要O(NP)空间。直接比较N个预测与G个真值,需要O(NGP)时间,并存储O(NG)个重叠值;排序为O(N log N),贪心匹配为O(NG)。这些描述本例代码,不是优化后的编码掩码后端。
运行一个能看见失败原因的基线
下面是完整程序,环境为Python 3.12、NumPy 1.26.4。它对有限灰度图阈值化,标记连通分量,再用分量平均亮度排序。物体是分离明亮区域时,这是一条可用基线。平均亮度只是合成例子方便使用的排序规则,不是学出的置信度估计器。
评测器接受二值掩码栈,以保留重叠。它要求非空真值掩码、有限分数、整数类别及相同图像尺寸,只处理普通实例。把连通性从4改成8,可以看到对角接触的像素合并;两种设置都无法可靠分开已经被前景像素连接的两个物体。
"""Original threshold/component baseline and one-image, one-class mask AP.
Ordinary, nonignored instances only. No crowd/area filters, multiple-image
aggregation or full COCO evaluator. AP uses 101-point interpolated precision
at one specified IoU threshold. Binary mask stacks can preserve overlap.
"""
import json
from collections import deque
import numpy as np
def binary(value, dimensions):
a = np.asarray(value)
if a.ndim != dimensions or min(a.shape[-2:]) < 1 or a.dtype.kind not in 'buif' or not np.isin(a, [0, 1]).all():
raise ValueError('binary arrays with nonempty height and width required')
return a.astype(bool)
def components(mask, connectivity=4):
mask = binary(mask, 2)
if connectivity not in (4, 8):
raise ValueError('connectivity must be 4 or 8')
directions = [(dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)
if (dy or dx) and (connectivity == 8 or abs(dy)+abs(dx) == 1)]
labels = np.zeros(mask.shape, int)
height, width = mask.shape
label = 0
for y, x in np.argwhere(mask):
if labels[y, x]:
continue
label += 1
labels[y, x] = label
queue = deque([(y, x)])
while queue:
yy, xx = queue.popleft()
for dy, dx in directions:
ny, nx = yy+dy, xx+dx
if 0 <= ny < height and 0 <= nx < width and mask[ny, nx] and not labels[ny, nx]:
labels[ny, nx] = label
queue.append((ny, nx))
return labels
def baseline(image, threshold=.5, connectivity=4):
image = np.asarray(image, float)
if image.ndim != 2 or min(image.shape) < 1 or not np.isfinite(image).all() or not np.isfinite(threshold):
raise ValueError('finite nonempty grayscale image and threshold required')
labels = components(image >= threshold, connectivity)
masks = np.array([labels == i for i in range(1, int(labels.max())+1)], bool).reshape(-1, *image.shape)
# Region mean intensity ranks this toy baseline; it is not a calibrated
# probability that the region is a correctly separated object.
scores = np.array([image[mask].mean() for mask in masks])
return masks, scores, labels
def mask_iou(predicted, truth):
p, g = binary(predicted, 3), binary(truth, 3)
if p.shape[1:] != g.shape[1:]:
raise ValueError('matching image dimensions required')
result = np.zeros((len(p), len(g)))
for i, pm in enumerate(p):
for j, gm in enumerate(g):
union = np.count_nonzero(pm | gm)
result[i, j] = np.count_nonzero(pm & gm)/union if union else 0.
return result
def category_array(labels, count):
a = np.asarray(labels)
if a.shape != (count,) or a.dtype.kind not in 'iu' or np.any(a < 0):
raise ValueError('nonnegative integer categories of the correct length required')
return a
def evaluate(truth, truth_classes, predicted, predicted_classes, scores,
category=1, threshold=.5, max_detections=100):
g, p = binary(truth, 3), binary(predicted, 3)
gc, pc = category_array(truth_classes, len(g)), category_array(predicted_classes, len(p))
scores = np.asarray(scores, float)
if g.shape[1:] != p.shape[1:] or scores.shape != (len(p),) or not np.isfinite(scores).all():
raise ValueError('same image size and finite score per prediction required')
if np.any(g.sum(axis=(1, 2)) == 0):
raise ValueError('ground-truth instance masks must be nonempty')
if type(category) is not int or category < 0 or not np.isfinite(threshold) or not 0 < threshold <= 1:
raise ValueError('nonnegative category and IoU threshold in (0,1] required')
if type(max_detections) is not int or max_detections < 1:
raise ValueError('positive integer detection limit required')
gt = np.flatnonzero(gc == category)
dt = np.flatnonzero(pc == category)
dt = dt[np.argsort(-scores[dt], kind='stable')[:max_detections]]
overlaps = mask_iou(p[dt], g[gt])
used = np.zeros(len(gt), bool)
matches = np.full(len(dt), -1, int)
for i in range(len(dt)):
best, chosen = threshold, -1
for j in range(len(gt)):
if not used[j] and overlaps[i, j] >= best:
best, chosen = overlaps[i, j], j
if chosen >= 0:
used[chosen] = True
matches[i] = int(gt[chosen])
tp = np.cumsum(matches >= 0)
precision = tp/np.arange(1, len(dt)+1)
# No applicable GT: AP is undefined, not a perfect score or a zero.
recall = tp/len(gt) if len(gt) else np.full(len(dt), np.nan)
ap = None
if len(gt):
envelope = np.maximum.accumulate(precision[::-1])[::-1]
positions = np.searchsorted(recall, np.linspace(0, 1, 101), side='left')
samples = np.zeros(101)
valid = positions < len(dt)
samples[valid] = envelope[positions[valid]]
ap = float(samples.mean())
return {'ap101': ap, 'detectionIndices': dt.tolist(), 'matchedTruthIndices': matches.tolist(),
'truePositive': (matches >= 0).tolist(), 'precision': precision.tolist(),
'recall': recall.tolist() if len(gt) else None, 'groundTruthCount': len(gt)}
def demo():
truth = np.zeros((2, 10, 12), bool)
truth[0, 2:6, 2:5] = True
truth[1, 2:6, 6:9] = True
image = np.where(truth.any(axis=0), .9, .1)
separate, scores, _ = baseline(image)
first = evaluate(truth, [1, 1], separate, np.ones(len(separate), int), scores)
image[3, 5] = .9 # One extra foreground pixel joins the two objects.
merged, scores, _ = baseline(image)
second = evaluate(truth, [1, 1], merged, np.ones(len(merged), int), scores)
semantic = np.count_nonzero(truth.any(axis=0) & merged.any(axis=0))/np.count_nonzero(truth.any(axis=0) | merged.any(axis=0))
assert first['ap101'] == 1 and second['ap101'] == 0
return {'separatePredictions': len(separate), 'separateAP50_101': first['ap101'],
'bridgedPredictions': len(merged), 'bridgedAP50_101': second['ap101'],
'bridgedForegroundIoU': float(semantic), 'bridgedPairwiseIoU': mask_iou(merged, truth).tolist(),
'scope': 'single image/category/IoU threshold; ordinary instances; not COCO AP'}
if __name__ == '__main__':
print(json.dumps(demo(), indent=2))
实际输出为:
{
"separatePredictions": 2,
"separateAP50_101": 1.0,
"bridgedPredictions": 1,
"bridgedAP50_101": 0.0,
"bridgedForegroundIoU": 0.96,
"bridgedPairwiseIoU": [
[
0.48,
0.48
]
],
"scope": "single image/category/IoU threshold; ordinary instances; not COCO AP"
}
13项计算检查覆盖分量成员、连通性、重叠掩码、对角掩码几何、重复预测、精度插值、包含等号的阈值、类别筛选、稳定并列、检测上限、空输入和错误输入。这里的数字只度量明确构造的图像,不估计自然场景性能。
基线不能从连接关系推断一切
连通分量只根据前景是否相连推断身份。相接的物体会合并;被遮挡或边缘较暗的物体可能碎成几个分量。最小面积过滤可能去掉噪声,也可能去掉真实小物体。修改指标前,先查看发生的究竟是哪一种错误。
学习方法能够利用连接关系之外的外观和上下文。基于区域的方法为每个检测物体预测掩码;Mask R-CNN介绍其中一种设计。U-Net的语义预测可以帮助生成前景,但类别logit本身不能确定实例成员。如果系统没有好的物体候选,精确的掩码头也无法找回一个从未被要求分割的物体。
评测要服从实际标注约定。可见掩码质量、推断的遮挡范围、物体数量、边界准确性和视频身份稳定性有关联,却不是同一个问题。报告掩码定义、IoU阈值、类别平均方式、分数顺序、检测数上限与缺失类别的处理。仅凭很高的前景IoU,无法知道有多少物体被正确分开。
先预测,再运行
1. 同类,但不是同一个物体
相邻两个人的类别都标为“人”。实例分割还必须保留什么信息?
答案:每个人各自的成员掩码或身份。类别只回答像素属于哪种物体,不回答属于哪一个人。如果没有额外的跟踪规则连接不同帧,身份只在本张图像内有效。
2. 一个桥接像素
两个互不相交的真值掩码各有12像素。单个预测掩码包含两者,再多一个连接像素。计算前景IoU、每个实例IoU,以及本例匹配约定下的AP50。
答案:前景IoU为24/25=0.96,每个实例IoU为12/25=0.48。虽然有一个检测,但它对两个真值都达不到0.5阈值,因此没有真阳性,AP50为0。整体覆盖正确,没有保住实例身份。
3. 中间夹一个重复预测
两个真值,置信度顺序为真阳性、重复假阳性、真阳性。为什么101点AP约为0.83498,而不是最后的精度2/3?
答案:AP对不同召回阈值上的精度包络取平均。在不超过0.5的召回阈值,第一条预测已提供精度1;超过0.5后,可取得的最好精度为2/3。把51个1与50个2/3对101个阈值平均;最终精度只是曲线上的一个点。
4. 相接的明亮物体
实际图像里存在相接的同类物体。把4邻域改成8邻域能解决分离吗?下一项实验应该比较什么?
答案:不能。8邻域增加连接,可能合并更多分量。保持标注和评测设置不变,比较连通分量基线与利用分离线索或逐物体掩码的方法。分别检查合并、碎裂和漏掉小物体的情况,不要只用前景IoU选方法。
把表示方式与评测器放在一起读
本篇核读范围是Mask R-CNN的任务与方法讨论,以及固定COCO掩码API说明、rleIou和指定的准备、匹配、累积代码范围。官方代码经过阅读,没有执行。原创NumPy例子遵守独立测试过的明确约定,不借用上游项目的基准成绩。
配套Mask R-CNN文章会从“怎样才算检测到一个物体”,推进到预测它所需的区域特征、掩码损失与梯度。后续主题即使换掉掩码预测器,仍然需要回答这些身份与评测问题。
先判断,再看解释
两个12像素真值合成一个25像素预测,它与任一实例的IoU是多少?
学习目标
- 区分类别、物体身份、掩码重叠与框重叠。
- 追踪置信度匹配、重复错误和明确设置的101点AP。
- 运行连通分量基线并解释单像素桥接失败。
先修与延伸
查看知识关联图 →参考文献
- Mask R-CNN — v3 region masks and alignment
Kaiming He; Georgia Gkioxari; Piotr Dollár; Ross Girshick · 2017 - COCO mask API — layout, encoding and overlap contract
COCO API contributors · 2019 - COCO rleIou — fixed binary mask overlap
COCO API contributors · 2019 - COCO evaluation — fixed instance matching and precision accumulation
COCO API contributors · 2019
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: scoped primary/source reading, explicit identity and coordinate counterexamples, independent arithmetic/gradient tests and complete bilingual comparison. Not independent human review or official benchmark reproduction.
- 逐节核对完整双语、展示公式、可执行代码/输出、四组解释习题与限定引用;区分玩具配置、官方接口和完整基准主张。
- 十三项计算加双语/图示绑定:分量、重叠、重复匹配、101点AP手算、包含等号阈值、类别/并列/上限/空值规则和桥接像素反例;正式代码生成图示掩码和指标。
核对的来源位置:
- Mask R-CNN — v3 region masks and alignment · Read physical pages 2-4; visually inspected pages 3 and 4. Page 5 targeted inference closing and experimental-setup opening only; full results/ablations/appendices not read or adopted. v1 submission 2017-03-20; read revision v3 2018-01-24.
- COCO mask API — layout, encoding and overlap contract · Read lines 1-108: run-length representation, column-major input, ordinary/crowd IoU and wrappers. Compressed wire codec not executed.
- COCO rleIou — fixed binary mask overlap · Read rleIou lines 77-96: intersections/unions, crowd detection-area denominator, dimension mismatch handling. Full C backend and codecs not audited.
- COCO evaluation — fixed instance matching and precision accumulation · New reading 84-125,145-191,228-310: preparation, IoU dispatch, per-image/category matching, crowd/area ignore. Reused unchanged existing Source cocoapi-eval-20191225. No official execution. Additional read of accumulation lines 360-410: precision envelope and 101 recall sample lookup; no upstream execution.
相关主题