Newer
Older
import torch
from torch import nn
from torchvision import transforms
import src.extractor as extractor
from PIL import Image
from typing import Union, List, Tuple
from src.correspondences import chunk_cosine_sim
from sklearn.cluster import KMeans
import numpy as np
import time
from external.kmeans_pytorch.kmeans_pytorch import kmeans
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
class PoseViTExtractor(extractor.ViTExtractor):
def __init__(self, model_type: str = 'dino_vits8', stride: int = 4, model: nn.Module = None, device: str = 'cuda'):
self.model_type = model_type
self.stride = stride
self.model = model
self.device = device
super().__init__(model_type = self.model_type, stride = self.stride, model=self.model, device=self.device)
self.prep = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=self.mean, std=self.std)
])
def preprocess(self, img: Image.Image,
load_size: Union[int, Tuple[int, int]] = None) -> Tuple[torch.Tensor, Image.Image]:
scale_factor = 1
if load_size is not None:
width, height = img.size # img has to be quadratic
img = transforms.Resize(load_size, interpolation=transforms.InterpolationMode.LANCZOS)(img)
scale_factor = img.size[0]/width
prep_img = self.prep(img)[None, ...]
return prep_img, img, scale_factor
# Overwrite functionality of _extract_features(self, batch: torch.Tensor, layers: List[int] = 11, facet: str = 'key') -> List[torch.Tensor]
# to extract multiple facets and layers in one turn
def _extract_multi_features(self, batch: torch.Tensor, layers: List[int] = [9,11], facet: str = 'key') -> List[torch.Tensor]:
B, C, H, W = batch.shape
self._feats = []
# for (layer,fac) in zip(layers,facet):
self._register_hooks(layers, facet)
_ = self.model(batch)
self._unregister_hooks()
self.load_size = (H, W)
self.num_patches = (1 + (H - self.p) // self.stride[0], 1 + (W - self.p) // self.stride[1])
return self._feats
def extract_multi_descriptors(self, batch: torch.Tensor, layers: List[int] = [9,11], facet: str = 'key',
bin: List[bool] = [True, False], include_cls: List[bool] = [False, False]) -> torch.Tensor:
assert facet in ['key', 'query', 'value', 'token'], f"""{facet} is not a supported facet for descriptors.
choose from ['key' | 'query' | 'value' | 'token'] """
self._extract_multi_features(batch, layers, facet)
descs = []
for i, x in enumerate(self._feats):
if facet[i] == 'token':
x.unsqueeze_(dim=1) #Bx1xtxd
if not include_cls[i]:
x = x[:, :, 1:, :] # remove cls token
else:
assert not bin[i], "bin = True and include_cls = True are not supported together, set one of them False."
if not bin:
desc = x.permute(0, 2, 3, 1).flatten(start_dim=-2, end_dim=-1).unsqueeze(dim=1) # Bx1xtx(dxh)
else:
desc = self._log_bin(x)
descs.append(desc)
return descs

PhilippAuss
committed
def find_correspondences_fastkmeans(self, pil_img1, pil_img2, num_pairs: int = 10, load_size: int = 224,
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
layer: int = 9, facet: str = 'key', bin: bool = True,
thresh: float = 0.05) -> Tuple[List[Tuple[float, float]], List[Tuple[float, float]], Image.Image, Image.Image]:
start_time_corr = time.time()
start_time_desc = time.time()
image1_batch, image1_pil, scale_factor = self.preprocess(pil_img1, load_size)
descriptors1 = self.extract_descriptors(image1_batch.to(self.device), layer, facet, bin)
num_patches1, load_size1 = self.num_patches, self.load_size
image2_batch, image2_pil, scale_factor = self.preprocess(pil_img2, load_size)
descriptors2 = self.extract_descriptors(image2_batch.to(self.device), layer, facet, bin)
num_patches2, load_size2 = self.num_patches, self.load_size
end_time_desc = time.time()
elapsed_desc = end_time_desc - start_time_desc
start_time_saliency = time.time()
# extracting saliency maps for each image
saliency_map1 = self.extract_saliency_maps(image1_batch.to(self.device))[0]
saliency_map2 = self.extract_saliency_maps(image2_batch.to(self.device))[0]
end_time_saliency = time.time()
elapsed_saliencey = end_time_saliency - start_time_saliency
# saliency_map1 = self.extract_saliency_maps(image1_batch)[0]
# saliency_map2 = self.extract_saliency_maps(image2_batch)[0]
# threshold saliency maps to get fg / bg masks
fg_mask1 = saliency_map1 > thresh
fg_mask2 = saliency_map2 > thresh
# calculate similarity between image1 and image2 descriptors
start_time_chunk_cosine = time.time()
similarities = chunk_cosine_sim(descriptors1, descriptors2)
end_time_chunk_cosine = time.time()
elapsed_time_chunk_cosine = end_time_chunk_cosine - start_time_chunk_cosine
start_time_bb = time.time()
# calculate best buddies
image_idxs = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)
sim_1, nn_1 = torch.max(similarities, dim=-1) # nn_1 - indices of block2 closest to block1
sim_2, nn_2 = torch.max(similarities, dim=-2) # nn_2 - indices of block1 closest to block2
sim_1, nn_1 = sim_1[0, 0], nn_1[0, 0]
sim_2, nn_2 = sim_2[0, 0], nn_2[0, 0]
bbs_mask = nn_2[nn_1] == image_idxs
# remove best buddies where at least one descriptor is marked bg by saliency mask.
fg_mask2_new_coors = nn_2[fg_mask2]
fg_mask2_mask_new_coors = torch.zeros(num_patches1[0] * num_patches1[1], dtype=torch.bool, device=self.device)
fg_mask2_mask_new_coors[fg_mask2_new_coors] = True
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask1)
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask2_mask_new_coors)
# applying k-means to extract k high quality well distributed correspondence pairs
# bb_descs1 = descriptors1[0, 0, bbs_mask, :].cpu().numpy()
# bb_descs2 = descriptors2[0, 0, nn_1[bbs_mask], :].cpu().numpy()
bb_descs1 = descriptors1[0, 0, bbs_mask, :]
bb_descs2 = descriptors2[0, 0, nn_1[bbs_mask], :]
# apply k-means on a concatenation of a pairs descriptors.
# all_keys_together = np.concatenate((bb_descs1, bb_descs2), axis=1)
all_keys_together = torch.cat((bb_descs1, bb_descs2), axis=1)
n_clusters = min(num_pairs, len(all_keys_together)) # if not enough pairs, show all found pairs.
length = torch.sqrt((all_keys_together ** 2).sum(axis=1, keepdim=True))
normalized = all_keys_together / length
start_time_kmeans = time.time()
# cluster_ids_x, cluster_centers = kmeans(X = normalized, num_clusters=n_clusters, distance='cosine', device=self.device)
cluster_ids_x, cluster_centers = kmeans(X = normalized,
num_clusters=n_clusters,
distance='cosine',
tqdm_flag = False,
iter_limit=200,
device=self.device)
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
kmeans_labels = cluster_ids_x.detach().cpu().numpy()
# kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(normalized)
end_time_kmeans = time.time()
elapsed_kmeans = end_time_kmeans - start_time_kmeans
bb_topk_sims = np.full((n_clusters), -np.inf)
bb_indices_to_show = np.full((n_clusters), -np.inf)
# rank pairs by their mean saliency value
bb_cls_attn1 = saliency_map1[bbs_mask]
bb_cls_attn2 = saliency_map2[nn_1[bbs_mask]]
bb_cls_attn = (bb_cls_attn1 + bb_cls_attn2) / 2
ranks = bb_cls_attn
for k in range(n_clusters):
for i, (label, rank) in enumerate(zip(kmeans_labels, ranks)):
if rank > bb_topk_sims[label]:
bb_topk_sims[label] = rank
bb_indices_to_show[label] = i
# get coordinates to show
indices_to_show = torch.nonzero(bbs_mask, as_tuple=False).squeeze(dim=1)[
bb_indices_to_show] # close bbs
img1_indices_to_show = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)[indices_to_show]
img2_indices_to_show = nn_1[indices_to_show]
# coordinates in descriptor map's dimensions
img1_y_to_show = (img1_indices_to_show / num_patches1[1]).cpu().numpy()
img1_x_to_show = (img1_indices_to_show % num_patches1[1]).cpu().numpy()
img2_y_to_show = (img2_indices_to_show / num_patches2[1]).cpu().numpy()
img2_x_to_show = (img2_indices_to_show % num_patches2[1]).cpu().numpy()
points1, points2 = [], []
for y1, x1, y2, x2 in zip(img1_y_to_show, img1_x_to_show, img2_y_to_show, img2_x_to_show):
x1_show = (int(x1) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y1_show = (int(y1) - 1) * self.stride[0] + self.stride[0] + self.p // 2
x2_show = (int(x2) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y2_show = (int(y2) - 1) * self.stride[0] + self.stride[0] + self.p // 2
points1.append((y1_show, x1_show))
points2.append((y2_show, x2_show))
end_time_bb = time.time()
end_time_corr = time.time()
elapsed_bb = end_time_bb - start_time_bb
elapsed_corr = end_time_corr - start_time_corr
#print(f"all_corr: {elapsed_corr}, desc: {elapsed_desc}, chunk cosine: {elapsed_time_chunk_cosine}, saliency: {elapsed_saliencey}, kmeans: {elapsed_kmeans}, bb: {elapsed_bb}")
return points1, points2, image1_pil, image2_pil
def find_correspondences(self, pil_img1, pil_img2, num_pairs: int = 10, load_size: int = 224,
layer: int = 9, facet: str = 'key', bin: bool = True,
thresh: float = 0.05) -> Tuple[List[Tuple[float, float]], List[Tuple[float, float]], Image.Image, Image.Image]:
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
start_time_corr = time.time()
start_time_desc = time.time()
image1_batch, image1_pil, scale_factor = self.preprocess(pil_img1, load_size)
descriptors1 = self.extract_descriptors(image1_batch.to(self.device), layer, facet, bin)
num_patches1, load_size1 = self.num_patches, self.load_size
image2_batch, image2_pil, scale_factor = self.preprocess(pil_img2, load_size)
descriptors2 = self.extract_descriptors(image2_batch.to(self.device), layer, facet, bin)
num_patches2, load_size2 = self.num_patches, self.load_size
end_time_desc = time.time()
elapsed_desc = end_time_desc - start_time_desc
start_time_saliency = time.time()
# extracting saliency maps for each image
saliency_map1 = self.extract_saliency_maps(image1_batch.to(self.device))[0]
saliency_map2 = self.extract_saliency_maps(image2_batch.to(self.device))[0]
end_time_saliency = time.time()
elapsed_saliencey = end_time_saliency - start_time_saliency
# saliency_map1 = self.extract_saliency_maps(image1_batch)[0]
# saliency_map2 = self.extract_saliency_maps(image2_batch)[0]
# threshold saliency maps to get fg / bg masks
fg_mask1 = saliency_map1 > thresh
fg_mask2 = saliency_map2 > thresh
# calculate similarity between image1 and image2 descriptors
start_time_chunk_cosine = time.time()
similarities = chunk_cosine_sim(descriptors1, descriptors2)
end_time_chunk_cosine = time.time()
elapsed_time_chunk_cosine = end_time_chunk_cosine - start_time_chunk_cosine
start_time_bb = time.time()
# calculate best buddies
image_idxs = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)
sim_1, nn_1 = torch.max(similarities, dim=-1) # nn_1 - indices of block2 closest to block1
sim_2, nn_2 = torch.max(similarities, dim=-2) # nn_2 - indices of block1 closest to block2
sim_1, nn_1 = sim_1[0, 0], nn_1[0, 0]
sim_2, nn_2 = sim_2[0, 0], nn_2[0, 0]
bbs_mask = nn_2[nn_1] == image_idxs
# remove best buddies where at least one descriptor is marked bg by saliency mask.
fg_mask2_new_coors = nn_2[fg_mask2]
fg_mask2_mask_new_coors = torch.zeros(num_patches1[0] * num_patches1[1], dtype=torch.bool, device=self.device)
fg_mask2_mask_new_coors[fg_mask2_new_coors] = True
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask1)
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask2_mask_new_coors)
# applying k-means to extract k high quality well distributed correspondence pairs
bb_descs1 = descriptors1[0, 0, bbs_mask, :].cpu().numpy()
bb_descs2 = descriptors2[0, 0, nn_1[bbs_mask], :].cpu().numpy()
# apply k-means on a concatenation of a pairs descriptors.
all_keys_together = np.concatenate((bb_descs1, bb_descs2), axis=1)
n_clusters = min(num_pairs, len(all_keys_together)) # if not enough pairs, show all found pairs.
length = np.sqrt((all_keys_together ** 2).sum(axis=1))[:, None]
normalized = all_keys_together / length
start_time_kmeans = time.time()
kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(normalized)
end_time_kmeans = time.time()
elapsed_kmeans = end_time_kmeans - start_time_kmeans
bb_topk_sims = np.full((n_clusters), -np.inf)
bb_indices_to_show = np.full((n_clusters), -np.inf)
# rank pairs by their mean saliency value
bb_cls_attn1 = saliency_map1[bbs_mask]
bb_cls_attn2 = saliency_map2[nn_1[bbs_mask]]
bb_cls_attn = (bb_cls_attn1 + bb_cls_attn2) / 2
ranks = bb_cls_attn
for k in range(n_clusters):
for i, (label, rank) in enumerate(zip(kmeans.labels_, ranks)):
if rank > bb_topk_sims[label]:
bb_topk_sims[label] = rank
bb_indices_to_show[label] = i
# get coordinates to show
indices_to_show = torch.nonzero(bbs_mask, as_tuple=False).squeeze(dim=1)[
bb_indices_to_show] # close bbs
img1_indices_to_show = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)[indices_to_show]
img2_indices_to_show = nn_1[indices_to_show]
# coordinates in descriptor map's dimensions
img1_y_to_show = (img1_indices_to_show / num_patches1[1]).cpu().numpy()
img1_x_to_show = (img1_indices_to_show % num_patches1[1]).cpu().numpy()
img2_y_to_show = (img2_indices_to_show / num_patches2[1]).cpu().numpy()
img2_x_to_show = (img2_indices_to_show % num_patches2[1]).cpu().numpy()
points1, points2 = [], []
for y1, x1, y2, x2 in zip(img1_y_to_show, img1_x_to_show, img2_y_to_show, img2_x_to_show):
x1_show = (int(x1) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y1_show = (int(y1) - 1) * self.stride[0] + self.stride[0] + self.p // 2
x2_show = (int(x2) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y2_show = (int(y2) - 1) * self.stride[0] + self.stride[0] + self.p // 2
points1.append((y1_show, x1_show))
points2.append((y2_show, x2_show))
end_time_bb = time.time()
end_time_corr = time.time()
elapsed_bb = end_time_bb - start_time_bb
elapsed_corr = end_time_corr - start_time_corr
print(f"all_corr: {elapsed_corr}, desc: {elapsed_desc}, chunk cosine: {elapsed_time_chunk_cosine}, saliency: {elapsed_saliencey}, kmeans: {elapsed_kmeans}, bb: {elapsed_bb}")
return points1, points2, image1_pil, image2_pil
def find_correspondences_old(self, pil_img1, pil_img2, num_pairs: int = 10, load_size: int = 224,
layer: int = 9, facet: str = 'key', bin: bool = True,
thresh: float = 0.05) -> Tuple[List[Tuple[float, float]], List[Tuple[float, float]], Image.Image, Image.Image]:
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
image1_batch, image1_pil, scale_factor = self.preprocess(pil_img1, load_size)
descriptors1 = self.extract_descriptors(image1_batch.to(self.device), layer, facet, bin)
num_patches1, load_size1 = self.num_patches, self.load_size
image2_batch, image2_pil, scale_factor = self.preprocess(pil_img2, load_size)
descriptors2 = self.extract_descriptors(image2_batch.to(self.device), layer, facet, bin)
num_patches2, load_size2 = self.num_patches, self.load_size
# extracting saliency maps for each image
saliency_map1 = self.extract_saliency_maps(image1_batch.to(self.device))[0]
saliency_map2 = self.extract_saliency_maps(image2_batch.to(self.device))[0]
# saliency_map1 = self.extract_saliency_maps(image1_batch)[0]
# saliency_map2 = self.extract_saliency_maps(image2_batch)[0]
# threshold saliency maps to get fg / bg masks
fg_mask1 = saliency_map1 > thresh
fg_mask2 = saliency_map2 > thresh
# calculate similarity between image1 and image2 descriptors
similarities = chunk_cosine_sim(descriptors1, descriptors2)
# calculate best buddies
image_idxs = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)
sim_1, nn_1 = torch.max(similarities, dim=-1) # nn_1 - indices of block2 closest to block1
sim_2, nn_2 = torch.max(similarities, dim=-2) # nn_2 - indices of block1 closest to block2
sim_1, nn_1 = sim_1[0, 0], nn_1[0, 0]
sim_2, nn_2 = sim_2[0, 0], nn_2[0, 0]
bbs_mask = nn_2[nn_1] == image_idxs
# remove best buddies where at least one descriptor is marked bg by saliency mask.
fg_mask2_new_coors = nn_2[fg_mask2]
fg_mask2_mask_new_coors = torch.zeros(num_patches1[0] * num_patches1[1], dtype=torch.bool, device=self.device)
fg_mask2_mask_new_coors[fg_mask2_new_coors] = True
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask1)
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask2_mask_new_coors)
# applying k-means to extract k high quality well distributed correspondence pairs
bb_descs1 = descriptors1[0, 0, bbs_mask, :].cpu().numpy()
bb_descs2 = descriptors2[0, 0, nn_1[bbs_mask], :].cpu().numpy()
# apply k-means on a concatenation of a pairs descriptors.
all_keys_together = np.concatenate((bb_descs1, bb_descs2), axis=1)
n_clusters = min(num_pairs, len(all_keys_together)) # if not enough pairs, show all found pairs.
length = np.sqrt((all_keys_together ** 2).sum(axis=1))[:, None]
normalized = all_keys_together / length
kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(normalized)
bb_topk_sims = np.full((n_clusters), -np.inf)
bb_indices_to_show = np.full((n_clusters), -np.inf)
# rank pairs by their mean saliency value
bb_cls_attn1 = saliency_map1[bbs_mask]
bb_cls_attn2 = saliency_map2[nn_1[bbs_mask]]
bb_cls_attn = (bb_cls_attn1 + bb_cls_attn2) / 2
ranks = bb_cls_attn
for k in range(n_clusters):
for i, (label, rank) in enumerate(zip(kmeans.labels_, ranks)):
if rank > bb_topk_sims[label]:
bb_topk_sims[label] = rank
bb_indices_to_show[label] = i
# get coordinates to show
indices_to_show = torch.nonzero(bbs_mask, as_tuple=False).squeeze(dim=1)[
bb_indices_to_show] # close bbs
img1_indices_to_show = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)[indices_to_show]
img2_indices_to_show = nn_1[indices_to_show]
# coordinates in descriptor map's dimensions
img1_y_to_show = (img1_indices_to_show / num_patches1[1]).cpu().numpy()
img1_x_to_show = (img1_indices_to_show % num_patches1[1]).cpu().numpy()
img2_y_to_show = (img2_indices_to_show / num_patches2[1]).cpu().numpy()
img2_x_to_show = (img2_indices_to_show % num_patches2[1]).cpu().numpy()
points1, points2 = [], []
for y1, x1, y2, x2 in zip(img1_y_to_show, img1_x_to_show, img2_y_to_show, img2_x_to_show):
x1_show = (int(x1) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y1_show = (int(y1) - 1) * self.stride[0] + self.stride[0] + self.p // 2
x2_show = (int(x2) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y2_show = (int(y2) - 1) * self.stride[0] + self.stride[0] + self.p // 2
points1.append((y1_show, x1_show))
points2.append((y2_show, x2_show))
return points1, points2, image1_pil, image2_pil
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
class PoseCroCoExtractor(extractor.CroCoExtractor):
def __init__(self, model_type: str = 'dino_vits8', stride: int = 4, model: nn.Module = None, device: str = 'cuda'):
self.model_type = model_type
self.stride = stride
self.model = model
self.device = device
super().__init__(model_type=self.model_type, stride=self.stride, model=self.model, device=self.device)
self.prep = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=self.mean, std=self.std)
])
def preprocess(self, img: Image.Image,
load_size: Union[int, Tuple[int, int]] = None) -> Tuple[torch.Tensor, Image.Image]:
scale_factor = 1
if load_size is not None:
width, height = img.size # img has to be quadratic
img = transforms.Resize(load_size, interpolation=transforms.InterpolationMode.LANCZOS)(img)
scale_factor = img.size[0] / width
prep_img = self.prep(img)[None, ...]
return prep_img, img, scale_factor
# Overwrite functionality of _extract_features(self, batch: torch.Tensor, layers: List[int] = 11, facet: str = 'key') -> List[torch.Tensor]
# to extract multiple facets and layers in one turn
def _extract_multi_features(self, batch: torch.Tensor, layers: List[int] = [9, 11], facet: str = 'key') -> List[
torch.Tensor]:
B, C, H, W = batch.shape
self._feats = []
# for (layer,fac) in zip(layers,facet):
self._register_hooks(layers, facet)
_ = self.model(batch)
self._unregister_hooks()
self.load_size = (H, W)
self.num_patches = (1 + (H - self.p) // self.stride[0], 1 + (W - self.p) // self.stride[1])
return self._feats
def extract_multi_descriptors(self, batch: torch.Tensor, layers: List[int] = [9, 11], facet: str = 'key',
bin: List[bool] = [True, False],
include_cls: List[bool] = [False, False]) -> torch.Tensor:
assert facet in ['key', 'query', 'value', 'token'], f"""{facet} is not a supported facet for descriptors.
choose from ['key' | 'query' | 'value' | 'token'] """
self._extract_multi_features(batch, layers, facet)
descs = []
for i, x in enumerate(self._feats):
if facet[i] == 'token':
x.unsqueeze_(dim=1) # Bx1xtxd
if not include_cls[i]:
x = x[:, :, 1:, :] # remove cls token
else:
assert not bin[
i], "bin = True and include_cls = True are not supported together, set one of them False."
if not bin:
desc = x.permute(0, 2, 3, 1).flatten(start_dim=-2, end_dim=-1).unsqueeze(dim=1) # Bx1xtx(dxh)
else:
desc = self._log_bin(x)
descs.append(desc)
return descs
def find_correspondences_fastkmeans(self, pil_img1, pil_img2, num_pairs: int = 10, load_size: int = 224,
layer: int = 9, facet: str = 'key', bin: bool = True,
thresh: float = 0.05) -> Tuple[
List[Tuple[float, float]], List[Tuple[float, float]], Image.Image, Image.Image]:
start_time_corr = time.time()
start_time_desc = time.time()
image1_batch, image1_pil, scale_factor = self.preprocess(pil_img1, load_size)
descriptors1 = self.extract_descriptors(image1_batch.to(self.device), layer, facet, bin)
num_patches1, load_size1 = self.num_patches, self.load_size
image2_batch, image2_pil, scale_factor = self.preprocess(pil_img2, load_size)
descriptors2 = self.extract_descriptors(image2_batch.to(self.device), layer, facet, bin)
num_patches2, load_size2 = self.num_patches, self.load_size
end_time_desc = time.time()
elapsed_desc = end_time_desc - start_time_desc
start_time_saliency = time.time()
# extracting saliency maps for each image
saliency_map1 = self.extract_saliency_maps(image1_batch.to(self.device))[0]
saliency_map2 = self.extract_saliency_maps(image2_batch.to(self.device))[0]
end_time_saliency = time.time()
elapsed_saliencey = end_time_saliency - start_time_saliency
# saliency_map1 = self.extract_saliency_maps(image1_batch)[0]
# saliency_map2 = self.extract_saliency_maps(image2_batch)[0]
# threshold saliency maps to get fg / bg masks
fg_mask1 = saliency_map1 > thresh
fg_mask2 = saliency_map2 > thresh
# calculate similarity between image1 and image2 descriptors
start_time_chunk_cosine = time.time()
similarities = chunk_cosine_sim(descriptors1, descriptors2)
end_time_chunk_cosine = time.time()
elapsed_time_chunk_cosine = end_time_chunk_cosine - start_time_chunk_cosine
start_time_bb = time.time()
# calculate best buddies
image_idxs = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)
sim_1, nn_1 = torch.max(similarities, dim=-1) # nn_1 - indices of block2 closest to block1
sim_2, nn_2 = torch.max(similarities, dim=-2) # nn_2 - indices of block1 closest to block2
sim_1, nn_1 = sim_1[0, 0], nn_1[0, 0]
sim_2, nn_2 = sim_2[0, 0], nn_2[0, 0]
bbs_mask = nn_2[nn_1] == image_idxs
# remove best buddies where at least one descriptor is marked bg by saliency mask.
fg_mask2_new_coors = nn_2[fg_mask2]
fg_mask2_mask_new_coors = torch.zeros(num_patches1[0] * num_patches1[1], dtype=torch.bool, device=self.device)
fg_mask2_mask_new_coors[fg_mask2_new_coors] = True
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask1)
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask2_mask_new_coors)
# applying k-means to extract k high quality well distributed correspondence pairs
# bb_descs1 = descriptors1[0, 0, bbs_mask, :].cpu().numpy()
# bb_descs2 = descriptors2[0, 0, nn_1[bbs_mask], :].cpu().numpy()
bb_descs1 = descriptors1[0, 0, bbs_mask, :]
bb_descs2 = descriptors2[0, 0, nn_1[bbs_mask], :]
# apply k-means on a concatenation of a pairs descriptors.
# all_keys_together = np.concatenate((bb_descs1, bb_descs2), axis=1)
all_keys_together = torch.cat((bb_descs1, bb_descs2), axis=1)
n_clusters = min(num_pairs, len(all_keys_together)) # if not enough pairs, show all found pairs.
length = torch.sqrt((all_keys_together ** 2).sum(axis=1, keepdim=True))
normalized = all_keys_together / length
start_time_kmeans = time.time()
# 'euclidean'
# cluster_ids_x, cluster_centers = kmeans(X = normalized, num_clusters=n_clusters, distance='cosine', device=self.device)
cluster_ids_x, cluster_centers = kmeans(X=normalized,
num_clusters=n_clusters,
distance='cosine',
tqdm_flag=False,
iter_limit=200,
device=self.device)
kmeans_labels = cluster_ids_x.detach().cpu().numpy()
# kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(normalized)
end_time_kmeans = time.time()
elapsed_kmeans = end_time_kmeans - start_time_kmeans
bb_topk_sims = np.full((n_clusters), -np.inf)
bb_indices_to_show = np.full((n_clusters), -np.inf)
# rank pairs by their mean saliency value
bb_cls_attn1 = saliency_map1[bbs_mask]
bb_cls_attn2 = saliency_map2[nn_1[bbs_mask]]
bb_cls_attn = (bb_cls_attn1 + bb_cls_attn2) / 2
ranks = bb_cls_attn
for k in range(n_clusters):
for i, (label, rank) in enumerate(zip(kmeans_labels, ranks)):
if rank > bb_topk_sims[label]:
bb_topk_sims[label] = rank
bb_indices_to_show[label] = i
# get coordinates to show
indices_to_show = torch.nonzero(bbs_mask, as_tuple=False).squeeze(dim=1)[
bb_indices_to_show] # close bbs
img1_indices_to_show = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)[indices_to_show]
img2_indices_to_show = nn_1[indices_to_show]
# coordinates in descriptor map's dimensions
img1_y_to_show = (img1_indices_to_show / num_patches1[1]).cpu().numpy()
img1_x_to_show = (img1_indices_to_show % num_patches1[1]).cpu().numpy()
img2_y_to_show = (img2_indices_to_show / num_patches2[1]).cpu().numpy()
img2_x_to_show = (img2_indices_to_show % num_patches2[1]).cpu().numpy()
points1, points2 = [], []
for y1, x1, y2, x2 in zip(img1_y_to_show, img1_x_to_show, img2_y_to_show, img2_x_to_show):
x1_show = (int(x1) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y1_show = (int(y1) - 1) * self.stride[0] + self.stride[0] + self.p // 2
x2_show = (int(x2) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y2_show = (int(y2) - 1) * self.stride[0] + self.stride[0] + self.p // 2
points1.append((y1_show, x1_show))
points2.append((y2_show, x2_show))
end_time_bb = time.time()
end_time_corr = time.time()
elapsed_bb = end_time_bb - start_time_bb
elapsed_corr = end_time_corr - start_time_corr
# print(f"all_corr: {elapsed_corr}, desc: {elapsed_desc}, chunk cosine: {elapsed_time_chunk_cosine}, saliency: {elapsed_saliencey}, kmeans: {elapsed_kmeans}, bb: {elapsed_bb}")
return points1, points2, image1_pil, image2_pil
def find_correspondences(self, pil_img1, pil_img2, num_pairs: int = 10, load_size: int = 224,
layer: int = 9, facet: str = 'key', bin: bool = True,
thresh: float = 0.05) -> Tuple[
List[Tuple[float, float]], List[Tuple[float, float]], Image.Image, Image.Image]:
start_time_corr = time.time()
start_time_desc = time.time()
image1_batch, image1_pil, scale_factor = self.preprocess(pil_img1, load_size)
descriptors1 = self.extract_descriptors(image1_batch.to(self.device), layer, facet, bin)
num_patches1, load_size1 = self.num_patches, self.load_size
image2_batch, image2_pil, scale_factor = self.preprocess(pil_img2, load_size)
descriptors2 = self.extract_descriptors(image2_batch.to(self.device), layer, facet, bin)
num_patches2, load_size2 = self.num_patches, self.load_size
end_time_desc = time.time()
elapsed_desc = end_time_desc - start_time_desc
start_time_saliency = time.time()
# extracting saliency maps for each image
saliency_map1 = self.extract_saliency_maps(image1_batch.to(self.device))[0]
saliency_map2 = self.extract_saliency_maps(image2_batch.to(self.device))[0]
end_time_saliency = time.time()
elapsed_saliencey = end_time_saliency - start_time_saliency
# saliency_map1 = self.extract_saliency_maps(image1_batch)[0]
# saliency_map2 = self.extract_saliency_maps(image2_batch)[0]
# threshold saliency maps to get fg / bg masks
fg_mask1 = saliency_map1 > thresh
fg_mask2 = saliency_map2 > thresh
# calculate similarity between image1 and image2 descriptors
start_time_chunk_cosine = time.time()
similarities = chunk_cosine_sim(descriptors1, descriptors2)
end_time_chunk_cosine = time.time()
elapsed_time_chunk_cosine = end_time_chunk_cosine - start_time_chunk_cosine
start_time_bb = time.time()
# calculate best buddies
image_idxs = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)
sim_1, nn_1 = torch.max(similarities, dim=-1) # nn_1 - indices of block2 closest to block1
sim_2, nn_2 = torch.max(similarities, dim=-2) # nn_2 - indices of block1 closest to block2
sim_1, nn_1 = sim_1[0, 0], nn_1[0, 0]
sim_2, nn_2 = sim_2[0, 0], nn_2[0, 0]
bbs_mask = nn_2[nn_1] == image_idxs
# remove best buddies where at least one descriptor is marked bg by saliency mask.
fg_mask2_new_coors = nn_2[fg_mask2]
fg_mask2_mask_new_coors = torch.zeros(num_patches1[0] * num_patches1[1], dtype=torch.bool, device=self.device)
fg_mask2_mask_new_coors[fg_mask2_new_coors] = True
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask1)
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask2_mask_new_coors)
# applying k-means to extract k high quality well distributed correspondence pairs
bb_descs1 = descriptors1[0, 0, bbs_mask, :].cpu().numpy()
bb_descs2 = descriptors2[0, 0, nn_1[bbs_mask], :].cpu().numpy()
# apply k-means on a concatenation of a pairs descriptors.
all_keys_together = np.concatenate((bb_descs1, bb_descs2), axis=1)
n_clusters = min(num_pairs, len(all_keys_together)) # if not enough pairs, show all found pairs.
length = np.sqrt((all_keys_together ** 2).sum(axis=1))[:, None]
normalized = all_keys_together / length
start_time_kmeans = time.time()
kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(normalized)
end_time_kmeans = time.time()
elapsed_kmeans = end_time_kmeans - start_time_kmeans
bb_topk_sims = np.full((n_clusters), -np.inf)
bb_indices_to_show = np.full((n_clusters), -np.inf)
# rank pairs by their mean saliency value
bb_cls_attn1 = saliency_map1[bbs_mask]
bb_cls_attn2 = saliency_map2[nn_1[bbs_mask]]
bb_cls_attn = (bb_cls_attn1 + bb_cls_attn2) / 2
ranks = bb_cls_attn
for k in range(n_clusters):
for i, (label, rank) in enumerate(zip(kmeans.labels_, ranks)):
if rank > bb_topk_sims[label]:
bb_topk_sims[label] = rank
bb_indices_to_show[label] = i
# get coordinates to show
indices_to_show = torch.nonzero(bbs_mask, as_tuple=False).squeeze(dim=1)[
bb_indices_to_show] # close bbs
img1_indices_to_show = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)[indices_to_show]
img2_indices_to_show = nn_1[indices_to_show]
# coordinates in descriptor map's dimensions
img1_y_to_show = (img1_indices_to_show / num_patches1[1]).cpu().numpy()
img1_x_to_show = (img1_indices_to_show % num_patches1[1]).cpu().numpy()
img2_y_to_show = (img2_indices_to_show / num_patches2[1]).cpu().numpy()
img2_x_to_show = (img2_indices_to_show % num_patches2[1]).cpu().numpy()
points1, points2 = [], []
for y1, x1, y2, x2 in zip(img1_y_to_show, img1_x_to_show, img2_y_to_show, img2_x_to_show):
x1_show = (int(x1) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y1_show = (int(y1) - 1) * self.stride[0] + self.stride[0] + self.p // 2
x2_show = (int(x2) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y2_show = (int(y2) - 1) * self.stride[0] + self.stride[0] + self.p // 2
points1.append((y1_show, x1_show))
points2.append((y2_show, x2_show))
end_time_bb = time.time()
end_time_corr = time.time()
elapsed_bb = end_time_bb - start_time_bb
elapsed_corr = end_time_corr - start_time_corr
print(
f"all_corr: {elapsed_corr}, desc: {elapsed_desc}, chunk cosine: {elapsed_time_chunk_cosine}, saliency: {elapsed_saliencey}, kmeans: {elapsed_kmeans}, bb: {elapsed_bb}")
return points1, points2, image1_pil, image2_pil
def find_correspondences_old(self, pil_img1, pil_img2, num_pairs: int = 10, load_size: int = 224,
layer: int = 9, facet: str = 'key', bin: bool = True,
thresh: float = 0.05) -> Tuple[
List[Tuple[float, float]], List[Tuple[float, float]], Image.Image, Image.Image]:
image1_batch, image1_pil, scale_factor = self.preprocess(pil_img1, load_size)
descriptors1 = self.extract_descriptors(image1_batch.to(self.device), layer, facet, bin)
num_patches1, load_size1 = self.num_patches, self.load_size
image2_batch, image2_pil, scale_factor = self.preprocess(pil_img2, load_size)
descriptors2 = self.extract_descriptors(image2_batch.to(self.device), layer, facet, bin)
num_patches2, load_size2 = self.num_patches, self.load_size
# extracting saliency maps for each image
saliency_map1 = self.extract_saliency_maps(image1_batch.to(self.device))[0]
saliency_map2 = self.extract_saliency_maps(image2_batch.to(self.device))[0]
# saliency_map1 = self.extract_saliency_maps(image1_batch)[0]
# saliency_map2 = self.extract_saliency_maps(image2_batch)[0]
# threshold saliency maps to get fg / bg masks
fg_mask1 = saliency_map1 > thresh
fg_mask2 = saliency_map2 > thresh
# calculate similarity between image1 and image2 descriptors
similarities = chunk_cosine_sim(descriptors1, descriptors2)
# calculate best buddies
image_idxs = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)
sim_1, nn_1 = torch.max(similarities, dim=-1) # nn_1 - indices of block2 closest to block1
sim_2, nn_2 = torch.max(similarities, dim=-2) # nn_2 - indices of block1 closest to block2
sim_1, nn_1 = sim_1[0, 0], nn_1[0, 0]
sim_2, nn_2 = sim_2[0, 0], nn_2[0, 0]
bbs_mask = nn_2[nn_1] == image_idxs
# remove best buddies where at least one descriptor is marked bg by saliency mask.
fg_mask2_new_coors = nn_2[fg_mask2]
fg_mask2_mask_new_coors = torch.zeros(num_patches1[0] * num_patches1[1], dtype=torch.bool, device=self.device)
fg_mask2_mask_new_coors[fg_mask2_new_coors] = True
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask1)
bbs_mask = torch.bitwise_and(bbs_mask, fg_mask2_mask_new_coors)
# applying k-means to extract k high quality well distributed correspondence pairs
bb_descs1 = descriptors1[0, 0, bbs_mask, :].cpu().numpy()
bb_descs2 = descriptors2[0, 0, nn_1[bbs_mask], :].cpu().numpy()
# apply k-means on a concatenation of a pairs descriptors.
all_keys_together = np.concatenate((bb_descs1, bb_descs2), axis=1)
n_clusters = min(num_pairs, len(all_keys_together)) # if not enough pairs, show all found pairs.
length = np.sqrt((all_keys_together ** 2).sum(axis=1))[:, None]
normalized = all_keys_together / length
kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(normalized)
bb_topk_sims = np.full((n_clusters), -np.inf)
bb_indices_to_show = np.full((n_clusters), -np.inf)
# rank pairs by their mean saliency value
bb_cls_attn1 = saliency_map1[bbs_mask]
bb_cls_attn2 = saliency_map2[nn_1[bbs_mask]]
bb_cls_attn = (bb_cls_attn1 + bb_cls_attn2) / 2
ranks = bb_cls_attn
for k in range(n_clusters):
for i, (label, rank) in enumerate(zip(kmeans.labels_, ranks)):
if rank > bb_topk_sims[label]:
bb_topk_sims[label] = rank
bb_indices_to_show[label] = i
# get coordinates to show
indices_to_show = torch.nonzero(bbs_mask, as_tuple=False).squeeze(dim=1)[
bb_indices_to_show] # close bbs
img1_indices_to_show = torch.arange(num_patches1[0] * num_patches1[1], device=self.device)[indices_to_show]
img2_indices_to_show = nn_1[indices_to_show]
# coordinates in descriptor map's dimensions
img1_y_to_show = (img1_indices_to_show / num_patches1[1]).cpu().numpy()
img1_x_to_show = (img1_indices_to_show % num_patches1[1]).cpu().numpy()
img2_y_to_show = (img2_indices_to_show / num_patches2[1]).cpu().numpy()
img2_x_to_show = (img2_indices_to_show % num_patches2[1]).cpu().numpy()
points1, points2 = [], []
for y1, x1, y2, x2 in zip(img1_y_to_show, img1_x_to_show, img2_y_to_show, img2_x_to_show):
x1_show = (int(x1) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y1_show = (int(y1) - 1) * self.stride[0] + self.stride[0] + self.p // 2
x2_show = (int(x2) - 1) * self.stride[1] + self.stride[1] + self.p // 2
y2_show = (int(y2) - 1) * self.stride[0] + self.stride[0] + self.p // 2
points1.append((y1_show, x1_show))
points2.append((y2_show, x2_show))
return points1, points2, image1_pil, image2_pil