#!/usr/bin/env python3 """ OV-LVIS Failure Case Analysis - Visualization (Rare Categories) 生成 rare 类别的可视化结果(DeCLIP vs CLIPSelf): - 直接使用分析结果中记录的bbox - 清晰显示分类结果(正确/错误/未定位) Usage: python visualize_comparison.py \ --cases analysis_output/comparison_vitb16/top_advantage_cases.json \ --ann-file /path/to/lvis_v1_val.json \ --img-dir /path/to/lvis_v1 \ --output analysis_output/visualizations/advantage \ --case-type advantage """ import argparse import json from collections import defaultdict from pathlib import Path from typing import List, Optional import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as patches import numpy as np from PIL import Image COLORS = { 'correct': '#27AE60', 'incorrect': '#E74C3C', 'missed': '#95A5A6', 'background': '#FFFFFF', } MODEL_NAMES = { 'declip': 'DeCLIP (Ours)', 'clipself': 'CLIPSelf', } MODEL_ORDER = ['declip', 'clipself'] 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='OV-LVIS visualization for rare analysis') parser.add_argument('--cases', required=True, help='Top cases JSON file (from compare_models_rare.py)') parser.add_argument('--ann-file', required=True, help='LVIS annotation file') parser.add_argument('--img-dir', required=True, help='Image directory (lvis_v1 root)') 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 load_image_map(ann_file: str) -> dict: with open(ann_file, 'r') as f: data = json.load(f) return {img['id']: img['file_name'] for img in data['images']} def draw_bbox( ax: plt.Axes, bbox: List[float], label: Optional[str], color: str, score: Optional[float] = None, linewidth: float = 2.5, alpha: float = 1.0, zorder: int = 2 ): x, y, w, h = bbox rect = patches.Rectangle( (x, y), w, h, linewidth=linewidth, edgecolor=color, facecolor='none', 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(ax: plt.Axes, img: np.ndarray, case: dict, model_name: str): ax.imshow(img) ax.axis('off') gt_cat = case['category_name'] pred_bbox = case.get(f'{model_name}_bbox') pred_iou = case.get(f'{model_name}_iou', 0) pred_score = case.get(f'{model_name}_score', 0) pred_category = case.get(f'{model_name}_pred_category') localized = case.get(f'{model_name}_localized', False) classified_correct = case.get(f'{model_name}_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: color = COLORS['missed'] status = f"Low IoU: {pred_category}" if not classified_correct: pred_text = pred_category if pred_category else "None" label = f"GT: {gt_cat}\nPred: {pred_text}" else: label = pred_category if pred_category else "?" draw_bbox( 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: dict, output_path: Path, dpi: int, case_type: str): img_h, img_w = img.shape[:2] aspect_ratio = img_w / img_h num_models = len(MODEL_ORDER) fig_width = 11 single_width = fig_width / num_models fig_height = single_width / aspect_ratio + 1.8 fig, axes = plt.subplots(1, num_models, figsize=(fig_width, fig_height)) if num_models == 1: axes = [axes] for ax, model_name in zip(axes, MODEL_ORDER): draw_single_model(ax, img, case, model_name) cat_name = case['category_name'] size_cat = case['size_category'] if case_type == 'advantage': advantage_type = case.get('advantage_type', 'N/A').replace('_', ' ').title() suptitle = f"GT: {cat_name} (Rare, {size_cat.capitalize()}) | DeCLIP Advantage: {advantage_type}" else: declip_iou = case.get('declip_iou', 0) declip_pred_cat = case.get('declip_pred_category', 'N/A') suptitle = f"GT: {cat_name} (Rare, {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=3, 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: dict, model_name: str, output_path: Path, dpi: int): 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(ax, img, case, 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): if case_type == 'advantage': title = "DeCLIP Classification Advantage Cases (Rare)" subtitle = "Rare categories where DeCLIP correctly classifies and CLIPSelf fails" description = "Ranked by advantage score." else: title = "DeCLIP Unsolved Rare Cases" subtitle = "Rare categories where DeCLIP fails to classify correctly" description = "Ranked by IoU (descending)." html_content = f"""
{description}