File size: 19,952 Bytes
a831c4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
#!/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"""<!DOCTYPE html>
<html>
<head>
    <title>OVD 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-novel {{ background: #E74C3C; 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 Detection 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')
        clip_html = get_cls_html('clip', 'CLIP')

        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-novel">Novel</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 class="model-result">{clip_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 = 150, case_type: str = 'advantage'):
    """生成汇总统计图(OVD优化版)"""
    # 按大小分组统计
    by_size = defaultdict(list)
    for case in cases:
        by_size[case['size_category']].append(case)

    if case_type == 'advantage':
        # 按优势类型统计
        by_advantage = defaultdict(list)
        for case in cases:
            by_advantage[case.get('advantage_type', 'unknown')].append(case)

        fig, axes = plt.subplots(1, 2, figsize=(12, 5))

        # 图1: 按类别分布
        by_category = defaultdict(int)
        for case in cases:
            by_category[case['category_name']] += 1

        # 取top 10类别
        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]

        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 Classification Advantage by Category', fontweight='bold')

        # 图2: 按优势类型分布
        advantage_types = ['unique_correct_classification', 'partial_correct_classification', 'better_iou']
        advantage_labels = ['Only DeCLIP\nCorrect', 'DeCLIP +\nPartial Correct', 'Better\nIoU']
        advantage_counts = [len(by_advantage[t]) for t in advantage_types]
        colors_adv = ['#27AE60', '#F39C12', '#3498DB']

        axes[1].bar(advantage_labels, advantage_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 Classification Advantage by Type', fontweight='bold')
        for i, c in enumerate(advantage_counts):
            axes[1].text(i, c + 0.5, str(c), ha='center', fontweight='bold')
    else:
        fig, axes = plt.subplots(1, 2, figsize=(12, 5))

        # 图1: 按类别分布
        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]

        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 Category', fontweight='bold')

        # 图2: DeCLIP预测类别 vs GT类别(分类错误分析)
        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("OVD Visualization Generator (Classification Analysis)")
    print("=" * 70)

    # 加载数据
    print("\n[1/4] Loading data...")

    print(f"  Loading cases: {args.cases}")
    with open(args.cases, 'r') as f:
        cases = json.load(f)
    print(f"  Total cases to visualize: {len(cases)}")

    print(f"  Loading annotations: {args.ann_file}")
    coco_gt = COCO(args.ann_file)

    case_type = args.case_type

    # 创建输出目录
    output_dir = Path(args.output)
    output_dir.mkdir(parents=True, exist_ok=True)

    print(f"  Case type: {case_type}")

    # 处理每个case
    print(f"\n[2/4] Generating visualizations...")

    for idx, case in enumerate(cases):
        img_id = case['image_id']
        cat_name = case['category_name']
        size_cat = case['size_category']

        # 创建case文件夹
        case_dir = output_dir / f"rank{idx+1:02d}_{cat_name}_{size_cat}_img{img_id}"
        case_dir.mkdir(parents=True, exist_ok=True)

        # 加载图像
        img_info = coco_gt.imgs[img_id]
        img_path = Path(args.img_dir) / img_info['file_name']

        if not img_path.exists():
            print(f"  [!] Image not found: {img_path}")
            continue

        img = np.array(Image.open(img_path).convert('RGB'))

        # 1. 生成单独的模型结果图
        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_single_model_figure(
            img, case, 'clip',
            case_dir / 'clip.png', args.dpi
        )

        # 2. 生成并排对比图
        create_comparison_figure(
            img, case,
            case_dir / 'comparison.png', args.dpi,
            case_type=case_type
        )

        # 3. 保存case信息
        with open(case_dir / 'info.json', 'w') as f:
            json.dump(case, f, indent=2)

        print(f"  [{idx+1}/{len(cases)}] {case_dir.name}")

    # 生成索引HTML页面
    print(f"\n[3/4] Generating index page...")
    generate_index_html(cases, output_dir, case_type)

    # 生成汇总图
    print(f"\n[4/4] Generating summary figure...")
    generate_summary_figure(cases, output_dir, args.dpi, case_type)

    print(f"\n{'='*70}")
    print("Visualization complete!")
    print(f"Output directory: {output_dir}")
    print(f"Total cases: {len(cases)}")
    print(f"{'='*70}")


if __name__ == '__main__':
    main()