-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdictionary.py
More file actions
210 lines (161 loc) · 6.09 KB
/
dictionary.py
File metadata and controls
210 lines (161 loc) · 6.09 KB
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
"""
Implementation of the dictionary that manages
the different templates.
"""
###########
# Imports #
###########
import io
import json
import torch
import torchvision.transforms as transforms
from PIL import Image
from random import randint
from tqdm import tqdm
def three2four(img):
"""
Convert an image represented by a 3 * h * w tensor
to a 4 * h * w tensor.
"""
if len(img.size()) > 3:
img = img.squeeze(0)
h, w = img.size()[1], img.size()[2]
converted = torch.zeros(4, h, w)
nonnul = torch.sum(img, dim=0)
colors = torch.argmax(img, dim=0)
colors[(nonnul == 0)] = 4
converted[1][(colors == 2).squeeze()] = 1
converted[2][(colors == 1).squeeze()] = 1
converted[3][(colors == 0).squeeze()] = 1
return converted
###########
# Classes #
###########
class Dictionary:
"""
The dictionary manages all the templates.
"""
def __init__(self, json_dict, field=None, from_scratch=False):
# Templates and associated homographies
self.pairs = []
# Pre computed elements (data matches and templates encoded)
self.d_matches, self.t_encoded = {}, []
# Save each template and associated homography
with open(json_dict) as json_file:
data = json.load(json_file)
count = 0
for template in tqdm(data):
if not from_scratch:
with open(template['image'].replace('dictionary-four', 'dictionary-three'), 'rb') as img:
self.pairs.append((
self.transform(io.BytesIO(img.read())),
torch.tensor([template['homography_resize']])
))
else:
homography = torch.tensor([template['homography_resize']])
template = field.warp_field(homography)
self.pairs.append((
self.transform2(template),
homography
))
count += 1
def pick(self, similarities):
# Pick a template and associate similarity for each
# image in the batch
batch_size = similarities.size()[0]
templates, y = [], []
for i in range(batch_size):
# Decide if we pick a similar or dissimilar
choice = randint(0, 1)
if choice:
idx = similarities[i].item()
else:
idx = randint(0, len(self.pairs) - 1)
if idx == similarities[i].item():
idx -= 1
if idx < 0:
idx += 2
template, _ = self.pairs[idx]
# template = self.transform(template)
similarity = choice
templates.append(template)
y.append(similarity)
templates = torch.stack(templates, dim=0)
y = torch.tensor(y)
y = y.view(batch_size, 1)
return templates, y
def pick_force(self, similarities, force=1):
batch_size = similarities.size()[0]
templates, homographies = [], []
for i in range(batch_size):
choice = force
if choice:
idx = similarities[i].item()
else:
idx = randint(0, len(self.pairs) - 1)
if idx == similarities[i].item():
idx -= 1
if idx < 0:
idx += 2
template, h = self.pairs[idx]
# template = self.transform(template)
templates.append(template)
homographies.append(h)
templates = torch.stack(templates, dim=0)
homographies = torch.stack(homographies, dim=0)
return templates, homographies
def encode(self, model):
print("Encoding dictionary")
model = model.to('cpu')
for pair in self.pairs:
# template = self.transform(pair[0])
template = pair[0]
template = template.unsqueeze(0)
template = model.encode(template)
self.t_encoded.append(template)
print("Encoding done !")
def match(self, masks, model, device, names=None):
batch_size = masks.size()[0]
matches, homographies, idxs = [], [], []
# Encode dictionary templates if not done
if len(self.t_encoded) == 0:
self.encode(model)
model = model.to(device)
# Calculate distances between masks and each template and
# get the matching template
for i in range(batch_size):
closest = None if names is None else self.d_matches.get(names[i])
if closest is None:
dist = []
encoded = model.encode(masks[i].unsqueeze(0))
# for template in self.t_encoded:
# template = template.to(device)
# dist.append(F.pairwise_distance(encoded, template).item())
# # print(dist.size())
# closest = dist.index(min(dist))
templates = torch.stack(self.t_encoded)
templates = templates.to(device)
templates = templates.squeeze(1)
d = templates - encoded
dist = torch.norm(d, dim=1, p=None)
closest = dist.topk(3, largest=False)
closest = closest.indices[0]
if names is not None:
self.d_matches[names[i]] = closest
idxs.append(closest)
match, homography = self.pairs[closest]
# match = self.transform(match)
matches.append(match)
homographies.append(homography)
matches = torch.stack(matches, dim=0)
homographies = torch.stack(homographies, dim=0)
return matches, homographies, idxs
def transform(self, template):
template = Image.open(template)
template = transforms.ToTensor()(template)
template = template.mul(255.)
template = three2four(template)
return template
def transform2(self, template):
template = template.squeeze(0)
return template