#!/usr/bin/env python3 """ OV-COCO Failure Case Analysis - CVPR-Quality Visualization 生成CVPR级别的可视化结果(针对OVD任务优化): - 直接使用分析结果中记录的bbox(不再按score过滤) - 清晰显示每个模型的分类结果(正确/错误) - 绿色=分类正确,红色=分类错误,蓝色=未定位到 Usage: python visualize_comparison.py \ --cases analysis_output/comparison_vitb16/top_advantage_cases.json \ --ann-file /path/to/instances_val2017_all_2.json \ --img-dir /path/to/val2017 \ --output analysis_output/visualizations """ import argparse import json from collections import defaultdict from pathlib import Path from typing import List, Optional import cv2 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as patches import numpy as np from PIL import Image from pycocotools.coco import COCO # 配色方案 - 针对OVD分类结果 COLORS = { 'correct': '#27AE60', # 绿色 - 分类正确 'incorrect': '#E74C3C', # 红色 - 分类错误(定位到但分类错) 'missed': '#95A5A6', # 灰色 - 未定位到 'gt': '#3498DB', # 蓝色 - Ground Truth 'background': '#FFFFFF', # 白色背景 'text': '#2C3E50', # 深灰色文字 } # 模型显示名称 MODEL_NAMES = { 'declip': 'DeCLIP (Ours)', 'clipself': 'CLIPSelf', 'clip': 'CLIP' } # 字体设置 plt.rcParams.update({ 'font.family': 'sans-serif', 'font.sans-serif': ['Arial', 'DejaVu Sans', 'Helvetica', 'Liberation Sans'], 'font.size': 10, 'axes.titlesize': 12, 'axes.labelsize': 10, 'xtick.labelsize': 9, 'ytick.labelsize': 9, 'legend.fontsize': 9, 'figure.titlesize': 14, 'axes.linewidth': 0.8, 'axes.edgecolor': '#CCCCCC', }) def parse_args(): parser = argparse.ArgumentParser(description='CVPR-quality visualization for OVD analysis') parser.add_argument('--cases', required=True, help='Top cases JSON file (from compare_models_v2.py)') parser.add_argument('--ann-file', required=True, help='COCO annotation file') parser.add_argument('--img-dir', required=True, help='Image directory') parser.add_argument('--output', required=True, help='Output directory') parser.add_argument('--dpi', type=int, default=150, help='Output DPI') parser.add_argument('--case-type', choices=['advantage', 'unsolved'], default='advantage', help='Type of cases to visualize') return parser.parse_args() def draw_bbox_cvpr_style( ax: plt.Axes, bbox: List[float], label: Optional[str], color: str, score: Optional[float] = None, linewidth: float = 2.5, is_gt: bool = False, alpha: float = 1.0, zorder: int = 2 ): """绘制CVPR风格的bbox""" x, y, w, h = bbox # 绘制bbox linestyle = '--' if is_gt else '-' rect = patches.Rectangle( (x, y), w, h, linewidth=linewidth, edgecolor=color, facecolor='none', linestyle=linestyle, alpha=alpha, zorder=zorder ) ax.add_patch(rect) if not label: return # 标签文本 if score is not None: text = f"{label} {score:.2f}" else: text = label # 标签背景框 fontsize = 8 text_y = y - 3 if y > 20 else y + h + 12 ax.text( x, text_y, text, fontsize=fontsize, fontweight='bold', color='white', bbox=dict( facecolor=color, edgecolor='none', alpha=0.85, pad=1.5, boxstyle='round,pad=0.3' ), verticalalignment='bottom' if y > 20 else 'top', zorder=zorder + 1 ) def draw_single_model_result_from_case( ax: plt.Axes, img: np.ndarray, case_info: dict, model_name: str ): """根据case信息绘制单个模型的检测结果(OVD优化版)""" ax.imshow(img) ax.axis('off') gt_bbox = case_info['gt_bbox'] gt_cat_name = case_info['category_name'] # 获取该模型的结果 prefix = model_name pred_bbox = case_info.get(f'{prefix}_bbox') pred_iou = case_info.get(f'{prefix}_iou', 0) pred_score = case_info.get(f'{prefix}_score', 0) pred_category = case_info.get(f'{prefix}_pred_category') localized = case_info.get(f'{prefix}_localized', False) classified_correct = case_info.get(f'{prefix}_classified_correct', False) # 绘制模型预测框(如果有) if pred_bbox is not None: if classified_correct: # 分类正确 - 绿色 color = COLORS['correct'] status = "Correct" elif localized: # 定位到但分类错误 - 红色 color = COLORS['incorrect'] status = f"Wrong: {pred_category}" else: # 未定位到(IoU < 0.5)- 灰色 color = COLORS['missed'] status = f"Low IoU: {pred_category}" # 绘制预测框(CLIP/CLIPSelf 分类错误时,显示GT在上) if model_name in ('clipself', 'clip') and not classified_correct: pred_text = pred_category if pred_category else "None" label = f"GT: {gt_cat_name}\nPred: {pred_text}" else: label = pred_category if pred_category else "?" draw_bbox_cvpr_style( ax, pred_bbox, label, color, score=pred_score, linewidth=3.0, zorder=2 ) # 设置标题 title = f"{MODEL_NAMES.get(model_name, model_name)}\nIoU: {pred_iou:.3f} | {status}" else: # 没有任何预测 title = f"{MODEL_NAMES.get(model_name, model_name)}\nNo Detection" # 根据分类结果设置标题颜色 if classified_correct: title_color = COLORS['correct'] elif localized: title_color = COLORS['incorrect'] else: title_color = COLORS['missed'] ax.set_title(title, fontweight='bold', fontsize=10, color=title_color) def create_comparison_figure( img: np.ndarray, case_info: dict, output_path: Path, dpi: int = 150, case_type: str = 'advantage' ): """创建三模型并排对比图(OVD优化版)""" # 计算合适的figure大小 img_h, img_w = img.shape[:2] aspect_ratio = img_w / img_h fig_width = 15 # 总宽度 single_width = fig_width / 3 fig_height = single_width / aspect_ratio + 1.8 # 加上标题空间 fig, axes = plt.subplots(1, 3, figsize=(fig_width, fig_height)) # 绘制三个模型的结果(直接使用case中的数据) draw_single_model_result_from_case(axes[0], img, case_info, 'declip') draw_single_model_result_from_case(axes[1], img, case_info, 'clipself') draw_single_model_result_from_case(axes[2], img, case_info, 'clip') # 添加总标题 cat_name = case_info['category_name'] size_cat = case_info['size_category'] if case_type == 'advantage': advantage_type = case_info.get('advantage_type', 'N/A').replace('_', ' ').title() suptitle = f"GT: {cat_name} (Novel, {size_cat.capitalize()}) | DeCLIP Advantage: {advantage_type}" else: # unsolved declip_iou = case_info.get('declip_iou', 0) declip_pred_cat = case_info.get('declip_pred_category', 'N/A') suptitle = f"GT: {cat_name} (Novel, {size_cat.capitalize()}) | DeCLIP: {declip_pred_cat} (IoU: {declip_iou:.2f})" fig.suptitle(suptitle, fontsize=12, fontweight='bold', y=0.98) # 添加图例 legend_elements = [ patches.Patch(facecolor=COLORS['correct'], edgecolor='none', label='Correct Classification'), patches.Patch(facecolor=COLORS['incorrect'], edgecolor='none', label='Wrong Classification'), patches.Patch(facecolor=COLORS['missed'], edgecolor='none', label='Not Localized (IoU<0.5)') ] fig.legend( handles=legend_elements, loc='lower center', ncol=4, frameon=True, fontsize=10, bbox_to_anchor=(0.5, 0.02), markerscale=1.5 ) plt.tight_layout(rect=[0, 0.08, 1, 0.95]) plt.savefig(output_path, dpi=dpi, bbox_inches='tight', facecolor='white', edgecolor='none') plt.close() def create_single_model_figure( img: np.ndarray, case_info: dict, model_name: str, output_path: Path, dpi: int = 150 ): """创建单个模型的检测结果图(OVD优化版)""" img_h, img_w = img.shape[:2] aspect_ratio = img_w / img_h fig_width = 8 fig_height = fig_width / aspect_ratio + 1.0 fig, ax = plt.subplots(1, 1, figsize=(fig_width, fig_height)) draw_single_model_result_from_case(ax, img, case_info, model_name) # 添加图例 legend_elements = [ patches.Patch(facecolor=COLORS['correct'], edgecolor='none', label='Correct'), patches.Patch(facecolor=COLORS['incorrect'], edgecolor='none', label='Wrong') ] ax.legend( handles=legend_elements, loc='upper right', fontsize=10, framealpha=0.9, markerscale=1.5 ) plt.tight_layout() plt.savefig(output_path, dpi=dpi, bbox_inches='tight', facecolor='white', edgecolor='none') plt.close() def generate_index_html(cases: List[dict], output_dir: Path, case_type: str = 'advantage'): """生成HTML索引页面,方便浏览(OVD优化版)""" if case_type == 'advantage': title = "DeCLIP Classification Advantage Cases" subtitle = "Cases where DeCLIP correctly classifies novel small objects" description = "DeCLIP classifies correctly while CLIPSelf/CLIP fail. Ranked by advantage score." else: # unsolved title = "DeCLIP Unsolved Cases" subtitle = "Novel small objects that DeCLIP failed to classify correctly" description = "Cases where DeCLIP's classification is incorrect, ranked by IoU (descending)." html_content = f"""
{description}