""" DeCLIP+ vs Integrated 基于 Panoptic 数据的特征可视化对比 改进点: 1. 使用 COCOPanopticDataset 获取带标注的验证集图像 2. 每张图的聚类数根据 GT 标注数量确定 3. 提高分辨率:560x560 输入,128x128 中间上采样 4. 添加 GT mask 对比可视化 5. 计算 mIoU 量化评估 6. 支持多 GPU 并行处理 使用方法: cd DeCLIP_private # 单 GPU CUDA_VISIBLE_DEVICES=0 python decoupling_analysis/visualize_panoptic_comparison.py # 多 GPU 并行(例如 8 张卡) python decoupling_analysis/visualize_panoptic_comparison.py --num-gpus 8 """ import sys import os import subprocess import argparse import multiprocessing as mp from functools import partial sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src')) import torch import torch.nn.functional as F import numpy as np from PIL import Image import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from torchvision.transforms import Compose, ToTensor, Normalize, Resize from sklearn.cluster import KMeans from sklearn.decomposition import PCA from scipy.optimize import linear_sum_assignment import json import logging import pickle # 禁用一些无关日志 logging.getLogger('PIL').setLevel(logging.WARNING) # ==================== 配置 ==================== class Config: # 路径配置 BASE_DIR = "/opt/tiger/xiaomoguhzz" DECLIP_CHECKPOINT = os.path.join(BASE_DIR, "declip_plus_seg/epoch_6.pt") INTEGRATED_CHECKPOINT = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/Integrated_EVA-B_DINOv2-B_560/checkpoints/epoch_5.pt" # COCO Panoptic 数据路径 COCO_ROOT = os.path.join(BASE_DIR, "standard_coco") VAL_IMAGE_ROOT = os.path.join(COCO_ROOT, "val2017") VAL_ANN_FILE = os.path.join(COCO_ROOT, "annotations/panoptic_val2017.json") SEGM_ROOT = os.path.join(COCO_ROOT, "annotations/panoptic_val2017") # 可视化配置 TARGET_SIZE = (560, 560) # 与训练一致 UPSAMPLE_SIZE = (128, 128) # 提高中间上采样分辨率 NUM_IMAGES = -1 # -1 表示跑全部符合条件的图片 MIN_SEGMENTS = 3 # 最少聚类数 MAX_SEGMENTS = 15 # 最多聚类数 RANDOM_SEED = 42 # 随机种子,保证可复现 TOP_K_CASES = 50 # 保存 IoU 差距最大的 top K 个 case 的可视化 # 输出目录 OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "results", "panoptic_comparison") # ==================== 工具函数 ==================== def download_checkpoint_if_needed(target_path, repo_id="xiaomoguhzz/xiaomogu_pami", filename="declip_plus_seg/epoch_6.pt"): """如果权重文件不存在,自动从 HuggingFace 下载""" if os.path.exists(target_path): print(f"Checkpoint exists: {target_path}") return True print(f"Downloading checkpoint to {target_path}...") target_dir = os.path.dirname(target_path) os.makedirs(target_dir, exist_ok=True) try: cmd = f"huggingface-cli download {repo_id} {filename} --local-dir {target_dir}" result = subprocess.run(cmd, shell=True, capture_output=True, text=True) if result.returncode == 0: downloaded_path = os.path.join(target_dir, filename) if os.path.exists(downloaded_path) and downloaded_path != target_path: os.makedirs(os.path.dirname(target_path), exist_ok=True) if not os.path.exists(target_path): os.rename(downloaded_path, target_path) print(f"Download complete: {target_path}") return True else: print(f"Download failed: {result.stderr}") return False except Exception as e: print(f"Download error: {e}") return False def rgb2id(color): """将 RGB 转换为 panoptic segment ID""" if isinstance(color, np.ndarray) and len(color.shape) == 3: if color.dtype == np.uint8: color = color.astype(np.int32) return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2] return int(color[0] + 256 * color[1] + 256 * 256 * color[2]) class UnNormalize: """反归一化""" def __init__(self, mean, std): self.mean = torch.tensor(mean).view(3, 1, 1) self.std = torch.tensor(std).view(3, 1, 1) def __call__(self, tensor): return tensor * self.std.to(tensor.device) + self.mean.to(tensor.device) def match_clusters_to_gt(gt_map, pred_map, num_segments): """使用匈牙利算法将聚类标签对齐到 GT""" # 获取 GT 中的唯一标签 gt_labels = np.unique(gt_map) gt_labels = gt_labels[gt_labels >= 0] # 排除背景(-1) if len(gt_labels) == 0: return pred_map, 0.0 # 构建 cost matrix n_gt = len(gt_labels) n_pred = num_segments cost_matrix = np.zeros((n_gt, n_pred), dtype=np.float32) for i, gt_label in enumerate(gt_labels): gt_mask = (gt_map == gt_label) for j in range(n_pred): pred_mask = (pred_map == j) intersection = np.sum(gt_mask & pred_mask) union = np.sum(gt_mask | pred_mask) if union > 0: cost_matrix[i, j] = -intersection / union # 负 IoU 作为 cost # 匈牙利算法匹配 row_ind, col_ind = linear_sum_assignment(cost_matrix) # 构造映射 matched_pred = np.full_like(pred_map, -1) total_iou = 0.0 for gt_idx, pred_idx in zip(row_ind, col_ind): matched_pred[pred_map == pred_idx] = gt_labels[gt_idx] total_iou += -cost_matrix[gt_idx, pred_idx] mean_iou = total_iou / len(row_ind) if len(row_ind) > 0 else 0.0 return matched_pred, mean_iou def calc_all_cosine(tokens): """计算 token 之间的余弦相似度矩阵""" if tokens.dim() == 3: tokens = tokens[0] tokens = F.normalize(tokens, dim=-1) cos_mat = torch.matmul(tokens, tokens.transpose(0, 1)) return cos_mat.cpu().numpy() def cluster_features(tokens, num_segments=5): """对特征进行 KMeans 聚类""" np.random.seed(42) tokens_np = tokens[0].cpu().numpy() if tokens.dim() == 3 else tokens.cpu().numpy() kmeans = KMeans(n_clusters=num_segments, n_init=10, random_state=42) clusters = kmeans.fit_predict(tokens_np) return clusters def get_cluster_map(tokens, orig_feature_map_size, upsampled_size, target_size, num_segments=5): """ 对特征进行聚类并上采样到目标尺寸 """ B, N, C = tokens.shape H, W = orig_feature_map_size assert N == H * W, f"tokens N={N} != H*W={H*W}" # reshape to (B, C, H, W) 并上采样到更高分辨率 tokens_2d = tokens.reshape(B, H, W, C).permute(0, 3, 1, 2) tokens_upsampled = F.interpolate(tokens_2d, size=upsampled_size, mode='bilinear', align_corners=False) B, C, H_up, W_up = tokens_upsampled.shape # reshape 回 (B, N', C) tokens_flatten = tokens_upsampled.permute(0, 2, 3, 1).reshape(B, H_up * W_up, C) # 在上采样后的特征上聚类 clusters = cluster_features(tokens_flatten, num_segments=num_segments) # 还原成 grid 并上采样到目标尺寸 clusters_grid = clusters.reshape(upsampled_size) clusters_tensor = torch.from_numpy(clusters_grid).unsqueeze(0).unsqueeze(0).float() upsampled = F.interpolate(clusters_tensor, size=target_size, mode='nearest') clusters_upsampled = upsampled.squeeze().cpu().numpy().astype(int) return clusters_upsampled def pca_visualization(tokens, orig_feature_map_size, target_size, n_components=3, pca_model=None, global_min=None, global_max=None): """ 对特征进行 PCA 可视化,提高分辨率 Args: tokens: (B, N, C) 特征 pca_model: 如果提供,使用这个 PCA 模型 transform(用于颜色对齐) global_min, global_max: 全局归一化范围(用于颜色对齐) Returns: pca_rgb: (H, W, 3) RGB 图像 pca_model: fit 后的 PCA 模型(用于后续对齐) pca_result: 原始 PCA 结果(用于计算全局 min/max) """ B, N, C = tokens.shape H, W = orig_feature_map_size # 先上采样到更高分辨率再做 PCA tokens_2d = tokens.reshape(B, H, W, C).permute(0, 3, 1, 2) tokens_upsampled = F.interpolate(tokens_2d, size=Config.UPSAMPLE_SIZE, mode='bilinear', align_corners=False) H_up, W_up = Config.UPSAMPLE_SIZE tokens_flat = tokens_upsampled.permute(0, 2, 3, 1).reshape(B, H_up * W_up, C) # PCA tokens_np = tokens_flat[0].cpu().numpy() if pca_model is None: # 新建 PCA 模型并 fit pca_model = PCA(n_components=n_components) pca_result = pca_model.fit_transform(tokens_np) else: # 使用已有 PCA 模型 transform pca_result = pca_model.transform(tokens_np) # 归一化到 [0, 1] if global_min is None or global_max is None: # 使用局部 min/max pca_min = pca_result.min(axis=0) pca_max = pca_result.max(axis=0) else: # 使用全局 min/max pca_min = global_min pca_max = global_max pca_normalized = (pca_result - pca_min) / (pca_max - pca_min + 1e-8) pca_normalized = np.clip(pca_normalized, 0, 1) # reshape 成图像 pca_image = pca_normalized.reshape(H_up, W_up, n_components) # 上采样到目标尺寸 pca_tensor = torch.from_numpy(pca_image).permute(2, 0, 1).unsqueeze(0).float() pca_upsampled = F.interpolate(pca_tensor, size=target_size, mode='bilinear', align_corners=False) pca_rgb = pca_upsampled.squeeze().permute(1, 2, 0).numpy() return pca_rgb, pca_model, pca_result def pca_visualization_aligned(feat_declip, feat_integrated, orig_feature_map_size, target_size, n_components=3): """ 对两个模型的特征进行对齐的 PCA 可视化 方法:使用 DeCLIP 的特征 fit PCA 作为标准空间,Integrated 特征投影到该空间。 这样 DeCLIP 的可视化不会被 Integrated 的"差"特征污染。 Args: feat_declip: (B, N, C) DeCLIP 模型的特征(作为 PCA 基准) feat_integrated: (B, N, C) Integrated 模型的特征(投影到 DeCLIP 空间) Returns: pca_declip, pca_integrated: 两个模型的 PCA RGB 图像 """ B, N, C = feat_declip.shape H, W = orig_feature_map_size # 上采样特征 def upsample_tokens(tokens): tokens_2d = tokens.reshape(B, H, W, C).permute(0, 3, 1, 2) tokens_upsampled = F.interpolate(tokens_2d, size=Config.UPSAMPLE_SIZE, mode='bilinear', align_corners=False) H_up, W_up = Config.UPSAMPLE_SIZE tokens_flat = tokens_upsampled.permute(0, 2, 3, 1).reshape(B, H_up * W_up, C) return tokens_flat[0].cpu().numpy() tokens_declip = upsample_tokens(feat_declip) tokens_integrated = upsample_tokens(feat_integrated) # 只用 DeCLIP 的特征 fit PCA(作为标准空间) pca = PCA(n_components=n_components) pca.fit(tokens_declip) # Transform 两个特征到 DeCLIP 的 PCA 空间 pca_declip = pca.transform(tokens_declip) pca_integrated = pca.transform(tokens_integrated) # 使用 DeCLIP 的 min/max 作为归一化范围 # 这样 Integrated 如果偏离 DeCLIP 空间,颜色会明显不同 global_min = pca_declip.min(axis=0) global_max = pca_declip.max(axis=0) def normalize_and_reshape(pca_result): pca_normalized = (pca_result - global_min) / (global_max - global_min + 1e-8) pca_normalized = np.clip(pca_normalized, 0, 1) H_up, W_up = Config.UPSAMPLE_SIZE pca_image = pca_normalized.reshape(H_up, W_up, n_components) pca_tensor = torch.from_numpy(pca_image).permute(2, 0, 1).unsqueeze(0).float() pca_upsampled = F.interpolate(pca_tensor, size=target_size, mode='bilinear', align_corners=False) pca_rgb = pca_upsampled.squeeze().permute(1, 2, 0).numpy() return pca_rgb return normalize_and_reshape(pca_declip), normalize_and_reshape(pca_integrated) def save_single_panel(save_path, draw_fn, figsize=(6, 6), dpi=200): """保存单个子图(无坐标轴)""" fig, ax = plt.subplots(1, 1, figsize=figsize) draw_fn(ax) ax.axis('off') plt.tight_layout(pad=0) fig.savefig(save_path, bbox_inches='tight', dpi=dpi) plt.close(fig) def normalize_case_dir_name(image_name): """将 image_name 转成安全的目录名""" base_name = os.path.basename(image_name) name_stem = os.path.splitext(base_name)[0] return name_stem.replace(os.sep, "_") # ==================== 数据加载 ==================== class SimplePanopticLoader: """简化的 Panoptic 数据加载器""" def __init__(self, ann_file, image_root, segm_root, transform, num_images=30, selected_ids=None): """ Args: ann_file: panoptic annotation json 文件路径 image_root: 图像目录 segm_root: panoptic segmentation png 目录 transform: 图像变换 num_images: 采样图片数量,-1 表示全部 selected_ids: 如果提供,只加载这些 image_id(用于多 GPU 分片) """ import random with open(ann_file, 'r') as f: self.panoptic_data = json.load(f) self.image_root = image_root self.segm_root = segm_root self.transform = transform # 创建 image_id -> annotation 映射 self.img_to_ann = {} for ann in self.panoptic_data['annotations']: self.img_to_ann[ann['image_id']] = ann # 创建 image_id -> image_info 映射 self.img_info = {img['id']: img for img in self.panoptic_data['images']} # 创建 category_id -> category 映射 self.categories = {cat['id']: cat for cat in self.panoptic_data['categories']} # 如果提供了 selected_ids,直接使用 if selected_ids is not None: self.selected_images = selected_ids print(f"Using {len(self.selected_images)} pre-selected images") return # 收集所有符合条件的图像 candidate_images = [] for img_id, ann in self.img_to_ann.items(): num_segments = len(ann['segments_info']) if Config.MIN_SEGMENTS <= num_segments <= Config.MAX_SEGMENTS: candidate_images.append(img_id) print(f"Found {len(candidate_images)} candidate images with {Config.MIN_SEGMENTS}-{Config.MAX_SEGMENTS} segments") # 处理图片数量 if num_images == -1: # -1 表示跑全部 self.selected_images = candidate_images print(f"Running on ALL {len(self.selected_images)} candidate images") else: # 随机采样 random.seed(Config.RANDOM_SEED) if len(candidate_images) > num_images: self.selected_images = random.sample(candidate_images, num_images) else: self.selected_images = candidate_images print(f"Randomly selected {len(self.selected_images)} images (seed={Config.RANDOM_SEED})") def __len__(self): return len(self.selected_images) def __getitem__(self, idx): img_id = self.selected_images[idx] img_info = self.img_info[img_id] ann = self.img_to_ann[img_id] # 加载图像 img_path = os.path.join(self.image_root, img_info['file_name']) image = Image.open(img_path).convert('RGB') img_tensor = self.transform(image) # 加载 panoptic segmentation segm_path = os.path.join(self.segm_root, ann['file_name']) segm_img = np.array(Image.open(segm_path)) segm_map = rgb2id(segm_img) # 获取 segment 信息 segments = ann['segments_info'] num_segments = len(segments) # 创建标签化的 GT mask (0, 1, 2, ...) gt_mask = np.full(segm_map.shape, -1, dtype=np.int32) segment_ids = [] for i, seg in enumerate(segments): seg_id = seg['id'] segment_ids.append(seg_id) gt_mask[segm_map == seg_id] = i # resize GT mask 到 target size gt_mask_resized = np.array( Image.fromarray(gt_mask.astype(np.int32)).resize( Config.TARGET_SIZE, Image.NEAREST ) ) return { 'image_id': int(img_id), # 确保是 int,便于序列化 'image_name': img_info['file_name'], 'image_tensor': img_tensor, 'image_pil': image, 'gt_mask': gt_mask_resized, 'num_segments': num_segments, 'segments_info': segments } def get_all_candidate_ids(self): """获取所有符合条件的 image_id 列表(用于多 GPU 分片)""" return self.selected_images.copy() # ==================== 模型加载 ==================== def load_model(checkpoint_path, device="cuda"): """加载 EVA-CLIP 模型""" from open_clip import create_model model = create_model("EVA02-CLIP-B-16", pretrained="eva", device=device) if checkpoint_path and os.path.exists(checkpoint_path): print(f"Loading checkpoint: {checkpoint_path}") checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False) if "state_dict" in checkpoint: state_dict = checkpoint["state_dict"] elif "model" in checkpoint: state_dict = checkpoint["model"] else: state_dict = checkpoint state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()} # 加载 visual encoder 权重 visual_state_dict = {k.replace("visual.", ""): v for k, v in state_dict.items() if k.startswith("visual.")} if visual_state_dict: missing, unexpected = model.visual.load_state_dict(visual_state_dict, strict=False) print(f"Loaded visual weights. Missing: {len(missing)}, Unexpected: {len(unexpected)}") else: missing, unexpected = model.load_state_dict(state_dict, strict=False) print(f"Loaded full model. Missing: {len(missing)}, Unexpected: {len(unexpected)}") model.eval() return model def extract_features(model, image, mode="vanilla"): """提取模型输出特征""" model.eval() with torch.no_grad(): output = model.visual.encode_dense(image, keep_shape=True, mode=mode) if isinstance(output, tuple): output = output[0] # output shape: (B, C, H, W) or (B, N, C) if output.dim() == 4: B, C, H, W = output.shape output = output.permute(0, 2, 3, 1).reshape(B, H * W, C) elif output.dim() == 3: pass # already (B, N, C) # normalize output = F.normalize(output, dim=-1) return output # ==================== Worker 函数(单 GPU 处理分片)==================== def worker_process(rank, world_size, all_image_ids, shared_config): """ 单个 GPU worker 处理分配的数据分片 Args: rank: 当前进程的 rank (0, 1, 2, ...) world_size: 总进程数 all_image_ids: 所有待处理的 image_id 列表 shared_config: 共享配置 """ # 设置 GPU device = f"cuda:{rank}" torch.cuda.set_device(rank) # 分配数据分片 total = len(all_image_ids) chunk_size = (total + world_size - 1) // world_size start_idx = rank * chunk_size end_idx = min(start_idx + chunk_size, total) my_image_ids = all_image_ids[start_idx:end_idx] print(f"[GPU {rank}] Processing {len(my_image_ids)} images (idx {start_idx}-{end_idx-1})") # 图像预处理 mean = [0.48145466, 0.4578275, 0.40821073] std = [0.26862954, 0.26130258, 0.27577711] normalize = Normalize(mean=mean, std=std) unnorm = UnNormalize(mean, std) transform = Compose([ Resize(Config.TARGET_SIZE), ToTensor(), normalize ]) feature_map_size = (Config.TARGET_SIZE[0] // 16, Config.TARGET_SIZE[1] // 16) # 加载数据(只加载分配给本 worker 的数据) dataset = SimplePanopticLoader( ann_file=Config.VAL_ANN_FILE, image_root=Config.VAL_IMAGE_ROOT, segm_root=Config.SEGM_ROOT, transform=transform, num_images=-1, # 加载全部 selected_ids=my_image_ids # 只处理分配的 image ids ) # 加载模型 model_declip = load_model(Config.DECLIP_CHECKPOINT, device) model_integrated = load_model(Config.INTEGRATED_CHECKPOINT, device) # 处理结果 worker_results = [] for idx in range(len(dataset)): sample = dataset[idx] img_name = sample['image_name'] img_id = sample['image_id'] img_tensor = sample['image_tensor'].to(device).unsqueeze(0) gt_mask = sample['gt_mask'] num_segments = sample['num_segments'] # 反归一化用于可视化 img_unnorm = unnorm(img_tensor.squeeze(0)).permute(1, 2, 0).cpu().numpy() img_unnorm = np.clip(img_unnorm, 0, 1) # 提取特征 with torch.no_grad(): feat_declip = extract_features(model_declip, img_tensor, mode="vanilla") feat_integrated = extract_features(model_integrated, img_tensor, mode="vanilla") # KMeans 聚类 clusters_declip = get_cluster_map( feat_declip, feature_map_size, Config.UPSAMPLE_SIZE, Config.TARGET_SIZE, num_segments ) clusters_integrated = get_cluster_map( feat_integrated, feature_map_size, Config.UPSAMPLE_SIZE, Config.TARGET_SIZE, num_segments ) # 匹配聚类到 GT 并计算 IoU matched_declip, iou_declip = match_clusters_to_gt(gt_mask, clusters_declip, num_segments) matched_integrated, iou_integrated = match_clusters_to_gt(gt_mask, clusters_integrated, num_segments) iou_diff = iou_declip - iou_integrated # PCA 可视化(以 DeCLIP 为基准) pca_declip, pca_integrated = pca_visualization_aligned( feat_declip, feat_integrated, feature_map_size, Config.TARGET_SIZE ) # 存储结果 worker_results.append({ 'image_id': img_id, 'img_name': img_name, 'img_unnorm': img_unnorm, 'gt_mask': gt_mask, 'num_segments': num_segments, 'clusters_declip': clusters_declip, 'clusters_integrated': clusters_integrated, 'iou_declip': iou_declip, 'iou_integrated': iou_integrated, 'iou_diff': iou_diff, 'pca_declip': pca_declip, 'pca_integrated': pca_integrated }) if (idx + 1) % 50 == 0: print(f"[GPU {rank}] Processed {idx + 1}/{len(dataset)} images") print(f"[GPU {rank}] Finished processing {len(worker_results)} images") # 保存 worker 结果到临时文件 tmp_path = os.path.join(Config.OUTPUT_DIR, f"tmp_worker_{rank}.pkl") with open(tmp_path, 'wb') as f: pickle.dump(worker_results, f) return tmp_path # ==================== 主函数 ==================== def run_panoptic_comparison(num_gpus=1): """运行基于 Panoptic 数据的特征可视化对比""" os.makedirs(Config.OUTPUT_DIR, exist_ok=True) # 检查数据路径 if not os.path.exists(Config.VAL_ANN_FILE): print(f"Error: Annotation file not found: {Config.VAL_ANN_FILE}") print("Please ensure COCO panoptic data is available.") return # 自动下载 DeCLIP+ 权重 download_checkpoint_if_needed(Config.DECLIP_CHECKPOINT) # 图像预处理 mean = [0.48145466, 0.4578275, 0.40821073] std = [0.26862954, 0.26130258, 0.27577711] normalize = Normalize(mean=mean, std=std) unnorm = UnNormalize(mean, std) transform = Compose([ Resize(Config.TARGET_SIZE), ToTensor(), normalize ]) feature_map_size = (Config.TARGET_SIZE[0] // 16, Config.TARGET_SIZE[1] // 16) # 加载数据获取所有 candidate image ids print("\n" + "=" * 60) print("Loading Panoptic data...") print("=" * 60) # 先获取所有符合条件的 image ids temp_dataset = SimplePanopticLoader( ann_file=Config.VAL_ANN_FILE, image_root=Config.VAL_IMAGE_ROOT, segm_root=Config.SEGM_ROOT, transform=transform, num_images=Config.NUM_IMAGES ) all_image_ids = temp_dataset.get_all_candidate_ids() del temp_dataset print(f"\nTotal images to process: {len(all_image_ids)}") print(f"Using {num_gpus} GPU(s)") # ==================== 多 GPU 并行处理 ==================== if num_gpus > 1: print("\n" + "=" * 60) print(f"Starting {num_gpus} parallel workers...") print("=" * 60) # 使用 spawn 启动多进程 mp.set_start_method('spawn', force=True) processes = [] for rank in range(num_gpus): p = mp.Process( target=worker_process, args=(rank, num_gpus, all_image_ids, None) ) p.start() processes.append(p) # 等待所有进程完成 for p in processes: p.join() print("\n" + "=" * 60) print("All workers finished. Merging results...") print("=" * 60) # 合并所有 worker 的结果 all_vis_data = [] for rank in range(num_gpus): tmp_path = os.path.join(Config.OUTPUT_DIR, f"tmp_worker_{rank}.pkl") if os.path.exists(tmp_path): with open(tmp_path, 'rb') as f: worker_results = pickle.load(f) all_vis_data.extend(worker_results) os.remove(tmp_path) # 清理临时文件 print(f" Loaded {len(worker_results)} results from worker {rank}") print(f"Total merged results: {len(all_vis_data)}") else: # ==================== 单 GPU 处理 ==================== device = "cuda" if torch.cuda.is_available() else "cpu" dataset = SimplePanopticLoader( ann_file=Config.VAL_ANN_FILE, image_root=Config.VAL_IMAGE_ROOT, segm_root=Config.SEGM_ROOT, transform=transform, num_images=Config.NUM_IMAGES ) # 加载模型 print("\n" + "=" * 60) print("Loading models...") print("=" * 60) model_declip = load_model(Config.DECLIP_CHECKPOINT, device) model_integrated = load_model(Config.INTEGRATED_CHECKPOINT, device) # 临时存储每个样本的可视化数据 all_vis_data = [] # 处理每张图像 for idx in range(len(dataset)): sample = dataset[idx] img_name = sample['image_name'] img_id = sample['image_id'] img_tensor = sample['image_tensor'].to(device).unsqueeze(0) gt_mask = sample['gt_mask'] num_segments = sample['num_segments'] if (idx + 1) % 50 == 0 or idx == 0: print(f"\n[{idx+1}/{len(dataset)}] Processing: {img_name} (segments: {num_segments})") # 反归一化用于可视化 img_unnorm = unnorm(img_tensor.squeeze(0)).permute(1, 2, 0).cpu().numpy() img_unnorm = np.clip(img_unnorm, 0, 1) # 提取特征 with torch.no_grad(): feat_declip = extract_features(model_declip, img_tensor, mode="vanilla") feat_integrated = extract_features(model_integrated, img_tensor, mode="vanilla") # KMeans 聚类 clusters_declip = get_cluster_map( feat_declip, feature_map_size, Config.UPSAMPLE_SIZE, Config.TARGET_SIZE, num_segments ) clusters_integrated = get_cluster_map( feat_integrated, feature_map_size, Config.UPSAMPLE_SIZE, Config.TARGET_SIZE, num_segments ) # 匹配聚类到 GT 并计算 IoU matched_declip, iou_declip = match_clusters_to_gt(gt_mask, clusters_declip, num_segments) matched_integrated, iou_integrated = match_clusters_to_gt(gt_mask, clusters_integrated, num_segments) iou_diff = iou_declip - iou_integrated # PCA 可视化(以 DeCLIP 为基准) pca_declip, pca_integrated = pca_visualization_aligned( feat_declip, feat_integrated, feature_map_size, Config.TARGET_SIZE ) # 存储可视化数据 all_vis_data.append({ 'image_id': img_id, 'img_name': img_name, 'img_unnorm': img_unnorm.copy(), 'gt_mask': gt_mask.copy(), 'num_segments': num_segments, 'clusters_declip': clusters_declip.copy(), 'clusters_integrated': clusters_integrated.copy(), 'iou_declip': iou_declip, 'iou_integrated': iou_integrated, 'iou_diff': iou_diff, 'pca_declip': pca_declip.copy(), 'pca_integrated': pca_integrated.copy() }) # ==================== 按 IoU 差距排序 ==================== print("\n" + "=" * 60) print("Sorting by IoU difference (DeCLIP - Integrated)...") print("=" * 60) # 按 IoU 差距降序排序(DeCLIP 优势大的排前面) all_vis_data.sort(key=lambda x: x['iou_diff'], reverse=True) # 创建排序后的结果列表 sorted_results = [] for rank, vis_data in enumerate(all_vis_data): sorted_results.append({ 'rank': rank + 1, 'image_name': vis_data['img_name'], 'num_segments': vis_data['num_segments'], 'iou_declip': vis_data['iou_declip'], 'iou_integrated': vis_data['iou_integrated'], 'iou_diff': vis_data['iou_diff'] }) # ==================== 保存 Top K 可视化 ==================== top_k = min(Config.TOP_K_CASES, len(all_vis_data)) print(f"\nSaving top {top_k} visualizations (highest IoU difference)...") vis_output_dir = os.path.join(Config.OUTPUT_DIR, "top_cases") os.makedirs(vis_output_dir, exist_ok=True) single_figsize = (6, 6) single_dpi = 200 for rank, vis_data in enumerate(all_vis_data[:top_k]): img_name = vis_data['img_name'] img_unnorm = vis_data['img_unnorm'] gt_mask = vis_data['gt_mask'] num_segments = vis_data['num_segments'] clusters_declip = vis_data['clusters_declip'] clusters_integrated = vis_data['clusters_integrated'] iou_declip = vis_data['iou_declip'] iou_integrated = vis_data['iou_integrated'] iou_diff = vis_data['iou_diff'] pca_declip = vis_data['pca_declip'] pca_integrated = vis_data['pca_integrated'] case_dir_name = normalize_case_dir_name(img_name) case_dir = os.path.join(vis_output_dir, case_dir_name) os.makedirs(case_dir, exist_ok=True) # ==================== 绘制对比图 ==================== fig, axs = plt.subplots(2, 4, figsize=(20, 10)) # 创建自定义 colormap n_colors = max(num_segments, 10) colors = plt.cm.tab20(np.linspace(0, 1, n_colors)) cmap = ListedColormap(colors) gt_display = np.ma.masked_where(gt_mask < 0, gt_mask) # 第一行:聚类结果 axs[0, 0].imshow(img_unnorm) axs[0, 0].set_title("Original Image", fontsize=12) axs[0, 0].axis('off') # GT mask axs[0, 1].imshow(img_unnorm) axs[0, 1].imshow(gt_display, cmap=cmap, alpha=0.6, interpolation='nearest', vmin=0, vmax=num_segments-1) axs[0, 1].set_title(f"GT Segments ({num_segments})", fontsize=12) axs[0, 1].axis('off') # DeCLIP+ 聚类 axs[0, 2].imshow(img_unnorm) axs[0, 2].imshow(clusters_declip, cmap=cmap, alpha=0.6, interpolation='nearest', vmin=0, vmax=num_segments-1) axs[0, 2].set_title(f"DeCLIP+ Clusters (mIoU: {iou_declip:.3f})", fontsize=12) axs[0, 2].axis('off') # Integrated 聚类 axs[0, 3].imshow(img_unnorm) axs[0, 3].imshow(clusters_integrated, cmap=cmap, alpha=0.6, interpolation='nearest', vmin=0, vmax=num_segments-1) axs[0, 3].set_title(f"Integrated Clusters (mIoU: {iou_integrated:.3f})", fontsize=12) axs[0, 3].axis('off') # 第二行:PCA 可视化 axs[1, 0].imshow(img_unnorm) axs[1, 0].set_title("Original Image", fontsize=12) axs[1, 0].axis('off') # 空白位置放 GT axs[1, 1].imshow(gt_display, cmap=cmap, interpolation='nearest', vmin=0, vmax=num_segments-1) axs[1, 1].set_title("GT Mask (clean)", fontsize=12) axs[1, 1].axis('off') # DeCLIP+ PCA axs[1, 2].imshow(pca_declip) axs[1, 2].set_title("DeCLIP+ PCA Features", fontsize=12) axs[1, 2].axis('off') # Integrated PCA axs[1, 3].imshow(pca_integrated) axs[1, 3].set_title("Integrated PCA Features", fontsize=12) axs[1, 3].axis('off') plt.suptitle( f"Rank #{rank+1} | {img_name} | Δ mIoU: {iou_diff:+.3f} (DeCLIP: {iou_declip:.3f}, Integrated: {iou_integrated:.3f})", fontsize=14, y=1.02 ) plt.tight_layout() # 保存(按排名命名) save_name = os.path.splitext(img_name)[0] save_path = os.path.join(vis_output_dir, f"rank{rank+1:03d}_{save_name}.png") plt.savefig(save_path, bbox_inches='tight', dpi=200) case_all_path = os.path.join(case_dir, "all.png") plt.savefig(case_all_path, bbox_inches='tight', dpi=200) plt.close() def save_panel(filename, draw_fn): save_path = os.path.join(case_dir, filename) save_single_panel(save_path, draw_fn, figsize=single_figsize, dpi=single_dpi) save_panel("original.png", lambda ax: ax.imshow(img_unnorm)) def draw_gt_overlay(ax): ax.imshow(img_unnorm) ax.imshow(gt_display, cmap=cmap, alpha=0.6, interpolation='nearest', vmin=0, vmax=num_segments-1) def draw_gt_clean(ax): ax.imshow(gt_display, cmap=cmap, interpolation='nearest', vmin=0, vmax=num_segments-1) def draw_declip_clusters(ax): ax.imshow(img_unnorm) ax.imshow(clusters_declip, cmap=cmap, alpha=0.6, interpolation='nearest', vmin=0, vmax=num_segments-1) def draw_integrated_clusters(ax): ax.imshow(img_unnorm) ax.imshow(clusters_integrated, cmap=cmap, alpha=0.6, interpolation='nearest', vmin=0, vmax=num_segments-1) def draw_declip_pca(ax): ax.imshow(pca_declip) def draw_integrated_pca(ax): ax.imshow(pca_integrated) save_panel("gt_overlay.png", draw_gt_overlay) save_panel("gt_mask.png", draw_gt_clean) save_panel("declip_clusters.png", draw_declip_clusters) save_panel("integrated_clusters.png", draw_integrated_clusters) save_panel("declip_pca.png", draw_declip_pca) save_panel("integrated_pca.png", draw_integrated_pca) if (rank + 1) % 10 == 0: print(f" Saved {rank + 1}/{top_k} visualizations...") print(f" Saved all {top_k} visualizations to: {vis_output_dir}") # ==================== 汇总结果 ==================== print("\n" + "=" * 60) print("SUMMARY") print("=" * 60) avg_declip = np.mean([d['iou_declip'] for d in all_vis_data]) avg_integrated = np.mean([d['iou_integrated'] for d in all_vis_data]) # 计算 DeCLIP 胜出的比例 wins = sum(1 for d in all_vis_data if d['iou_diff'] > 0) win_rate = wins / len(all_vis_data) * 100 print(f"\nTotal images processed: {len(all_vis_data)}") print(f"\nAverage mIoU:") print(f" DeCLIP+ (Decoupled): {avg_declip:.4f}") print(f" Integrated: {avg_integrated:.4f}") print(f" Difference: {avg_declip - avg_integrated:+.4f}") print(f"\nDeCLIP+ wins: {wins}/{len(all_vis_data)} ({win_rate:.1f}%)") print(f"\nTop 10 cases (DeCLIP advantage):") for i, r in enumerate(sorted_results[:10]): print(f" {r['rank']:3d}. {r['image_name']}: Δ={r['iou_diff']:+.4f} (D:{r['iou_declip']:.3f}, I:{r['iou_integrated']:.3f})") # 保存完整结果 results_path = os.path.join(Config.OUTPUT_DIR, "panoptic_comparison_results.json") with open(results_path, 'w') as f: json.dump({ 'summary': { 'num_images': len(all_vis_data), 'avg_declip_iou': avg_declip, 'avg_integrated_iou': avg_integrated, 'avg_diff': avg_declip - avg_integrated, 'declip_win_count': wins, 'declip_win_rate': win_rate }, 'sorted_results': sorted_results }, f, indent=2) print(f"\nFull results saved to: {results_path}") print(f"\nTop {top_k} visualizations saved to: {vis_output_dir}") print("=" * 60) if __name__ == "__main__": parser = argparse.ArgumentParser(description="DeCLIP+ vs Integrated Panoptic Comparison") parser.add_argument("--num-gpus", type=int, default=1, help="Number of GPUs for parallel processing (default: 1)") parser.add_argument("--top-k", type=int, default=None, help="Number of top cases to save (default: use Config.TOP_K_CASES)") args = parser.parse_args() if args.top_k is not None: Config.TOP_K_CASES = args.top_k run_panoptic_comparison(num_gpus=args.num_gpus)