Upload code/model_vis_tools/vis_sd_feats.py with huggingface_hub
Browse files
code/model_vis_tools/vis_sd_feats.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import os
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image,ImageDraw
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from extractor_sd import load_model, load_sd_backbone, get_mask
|
| 8 |
+
from open_clip.transform import ResizeMaxSize,_convert_to_rgb
|
| 9 |
+
from torchvision.transforms import ToTensor
|
| 10 |
+
from third_party.utils.utils_correspondence import co_pca, pca, resize
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
from extractor_dino import ViTExtractor
|
| 13 |
+
from torchvision import transforms
|
| 14 |
+
|
| 15 |
+
def draw_point_on_image(image, x, y, color=(255, 0, 0), radius=8):
|
| 16 |
+
draw = ImageDraw.Draw(image)
|
| 17 |
+
left_up = (x - radius, y - radius)
|
| 18 |
+
right_down = (x + radius, y + radius)
|
| 19 |
+
draw.ellipse([left_up, right_down], fill=color, outline=(0,0,0), width=2)
|
| 20 |
+
return image
|
| 21 |
+
|
| 22 |
+
def overlay_heatmap_on_image(image, heatmap, alpha=0.5, colormap='jet'):
|
| 23 |
+
"""
|
| 24 |
+
image: PIL.Image (RGB)
|
| 25 |
+
heatmap: torch.Tensor [1,1,H,W] or numpy array [H,W]
|
| 26 |
+
alpha: float, blending factor
|
| 27 |
+
colormap: matplotlib colormap name
|
| 28 |
+
"""
|
| 29 |
+
if isinstance(heatmap, torch.Tensor):
|
| 30 |
+
heatmap = heatmap.squeeze().cpu().numpy() # [H, W]
|
| 31 |
+
# Normalize heatmap to [0, 1]
|
| 32 |
+
heatmap = (heatmap - np.min(heatmap)) / (np.max(heatmap) - np.min(heatmap) + 1e-8)
|
| 33 |
+
# Get colormap
|
| 34 |
+
cmap = plt.get_cmap(colormap)
|
| 35 |
+
heatmap_color = cmap(heatmap)[:, :, :3] # ignore alpha, [H, W, 3]
|
| 36 |
+
heatmap_color = (heatmap_color * 255).astype(np.uint8)
|
| 37 |
+
heatmap_img = Image.fromarray(heatmap_color).convert("RGBA")
|
| 38 |
+
image = image.convert("RGBA")
|
| 39 |
+
# Blend heatmap to image
|
| 40 |
+
blended = Image.blend(image, heatmap_img, alpha=alpha)
|
| 41 |
+
return blended
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def preprocess_pil(pil_image):
|
| 45 |
+
prep = transforms.Compose([
|
| 46 |
+
transforms.ToTensor(),
|
| 47 |
+
transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
|
| 48 |
+
])
|
| 49 |
+
prep_img = prep(pil_image)[None, ...]
|
| 50 |
+
return prep_img
|
| 51 |
+
|
| 52 |
+
MASK = True
|
| 53 |
+
VER = "v1-5"
|
| 54 |
+
PCA = False
|
| 55 |
+
CO_PCA = True
|
| 56 |
+
PCA_DIMS = [256, 256, 256]
|
| 57 |
+
SIZE =960
|
| 58 |
+
EDGE_PAD = False
|
| 59 |
+
|
| 60 |
+
FUSE_DINO = 1
|
| 61 |
+
ONLY_DINO = 0
|
| 62 |
+
MODEL_SIZE = 'base'
|
| 63 |
+
DRAW=1
|
| 64 |
+
TEXT_INPUT = False
|
| 65 |
+
SEED = 42
|
| 66 |
+
TIMESTEP = 100
|
| 67 |
+
|
| 68 |
+
DIST = 'l2' if FUSE_DINO and not ONLY_DINO else 'cos'
|
| 69 |
+
if ONLY_DINO:
|
| 70 |
+
FUSE_DINO = True
|
| 71 |
+
|
| 72 |
+
np.random.seed(SEED)
|
| 73 |
+
torch.manual_seed(SEED)
|
| 74 |
+
torch.cuda.manual_seed(SEED)
|
| 75 |
+
torch.backends.cudnn.benchmark = True
|
| 76 |
+
|
| 77 |
+
sd_transform=transforms.Compose([
|
| 78 |
+
ResizeMaxSize(960, fill=0),
|
| 79 |
+
_convert_to_rgb,
|
| 80 |
+
ToTensor(),
|
| 81 |
+
])
|
| 82 |
+
img_path = "demo_images/dog.jpg"
|
| 83 |
+
model = load_sd_backbone(diffusion_ver=VER, image_size=SIZE, num_timesteps=TIMESTEP, decoder_only=False)
|
| 84 |
+
img_size = 840
|
| 85 |
+
stride = 14
|
| 86 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 87 |
+
extractor = ViTExtractor('dinov2_vitb14', 14, device=device)
|
| 88 |
+
patch_size = 14
|
| 89 |
+
num_patches = int(patch_size / stride * (img_size // patch_size - 1) + 1)
|
| 90 |
+
# Load image 1
|
| 91 |
+
img1 = Image.open(img_path)
|
| 92 |
+
sd_input1=sd_transform(img1).to(device).unsqueeze(0)
|
| 93 |
+
img1 = resize(img1, img_size, resize=True, to_pil=True, edge=EDGE_PAD)
|
| 94 |
+
result = []
|
| 95 |
+
target_size=560
|
| 96 |
+
with torch.no_grad():
|
| 97 |
+
sd_features=model(sd_input1, raw=True)
|
| 98 |
+
sd_features = pca(sd_features)# torch.Size([bs, c_1, h, w])
|
| 99 |
+
img1_batch = preprocess_pil(img1).to(device)
|
| 100 |
+
dino_feats = extractor.extract_descriptors(img1_batch, 11, 'token') # torch.Size([bs, 1, h*w, c_2])
|
| 101 |
+
# sd_features: [bs, c1, h1, w1] -> [bs, h1*w1, c1]
|
| 102 |
+
bs, c1, h1, w1 = sd_features.shape
|
| 103 |
+
sd_tokens = sd_features.permute(0, 2, 3, 1).reshape(bs, -1, c1) # [bs, n_sd, c1]
|
| 104 |
+
|
| 105 |
+
# dino_feats: [bs, 1, h2*w2, c2] -> [bs, h2*w2, c2]
|
| 106 |
+
bs2, _, n_dino, c2 = dino_feats.shape
|
| 107 |
+
dino_tokens = dino_feats.squeeze(1) # [bs, n_dino, c2]
|
| 108 |
+
sd_tokens_norm = F.normalize(sd_tokens, dim=-1)
|
| 109 |
+
dino_tokens_norm = F.normalize(dino_tokens, dim=-1)
|
| 110 |
+
# 图像内自相关性
|
| 111 |
+
sim_sd = torch.einsum('bic,bjc->bij', sd_tokens_norm, sd_tokens_norm) # [bs, n_sd, n_sd]
|
| 112 |
+
sim_dino = torch.einsum('bic,bjc->bij', dino_tokens_norm, dino_tokens_norm) # [bs, n_dino, n_dino]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
output_dir = "vis"
|
| 116 |
+
vis_img = Image.open(img_path).convert('RGB')
|
| 117 |
+
target_size = (960,960)
|
| 118 |
+
vis_img = resize(vis_img, target_size[0], resize=True, to_pil=True, edge=EDGE_PAD)
|
| 119 |
+
low_res_size = (60, 60)
|
| 120 |
+
low_res_token_choosen = (30, 30)
|
| 121 |
+
token_chosen = int(
|
| 122 |
+
low_res_token_choosen[0] * low_res_size[1] + low_res_token_choosen[1]
|
| 123 |
+
)
|
| 124 |
+
token_x_low_res = token_chosen % low_res_size[0]
|
| 125 |
+
token_y_low_res = token_chosen // low_res_size[1]
|
| 126 |
+
token_x_img = int((token_x_low_res / low_res_size[0]) * target_size[0])
|
| 127 |
+
token_y_img = int((token_y_low_res / low_res_size[1]) * target_size[1])
|
| 128 |
+
if not os.path.exists(output_dir):
|
| 129 |
+
os.mkdir(output_dir)
|
| 130 |
+
sim_sd=sim_sd[:, token_chosen, :] # 1, h*w
|
| 131 |
+
sim_dino=sim_dino[:, token_chosen, :] # 1, h*w
|
| 132 |
+
sim_sd_map = sim_sd.view(1, 1, low_res_size[0], low_res_size[1])
|
| 133 |
+
sim_dino_map = sim_dino.view(1, 1, low_res_size[0], low_res_size[1])
|
| 134 |
+
sim_sd_up = F.interpolate(sim_sd_map, size=target_size, mode="bilinear", align_corners=False)
|
| 135 |
+
sim_dino_up = F.interpolate(sim_dino_map, size=target_size, mode="bilinear", align_corners=False)
|
| 136 |
+
img_sd = overlay_heatmap_on_image(vis_img, sim_sd_up, alpha=0.5, colormap='jet')
|
| 137 |
+
img_sd = draw_point_on_image(img_sd, token_x_img, token_y_img, color=(255,0,0), radius=8)
|
| 138 |
+
img_sd = img_sd.convert('RGB')
|
| 139 |
+
img_sd.save(os.path.join(output_dir,"sd_sim.jpg"))
|
| 140 |
+
|
| 141 |
+
img_dino = overlay_heatmap_on_image(vis_img, sim_dino_up, alpha=0.5, colormap='jet')
|
| 142 |
+
img_dino = draw_point_on_image(img_dino, token_x_img, token_y_img, color=(255,0,0), radius=8)
|
| 143 |
+
img_dino = img_dino.convert('RGB')
|
| 144 |
+
img_dino.save(os.path.join(output_dir,"dino_sim.jpg"))
|