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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
import requests
|
| 6 |
+
import timm
|
| 7 |
+
import torch
|
| 8 |
+
import torchvision.transforms as T
|
| 9 |
+
import types
|
| 10 |
+
import albumentations as A
|
| 11 |
+
|
| 12 |
+
from PIL import Image
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
from sklearn.decomposition import PCA
|
| 15 |
+
from torch_kmeans import KMeans, CosineSimilarity
|
| 16 |
+
|
| 17 |
+
cmap = plt.get_cmap("tab20")
|
| 18 |
+
MEAN = np.array([123.675, 116.280, 103.530]) / 255
|
| 19 |
+
STD = np.array([58.395, 57.120, 57.375]) / 255
|
| 20 |
+
|
| 21 |
+
transforms = A.Compose([
|
| 22 |
+
A.Normalize(mean=list(MEAN), std=list(STD)),
|
| 23 |
+
])
|
| 24 |
+
|
| 25 |
+
def get_intermediate_layers(
|
| 26 |
+
self,
|
| 27 |
+
x: torch.Tensor,
|
| 28 |
+
n=1,
|
| 29 |
+
reshape: bool = False,
|
| 30 |
+
return_prefix_tokens: bool = False,
|
| 31 |
+
return_class_token: bool = False,
|
| 32 |
+
norm: bool = True,
|
| 33 |
+
):
|
| 34 |
+
outputs = self._intermediate_layers(x, n)
|
| 35 |
+
if norm:
|
| 36 |
+
outputs = [self.norm(out) for out in outputs]
|
| 37 |
+
if return_class_token:
|
| 38 |
+
prefix_tokens = [out[:, 0] for out in outputs]
|
| 39 |
+
else:
|
| 40 |
+
prefix_tokens = [out[:, 0 : self.num_prefix_tokens] for out in outputs]
|
| 41 |
+
outputs = [out[:, self.num_prefix_tokens :] for out in outputs]
|
| 42 |
+
|
| 43 |
+
if reshape:
|
| 44 |
+
B, C, H, W = x.shape
|
| 45 |
+
grid_size = (
|
| 46 |
+
(H - self.patch_embed.patch_size[0])
|
| 47 |
+
// self.patch_embed.proj.stride[0]
|
| 48 |
+
+ 1,
|
| 49 |
+
(W - self.patch_embed.patch_size[1])
|
| 50 |
+
// self.patch_embed.proj.stride[1]
|
| 51 |
+
+ 1,
|
| 52 |
+
)
|
| 53 |
+
outputs = [
|
| 54 |
+
out.reshape(x.shape[0], grid_size[0], grid_size[1], -1)
|
| 55 |
+
.permute(0, 3, 1, 2)
|
| 56 |
+
.contiguous()
|
| 57 |
+
for out in outputs
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
if return_prefix_tokens or return_class_token:
|
| 61 |
+
return tuple(zip(outputs, prefix_tokens))
|
| 62 |
+
return tuple(outputs)
|
| 63 |
+
|
| 64 |
+
def viz_feat(feat):
|
| 65 |
+
|
| 66 |
+
_,_,h,w = feat.shape
|
| 67 |
+
feat = feat.squeeze(0).permute((1,2,0))
|
| 68 |
+
projected_featmap = feat.reshape(-1, feat.shape[-1]).cpu()
|
| 69 |
+
|
| 70 |
+
pca = PCA(n_components=3)
|
| 71 |
+
pca.fit(projected_featmap)
|
| 72 |
+
pca_features = pca.transform(projected_featmap)
|
| 73 |
+
pca_features = (pca_features - pca_features.min()) / (pca_features.max() - pca_features.min())
|
| 74 |
+
pca_features = pca_features * 255
|
| 75 |
+
res_pred = Image.fromarray(pca_features.reshape(h, w, 3).astype(np.uint8))
|
| 76 |
+
|
| 77 |
+
return res_pred
|
| 78 |
+
|
| 79 |
+
def plot_feats(model_option, ori_feats, fine_feats, ori_labels=None, fine_labels=None):
|
| 80 |
+
|
| 81 |
+
ori_feats_map = viz_feat(ori_feats)
|
| 82 |
+
fine_feats_map = viz_feat(fine_feats)
|
| 83 |
+
|
| 84 |
+
fig, ax = plt.subplots(2, 2, figsize=(6, 5))
|
| 85 |
+
ax[0][0].imshow(ori_feats_map)
|
| 86 |
+
ax[0][0].set_title("Original " + model_option, fontsize=15)
|
| 87 |
+
ax[0][1].imshow(fine_feats_map)
|
| 88 |
+
ax[0][1].set_title("Ours", fontsize=15)
|
| 89 |
+
ax[1][0].imshow(ori_labels)
|
| 90 |
+
ax[1][1].imshow(fine_labels)
|
| 91 |
+
for xx in ax:
|
| 92 |
+
for x in xx:
|
| 93 |
+
x.xaxis.set_major_formatter(plt.NullFormatter())
|
| 94 |
+
x.yaxis.set_major_formatter(plt.NullFormatter())
|
| 95 |
+
x.set_xticks([])
|
| 96 |
+
x.set_yticks([])
|
| 97 |
+
x.axis('off')
|
| 98 |
+
|
| 99 |
+
plt.tight_layout()
|
| 100 |
+
plt.close(fig)
|
| 101 |
+
return fig
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def download_image(url, save_path):
|
| 105 |
+
response = requests.get(url)
|
| 106 |
+
with open(save_path, 'wb') as file:
|
| 107 |
+
file.write(response.content)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def process_image(image, stride, transforms):
|
| 111 |
+
transformed = transforms(image=np.array(image))
|
| 112 |
+
image_tensor = torch.tensor(transformed['image'])
|
| 113 |
+
image_tensor = image_tensor.permute(2,0,1)
|
| 114 |
+
image_tensor = image_tensor.unsqueeze(0).to(device)
|
| 115 |
+
|
| 116 |
+
h, w = image_tensor.shape[2:]
|
| 117 |
+
|
| 118 |
+
height_int = (h // stride)*stride
|
| 119 |
+
width_int = (w // stride)*stride
|
| 120 |
+
|
| 121 |
+
image_resized = torch.nn.functional.interpolate(image_tensor, size=(height_int, width_int), mode='bilinear')
|
| 122 |
+
|
| 123 |
+
return image_resized
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def kmeans_clustering(feats_map, n_clusters=20):
|
| 127 |
+
if n_clusters == None:
|
| 128 |
+
n_clusters = 20
|
| 129 |
+
print('num clusters: ', n_clusters)
|
| 130 |
+
B, D, h, w = feats_map.shape
|
| 131 |
+
feats_map_flattened = feats_map.permute((0, 2, 3, 1)).reshape(B, -1, D)
|
| 132 |
+
|
| 133 |
+
kmeans_engine = KMeans(n_clusters=n_clusters, distance=CosineSimilarity)
|
| 134 |
+
kmeans_engine.fit(feats_map_flattened)
|
| 135 |
+
labels = kmeans_engine.predict(
|
| 136 |
+
feats_map_flattened
|
| 137 |
+
)
|
| 138 |
+
labels = labels.reshape(
|
| 139 |
+
B, h, w
|
| 140 |
+
).float()
|
| 141 |
+
labels = labels[0].cpu().numpy()
|
| 142 |
+
|
| 143 |
+
label_map = cmap(labels / n_clusters)[..., :3]
|
| 144 |
+
label_map = np.uint8(label_map * 255)
|
| 145 |
+
label_map = Image.fromarray(label_map)
|
| 146 |
+
|
| 147 |
+
return label_map
|
| 148 |
+
|
| 149 |
+
def load_model(options):
|
| 150 |
+
original_models = {}
|
| 151 |
+
fine_models = {}
|
| 152 |
+
for option in tqdm(options):
|
| 153 |
+
print('Please wait ...')
|
| 154 |
+
print('loading weights of ', option)
|
| 155 |
+
original_models[option] = timm.create_model(
|
| 156 |
+
timm_model_card[option],
|
| 157 |
+
pretrained=True,
|
| 158 |
+
num_classes=0,
|
| 159 |
+
dynamic_img_size=True,
|
| 160 |
+
dynamic_img_pad=False,
|
| 161 |
+
).to(device)
|
| 162 |
+
original_models[option].get_intermediate_layers = types.MethodType(
|
| 163 |
+
get_intermediate_layers,
|
| 164 |
+
original_models[option]
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
fine_models[option] = torch.hub.load("ywyue/FiT3D", our_model_card[option]).to(device)
|
| 168 |
+
fine_models[option].get_intermediate_layers = types.MethodType(
|
| 169 |
+
get_intermediate_layers,
|
| 170 |
+
fine_models[option]
|
| 171 |
+
)
|
| 172 |
+
print('Done! Now play the demo :)')
|
| 173 |
+
return original_models, fine_models
|
| 174 |
+
|
| 175 |
+
if __name__ == "__main__":
|
| 176 |
+
|
| 177 |
+
if torch.cuda.is_available():
|
| 178 |
+
device = torch.device('cuda')
|
| 179 |
+
else:
|
| 180 |
+
device = torch.device('cpu')
|
| 181 |
+
|
| 182 |
+
print("device: ")
|
| 183 |
+
print(device)
|
| 184 |
+
|
| 185 |
+
example_urls = {
|
| 186 |
+
"library.jpg": "https://n.ethz.ch/~yuayue/assets/fit3d/demo_images/library.jpg",
|
| 187 |
+
"livingroom.jpg": "https://n.ethz.ch/~yuayue/assets/fit3d/demo_images/livingroom.jpg",
|
| 188 |
+
"airplane.jpg": "https://n.ethz.ch/~yuayue/assets/fit3d/demo_images/airplane.jpg",
|
| 189 |
+
"ship.jpg": "https://n.ethz.ch/~yuayue/assets/fit3d/demo_images/ship.jpg",
|
| 190 |
+
"chair.jpg": "https://n.ethz.ch/~yuayue/assets/fit3d/demo_images/chair.jpg",
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
example_dir = "/tmp/examples"
|
| 194 |
+
|
| 195 |
+
os.makedirs(example_dir, exist_ok=True)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
for name, url in example_urls.items():
|
| 199 |
+
save_path = os.path.join(example_dir, name)
|
| 200 |
+
if not os.path.exists(save_path):
|
| 201 |
+
print(f"Downloading to {save_path}...")
|
| 202 |
+
download_image(url, save_path)
|
| 203 |
+
else:
|
| 204 |
+
print(f"{save_path} already exists.")
|
| 205 |
+
|
| 206 |
+
image_input = gr.Image(label="Choose an image:",
|
| 207 |
+
height=500,
|
| 208 |
+
type="pil",
|
| 209 |
+
image_mode='RGB',
|
| 210 |
+
sources=['upload', 'webcam', 'clipboard']
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
options = ['DINOv2', 'DINOv2-reg', 'CLIP', 'MAE', 'DeiT-III']
|
| 214 |
+
model_option = gr.Radio(options, value="DINOv2", label='Choose a 2D foundation model')
|
| 215 |
+
kmeans_num = gr.Number(
|
| 216 |
+
label="number of K-Means clusters", value=20
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
timm_model_card = {
|
| 220 |
+
"DINOv2": "vit_small_patch14_dinov2.lvd142m",
|
| 221 |
+
"DINOv2-reg": "vit_small_patch14_reg4_dinov2.lvd142m",
|
| 222 |
+
"CLIP": "vit_base_patch16_clip_384.laion2b_ft_in12k_in1k",
|
| 223 |
+
"MAE": "vit_base_patch16_224.mae",
|
| 224 |
+
"DeiT-III": "deit3_base_patch16_224.fb_in1k"
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
our_model_card = {
|
| 228 |
+
"DINOv2": "dinov2_small_fine",
|
| 229 |
+
"DINOv2-reg": "dinov2_reg_small_fine",
|
| 230 |
+
"CLIP": "clip_base_fine",
|
| 231 |
+
"MAE": "mae_base_fine",
|
| 232 |
+
"DeiT-III": "deit3_base_fine"
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
os.environ['TORCH_HOME'] = '/tmp/.cache'
|
| 237 |
+
os.environ['GRADIO_EXAMPLES_CACHE'] = '/tmp/gradio_cache'
|
| 238 |
+
|
| 239 |
+
# Pre-load all models
|
| 240 |
+
original_models, fine_models = load_model(options)
|
| 241 |
+
|
| 242 |
+
def fit3d(image, model_option, kmeans_num):
|
| 243 |
+
|
| 244 |
+
# Select model
|
| 245 |
+
original_model = original_models[model_option]
|
| 246 |
+
fine_model = fine_models[model_option]
|
| 247 |
+
|
| 248 |
+
# Data preprocessing
|
| 249 |
+
p = original_model.patch_embed.patch_size
|
| 250 |
+
stride = p if isinstance(p, int) else p[0]
|
| 251 |
+
image_resized = process_image(image, stride, transforms)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
with torch.no_grad():
|
| 255 |
+
ori_feats = original_model.get_intermediate_layers(image_resized, n=[8,9,10,11], reshape=True, return_prefix_tokens=False,
|
| 256 |
+
return_class_token=False, norm=True)
|
| 257 |
+
fine_feats = fine_model.get_intermediate_layers(image_resized, n=[8,9,10,11], reshape=True, return_prefix_tokens=False,
|
| 258 |
+
return_class_token=False, norm=True)
|
| 259 |
+
|
| 260 |
+
ori_feats = ori_feats[-1]
|
| 261 |
+
fine_feats = fine_feats[-1]
|
| 262 |
+
|
| 263 |
+
ori_labels = kmeans_clustering(ori_feats, kmeans_num)
|
| 264 |
+
fine_labels = kmeans_clustering(fine_feats, kmeans_num)
|
| 265 |
+
|
| 266 |
+
return plot_feats(model_option, ori_feats, fine_feats, ori_labels, fine_labels)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
demo = gr.Interface(
|
| 272 |
+
title="<div> \
|
| 273 |
+
<h1>FiT3D</h1> \
|
| 274 |
+
<h2>Improving 2D Feature Representations by 3D-Aware Fine-Tuning</h2> \
|
| 275 |
+
<h2>ECCV 2024</h2> \
|
| 276 |
+
</div>",
|
| 277 |
+
description="<div style='display: flex; justify-content: center; align-items: center; text-align: center;'> \
|
| 278 |
+
<a href='https://arxiv.org/abs/2407.20229'><img src='https://img.shields.io/badge/arXiv-2407.20229-red'></a> \
|
| 279 |
+
\
|
| 280 |
+
<a href='https://ywyue.github.io/FiT3D'><img src='https://img.shields.io/badge/Project_Page-FiT3D-green' alt='Project Page'></a> \
|
| 281 |
+
\
|
| 282 |
+
<a href='https://github.com/ywyue/FiT3D'><img src='https://img.shields.io/badge/Github-Code-blue'></a> \
|
| 283 |
+
</div>",
|
| 284 |
+
fn=fit3d,
|
| 285 |
+
inputs=[image_input, model_option, kmeans_num],
|
| 286 |
+
outputs="plot",
|
| 287 |
+
examples=[
|
| 288 |
+
["/tmp/examples/library.jpg", "DINOv2"],
|
| 289 |
+
["/tmp/examples/livingroom.jpg", "DINOv2"],
|
| 290 |
+
["/tmp/examples/airplane.jpg", "DINOv2"],
|
| 291 |
+
["/tmp/examples/ship.jpg", "DINOv2"],
|
| 292 |
+
["/tmp/examples/chair.jpg", "DINOv2"],
|
| 293 |
+
])
|
| 294 |
+
demo.launch()
|
| 295 |
+
|