import os import torch import os import numpy as np from PIL import Image,ImageDraw import torch.nn.functional as F from extractor_sd import load_model, load_sd_backbone, get_mask from open_clip.transform import ResizeMaxSize,_convert_to_rgb from torchvision.transforms import ToTensor from third_party.utils.utils_correspondence import co_pca, pca, resize import matplotlib.pyplot as plt from extractor_dino import ViTExtractor from torchvision import transforms def draw_point_on_image(image, x, y, color=(255, 0, 0), radius=8): draw = ImageDraw.Draw(image) left_up = (x - radius, y - radius) right_down = (x + radius, y + radius) draw.ellipse([left_up, right_down], fill=color, outline=(0,0,0), width=2) return image def overlay_heatmap_on_image(image, heatmap, alpha=0.5, colormap='jet'): """ image: PIL.Image (RGB) heatmap: torch.Tensor [1,1,H,W] or numpy array [H,W] alpha: float, blending factor colormap: matplotlib colormap name """ if isinstance(heatmap, torch.Tensor): heatmap = heatmap.squeeze().cpu().numpy() # [H, W] # Normalize heatmap to [0, 1] heatmap = (heatmap - np.min(heatmap)) / (np.max(heatmap) - np.min(heatmap) + 1e-8) # Get colormap cmap = plt.get_cmap(colormap) heatmap_color = cmap(heatmap)[:, :, :3] # ignore alpha, [H, W, 3] heatmap_color = (heatmap_color * 255).astype(np.uint8) heatmap_img = Image.fromarray(heatmap_color).convert("RGBA") image = image.convert("RGBA") # Blend heatmap to image blended = Image.blend(image, heatmap_img, alpha=alpha) return blended def preprocess_pil(pil_image): prep = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)) ]) prep_img = prep(pil_image)[None, ...] return prep_img MASK = True VER = "v1-5" PCA = False CO_PCA = True PCA_DIMS = [256, 256, 256] SIZE =960 EDGE_PAD = False FUSE_DINO = 1 ONLY_DINO = 0 MODEL_SIZE = 'base' DRAW=1 TEXT_INPUT = False SEED = 42 TIMESTEP = 100 DIST = 'l2' if FUSE_DINO and not ONLY_DINO else 'cos' if ONLY_DINO: FUSE_DINO = True np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) torch.backends.cudnn.benchmark = True sd_transform=transforms.Compose([ ResizeMaxSize(960, fill=0), _convert_to_rgb, ToTensor(), ]) img_path = "demo_images/dog.jpg" model = load_sd_backbone(diffusion_ver=VER, image_size=SIZE, num_timesteps=TIMESTEP, decoder_only=False) img_size = 840 stride = 14 device = 'cuda' if torch.cuda.is_available() else 'cpu' extractor = ViTExtractor('dinov2_vitb14', 14, device=device) patch_size = 14 num_patches = int(patch_size / stride * (img_size // patch_size - 1) + 1) # Load image 1 img1 = Image.open(img_path) sd_input1=sd_transform(img1).to(device).unsqueeze(0) img1 = resize(img1, img_size, resize=True, to_pil=True, edge=EDGE_PAD) result = [] target_size=560 with torch.no_grad(): sd_features=model(sd_input1, raw=True) sd_features = pca(sd_features)# torch.Size([bs, c_1, h, w]) img1_batch = preprocess_pil(img1).to(device) dino_feats = extractor.extract_descriptors(img1_batch, 11, 'token') # torch.Size([bs, 1, h*w, c_2]) # sd_features: [bs, c1, h1, w1] -> [bs, h1*w1, c1] bs, c1, h1, w1 = sd_features.shape sd_tokens = sd_features.permute(0, 2, 3, 1).reshape(bs, -1, c1) # [bs, n_sd, c1] # dino_feats: [bs, 1, h2*w2, c2] -> [bs, h2*w2, c2] bs2, _, n_dino, c2 = dino_feats.shape dino_tokens = dino_feats.squeeze(1) # [bs, n_dino, c2] sd_tokens_norm = F.normalize(sd_tokens, dim=-1) dino_tokens_norm = F.normalize(dino_tokens, dim=-1) # 图像内自相关性 sim_sd = torch.einsum('bic,bjc->bij', sd_tokens_norm, sd_tokens_norm) # [bs, n_sd, n_sd] sim_dino = torch.einsum('bic,bjc->bij', dino_tokens_norm, dino_tokens_norm) # [bs, n_dino, n_dino] output_dir = "vis" vis_img = Image.open(img_path).convert('RGB') target_size = (960,960) vis_img = resize(vis_img, target_size[0], resize=True, to_pil=True, edge=EDGE_PAD) low_res_size = (60, 60) low_res_token_choosen = (30, 30) 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[1] token_x_img = int((token_x_low_res / low_res_size[0]) * target_size[0]) token_y_img = int((token_y_low_res / low_res_size[1]) * target_size[1]) if not os.path.exists(output_dir): os.mkdir(output_dir) sim_sd=sim_sd[:, token_chosen, :] # 1, h*w sim_dino=sim_dino[:, token_chosen, :] # 1, h*w sim_sd_map = sim_sd.view(1, 1, low_res_size[0], low_res_size[1]) sim_dino_map = sim_dino.view(1, 1, low_res_size[0], low_res_size[1]) sim_sd_up = F.interpolate(sim_sd_map, size=target_size, mode="bilinear", align_corners=False) sim_dino_up = F.interpolate(sim_dino_map, size=target_size, mode="bilinear", align_corners=False) img_sd = overlay_heatmap_on_image(vis_img, sim_sd_up, alpha=0.5, colormap='jet') img_sd = draw_point_on_image(img_sd, token_x_img, token_y_img, color=(255,0,0), radius=8) img_sd = img_sd.convert('RGB') img_sd.save(os.path.join(output_dir,"sd_sim.jpg")) img_dino = overlay_heatmap_on_image(vis_img, sim_dino_up, alpha=0.5, colormap='jet') img_dino = draw_point_on_image(img_dino, token_x_img, token_y_img, color=(255,0,0), radius=8) img_dino = img_dino.convert('RGB') img_dino.save(os.path.join(output_dir,"dino_sim.jpg"))