xiaomoguhzz's picture
Add files using upload-large-folder tool
a831c4c verified
#!/usr/bin/env python3
"""
OV-COCO Failure Case Analysis - Cross-Model Comparison V2
开放词汇检测(OVD)场景下的模型对比分析。
核心逻辑(针对OVD任务优化):
1. 对于每个GT目标(novel类别 + 小目标),在所有预测中找IoU最高的框(不限类别)
2. 判断该预测框的分类是否正确(预测类别 == GT类别)
3. DeCLIP优势case = DeCLIP分类正确 + CLIPSelf/CLIP分类错误
这样可以清晰展示DeCLIP在novel小目标上的分类优势。
Usage:
python compare_models_v2.py \
--declip-pred results/declip_vitb16/predictions.json \
--clipself-pred results/clipself_vitb16/predictions.json \
--clip-pred results/clearclip_vitb16/predictions.json \
--ann-file /path/to/instances_val2017_all_2.json \
--seen-classes /path/to/mscoco_seen_classes.json \
--output analysis_output/comparison_vitb16
"""
import argparse
import json
from collections import defaultdict
from pathlib import Path
from typing import Dict, List
import numpy as np
from pycocotools.coco import COCO
# COCO目标大小标准
SIZE_THRESHOLDS = {
'small': (0, 32 * 32),
'medium': (32 * 32, 96 * 96),
'large': (96 * 96, float('inf'))
}
def parse_args():
parser = argparse.ArgumentParser(description='Cross-model comparison analysis V2')
parser.add_argument('--declip-pred', required=True, help='DeCLIP predictions JSON')
parser.add_argument('--clipself-pred', required=True, help='CLIPSelf predictions JSON')
parser.add_argument('--clip-pred', required=True, help='CLIP (ClearCLIP) predictions JSON')
parser.add_argument('--ann-file', required=True, help='COCO annotation file')
parser.add_argument('--seen-classes', required=True, help='Seen classes JSON file')
parser.add_argument('--output', required=True, help='Output directory')
parser.add_argument('--iou-threshold', type=float, default=0.5, help='IoU threshold for TP')
parser.add_argument('--top-k', type=int, default=50, help='Number of top cases to output')
return parser.parse_args()
def compute_iou(bbox1: List[float], bbox2: List[float]) -> float:
"""计算IoU,bbox格式: [x, y, w, h]"""
x1, y1, w1, h1 = bbox1
x2, y2, w2, h2 = bbox2
box1 = [x1, y1, x1 + w1, y1 + h1]
box2 = [x2, y2, x2 + w2, y2 + h2]
xi1 = max(box1[0], box2[0])
yi1 = max(box1[1], box2[1])
xi2 = min(box1[2], box2[2])
yi2 = min(box1[3], box2[3])
inter_area = max(0, xi2 - xi1) * max(0, yi2 - yi1)
box1_area = w1 * h1
box2_area = w2 * h2
union_area = box1_area + box2_area - inter_area
return inter_area / union_area if union_area > 0 else 0
def get_size_category(area: float) -> str:
"""根据面积返回大小类别"""
for size_name, (min_area, max_area) in SIZE_THRESHOLDS.items():
if min_area <= area < max_area:
return size_name
return 'large'
def load_predictions(pred_file: str) -> Dict[int, List[dict]]:
"""
加载预测结果,按image_id组织(包含所有类别的预测)
Returns:
Dict[image_id -> List[prediction]]
"""
with open(pred_file, 'r') as f:
predictions = json.load(f)
# 按image_id组织,并按score降序排列
pred_by_img = defaultdict(list)
for pred in predictions:
pred_by_img[pred['image_id']].append(pred)
# 按score降序排列
for img_id in pred_by_img:
pred_by_img[img_id] = sorted(
pred_by_img[img_id],
key=lambda x: x['score'],
reverse=True
)
return dict(pred_by_img)
def find_best_matching_pred(
predictions: List[dict],
gt_bbox: List[float],
gt_category_id: int,
id_to_name: dict,
min_iou: float = 0.1
) -> dict:
"""
在所有预测中找与GT位置最匹配的框(IoU最高),不限类别。
然后判断分类是否正确。
Args:
predictions: 该图像的所有预测
gt_bbox: GT的bbox
gt_category_id: GT的类别ID
id_to_name: category_id到name的映射
min_iou: 最小IoU阈值(低于此值认为没有定位到)
Returns:
dict: {
'pred': 最佳匹配的预测框(或None),
'iou': IoU值,
'localized': 是否定位成功(IoU >= min_iou),
'classified_correct': 分类是否正确,
'pred_category_id': 预测的类别ID,
'pred_category_name': 预测的类别名称
}
"""
best_pred = None
best_iou = 0
for pred in predictions:
iou = compute_iou(pred['bbox'], gt_bbox)
if iou > best_iou:
best_iou = iou
best_pred = pred
if best_pred is None or best_iou < min_iou:
return {
'pred': None,
'iou': best_iou,
'localized': False,
'classified_correct': False,
'pred_category_id': None,
'pred_category_name': None
}
pred_cat_id = best_pred['category_id']
pred_cat_name = id_to_name.get(pred_cat_id, 'unknown')
classified_correct = (pred_cat_id == gt_category_id)
return {
'pred': best_pred,
'iou': best_iou,
'localized': True,
'classified_correct': classified_correct,
'pred_category_id': pred_cat_id,
'pred_category_name': pred_cat_name
}
def analyze_single_gt(
gt_ann: dict,
declip_preds: List[dict],
clipself_preds: List[dict],
clip_preds: List[dict],
category_name: str,
is_novel: bool,
id_to_name: dict,
iou_threshold: float = 0.5
) -> dict:
"""
分析单个GT目标在三个模型上的检测结果。
核心逻辑(针对OVD优化):
1. 在所有预测中找IoU最高的框(不限类别)
2. 判断分类是否正确
3. 计算优势分数:DeCLIP分类正确 + 其他模型分类错误
"""
gt_bbox = gt_ann['bbox']
gt_category_id = gt_ann['category_id']
gt_area = gt_ann['area']
size_category = get_size_category(gt_area)
# 在所有预测中找IoU最高的框(不限类别)
declip_result = find_best_matching_pred(declip_preds, gt_bbox, gt_category_id, id_to_name, min_iou=0.1)
clipself_result = find_best_matching_pred(clipself_preds, gt_bbox, gt_category_id, id_to_name, min_iou=0.1)
clip_result = find_best_matching_pred(clip_preds, gt_bbox, gt_category_id, id_to_name, min_iou=0.1)
# 提取结果
declip_pred = declip_result['pred']
clipself_pred = clipself_result['pred']
clip_pred = clip_result['pred']
declip_iou = declip_result['iou']
clipself_iou = clipself_result['iou']
clip_iou = clip_result['iou']
# 定位成功 = IoU >= threshold
declip_localized = declip_iou >= iou_threshold
clipself_localized = clipself_iou >= iou_threshold
clip_localized = clip_iou >= iou_threshold
# 分类正确 = 定位成功 + 预测类别等于GT类别
declip_classified_correct = declip_localized and declip_result['classified_correct']
clipself_classified_correct = clipself_localized and clipself_result['classified_correct']
clip_classified_correct = clip_localized and clip_result['classified_correct']
# 计算DeCLIP优势分数(基于分类能力)
advantage_score = 0
advantage_type = 'none'
if declip_classified_correct:
# DeCLIP分类正确
if not clipself_classified_correct and not clip_classified_correct:
# 只有DeCLIP分类正确(最强优势)
advantage_score = 3.0 + declip_iou
advantage_type = 'unique_correct_classification'
elif not clipself_classified_correct or not clip_classified_correct:
# DeCLIP + 部分模型分类正确
advantage_score = 2.0 + declip_iou
advantage_type = 'partial_correct_classification'
else:
# 三个模型都分类正确,比较IoU
min_iou_advantage = min(declip_iou - clipself_iou, declip_iou - clip_iou)
if min_iou_advantage > 0.05:
advantage_score = 1.0 + min_iou_advantage
advantage_type = 'better_iou'
return {
'gt_id': gt_ann['id'],
'image_id': gt_ann['image_id'],
'category_id': gt_category_id,
'category_name': category_name,
'is_novel': is_novel,
'gt_bbox': gt_bbox,
'gt_area': gt_area,
'size_category': size_category,
# DeCLIP结果
'declip_localized': declip_localized,
'declip_classified_correct': declip_classified_correct,
'declip_iou': declip_iou,
'declip_score': declip_pred['score'] if declip_pred else 0,
'declip_bbox': declip_pred['bbox'] if declip_pred else None,
'declip_pred_category': declip_result['pred_category_name'],
# CLIPSelf结果
'clipself_localized': clipself_localized,
'clipself_classified_correct': clipself_classified_correct,
'clipself_iou': clipself_iou,
'clipself_score': clipself_pred['score'] if clipself_pred else 0,
'clipself_bbox': clipself_pred['bbox'] if clipself_pred else None,
'clipself_pred_category': clipself_result['pred_category_name'],
# CLIP结果
'clip_localized': clip_localized,
'clip_classified_correct': clip_classified_correct,
'clip_iou': clip_iou,
'clip_score': clip_pred['score'] if clip_pred else 0,
'clip_bbox': clip_pred['bbox'] if clip_pred else None,
'clip_pred_category': clip_result['pred_category_name'],
# 优势分析
'advantage_score': advantage_score,
'advantage_type': advantage_type,
'iou_advantage_vs_clipself': declip_iou - clipself_iou,
'iou_advantage_vs_clip': declip_iou - clip_iou,
}
def compute_statistics(results: List[dict], iou_threshold: float = 0.5) -> dict:
"""
计算统计信息。
新增指标:
- localized: 定位成功(IoU >= threshold)
- classified_correct: 分类正确(定位成功 + 类别正确)
"""
stats = {
'total': len(results),
'iou_threshold': iou_threshold,
'by_size': {size: {
'total': 0,
'declip_localized': 0, 'clipself_localized': 0, 'clip_localized': 0,
'declip_correct': 0, 'clipself_correct': 0, 'clip_correct': 0,
'declip_iou_sum': 0, 'clipself_iou_sum': 0, 'clip_iou_sum': 0
} for size in ['small', 'medium', 'large']},
'by_category_type': {
'novel': {'total': 0, 'declip_correct': 0, 'clipself_correct': 0, 'clip_correct': 0},
'base': {'total': 0, 'declip_correct': 0, 'clipself_correct': 0, 'clip_correct': 0}
},
'by_size_and_type': {}
}
# 初始化by_size_and_type
for size in ['small', 'medium', 'large']:
for cat_type in ['novel', 'base']:
key = f"{size}_{cat_type}"
stats['by_size_and_type'][key] = {
'total': 0,
'declip_localized': 0, 'clipself_localized': 0, 'clip_localized': 0,
'declip_correct': 0, 'clipself_correct': 0, 'clip_correct': 0,
'declip_unique_correct': 0, # 只有DeCLIP分类正确
'declip_better_iou': 0, # DeCLIP IoU最高
'declip_iou_sum': 0, 'clipself_iou_sum': 0, 'clip_iou_sum': 0,
}
for r in results:
size = r['size_category']
cat_type = 'novel' if r['is_novel'] else 'base'
key = f"{size}_{cat_type}"
# by_size
stats['by_size'][size]['total'] += 1
if r['declip_localized']:
stats['by_size'][size]['declip_localized'] += 1
stats['by_size'][size]['declip_iou_sum'] += r['declip_iou']
if r['clipself_localized']:
stats['by_size'][size]['clipself_localized'] += 1
stats['by_size'][size]['clipself_iou_sum'] += r['clipself_iou']
if r['clip_localized']:
stats['by_size'][size]['clip_localized'] += 1
stats['by_size'][size]['clip_iou_sum'] += r['clip_iou']
if r['declip_classified_correct']:
stats['by_size'][size]['declip_correct'] += 1
if r['clipself_classified_correct']:
stats['by_size'][size]['clipself_correct'] += 1
if r['clip_classified_correct']:
stats['by_size'][size]['clip_correct'] += 1
# by_category_type
stats['by_category_type'][cat_type]['total'] += 1
if r['declip_classified_correct']:
stats['by_category_type'][cat_type]['declip_correct'] += 1
if r['clipself_classified_correct']:
stats['by_category_type'][cat_type]['clipself_correct'] += 1
if r['clip_classified_correct']:
stats['by_category_type'][cat_type]['clip_correct'] += 1
# by_size_and_type
stats['by_size_and_type'][key]['total'] += 1
if r['declip_localized']:
stats['by_size_and_type'][key]['declip_localized'] += 1
stats['by_size_and_type'][key]['declip_iou_sum'] += r['declip_iou']
if r['clipself_localized']:
stats['by_size_and_type'][key]['clipself_localized'] += 1
stats['by_size_and_type'][key]['clipself_iou_sum'] += r['clipself_iou']
if r['clip_localized']:
stats['by_size_and_type'][key]['clip_localized'] += 1
stats['by_size_and_type'][key]['clip_iou_sum'] += r['clip_iou']
if r['declip_classified_correct']:
stats['by_size_and_type'][key]['declip_correct'] += 1
if r['clipself_classified_correct']:
stats['by_size_and_type'][key]['clipself_correct'] += 1
if r['clip_classified_correct']:
stats['by_size_and_type'][key]['clip_correct'] += 1
# DeCLIP优势统计
if r['declip_classified_correct'] and not r['clipself_classified_correct'] and not r['clip_classified_correct']:
stats['by_size_and_type'][key]['declip_unique_correct'] += 1
if r['declip_iou'] > r['clipself_iou'] and r['declip_iou'] > r['clip_iou']:
stats['by_size_and_type'][key]['declip_better_iou'] += 1
# 计算分类正确率(Localized + Correct)和定位率
for key in stats['by_size_and_type']:
s = stats['by_size_and_type'][key]
total = max(s['total'], 1)
s['declip_cls_acc'] = s['declip_correct'] / total
s['clipself_cls_acc'] = s['clipself_correct'] / total
s['clip_cls_acc'] = s['clip_correct'] / total
s['declip_loc_rate'] = s['declip_localized'] / total
s['clipself_loc_rate'] = s['clipself_localized'] / total
s['clip_loc_rate'] = s['clip_localized'] / total
for size in stats['by_size']:
s = stats['by_size'][size]
total = max(s['total'], 1)
s['declip_cls_acc'] = s['declip_correct'] / total
s['clipself_cls_acc'] = s['clipself_correct'] / total
s['clip_cls_acc'] = s['clip_correct'] / total
return stats
def main():
args = parse_args()
print("=" * 70)
print("OV-COCO Cross-Model Comparison Analysis V2")
print("=" * 70)
# 加载数据
print("\n[1/5] Loading data...")
print(f" Loading annotations: {args.ann_file}")
coco_gt = COCO(args.ann_file)
print(f" Loading seen classes: {args.seen_classes}")
with open(args.seen_classes, 'r') as f:
seen_classes = set(json.load(f))
id_to_name = {cat['id']: cat['name'] for cat in coco_gt.dataset['categories']}
print(f" Loading DeCLIP predictions...")
declip_preds = load_predictions(args.declip_pred)
print(f" Loading CLIPSelf predictions...")
clipself_preds = load_predictions(args.clipself_pred)
print(f" Loading CLIP predictions...")
clip_preds = load_predictions(args.clip_pred)
print(f"\n Total images: {len(coco_gt.imgs)}")
print(f" Total GT annotations: {len(coco_gt.anns)}")
# 分析每个GT目标
print("\n[2/5] Analyzing each GT object...")
all_results = []
novel_results = []
for ann_id in coco_gt.anns:
ann = coco_gt.anns[ann_id]
img_id = ann['image_id']
category_name = id_to_name.get(ann['category_id'], 'unknown')
is_novel = category_name not in seen_classes
# 获取该图像的所有预测(不按类别分组)
img_declip_preds = declip_preds.get(img_id, [])
img_clipself_preds = clipself_preds.get(img_id, [])
img_clip_preds = clip_preds.get(img_id, [])
result = analyze_single_gt(
ann,
img_declip_preds,
img_clipself_preds,
img_clip_preds,
category_name,
is_novel,
id_to_name,
args.iou_threshold
)
all_results.append(result)
if is_novel:
novel_results.append(result)
print(f" Analyzed {len(all_results)} GT objects")
print(f" Novel category objects: {len(novel_results)}")
# 计算统计
print("\n[3/5] Computing statistics...")
all_stats = compute_statistics(all_results, args.iou_threshold)
novel_stats = compute_statistics(novel_results, args.iou_threshold)
# 找出DeCLIP优势case(只保留 small + novel)
# 优势定义:DeCLIP分类正确 + 其他模型分类错误
print("\n[4/5] Finding DeCLIP advantage cases...")
advantage_cases = [
r for r in novel_results
if r['advantage_score'] > 0 and r['size_category'] == 'small'
]
# 按 advantage_score 降序排列(优先 unique_correct_classification),然后按 IoU 降序
advantage_cases = sorted(advantage_cases, key=lambda x: (x['advantage_score'], x['declip_iou']), reverse=True)
top_cases = advantage_cases[:args.top_k]
print(f" Found {len(advantage_cases)} small novel cases where DeCLIP has classification advantage")
print(f" Top {args.top_k} cases selected")
# 找出DeCLIP未解决的 novel 小目标 case(分类不正确)
unsolved_cases = [
r for r in novel_results
if r['size_category'] == 'small' and not r['declip_classified_correct']
]
# 优先展示定位更接近但分类错误的case(IoU从大到小)
unsolved_cases = sorted(unsolved_cases, key=lambda x: x['declip_iou'], reverse=True)[:args.top_k]
total_unsolved = len([r for r in novel_results if r['size_category'] == 'small' and not r['declip_classified_correct']])
print(f" Found {total_unsolved} unsolved small novel cases (DeCLIP classification incorrect)")
print(f" Top {args.top_k} unsolved cases selected")
# 保存结果
print("\n[5/5] Saving results...")
output_dir = Path(args.output)
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / 'all_results.json', 'w') as f:
json.dump(all_results, f, indent=2)
with open(output_dir / 'novel_results.json', 'w') as f:
json.dump(novel_results, f, indent=2)
with open(output_dir / 'top_advantage_cases.json', 'w') as f:
json.dump(top_cases, f, indent=2)
with open(output_dir / 'unsolved_small_novel_cases.json', 'w') as f:
json.dump(unsolved_cases, f, indent=2)
# 统计信息
top_by_size = defaultdict(list)
for case in top_cases:
top_by_size[case['size_category']].append(case)
stats_output = {
'config': {
'declip_pred': args.declip_pred,
'clipself_pred': args.clipself_pred,
'clip_pred': args.clip_pred,
'iou_threshold': args.iou_threshold,
},
'all_categories': all_stats,
'novel_categories': novel_stats,
'top_cases_summary': {
'total': len(top_cases),
'by_size': {size: len(cases) for size, cases in top_by_size.items()},
'advantage_types': {
'unique_correct_classification': sum(1 for c in top_cases if c['advantage_type'] == 'unique_correct_classification'),
'partial_correct_classification': sum(1 for c in top_cases if c['advantage_type'] == 'partial_correct_classification'),
'better_iou': sum(1 for c in top_cases if c['advantage_type'] == 'better_iou')
}
}
}
with open(output_dir / 'statistics.json', 'w') as f:
json.dump(stats_output, f, indent=2)
# 打印关键统计
print("\n" + "=" * 70)
print("SUMMARY - Novel Categories (OVD Analysis)")
print("=" * 70)
print("\n[Classification Accuracy by Size] (Localized + Correct Category)")
print("-" * 75)
print(f"{'Size':<10} {'Total':<8} {'DeCLIP':<18} {'CLIPSelf':<15} {'CLIP':<15}")
print("-" * 75)
for size in ['small', 'medium', 'large']:
key = f"{size}_novel"
s = novel_stats['by_size_and_type'].get(key, {})
total = s.get('total', 0)
if total > 0:
declip_acc = s.get('declip_cls_acc', 0) * 100
clipself_acc = s.get('clipself_cls_acc', 0) * 100
clip_acc = s.get('clip_cls_acc', 0) * 100
delta = declip_acc - clipself_acc
print(f"{size:<10} {total:<8} {declip_acc:>6.1f}% (+{delta:>4.1f}) {clipself_acc:>6.1f}% {clip_acc:>6.1f}%")
print("\n[DeCLIP Classification Advantages]")
print("-" * 75)
print(f"{'Size':<10} {'Unique Correct':<18} {'Better IoU':<15} {'Total Adv.':<15}")
print("-" * 75)
for size in ['small', 'medium', 'large']:
key = f"{size}_novel"
s = novel_stats['by_size_and_type'].get(key, {})
unique_correct = s.get('declip_unique_correct', 0)
better = s.get('declip_better_iou', 0)
total_adv = sum(1 for c in advantage_cases if c['size_category'] == size)
print(f"{size:<10} {unique_correct:<18} {better:<15} {total_adv:<15}")
print(f"\nResults saved to: {output_dir}")
print("=" * 70)
if __name__ == '__main__':
main()