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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 2,
|
| 6 |
+
"id": "71c25a25",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [
|
| 9 |
+
{
|
| 10 |
+
"name": "stdout",
|
| 11 |
+
"output_type": "stream",
|
| 12 |
+
"text": [
|
| 13 |
+
"cuda\n"
|
| 14 |
+
]
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"ename": "NameError",
|
| 18 |
+
"evalue": "name 'exit' is not defined",
|
| 19 |
+
"output_type": "error",
|
| 20 |
+
"traceback": [
|
| 21 |
+
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
| 22 |
+
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
|
| 23 |
+
"Cell \u001b[0;32mIn[2], line 55\u001b[0m\n\u001b[1;32m 53\u001b[0m torch\u001b[38;5;241m.\u001b[39mcuda\u001b[38;5;241m.\u001b[39mmanual_seed(SEED)\n\u001b[1;32m 54\u001b[0m torch\u001b[38;5;241m.\u001b[39mbackends\u001b[38;5;241m.\u001b[39mcudnn\u001b[38;5;241m.\u001b[39mbenchmark \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[0;32m---> 55\u001b[0m model, aug \u001b[38;5;241m=\u001b[39m \u001b[43mload_model\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdiffusion_ver\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mVER\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mimage_size\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mSIZE\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mnum_timesteps\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mTIMESTEP\u001b[49m\u001b[43m,\u001b[49m\u001b[43mdecoder_only\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m)\u001b[49m\n",
|
| 24 |
+
"File \u001b[0;32m~/code/DeCLIP/extractor_sd.py:186\u001b[0m, in \u001b[0;36mload_model\u001b[0;34m(config_path, seed, diffusion_ver, image_size, num_timesteps, block_indices, decoder_only, encoder_only, resblock_only)\u001b[0m\n\u001b[1;32m 184\u001b[0m dataset_cfg \u001b[38;5;241m=\u001b[39m cfg\u001b[38;5;241m.\u001b[39mdataloader\u001b[38;5;241m.\u001b[39mtest\n\u001b[1;32m 185\u001b[0m \u001b[38;5;28mprint\u001b[39m(cfg\u001b[38;5;241m.\u001b[39mtrain\u001b[38;5;241m.\u001b[39mdevice)\n\u001b[0;32m--> 186\u001b[0m \u001b[43mexit\u001b[49m()\n\u001b[1;32m 187\u001b[0m aug \u001b[38;5;241m=\u001b[39m instantiate(dataset_cfg\u001b[38;5;241m.\u001b[39mmapper)\u001b[38;5;241m.\u001b[39maugmentations\n\u001b[1;32m 188\u001b[0m model \u001b[38;5;241m=\u001b[39m instantiate_odise(cfg\u001b[38;5;241m.\u001b[39mmodel)\n",
|
| 25 |
+
"\u001b[0;31mNameError\u001b[0m: name 'exit' is not defined"
|
| 26 |
+
]
|
| 27 |
+
}
|
| 28 |
+
],
|
| 29 |
+
"source": [
|
| 30 |
+
"import os\n",
|
| 31 |
+
"from training.utils import build_vfm\n",
|
| 32 |
+
"os.environ['CUDA_VISIBLE_DEVICES'] = '3'\n",
|
| 33 |
+
"import torch\n",
|
| 34 |
+
"import os\n",
|
| 35 |
+
"import pandas as pd\n",
|
| 36 |
+
"import numpy as np\n",
|
| 37 |
+
"from PIL import Image\n",
|
| 38 |
+
"from tqdm import tqdm\n",
|
| 39 |
+
"import torch.nn.functional as F\n",
|
| 40 |
+
"from extractor_sd import load_model, process_features_and_mask, get_mask\n",
|
| 41 |
+
"from third_party.utils.utils_correspondence import co_pca, resize, find_nearest_patchs, find_nearest_patchs_replace\n",
|
| 42 |
+
"import matplotlib.pyplot as plt\n",
|
| 43 |
+
"import sys\n",
|
| 44 |
+
"from extractor_dino import ViTExtractor\n",
|
| 45 |
+
"from sklearn.decomposition import PCA as sklearnPCA\n",
|
| 46 |
+
"import math\n",
|
| 47 |
+
"from sklearn.cluster import KMeans\n",
|
| 48 |
+
"from scipy.optimize import linear_sum_assignment\n",
|
| 49 |
+
"from torchvision import transforms\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"def preprocess_pil(pil_image):\n",
|
| 52 |
+
" prep = transforms.Compose([\n",
|
| 53 |
+
" transforms.ToTensor(),\n",
|
| 54 |
+
" transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))\n",
|
| 55 |
+
" ])\n",
|
| 56 |
+
" prep_img = prep(pil_image)[None, ...]\n",
|
| 57 |
+
" return prep_img\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"MASK = True\n",
|
| 60 |
+
"VER = \"v1-5\"\n",
|
| 61 |
+
"PCA = False\n",
|
| 62 |
+
"CO_PCA = True\n",
|
| 63 |
+
"PCA_DIMS = [256, 256, 256]\n",
|
| 64 |
+
"SIZE =960\n",
|
| 65 |
+
"EDGE_PAD = False\n",
|
| 66 |
+
"\n",
|
| 67 |
+
"FUSE_DINO = 1\n",
|
| 68 |
+
"ONLY_DINO = 0\n",
|
| 69 |
+
"MODEL_SIZE = 'base'\n",
|
| 70 |
+
"DRAW_DENSE = 1\n",
|
| 71 |
+
"DRAW_SWAP = 1\n",
|
| 72 |
+
"TEXT_INPUT = False\n",
|
| 73 |
+
"SEED = 42\n",
|
| 74 |
+
"TIMESTEP = 100\n",
|
| 75 |
+
"\n",
|
| 76 |
+
"DIST = 'l2' if FUSE_DINO and not ONLY_DINO else 'cos'\n",
|
| 77 |
+
"if ONLY_DINO:\n",
|
| 78 |
+
" FUSE_DINO = True\n",
|
| 79 |
+
"\n",
|
| 80 |
+
"np.random.seed(SEED)\n",
|
| 81 |
+
"torch.manual_seed(SEED)\n",
|
| 82 |
+
"torch.cuda.manual_seed(SEED)\n",
|
| 83 |
+
"torch.backends.cudnn.benchmark = True\n",
|
| 84 |
+
"model, aug = load_model(diffusion_ver=VER, image_size=SIZE, num_timesteps=TIMESTEP,decoder_only=False)\n",
|
| 85 |
+
"\n"
|
| 86 |
+
]
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"id": "75082563",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"outputs": [],
|
| 94 |
+
"source": [
|
| 95 |
+
"def compute_pair_feature(model, aug, save_path, files, category, mask=False, dist='cos', real_size=960):\n",
|
| 96 |
+
" img_size = 840\n",
|
| 97 |
+
" stride = 14 \n",
|
| 98 |
+
" device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
|
| 99 |
+
" extractor=build_vfm(\"dinov2-B\").to(device).eval().to(torch.float32)\n",
|
| 100 |
+
" patch_size = 14\n",
|
| 101 |
+
" num_patches = int(patch_size / stride * (img_size // patch_size - 1) + 1)\n",
|
| 102 |
+
" input_text = None\n",
|
| 103 |
+
"\n",
|
| 104 |
+
" # Load image 1\n",
|
| 105 |
+
" img1 = Image.open(files[0]).convert('RGB')\n",
|
| 106 |
+
" img1_input = resize(img1, real_size, resize=True, to_pil=True, edge=EDGE_PAD)\n",
|
| 107 |
+
" img1 = resize(img1, img_size, resize=True, to_pil=True, edge=EDGE_PAD)\n",
|
| 108 |
+
"\n",
|
| 109 |
+
" # Load image 2\n",
|
| 110 |
+
" img2 = Image.open(files[1]).convert('RGB')\n",
|
| 111 |
+
" img2_input = resize(img2, real_size, resize=True, to_pil=True, edge=EDGE_PAD)\n",
|
| 112 |
+
" img2 = resize(img2, img_size, resize=True, to_pil=True, edge=EDGE_PAD)\n",
|
| 113 |
+
"\n",
|
| 114 |
+
" with torch.no_grad():\n",
|
| 115 |
+
" features1 = process_features_and_mask(model, aug, img1_input, input_text=input_text, mask=False, raw=True)\n",
|
| 116 |
+
" features2 = process_features_and_mask(model, aug, img2_input, input_text=input_text, mask=False, raw=True)\n",
|
| 117 |
+
" processed_features1, processed_features2 = co_pca(features1, features2, PCA_DIMS)\n",
|
| 118 |
+
" img1_desc = processed_features1.reshape(1, 1, -1, num_patches**2).permute(0,1,3,2)\n",
|
| 119 |
+
" img2_desc = processed_features2.reshape(1, 1, -1, num_patches**2).permute(0,1,3,2)\n",
|
| 120 |
+
" img1_batch = preprocess_pil(img1).to(device)\n",
|
| 121 |
+
" img1_desc_dino = extractor.get_intermediate_layers(img1_batch)[0].unsqueeze(1)\n",
|
| 122 |
+
" img2_batch = preprocess_pil(img2).to(device)\n",
|
| 123 |
+
" img2_desc_dino = extractor.get_intermediate_layers(img2_batch)[0].unsqueeze(1)\n",
|
| 124 |
+
" img1_desc = img1_desc / img1_desc.norm(dim=-1, keepdim=True)\n",
|
| 125 |
+
" img2_desc = img2_desc / img2_desc.norm(dim=-1, keepdim=True)\n",
|
| 126 |
+
" img1_desc_dino = img1_desc_dino / img1_desc_dino.norm(dim=-1, keepdim=True)\n",
|
| 127 |
+
" img2_desc_dino = img2_desc_dino / img2_desc_dino.norm(dim=-1, keepdim=True)\n",
|
| 128 |
+
" img1_desc = torch.cat((img1_desc, img1_desc_dino), dim=-1)\n",
|
| 129 |
+
" img2_desc = torch.cat((img2_desc, img2_desc_dino), dim=-1)\n",
|
| 130 |
+
" if DRAW_DENSE:\n",
|
| 131 |
+
" mask1 = get_mask(model, aug, img1, category[0])\n",
|
| 132 |
+
" mask2 = get_mask(model, aug, img2, category[-1])\n",
|
| 133 |
+
" img1_desc_reshaped = img1_desc.permute(0,1,3,2).reshape(-1, img1_desc.shape[-1], num_patches, num_patches)\n",
|
| 134 |
+
" img2_desc_reshaped = img2_desc.permute(0,1,3,2).reshape(-1, img2_desc.shape[-1], num_patches, num_patches)\n",
|
| 135 |
+
" trg_dense_output, src_color_map = find_nearest_patchs(mask2, mask1, img2, img1, img2_desc_reshaped, img1_desc_reshaped, mask=mask)\n",
|
| 136 |
+
"\n",
|
| 137 |
+
" if not os.path.exists(f'{save_path}/{category[0]}'):\n",
|
| 138 |
+
" os.makedirs(f'{save_path}/{category[0]}')\n",
|
| 139 |
+
" fig_colormap, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8))\n",
|
| 140 |
+
" ax1.axis('off')\n",
|
| 141 |
+
" ax2.axis('off')\n",
|
| 142 |
+
" ax1.imshow(src_color_map)\n",
|
| 143 |
+
" ax2.imshow(trg_dense_output)\n",
|
| 144 |
+
" fig_colormap.savefig(f'{save_path}/{category[0]}_colormap.png')\n",
|
| 145 |
+
" plt.close(fig_colormap)\n",
|
| 146 |
+
" \n",
|
| 147 |
+
" if DRAW_SWAP:\n",
|
| 148 |
+
" if not DRAW_DENSE:\n",
|
| 149 |
+
" mask1 = get_mask(model, aug, img1, category[0])\n",
|
| 150 |
+
" mask2 = get_mask(model, aug, img2, category[-1])\n",
|
| 151 |
+
"\n",
|
| 152 |
+
" if (ONLY_DINO or not FUSE_DINO) and not DRAW_DENSE:\n",
|
| 153 |
+
" img1_desc = img1_desc / img1_desc.norm(dim=-1, keepdim=True)\n",
|
| 154 |
+
" img2_desc = img2_desc / img2_desc.norm(dim=-1, keepdim=True)\n",
|
| 155 |
+
" \n",
|
| 156 |
+
" img1_desc_reshaped = img1_desc.permute(0,1,3,2).reshape(-1, img1_desc.shape[-1], num_patches, num_patches)\n",
|
| 157 |
+
" img2_desc_reshaped = img2_desc.permute(0,1,3,2).reshape(-1, img2_desc.shape[-1], num_patches, num_patches)\n",
|
| 158 |
+
" trg_dense_output, src_color_map = find_nearest_patchs_replace(mask2, mask1, img2, img1, img2_desc_reshaped, img1_desc_reshaped, mask=mask, resolution=156)\n",
|
| 159 |
+
" if not os.path.exists(f'{save_path}/{category[0]}'):\n",
|
| 160 |
+
" os.makedirs(f'{save_path}/{category[0]}')\n",
|
| 161 |
+
" fig_colormap, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8))\n",
|
| 162 |
+
" ax1.axis('off')\n",
|
| 163 |
+
" ax2.axis('off')\n",
|
| 164 |
+
" ax1.imshow(src_color_map)\n",
|
| 165 |
+
" ax2.imshow(trg_dense_output)\n",
|
| 166 |
+
" fig_colormap.savefig(f'{save_path}/{category[0]}/swap.png')\n",
|
| 167 |
+
" plt.close(fig_colormap)\n"
|
| 168 |
+
]
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"cell_type": "code",
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"id": "e4d1bdc6",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"outputs": [],
|
| 176 |
+
"source": [
|
| 177 |
+
"def process_images(src_img_path,trg_img_path):\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" categories = [['dog'], ['dog']]\n",
|
| 180 |
+
" files = [src_img_path, trg_img_path]\n",
|
| 181 |
+
" save_path = './my_results_vis' + f'/{trg_img_path.split(\"/\")[-1].split(\".\")[0]}_{src_img_path.split(\"/\")[-1].split(\".\")[0]}'\n",
|
| 182 |
+
" result = compute_pair_feature(model, aug, save_path, files, mask=MASK, category=categories, dist=DIST)\n",
|
| 183 |
+
" return result\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"src_img_path = \"demo_images/dog.jpg\"\n",
|
| 186 |
+
"trg_img_path = \"demo_images/whitedog.jpg\"\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"result = process_images(src_img_path, trg_img_path)"
|
| 189 |
+
]
|
| 190 |
+
}
|
| 191 |
+
],
|
| 192 |
+
"metadata": {
|
| 193 |
+
"kernelspec": {
|
| 194 |
+
"display_name": "declip",
|
| 195 |
+
"language": "python",
|
| 196 |
+
"name": "python3"
|
| 197 |
+
},
|
| 198 |
+
"language_info": {
|
| 199 |
+
"codemirror_mode": {
|
| 200 |
+
"name": "ipython",
|
| 201 |
+
"version": 3
|
| 202 |
+
},
|
| 203 |
+
"file_extension": ".py",
|
| 204 |
+
"mimetype": "text/x-python",
|
| 205 |
+
"name": "python",
|
| 206 |
+
"nbconvert_exporter": "python",
|
| 207 |
+
"pygments_lexer": "ipython3",
|
| 208 |
+
"version": "3.9.0"
|
| 209 |
+
}
|
| 210 |
+
},
|
| 211 |
+
"nbformat": 4,
|
| 212 |
+
"nbformat_minor": 5
|
| 213 |
+
}
|