从零实践:利用aitodpycocotools精准评估小目标检测模型的APvt/APt/APs/APm
2026/4/5 22:15:05 网站建设 项目流程
1. 为什么需要细分评估小目标检测性能在计算机视觉领域目标检测模型的评估一直是个技术难点。特别是当遇到AI-TOD这类以小目标为主的数据集时传统评估指标往往难以真实反映模型性能。这就好比用普通体温计测量蚂蚁的体温——工具本身没问题但用在特殊场景下就显得力不从心。我去年在做一个遥感图像分析项目时就深有体会。当时用经典COCO指标评估模型整体AP值看起来不错但实际部署后发现对小飞机的检测效果极差。后来才发现那些表现良好的指标其实是被大量中等尺寸目标拉高的模型对小目标的检测能力其实很糟糕。这就是aitodpycocotools的价值所在。它基于pycocotools改造专门针对小目标检测场景新增了四个关键指标APvt(very tiny): 极微小目标(8×8像素以下)APt(tiny): 微小目标(8×8到16×16像素)APs(small): 小目标(16×16到32×32像素)APm(medium): 中等目标(32×32到96×96像素)这种细分评估特别适合无人机航拍、遥感影像、显微图像等场景。举个例子在细胞检测任务中区分APvt和APt就很有必要——前者可能代表异常细胞后者则是正常细胞。2. 环境搭建与数据准备2.1 安装aitodpycocotools这个工具库的安装其实很简单但有几个依赖项需要特别注意。建议按以下顺序操作# 先确保有基础环境 pip install numpy cython matplotlib # 官方推荐从源码安装 git clone https://github.com/jwwangchn/cocoapi-aitod.git cd cocoapi-aitod/PythonAPI python setup.py build_ext install我遇到过的一个典型问题是Python版本冲突。这个库最好在Python 3.6-3.8环境下使用3.9可能会遇到编译错误。如果遇到Unable to find vcvarsall.bat这类报错需要安装Visual Studio Build Tools。2.2 准备标注数据AI-TOD数据集已经提供了标准格式的标注文件如aitodv2_test.json。如果是自定义数据集需要确保标注格式符合COCO标准。关键字段包括{ images: [{id: int, width: int, height: int,...}], annotations: [{ id: int, image_id: int, category_id: int, bbox: [x,y,width,height], // 注意是xywh格式 area: float, iscrowd: 0 }], categories: [{id: int, name: str,...}] }特别提醒标注文件中的bbox面积(area)字段直接影响尺寸分组的准确性。我曾经因为漏算这个字段导致APs和APm指标完全错乱。3. 模型预测结果格式转换3.1 理解prediction.json结构评估需要的prediction.json是个包含多个字典的列表每个字典代表一个预测框[ { image_id: 1024, # 对应标注中的图片ID category_id: 1, # 类别ID bbox: [100,200,30,40], # [x,y,width,height] score: 0.92 # 置信度 }, # 更多预测框... ]3.2 处理不同模型的输出格式不同模型的输出格式各异这里以DETR和YOLO为例DETR类模型通常输出cxcywh格式# 原始输出示例 (cx,cy,w,h) predictions [ [0.5, 0.5, 0.2, 0.3], # 归一化坐标 [0.3, 0.7, 0.1, 0.1], ... ] # 转换函数 def convert_detr_output(preds, img_size): converted [] for pred in preds: cx, cy, w, h pred[:4] x (cx - w/2) * img_size[0] # 转为绝对坐标 y (cy - h/2) * img_size[1] converted.append([x, y, w*img_size[0], h*img_size[1]]) return convertedYOLO类模型通常输出xywh格式# 直接使用xywh格式但要注意归一化处理 def convert_yolo_output(preds, img_size): return [[x*img_size[0], y*img_size[1], w*img_size[0], h*img_size[1]] for x,y,w,h in preds]3.3 生成完整prediction.json完整流程示例import json def save_predictions(image_ids, all_boxes, all_scores, output_path): results [] for img_id, boxes, scores in zip(image_ids, all_boxes, all_scores): for box, score in zip(boxes, scores): results.append({ image_id: int(img_id), category_id: 1, # 根据实际情况修改 bbox: [round(x,2) for x in box], # 保留两位小数 score: float(score) }) with open(output_path, w) as f: json.dump(results, f) # 使用示例 save_predictions( image_ids[1,1,2,2], # 图片ID列表 all_boxes[[[10,20,30,40],[20,30,40,50]], [[15,25,35,45]]], # 每张图的预测框 all_scores[[0.9,0.8], [0.95]], # 对应置信度 output_pathpredictions.json )4. 运行评估与结果解读4.1 基础评估代码from aitodpycocotools.coco import COCO from aitodpycocotools.cocoeval import COCOeval # 加载标注和预测 coco_true COCO(aitodv2_test.json) coco_pred coco_true.loadRes(predictions.json) # 初始化评估器 evaluator COCOeval(coco_true, coco_pred, bbox) # 运行评估流程 evaluator.evaluate() evaluator.accumulate() evaluator.summarize()4.2 关键参数配置通过params属性可以调整评估参数evaluator.params.iouThrs [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95] # IoU阈值 evaluator.params.areaRng [[0, 8**2], [8**2, 16**2], [16**2, 32**2], [32**2, 96**2]] # 面积范围 evaluator.params.areaRngLbl [verytiny, tiny, small, medium] # 对应标签4.3 理解输出结果典型输出示例Average Precision (AP) [ IoU0.50:0.95 | areaverytiny | maxDets1500 ] 0.035 (APvt) Average Precision (AP) [ IoU0.50:0.95 | area tiny | maxDets1500 ] 0.128 (APt) Average Precision (AP) [ IoU0.50:0.95 | area small | maxDets1500 ] 0.181 (APs) Average Precision (AP) [ IoU0.50:0.95 | areamedium | maxDets1500 ] 0.242 (APm)解读技巧关注APvt和APt这两个指标最能反映小目标检测能力指标对比好的模型应该在各尺寸上表现均衡-1的特殊含义表示该尺寸范围内没有真实标注或预测5. 实战中的常见问题排查5.1 评估结果全为0这是最常见的问题通常由以下原因导致坐标格式错误如将cxcywh直接当作xywh使用ID不匹配预测中的image_id与标注文件不一致类别错误category_id不在标注文件的categories中排查方法# 检查前10个预测 print(json.load(open(predictions.json))[:10]) # 验证标注文件 coco COCO(aitodv2_test.json) print(coco.getImgIds()[:5]) # 查看有效图片ID print(coco.getCatIds()) # 查看有效类别ID5.2 APvt异常偏低可能原因小目标标注质量问题极微小目标标注可能不准确模型感受野问题需要调整anchor大小或网络结构数据增强不足缺少针对小目标的特殊增强解决方案# 可视化检查小目标预测 import matplotlib.pyplot as plt def visualize_small_objects(coco, pred, img_id, size_thresh8): img_info coco.loadImgs(img_id)[0] ann_ids coco.getAnnIds(imgIdsimg_id) anns coco.loadAnns(ann_ids) # 筛选小目标 small_anns [a for a in anns if a[area] size_thresh**2] print(fFound {len(small_anns)} small objects) # 可视化代码...5.3 评估速度优化当预测框很多时评估可能很慢。可以限制maxDets适当降低这个参数如从1500改为500并行评估修改源码中的循环部分采样评估只评估部分图片需修改标注文件# 快速评估方案 evaluator.params.maxDets [1, 100, 500] # 减少检测数量 evaluator.params.iouThrs [0.5, 0.75] # 减少IoU阈值6. 进阶技巧与最佳实践6.1 自定义尺寸分组默认的尺寸划分可能不适合你的数据可以这样调整# 修改面积范围单位为像素面积的平方 evaluator.params.areaRng [ [0, 5**2], # 新定义超小目标 [5**2, 10**2], # 极小目标 [10**2, 20**2], # 小目标 [20**2, 50**2] # 中等目标 ] evaluator.params.areaRngLbl [ultratiny, verytiny, tiny, small]6.2 跨数据集评估有时需要在多个数据集上比较性能def evaluate_multiple_datasets(pred_file, gt_files): results {} for name, gt_path in gt_files.items(): coco_true COCO(gt_path) coco_pred coco_true.loadRes(pred_file) evaluator COCOeval(coco_true, coco_pred, bbox) evaluator.evaluate() evaluator.accumulate() evaluator.summarize() results[name] evaluator.stats[:4] # 保存APvt-APm return pd.DataFrame(results)6.3 结果可视化分析用Matplotlib绘制雷达图能直观展示模型在不同尺寸上的表现def draw_ap_radar(ap_values, labels): angles np.linspace(0, 2*np.pi, len(labels), endpointFalse) values np.concatenate((ap_values, [ap_values[0]])) angles np.concatenate((angles, [angles[0]])) fig plt.figure() ax fig.add_subplot(111, polarTrue) ax.plot(angles, values, o-, linewidth2) ax.fill(angles, values, alpha0.25) ax.set_thetagrids(angles[:-1] * 180/np.pi, labels) ax.set_ylim(0, 1) plt.show() # 使用示例 draw_ap_radar([0.1, 0.3, 0.5, 0.4], [APvt, APt, APs, APm])在实际项目中我发现持续监控这些细分指标的变化比单纯看整体AP更能指导模型优化方向。比如当发现APvt提升但APm下降时可能是模型过度关注小目标而忽略了大目标这时就需要调整损失函数或数据采样策略。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询