| import os |
| import h5py |
| import torch |
| import os |
| import numpy as np |
| from PIL import Image,ImageDraw |
| import torch.nn.functional as F |
| from open_clip.transform import ResizeMaxSize,_convert_to_rgb,det_image_transform,ResizeLongest |
| from torchvision.transforms import ToTensor,Normalize |
| import matplotlib.pyplot as plt |
| from torchvision import transforms |
| from pycocotools.coco import COCO |
| from sklearn.decomposition import PCA |
| from math import sqrt |
| from third_party.utils.utils_correspondence import pca_reduce_features |
| import math |
| from sklearn.cluster import DBSCAN |
| os.environ["CUDA_VISIBLE_DEVICES"] = "0" |
| from matplotlib import colors |
| import matplotlib as mpl |
| def dbscan_cluster_from_self_similarity(self_corr_matrix, eps=1.1, min_samples=5): |
| if isinstance(self_corr_matrix, torch.Tensor): |
| mat = self_corr_matrix.squeeze(0).cpu().numpy() |
| else: |
| mat = np.squeeze(self_corr_matrix) |
| assert mat.ndim == 2 and mat.shape[0] == mat.shape[1], "输入应为(N,N)自相关矩阵" |
| X = mat |
|
|
| clustering = DBSCAN(eps=eps, min_samples=min_samples) |
| labels = clustering.fit_predict(X) |
| return labels |
|
|
| def gaussian_window(dim1, dim2, std=1.): |
| constant = 1 / (std * math.sqrt(2)) |
| ks = list() |
| for dim in [dim1, dim2]: |
| start = -(dim - 1) / 2.0 |
| k = torch.linspace(start=start * constant, |
| end=(start + (dim - 1)) * constant, |
| steps=dim, |
| dtype=torch.float) |
| ks.append(k) |
| dist_square_to_mu = (torch.stack(torch.meshgrid(*ks, indexing='ij')) ** 2).sum(0) |
| return torch.exp(-dist_square_to_mu) |
|
|
| def get_attention_addition(dim1, dim2, window, adjust_for_cls=True): |
| m = torch.einsum('ij,kl->ijkl', torch.eye(dim1), torch.eye(dim2)) |
| m = m.permute((0, 3, 1, 2)).contiguous() |
| out = F.conv2d(m.view(-1, dim1, dim2).unsqueeze(1), window.unsqueeze(0).unsqueeze(1), padding='same').squeeze(1) |
| out = out.view(dim1 * dim2, dim1 * dim2) |
| if adjust_for_cls: |
| v_adjusted = torch.vstack([torch.zeros((1, dim1 * dim2)), out]) |
| out = torch.hstack([torch.zeros((dim1 * dim2 + 1, 1)), v_adjusted]) |
| return out |
|
|
|
|
|
|
| class UnNormalize(object): |
| def __init__(self, mean, std): |
| self.mean = mean |
| self.std = std |
|
|
| def __call__(self, image): |
| image2 = torch.clone(image) |
| if len(image2.shape) == 4: |
| |
| image2 = image2.permute(1, 0, 2, 3).contiguous() |
| for t, m, s in zip(image2, self.mean, self.std): |
| t.mul_(s).add_(m) |
| return image2.permute(1, 0, 2, 3).contiguous() |
| elif len(image2.shape) == 3: |
| |
| for t, m, s in zip(image2, self.mean, self.std): |
| t.mul_(s).add_(m) |
| return image2 |
| else: |
| raise ValueError(f"Unsupported image shape: {image2.shape}") |
|
|
| def plot_pca(f, path,target_size): |
| |
| pca = PCA(n_components=3) |
| pca.fit(f) |
| pca_img = pca.transform(f) |
| h = w = int(sqrt(pca_img.shape[0])) |
| pca_img = pca_img.reshape(h, w, 3) |
| pca_img_min = pca_img.min(axis=(0, 1)) |
| pca_img_max = pca_img.max(axis=(0, 1)) |
| pca_img = (pca_img - pca_img_min) / (pca_img_max - pca_img_min + 1e-8) |
| pca_img = Image.fromarray((pca_img * 255).astype(np.uint8)) |
| pca_img = transforms.Resize(target_size, interpolation=transforms.InterpolationMode.NEAREST)(pca_img) |
| pca_img.save(path) |
|
|
|
|
| def load_data(coco): |
| image_ids=[] |
| img_ids = coco.getImgIds() |
| cat_ids = coco.getCatIds() |
| for img_id in img_ids: |
| img = coco.loadImgs(img_id)[0] |
| ann_ids = coco.getAnnIds(imgIds=img['id'], catIds=cat_ids, iscrowd=None) |
| anns = coco.loadAnns(ann_ids) |
| anns = [ann for ann in anns if ann['iscrowd'] == 0] |
| if len(anns) == 0: |
| continue |
| image_ids.append(img_id) |
| torch.manual_seed(42) |
| image_ids = [image_ids[i] for i in torch.randperm(len(image_ids))] |
| return image_ids |
|
|
| def build_DINOv2(): |
| model_name='dinov2_vitb14_reg' |
| hub_path = '/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main' |
| try: |
| vfm = torch.hub.load(hub_path, model_name, source='local').half() |
| except Exception as e: |
| raise RuntimeError(f"Failed to load DINOv2 model '{model_name}': {e}") |
| return vfm |
|
|
| mean=[0.485, 0.456, 0.406] |
| std=[0.229, 0.224, 0.225] |
| normalize = Normalize(mean=mean, std=std) |
| DINO_transform=transforms.Compose([ |
| ResizeLongest(35*14, fill=0), |
| _convert_to_rgb, |
| ToTensor(), |
| normalize |
| ]) |
| _transform=transforms.Compose([ |
| ResizeLongest(560, fill=0), |
| _convert_to_rgb,]) |
|
|
| with torch.no_grad(): |
| device="cuda" |
| coco_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/instances_train2017.json' |
| img_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017' |
| cache_path = "/mnt/SSD8T/home/wjj/code/distilldift/train/cache/Dift_COCO_dift_merged_fp16.h5" |
| cache=h5py.File(cache_path, 'r')[str(0)] |
| weights = torch.load("/mnt/SSD8T/home/wjj/code/DeCLIP/EVAB_COCO_117K_topk10.pth", map_location="cpu") |
| coco=COCO(coco_path) |
| image_ids=load_data(coco) |
| dino=build_DINOv2().to(device) |
| image_select=200 |
| img_name = coco.loadImgs(image_ids[image_select])[0]['file_name'] |
|
|
| weight = weights[image_select] |
| match_id = weight[np.random.choice(10)] |
| matching_sample = image_ids[match_id] |
| matching_sample_info = coco.imgs[matching_sample] |
| knn_image_name=matching_sample_info['file_name'] |
| knn_image_path = os.path.join(img_path, knn_image_name) |
| knn_image= Image.open(knn_image_path) |
| knn_image_tensor = DINO_transform(knn_image).unsqueeze(0).to(torch.float16).to(device) |
| knn_dino_feats_raw = dino.get_intermediate_layers(knn_image_tensor, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1) |
| knn_sd_feats_raw = torch.from_numpy(cache[knn_image_name][()]).unsqueeze(0).flatten(start_dim=-2).transpose(-2,-1).to(torch.float32).to(device) |
|
|
| knn_dino_feats = F.normalize(knn_dino_feats_raw, dim=2) |
| knn_sd_feats = F.normalize(knn_sd_feats_raw, dim=2) |
|
|
| image_path = os.path.join(img_path, img_name) |
| image = Image.open(image_path) |
| sd_feats_raw=torch.from_numpy(cache[img_name][()]).unsqueeze(0) |
| |
| sd_feats_raw =sd_feats_raw.flatten(start_dim=-2).transpose(-2,-1).to(torch.float32).to(device) |
| image_tensor = DINO_transform(image).unsqueeze(0).to(torch.float16).to(device) |
| dino_feats_raw = dino.get_intermediate_layers(image_tensor, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1) |
|
|
| |
| sd_feats = F.normalize(sd_feats_raw, dim=2) |
| dino_feats = F.normalize(dino_feats_raw, dim=2) |
| w_dino=0.5 |
| w_sd=0.5 |
| dino_weighted = (w_dino ** 0.5) * dino_feats |
| sd_weighted = (w_sd ** 0.5) * sd_feats |
|
|
| |
| sd_dino_feats_raw = torch.cat([sd_weighted, dino_weighted], dim=2) |
| sd_dino_feats=F.normalize(sd_dino_feats_raw, dim=2) |
|
|
| |
| sim_sd = torch.einsum('bic,bjc->bij', sd_feats, sd_feats) |
| sim_dino = torch.einsum('bic,bjc->bij', dino_feats, dino_feats) |
| sim_sd_dino = torch.einsum('bic,bjc->bij', sd_dino_feats, sd_dino_feats) |
| dino_dbscan_labels=dbscan_cluster_from_self_similarity(sim_dino) |
| |
| target_size = (560, 560) |
| low_res_size = (35, 35) |
| low_res_token_choosen = (14, 12) |
| token_chosen = int( |
| low_res_token_choosen[0] * low_res_size[1] + low_res_token_choosen[1] |
| ) |
| token_x_low_res = token_chosen % low_res_size[0] |
| token_y_low_res = token_chosen // low_res_size[0] |
| token_x_img = int(((token_x_low_res+ 0.5) / low_res_size[0]) * target_size[0]) |
| token_y_img = int(((token_y_low_res+ 0.5) / low_res_size[1]) * target_size[1]) |
|
|
| output_dir = "sd_vis" |
| if not os.path.exists(output_dir): |
| os.mkdir(output_dir) |
| unnormalize = UnNormalize(mean, std) |
| sim_sd = sim_sd[:, token_chosen, :] |
| sim_dino = sim_dino[:, token_chosen, :] |
| sim_sd_dino = sim_sd_dino[:, token_chosen, :] |
| vis_img1=_transform(image) |
|
|
| window_size = [side * 2 - 1 for side in low_res_size] |
| window = gaussian_window(*window_size, std=15) |
| addition = get_attention_addition(*low_res_size, window,adjust_for_cls=False).unsqueeze(0) |
| addition=addition[:,token_chosen].to(sim_dino.device) |
| |
| addition = addition.to(sim_dino.dtype) |
| mask = sim_dino > 0 |
| sim_dino_new = sim_dino.clone() |
| sim_dino_new[mask] = sim_dino[mask] * addition.expand_as(sim_dino)[mask] |
| sim_dino_gaussian=sim_dino_new |
| |
| sim_maps = [sim_sd, sim_dino, sim_dino_gaussian, sim_sd_dino] |
| sim_np_maps = [] |
|
|
| |
| cluster_map = dino_dbscan_labels.reshape(low_res_size) |
| cluster_map_tensor = torch.from_numpy(cluster_map).unsqueeze(0).unsqueeze(0).float() |
| cluster_map_up = F.interpolate(cluster_map_tensor, size=target_size, mode="nearest") |
| cluster_map_np = cluster_map_up.squeeze().cpu().numpy() |
|
|
| |
| all_labels = np.unique(dino_dbscan_labels) |
| print(all_labels) |
| n_clusters = len(all_labels) |
|
|
| |
| cluster_colors = ['black'] + [mpl.colormaps['tab20'](i) for i in range(n_clusters-1)] |
| cmap = mpl.colors.ListedColormap(cluster_colors) |
| bounds = np.arange(-1, n_clusters) |
| norm = mpl.colors.BoundaryNorm(bounds, cmap.N) |
|
|
| for sim in sim_maps: |
| sim_map = sim.view(1, 1, low_res_size[0], low_res_size[1]) |
| sim_map_up = F.interpolate(sim_map, size=target_size, mode="bilinear", align_corners=False) |
| sim_map_np = sim_map_up.squeeze().cpu().numpy() |
| sim_np_maps.append(sim_map_np) |
|
|
| |
| fig, axes = plt.subplots(1, 6, figsize=(30, 5.5)) |
|
|
| |
| axes[0].imshow(vis_img1) |
| axes[0].scatter([token_x_img], [token_y_img], c='red', s=200, marker="o", edgecolors='black', linewidths=2) |
| axes[0].set_title('Image') |
| axes[0].axis('off') |
|
|
| |
| sim_titles = [ |
| 'Token Similarity (SD)', |
| 'Token Similarity (DINOv2)', |
| 'Token Similarity (DINOv2_gaussian)', |
| 'Token Similarity (SD+DINOv2)' |
| ] |
| for i in range(len(sim_np_maps)): |
| axes[i+1].imshow(sim_np_maps[i], cmap='jet') |
| axes[i+1].set_title(sim_titles[i]) |
| axes[i+1].axis('off') |
|
|
| |
| im = axes[-1].imshow(cluster_map_np, cmap=cmap, norm=norm, interpolation='nearest') |
| axes[-1].set_title('DBSCAN Clusters') |
| axes[-1].axis('off') |
|
|
| plt.tight_layout() |
| plt.savefig(os.path.join(output_dir, "token_similarity_vis_plus_cluster.png")) |
| plt.close(fig) |
|
|
|
|
| |
| |
| pca_paths = [] |
| feats_to_pca = [dino_feats_raw, sd_feats_raw, sd_dino_feats_raw] |
| pca_titles = ["DINOv2 PCA", "SD PCA", "SD+DINOv2 PCA"] |
| for i, feats in enumerate(feats_to_pca): |
| feats_np = feats[0].cpu().numpy() |
| pca_path = os.path.join(output_dir, f"pca_vis_{i}.png") |
| plot_pca(feats_np, pca_path, target_size) |
| pca_paths.append(pca_path) |
|
|
|
|
| |
| pca_imgs = [ |
| transforms.Resize(target_size, interpolation=transforms.InterpolationMode.NEAREST)(Image.open(p)) |
| for p in pca_paths |
| ] |
| |
| fig, axes = plt.subplots(1, 4, figsize=(20, 6)) |
|
|
| |
| axes[0].imshow(vis_img1) |
| axes[0].set_title('Image') |
| axes[0].axis('off') |
|
|
| |
| pca_titles = ["DINOv2 PCA", "SD PCA", "SD+DINOv2 PCA"] |
| for i in range(3): |
| axes[i+1].imshow(pca_imgs[i]) |
| axes[i+1].set_title(pca_titles[i]) |
| axes[i+1].axis('off') |
|
|
| plt.tight_layout() |
| plt.savefig(os.path.join(output_dir, "pca_vis.png")) |
| plt.close(fig) |