| |
| """ |
| 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"""<!DOCTYPE html> |
| <html> |
| <head> |
| <title>OV-LVIS Analysis - {title}</title> |
| <style> |
| body {{ font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }} |
| h1 {{ color: #2C3E50; }} |
| .case-grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(450px, 1fr)); gap: 20px; }} |
| .case-card {{ background: white; border-radius: 8px; padding: 15px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }} |
| .case-card img {{ width: 100%; border-radius: 4px; }} |
| .case-info {{ margin-top: 10px; font-size: 14px; line-height: 1.6; }} |
| .tag {{ display: inline-block; padding: 2px 8px; border-radius: 4px; margin-right: 5px; font-size: 12px; }} |
| .tag-rare {{ background: #8E44AD; color: white; }} |
| .tag-small {{ background: #3498DB; color: white; }} |
| .correct {{ color: #27AE60; font-weight: bold; }} |
| .incorrect {{ color: #E74C3C; font-weight: bold; }} |
| .model-result {{ margin: 5px 0; padding: 5px; background: #f9f9f9; border-radius: 4px; }} |
| </style> |
| </head> |
| <body> |
| <h1>Open-Vocabulary LVIS Analysis</h1> |
| <h2>{subtitle}</h2> |
| <p>{description}</p> |
| |
| <div class="case-grid"> |
| """ |
|
|
| for idx, case in enumerate(cases): |
| cat_name = case['category_name'] |
| size_cat = case['size_category'] |
| img_id = case['image_id'] |
|
|
| case_folder = f"rank{idx+1:02d}_{cat_name}_{size_cat}_img{img_id}" |
|
|
| def get_cls_html(prefix, model_name): |
| pred_cat = case.get(f'{prefix}_pred_category', 'N/A') |
| correct = case.get(f'{prefix}_classified_correct', False) |
| iou = case.get(f'{prefix}_iou', 0) |
| if correct: |
| return f'<span class="correct">{model_name}: {pred_cat} ✓ (IoU: {iou:.2f})</span>' |
| if pred_cat: |
| return f'<span class="incorrect">{model_name}: {pred_cat} ✗ (IoU: {iou:.2f})</span>' |
| return f'<span class="incorrect">{model_name}: No detection</span>' |
|
|
| declip_html = get_cls_html('declip', 'DeCLIP') |
| clipself_html = get_cls_html('clipself', 'CLIPSelf') |
|
|
| if case_type == 'advantage': |
| advantage_type = case.get('advantage_type', 'N/A').replace('_', ' ').title() |
| status_html = f'<strong>Advantage: {advantage_type}</strong>' |
| else: |
| status_html = '<strong class="incorrect">Unsolved</strong>' |
|
|
| html_content += f""" |
| <div class="case-card"> |
| <a href="{case_folder}/comparison.png" target="_blank"> |
| <img src="{case_folder}/comparison.png" alt="Case {idx+1}"> |
| </a> |
| <div class="case-info"> |
| <strong>Rank #{idx+1}</strong> - GT: {cat_name}<br> |
| <span class="tag tag-rare">Rare</span> |
| <span class="tag tag-{size_cat}">{size_cat.capitalize()}</span> |
| {status_html}<br> |
| <div class="model-result">{declip_html}</div> |
| <div class="model-result">{clipself_html}</div> |
| </div> |
| </div> |
| """ |
|
|
| html_content += """ |
| </div> |
| </body> |
| </html> |
| """ |
|
|
| with open(output_dir / 'index.html', 'w') as f: |
| f.write(html_content) |
|
|
| print(f" Index page saved to: {output_dir / 'index.html'}") |
|
|
|
|
| def generate_summary_figure(cases: List[dict], output_dir: Path, dpi: int, case_type: str): |
| by_category = defaultdict(int) |
| for case in cases: |
| by_category[case['category_name']] += 1 |
|
|
| sorted_cats = sorted(by_category.items(), key=lambda x: x[1], reverse=True)[:10] |
| cat_names = [c[0] for c in sorted_cats] |
| cat_counts = [c[1] for c in sorted_cats] |
|
|
| if case_type == 'advantage': |
| fig, axes = plt.subplots(1, 2, figsize=(12, 5)) |
|
|
| axes[0].barh(cat_names[::-1], cat_counts[::-1], color='#3498DB', edgecolor='white', linewidth=1.5) |
| axes[0].set_xlabel('Number of Cases', fontweight='bold') |
| axes[0].set_title('DeCLIP Advantage by Rare Category', fontweight='bold') |
|
|
| by_adv = defaultdict(int) |
| for case in cases: |
| by_adv[case.get('advantage_type', 'unknown')] += 1 |
|
|
| adv_types = ['unique_correct_classification', 'better_iou'] |
| adv_labels = ['Only DeCLIP\nCorrect', 'Better\nIoU'] |
| adv_counts = [by_adv[t] for t in adv_types] |
| colors_adv = ['#27AE60', '#3498DB'] |
|
|
| axes[1].bar(adv_labels, adv_counts, color=colors_adv, edgecolor='white', linewidth=1.5) |
| axes[1].set_xlabel('Advantage Type', fontweight='bold') |
| axes[1].set_ylabel('Number of Cases', fontweight='bold') |
| axes[1].set_title('DeCLIP Advantage Types', fontweight='bold') |
| for i, c in enumerate(adv_counts): |
| axes[1].text(i, c + 0.5, str(c), ha='center', fontweight='bold') |
| else: |
| fig, axes = plt.subplots(1, 2, figsize=(12, 5)) |
|
|
| axes[0].barh(cat_names[::-1], cat_counts[::-1], color='#E74C3C', edgecolor='white', linewidth=1.5) |
| axes[0].set_xlabel('Number of Cases', fontweight='bold') |
| axes[0].set_title('DeCLIP Unsolved Cases by Rare Category', fontweight='bold') |
|
|
| confusion = defaultdict(int) |
| for case in cases: |
| gt_cat = case['category_name'] |
| pred_cat = case.get('declip_pred_category', 'N/A') |
| if pred_cat and pred_cat != gt_cat: |
| confusion[(gt_cat, pred_cat)] += 1 |
|
|
| sorted_conf = sorted(confusion.items(), key=lambda x: x[1], reverse=True)[:10] |
| conf_labels = [f"{c[0][0]}→{c[0][1]}" for c in sorted_conf] |
| conf_counts = [c[1] for c in sorted_conf] |
|
|
| if conf_labels: |
| axes[1].barh(conf_labels[::-1], conf_counts[::-1], color='#9B59B6', edgecolor='white', linewidth=1.5) |
| axes[1].set_xlabel('Number of Cases', fontweight='bold') |
| axes[1].set_title('Top Misclassification Patterns (GT→Pred)', fontweight='bold') |
| else: |
| axes[1].text(0.5, 0.5, 'No misclassification data', ha='center', va='center', transform=axes[1].transAxes) |
| axes[1].set_title('Misclassification Patterns', fontweight='bold') |
|
|
| plt.tight_layout() |
| plt.savefig(output_dir / 'summary_statistics.png', dpi=dpi, bbox_inches='tight', facecolor='white') |
| plt.close() |
|
|
| print(f" Summary figure saved to: {output_dir / 'summary_statistics.png'}") |
|
|
|
|
| def main(): |
| args = parse_args() |
|
|
| print("=" * 70) |
| print("OV-LVIS Visualization Generator (Rare Categories)") |
| print("=" * 70) |
|
|
| with open(args.cases, 'r') as f: |
| cases = json.load(f) |
| print(f" Total cases to visualize: {len(cases)}") |
|
|
| img_id_to_file = load_image_map(args.ann_file) |
| output_dir = Path(args.output) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| for idx, case in enumerate(cases): |
| img_id = case['image_id'] |
| cat_name = case['category_name'] |
| size_cat = case['size_category'] |
|
|
| case_dir = output_dir / f"rank{idx+1:02d}_{cat_name}_{size_cat}_img{img_id}" |
| case_dir.mkdir(parents=True, exist_ok=True) |
|
|
| file_name = img_id_to_file.get(img_id) |
| if not file_name: |
| print(f" [!] Image id not found: {img_id}") |
| continue |
|
|
| img_path = Path(args.img_dir) / file_name |
| if not img_path.exists(): |
| print(f" [!] Image not found: {img_path}") |
| continue |
|
|
| img = np.array(Image.open(img_path).convert('RGB')) |
|
|
| create_single_model_figure(img, case, 'declip', case_dir / 'declip.png', args.dpi) |
| create_single_model_figure(img, case, 'clipself', case_dir / 'clipself.png', args.dpi) |
|
|
| create_comparison_figure(img, case, case_dir / 'comparison.png', args.dpi, args.case_type) |
|
|
| with open(case_dir / 'info.json', 'w') as f: |
| json.dump(case, f, indent=2) |
|
|
| print(f" [{idx+1}/{len(cases)}] {case_dir.name}") |
|
|
| print("\nGenerating index page...") |
| generate_index_html(cases, output_dir, args.case_type) |
|
|
| print("Generating summary figure...") |
| generate_summary_figure(cases, output_dir, args.dpi, args.case_type) |
|
|
| print(f"\nVisualization complete: {output_dir}") |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|