| """ |
| 可视化消融实验:比较 SD-GSC, SAM-GSC, JEPA-GSC 的效果 |
| |
| 类似于 vis_sd_featsv5.2.py,但同时展示三种方法的结果 |
| """ |
|
|
| import torch |
| import torch.nn.functional as F |
| import numpy as np |
| import matplotlib.pyplot as plt |
| from PIL import Image |
| import os |
| import sys |
| from typing import Tuple |
|
|
| |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
|
|
| from refine_functions import ( |
| refine_dino_with_sd, |
| refine_dino_with_sam, |
| refine_dino_with_ijepa, |
| compute_dino_correlation, |
| resize_attention |
| ) |
|
|
| |
| class ImagePreprocessor: |
| def __init__(self, size: int = 224): |
| self.size = size |
| self.mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1) |
| self.std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1) |
| |
| def __call__(self, img: Image.Image) -> torch.Tensor: |
| img = img.convert("RGB") |
| img = img.resize((self.size, self.size), Image.BILINEAR) |
| img = torch.from_numpy(np.array(img)).float() / 255.0 |
| img = img.permute(2, 0, 1) |
| img = (img - self.mean) / self.std |
| return img.unsqueeze(0) |
|
|
|
|
| def build_dinov2(device: str = "cuda"): |
| """构建 DINOv2 模型""" |
| hub_path = '/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main' |
| model = torch.hub.load(hub_path, 'dinov2_vitb14_reg', source='local').half() |
| model = model.to(device).eval() |
| for p in model.parameters(): |
| p.requires_grad = False |
| return model |
|
|
|
|
| def extract_dino_features(model, image: torch.Tensor) -> torch.Tensor: |
| """提取 DINO 特征""" |
| with torch.no_grad(): |
| features = model.get_intermediate_layers(image, reshape=True)[0] |
| return features |
|
|
|
|
| def visualize_similarity_comparison( |
| image_path: str, |
| dino_model, |
| sd_attn: torch.Tensor, |
| sam_attn: torch.Tensor, |
| ijepa_attn: torch.Tensor, |
| query_point: Tuple[int, int], |
| refine_weight: float = 0.3, |
| save_path: str = None, |
| device: str = "cuda" |
| ): |
| """ |
| 可视化比较三种方法的相似度图 |
| |
| Args: |
| image_path: 输入图像路径 |
| dino_model: DINOv2 模型 |
| sd_attn: SD attention (B, HW, HW) |
| sam_attn: SAM attention (B, HW, HW) |
| ijepa_attn: I-JEPA attention (B, HW, HW) |
| query_point: 查询点位置 (y, x) in patch coordinates |
| refine_weight: refine 权重 |
| save_path: 保存路径 |
| device: 设备 |
| """ |
| |
| preprocess = ImagePreprocessor(size=224) |
| image = Image.open(image_path) |
| image_tensor = preprocess(image).to(device).half() |
| |
| |
| dino_feats = extract_dino_features(dino_model, image_tensor) |
| B, C, H, W = dino_feats.shape |
| |
| |
| dino_corr = compute_dino_correlation(dino_feats) |
| |
| |
| target_size = H |
| |
| if sd_attn is not None: |
| sd_attn_resized = resize_attention(sd_attn, target_size) |
| else: |
| sd_attn_resized = None |
| |
| if sam_attn is not None: |
| sam_attn_resized = resize_attention(sam_attn, target_size) |
| else: |
| sam_attn_resized = None |
| |
| if ijepa_attn is not None: |
| ijepa_attn_resized = resize_attention(ijepa_attn, target_size) |
| else: |
| ijepa_attn_resized = None |
| |
| |
| methods = { |
| "Original DINO": dino_corr, |
| } |
| |
| if sd_attn_resized is not None: |
| methods["SD-GSC (Ours)"] = refine_dino_with_sd(dino_corr, sd_attn_resized, refine_weight) |
| |
| if sam_attn_resized is not None: |
| methods["SAM-GSC"] = refine_dino_with_sam(dino_corr, sam_attn_resized, refine_weight) |
| |
| if ijepa_attn_resized is not None: |
| methods["JEPA-GSC"] = refine_dino_with_ijepa(dino_corr, ijepa_attn_resized, refine_weight) |
| |
| |
| query_idx = query_point[0] * W + query_point[1] |
| |
| similarity_maps = {} |
| for name, corr in methods.items(): |
| sim_map = corr[0, query_idx].view(H, W).cpu().numpy() |
| similarity_maps[name] = sim_map |
| |
| |
| n_methods = len(similarity_maps) |
| fig, axes = plt.subplots(1, n_methods + 1, figsize=(4 * (n_methods + 1), 4)) |
| |
| |
| axes[0].imshow(image.resize((224, 224))) |
| axes[0].scatter([query_point[1] * (224 // W)], [query_point[0] * (224 // H)], |
| c='red', s=100, marker='x') |
| axes[0].set_title("Input Image") |
| axes[0].axis('off') |
| |
| |
| for i, (name, sim_map) in enumerate(similarity_maps.items()): |
| im = axes[i + 1].imshow(sim_map, cmap='hot', vmin=0, vmax=1) |
| axes[i + 1].scatter([query_point[1]], [query_point[0]], c='cyan', s=50, marker='x') |
| axes[i + 1].set_title(name) |
| axes[i + 1].axis('off') |
| |
| plt.colorbar(im, ax=axes[-1], fraction=0.046, pad=0.04) |
| plt.tight_layout() |
| |
| if save_path: |
| plt.savefig(save_path, dpi=150, bbox_inches='tight') |
| print(f"Saved visualization to {save_path}") |
| |
| plt.show() |
| plt.close() |
|
|
|
|
| def visualize_attention_comparison( |
| sd_attn: torch.Tensor, |
| sam_attn: torch.Tensor, |
| ijepa_attn: torch.Tensor, |
| query_point: Tuple[int, int], |
| save_path: str = None |
| ): |
| """ |
| 直接可视化三种方法的 attention map(不经过 DINO) |
| """ |
| H = W = int(sd_attn.shape[1] ** 0.5) if sd_attn is not None else int(sam_attn.shape[1] ** 0.5) |
| query_idx = query_point[0] * W + query_point[1] |
| |
| attentions = {} |
| if sd_attn is not None: |
| attentions["SD Attention"] = sd_attn[0, query_idx].view(H, W).cpu().numpy() |
| if sam_attn is not None: |
| attentions["SAM Attention"] = sam_attn[0, query_idx].view(H, W).cpu().numpy() |
| if ijepa_attn is not None: |
| attentions["I-JEPA Attention"] = ijepa_attn[0, query_idx].view(H, W).cpu().numpy() |
| |
| n_attns = len(attentions) |
| fig, axes = plt.subplots(1, n_attns, figsize=(4 * n_attns, 4)) |
| |
| if n_attns == 1: |
| axes = [axes] |
| |
| for i, (name, attn_map) in enumerate(attentions.items()): |
| im = axes[i].imshow(attn_map, cmap='viridis') |
| axes[i].scatter([query_point[1]], [query_point[0]], c='red', s=50, marker='x') |
| axes[i].set_title(name) |
| axes[i].axis('off') |
| plt.colorbar(im, ax=axes[i], fraction=0.046, pad=0.04) |
| |
| plt.tight_layout() |
| |
| if save_path: |
| plt.savefig(save_path, dpi=150, bbox_inches='tight') |
| print(f"Saved attention comparison to {save_path}") |
| |
| plt.show() |
| plt.close() |
|
|
|
|
| |
| if __name__ == "__main__": |
| import argparse |
| |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--image", type=str, required=True, help="Input image path") |
| parser.add_argument("--query_y", type=int, default=8, help="Query point y (in patch coords)") |
| parser.add_argument("--query_x", type=int, default=8, help="Query point x (in patch coords)") |
| parser.add_argument("--refine_weight", type=float, default=0.3) |
| parser.add_argument("--save_dir", type=str, default="./ablation_results") |
| args = parser.parse_args() |
| |
| os.makedirs(args.save_dir, exist_ok=True) |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| |
| print("Building DINOv2 model...") |
| dino_model = build_dinov2(device) |
| |
| |
| |
| print("Using dummy attention for demonstration...") |
| HW = 256 |
| sd_attn = F.softmax(torch.randn(1, HW, HW, device=device), dim=-1) |
| sam_attn = F.softmax(torch.randn(1, HW, HW, device=device), dim=-1) |
| ijepa_attn = F.softmax(torch.randn(1, HW, HW, device=device), dim=-1) |
| |
| query_point = (args.query_y, args.query_x) |
| |
| print("Visualizing similarity comparison...") |
| save_path = os.path.join(args.save_dir, "similarity_comparison.png") |
| visualize_similarity_comparison( |
| args.image, |
| dino_model, |
| sd_attn, |
| sam_attn, |
| ijepa_attn, |
| query_point, |
| args.refine_weight, |
| save_path, |
| device |
| ) |
| |
| print("Done!") |
|
|