-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinference_pixel_attention_1.py
185 lines (152 loc) · 7.3 KB
/
inference_pixel_attention_1.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
178
179
180
181
182
183
184
185
import os
import argparse
import jittor as jt
import jittor.nn as nn
jt.flags.use_cuda = 1
import numpy as np
from tqdm import tqdm
import jittor.transform as transforms
from PIL import Image
import src.resnet as resnet_model
from src.singlecropdataset import InferImageFolder
from src.utils import bool_flag
import cv2
import copy
def parse_args():
parser = argparse.ArgumentParser(description="Inference")
parser.add_argument("--mode", type=str, required=True)
parser.add_argument("--dump_path", type=str, default=None, help="The path to save results.")
parser.add_argument("--dump_path_1", type=str, default=None, help="The path to save results.")
parser.add_argument("--testPoint_path", type=str, default=None, help="The path to save results.")
parser.add_argument("--testLabel_path", type=str, default=None, help="The path to save results.")
parser.add_argument("--data_path", type=str, default=None, help="The path to ImagenetS dataset.")
parser.add_argument("--pretrained", type=str, default=None, help="The model checkpoint file.")
parser.add_argument("-a", "--arch", metavar="ARCH", help="The model architecture.")
parser.add_argument("-c", "--num-classes", default=50, type=int, help="The number of classes.")
parser.add_argument("-t", "--threshold", default=0, type=float,
help="The threshold to filter the 'others' categroies.")
parser.add_argument("--test", action='store_true',
help="whether to save the logit. Enabled when finding the best threshold.")
parser.add_argument("--centroid", type=str, default=None, help="The centroids of clustering.")
parser.add_argument("--checkpoint_key", type=str, default='state_dict', help="key of model in checkpoint")
args = parser.parse_args()
return args
def main_worker(args):
centroids = np.load(args.centroid)
centroids = jt.array(centroids)
centroids = jt.normalize(centroids, dim=1, p=2)
# build model
if 'resnet' in args.arch:
model = resnet_model.__dict__[args.arch](hidden_mlp=0, output_dim=0, nmb_prototypes=0, train_mode='pixelattn')
else:
raise NotImplementedError()
checkpoint = jt.load(args.pretrained)[args.checkpoint_key]
for k in list(checkpoint.keys()):
if k.startswith('module.'):
checkpoint[k[len('module.'):]] = checkpoint[k]
del checkpoint[k]
k = k[len('module.'):]
if k not in model.state_dict().keys():
del checkpoint[k]
model.load_state_dict(checkpoint)
print("=> loaded model '{}'".format(args.pretrained))
model.eval()
# build dataset
data_path = os.path.join(args.data_path, args.mode)
# data_path = args.data_path
normalize = transforms.ImageNormalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
dataset = InferImageFolder(
root=data_path,
transform=transforms.Compose(
[
transforms.Resize(256),
transforms.ToTensor(),
normalize,
]
),
num_gpus=jt.world_size
)
dataloader = dataset.set_attrs(
batch_size=jt.world_size, num_workers=16, drop_last=False, shuffle=False
)
dump_path = os.path.join(args.dump_path, args.mode)
dump_path_1 = os.path.join(args.dump_path_1, args.mode)
if not jt.in_mpi or (jt.in_mpi and jt.rank == 0):
for cate in os.listdir(data_path):
if not os.path.exists(os.path.join(dump_path, cate)):
os.makedirs(os.path.join(dump_path, cate))
if not os.path.exists(os.path.join(dump_path_1, cate )):
os.makedirs(os.path.join(dump_path_1, cate))
# testPoint_path = args.testPoint_path
# testLabel_path = args.testLabel_path
for images, path, height, width in tqdm(dataloader):
path = path[0]
cate = path.split("/")[-2]
name = path.split("/")[-1].split(".")[0]
with jt.no_grad():
h = height.item()
w = width.item()
out, mask = model(images, mode='inference_pixel_attention')
mask = nn.upsample(mask, (h, w), mode="bilinear", align_corners=False).squeeze(0).squeeze(0)
out = jt.normalize(out, dim=1, p=2)
B, C, H, W = out.shape
out = out.view(B, C, -1).permute(0, 2, 1).contiguous().view(-1, C)
cosine = jt.matmul(out, centroids.t())
cosine = cosine.view(1, H, W, args.num_classes).permute(0, 3, 1, 2)
#cosine最大点坐标
l = np.unravel_index(np.argmax(cosine), cosine.shape)
logit = mask
prediction = jt.argmax(cosine, dim=1, keepdims=True)[0] + 1
out1 = jt.argmax(cosine, dim=1, keepdims=True)[0] + 1
out2 = jt.argmax(cosine, dim=1, keepdims=True)[1]
# with open(testLabel_path, 'a') as f:
# f.write(str(path)+' '+str(l[1])+ '\n')
prediction = nn.interpolate(prediction.float(), (h, w), mode="nearest").squeeze(0).squeeze(0)
out1 = nn.interpolate(out1.float(), (h, w), mode="nearest").squeeze(0).squeeze(0)
out2 = nn.interpolate(out2.float(), (h, w), mode="nearest").squeeze(0).squeeze(0)
prediction[logit < args.threshold] = 0
out1[logit < args.threshold] = 0
result = []
# label = -1000
for i in range(1, 51):
result.append(out2[out1 == i].mean())
if max(result) <= 0:
label = -2
else:
label = result.index(max(result))
with open(args.testLabel_path, 'a') as f:
f.write(os.path.join(cate, name + '.JPEG') + ' ' + str(label) + '\n')
res = jt.zeros((prediction.shape[0], prediction.shape[1], 3))
res[:, :, 0] = prediction % 256
# print(res[:, :, 0])
res[:, :, 1] = prediction // 256
res = res.cpu().numpy()
logit = logit.cpu().numpy()
# images = images.cpu.numpy()
# print(logit.shape)
# print(np.max(logit))
# r, c = np.where(logit == np.max(logit))
# print(r, c)
h,l = np.unravel_index(logit.argmax(), logit.shape)
# print(h,l)
img = cv2.imread(os.path.join(data_path,cate, name + ".JPEG"))
# ret, res_1 = cv2.threshold(res_1, 1, 255, cv2.THRESH_BINARY)
cv2.circle(img, (l,h), 5, (255, 255, 0), 2)
cv2.imwrite(os.path.join(dump_path_1, cate, name + ".png"),img)
# filename = str(path).split('/')
# print(filename[-2:])
with open(args.testPoint_path, 'a') as f:
f.write(cate+'/'+name+'.JPEG'+' '+str(l) + ','+ str(h) + '\n')
#str(os.path.join(data_path,cate, name + ".JPEG"))
res = Image.fromarray(res.astype(np.uint8))
res.save(os.path.join(dump_path, cate, name + ".png"))
if args.test:
np.save(os.path.join(dump_path, cate, name + ".npy"), logit)
jt.clean_graph()
jt.sync_all()
jt.gc()
if __name__ == "__main__":
args = parse_args()
main_worker(args=args)