| 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 src.segment_anything import sam_model_registry |
| from math import sqrt |
|
|
| from vis_sd_featsv2 import plot_pca |
| os.environ["CUDA_VISIBLE_DEVICES"] = "0" |
| |
| 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_SAM(): |
| try: |
| vfm = sam_model_registry['vit_l'](checkpoint='/mnt/SSD8T/home/wjj/code/ProxyCLIP/sam_ckpts/sam_vit_l_0b3195.pth').half() |
| except Exception as e: |
| raise RuntimeError(f"Failed to load SAM model: {e}") |
| return vfm |
|
|
| mean=[0.485, 0.456, 0.406] |
| std=[0.229, 0.224, 0.225] |
| normalize = Normalize(mean=mean, std=std) |
| SAM_transform=transforms.Compose([ |
| ResizeLongest(560, 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) |
| sam=build_SAM().to(device) |
| image_select=5 |
| 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 = SAM_transform(knn_image).unsqueeze(0).to(torch.float16).to(device) |
|
|
|
|
| |
| |
| knn_sam_feats_raw = sam.image_encoder(knn_image_tensor).flatten(start_dim=-2).transpose(-2, -1).to(torch.float32).to(device) |
| 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_sam_feats = F.normalize(knn_sam_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) |
| image_tensor = SAM_transform(image).unsqueeze(0).to(torch.float16).to(device) |
| sd_feats_raw = torch.from_numpy(cache[img_name][()]).unsqueeze(0).flatten(start_dim=-2).transpose(-2, -1).to(torch.float32).to(device) |
| sam_feats_raw = sam.image_encoder(image_tensor).flatten(start_dim=-2).transpose(-2, -1).to(torch.float32).to(device) |
|
|
| sd_feats = F.normalize(sd_feats_raw, dim=2) |
| sam_feats = F.normalize(sam_feats_raw, dim=2) |
|
|
| w_sam = 0.9 |
| w_sd = 0.1 |
| sam_weighted = (w_sam ** 0.5) * sam_feats |
| sd_weighted = (w_sd ** 0.5) * sd_feats |
| sd_sam_feats_raw = torch.cat([sam_weighted, sd_weighted], dim=2) |
| sd_sam_feats=F.normalize(sd_sam_feats_raw, dim=2) |
|
|
| |
| sim_sd = torch.einsum('bic,bjc->bij', sd_feats, sd_feats) |
| sim_sam = torch.einsum('bic,bjc->bij', sam_feats, sam_feats) |
| sim_sam = (sim_sam - torch.mean(sim_sam) * 1.2) * 3.0 |
| sim_sd_sam = torch.einsum('bic,bjc->bij', sd_sam_feats, sd_sam_feats) |
|
|
| target_size = (560, 560) |
| low_res_size = (35, 35) |
| low_res_token_choosen = (8, 10) |
| 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 = "sam_vis" |
| if not os.path.exists(output_dir): |
| os.mkdir(output_dir) |
|
|
| sim_sd = sim_sd[:, token_chosen, :] |
| sim_sam = sim_sam[:, token_chosen, :] |
| sim_sd_sam = sim_sd_sam[:, token_chosen, :] |
|
|
|
|
| vis_img1=_transform(image) |
|
|
| |
| sim_maps = [sim_sd, sim_sam, sim_sd_sam] |
| sim_np_maps = [] |
|
|
| 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, 4, figsize=(20, 6)) |
|
|
| |
| axes[0].imshow(vis_img1) |
| axes[0].scatter([token_x_img], [token_y_img], c='red', s=100, marker="o", edgecolors='black', linewidths=2) |
| axes[0].set_title('Image') |
| axes[0].axis('off') |
|
|
| |
| titles = [ |
| 'Token Similarity (SD)', |
| 'Token Similarity (SAM)', |
| 'Token Similarity (SD+SAM)' |
| ] |
| for i in range(3): |
| axes[i+1].imshow(sim_np_maps[i], cmap='jet') |
| axes[i+1].set_title(titles[i]) |
| axes[i+1].axis('off') |
|
|
| plt.tight_layout() |
| plt.savefig(os.path.join(output_dir, "token_similarity_vis.png")) |
| plt.close(fig) |
|
|
| |
| |
| |
| |
| |
| |
| sd_sam_feats_raw = torch.cat([ |
| (w_sam ** 0.5) * sam_feats_raw, |
| (w_sd ** 0.5) * sd_feats_raw |
| ], dim=2) |
|
|
| feats_to_pca = [sam_feats_raw, sd_feats_raw, sd_sam_feats_raw] |
| pca_titles = ["SAM PCA", "SD PCA", "SAM+SD PCA"] |
| pca_paths = [] |
| 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') |
| 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) |