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