-
Notifications
You must be signed in to change notification settings - Fork 0
/
vehicle_ReID_customData.py
177 lines (133 loc) · 6.12 KB
/
vehicle_ReID_customData.py
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
import numpy as np
import pandas as pd
import os
import random
import torch
from torchvision import transforms
from PIL import Image
from vehicle_reid_repo.vehicle_reid.load_model import load_model_from_opts
import matplotlib.pyplot as plt
VRIC = "../data/VRIC/"
#DATA_ROOT = "../data/" <-- originaalais
DATA_ROOT = "cropped/"
#TXT anotaciju failu parversana uz CSV (tikai imdir un vehicle ID laukus atstaj)
# def txt_labels_to_csv(txt_path, out_path, img_dir):
# df = pd.read_csv(txt_path, sep=" ")
# df.columns = ["path", "id", "cam"]
# df = df[["path", "id"]]
# df["path"] = df["path"].apply(lambda x: os.path.join(img_dir, x))
# df.to_csv(out_path, index=False)
# txt_labels_to_csv(VRIC + "vric_gallery.txt", VRIC + "vric_gallery.csv", "VRIC/gallery_images/")
# txt_labels_to_csv(VRIC + "vric_probe.txt", VRIC + "vric_query.csv", "VRIC/probe_images/")
#TXT anotaciju failu parversana uz CSV un sadalisana test un validation datasetos (tikai imdir un vehicle ID laukus atstaj)
# def train_data_split_and_to_csv(train_ann, train_out_path, val_out_path, img_dir):
# df = pd.read_csv(train_ann, sep=" ")
# df.columns = ["path", "id", "cam"]
# df = df[["path", "id"]]
# df["path"] = df["path"].apply(lambda x: os.path.join(img_dir, x))
# random.seed(42)
# train_size = int(0.75 * len(df))
# val_size = len(df) - train_size
# val_idxes = random.sample(range(len(df)), val_size)
# train_idxes = list(set(range(len(df))) - set(val_idxes))
# train_df, val_df = df.loc[train_idxes], df.loc[val_idxes]
# train_df.to_csv(train_out_path, index=False)
# val_df.to_csv(val_out_path, index=False)
# train_data_split_and_to_csv(VRIC + "vric_train.txt", VRIC + "vric_train.csv", VRIC + "vric_val.csv", "VRIC/train_images/")
device = "cuda"
model = load_model_from_opts("vehicle_reid_repo/vehicle_reid/model/result/opts.yaml", ckpt="vehicle_reid_repo/vehicle_reid/model/result/net_19.pth", remove_classifier=True)
model.eval()
model.to(device)
# X = torch.randn(32, 3, 224, 224).to(device)
# X = model(X)
# print(X.shape)
random.seed(0) #420
QUERIED_IMAGE = 1
#Image transforms probably adapted from vehicle Re-ID model code
data_transforms = transforms.Compose([
transforms.Resize((224, 224), interpolation=3),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
#Selecting a random query image
#query_df = pd.read_csv(DATA_ROOT + "VRIC/vric_query.csv") <---- originaaalais
query_df = pd.read_csv(DATA_ROOT + "scene2/3jpg.csv")
query_path, query_label = query_df.loc[QUERIED_IMAGE]
query_image = Image.open(DATA_ROOT + query_path)
X_query = torch.unsqueeze(data_transforms(query_image), 0).to(device)
#print(X_query.shape)
#Ielasam gallery datafailu
#gallery_df = pd.read_csv(DATA_ROOT + "VRIC/vric_gallery.csv") <---- originaaalais
gallery_df = pd.read_csv(DATA_ROOT + "scene2/1jpg.csv")
# make sure we choose at least one with the same id as the query
same_id_idxes = list(gallery_df[gallery_df["id"] == query_label].index)[:4]
# choose the rest from negative ids
other_id_idxes = set(gallery_df[gallery_df["id"] != query_label].index)
other_id_idxes = random.sample(other_id_idxes - set(same_id_idxes), len(gallery_df) - len(same_id_idxes))
gallery_idxes = other_id_idxes + same_id_idxes
gallery_sample = [(x[1]["path"], x[1]["id"]) for x in gallery_df.loc[gallery_idxes].iterrows()]
#Create input from gallery images
gallery_images = [Image.open(DATA_ROOT + x) for x, _ in gallery_sample]
gallery_labels = [y for _, y in gallery_sample]
X_gallery = torch.stack(tuple(map(data_transforms, gallery_images))).to(device)
# print(X_gallery.shape)
def fliplr(img):
"""flip images horizontally in a batch"""
inv_idx = torch.arange(img.size(3) - 1, -1, -1).long()
inv_idx = inv_idx.to(img.device)
img_flip = img.index_select(3, inv_idx)
return img_flip
def extract_feature(model, X, device="cuda"):
"""Exract the embeddings of a single image tensor X"""
if len(X.shape) == 3:
X = torch.unsqueeze(X, 0)
X = X.to(device)
feature = model(X).reshape(-1)
X = fliplr(X)
flipped_feature = model(X).reshape(-1)
feature += flipped_feature
fnorm = torch.norm(feature, p=2)
return feature.div(fnorm)
def get_scores(query_feature, gallery_features):
"""Calculate the similarity scores of the query and gallery features"""
query = query_feature.view(-1, 1)
score = torch.mm(gallery_features, query)
score = score.squeeze(1).cpu()
score = score.numpy()
return score
f_query = extract_feature(model, X_query).detach().cpu()
f_gallery = [extract_feature(model, X) for X in X_gallery]
f_gallery = torch.stack(f_gallery).detach().cpu()
scores = get_scores(f_query, f_gallery)
print(scores)
reference_trans = transforms.Pad(4, (0, 0, 255)) # blue border for the image being compared to
good_trans = transforms.Pad(4, (0, 255, 0)) # green border
bad_trans = transforms.Pad(4, (255, 0, 0)) # red border
gallery_images = [img.resize((112, 112)) for img in gallery_images]
display_images = [(good_trans(img) if lab == query_label else bad_trans(img)) \
for img, lab in zip(gallery_images, gallery_labels)]
display_images = [display_images[i] for i in np.argsort(scores)[::-1]]
#Plot gallery images from the highest score to the lowest
import matplotlib.pyplot as plt
N_ROWS, N_COLS = 1, (display_images.__len__() +1) #4, 8
score_labels = scores[np.argsort(scores)[::-1]]
fig, axes = plt.subplots(N_ROWS, N_COLS, figsize=(12, 8)) #12,8
query_image = reference_trans(query_image.resize((112,112)))
axes[0].imshow(query_image)
for i in range(display_images.__len__()):
axes[i+1].imshow(display_images[i])
for i, ax in enumerate(axes.flat):
if(i > 0):
ax.set_xticks([])
ax.set_xticks([], minor=True)
ax.set_yticks([])
ax.set_yticks([], minor=True)
if(i-1 < score_labels.size):
ax.set_xlabel(str(round(score_labels[i-1], 3)))
for spine in [ax.spines.left, ax.spines.right, ax.spines.top, ax.spines.bottom]:
spine.set(visible=False)
plt.show()
# if out of memory issues arise, we come here to cleanup
import gc
gc.collect()
torch.cuda.empty_cache()