forked from princeton-vl/pytorch_stacked_hourglass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
233 lines (194 loc) · 7.46 KB
/
test.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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import cv2
import torch
import tqdm
import os
import numpy as np
import h5py
import copy
from utils.group import HeatmapParser
import utils.img
import data.MPII.ref as ds
parser = HeatmapParser()
def post_process(det, mat_, trainval, c=None, s=None, resolution=None):
mat = np.linalg.pinv(np.array(mat_).tolist() + [[0,0,1]])[:2]
res = det.shape[1:3]
cropped_preds = parser.parse(np.float32([det]))[0]
if len(cropped_preds) > 0:
cropped_preds[:,:,:2] = utils.img.kpt_affine(cropped_preds[:,:,:2] * 4, mat) #size 1x16x3
preds = np.copy(cropped_preds)
##for inverting predictions from input res on cropped to original image
if trainval != 'cropped':
for j in range(preds.shape[1]):
preds[0,j,:2] = utils.img.transform(preds[0,j,:2], c, s, resolution, invert=1)
return preds
def inference(img, func, config, c, s):
"""
forward pass at test time
calls post_process to post process results
"""
height, width = img.shape[0:2]
center = (width/2, height/2)
scale = max(height, width)/200
res = (config['train']['input_res'], config['train']['input_res'])
mat_ = utils.img.get_transform(center, scale, res)[:2]
inp = img/255
def array2dict(tmp):
return {
'det': tmp[0][:,:,:16],
}
tmp1 = array2dict(func([inp]))
tmp2 = array2dict(func([inp[:,::-1]]))
tmp = {}
for ii in tmp1:
tmp[ii] = np.concatenate((tmp1[ii], tmp2[ii]),axis=0)
det = tmp['det'][0, -1] + tmp['det'][1, -1, :, :, ::-1][ds.flipped_parts['mpii']]
if det is None:
return [], []
det = det/2
det = np.minimum(det, 1)
return post_process(det, mat_, 'valid', c, s, res)
def mpii_eval(pred, gt, normalizing, num_train, bound=0.5):
"""
Use PCK with threshold of .5 of normalized distance (presumably head size)
"""
correct = {'all': {'total': 0, 'ankle': 0, 'knee': 0, 'hip': 0, 'pelvis': 0,
'thorax': 0, 'neck': 0, 'head': 0, 'wrist': 0, 'elbow': 0,
'shoulder': 0},
'visible': {'total': 0, 'ankle': 0, 'knee': 0, 'hip': 0, 'pelvis': 0,
'thorax': 0, 'neck': 0, 'head': 0, 'wrist': 0, 'elbow': 0,
'shoulder': 0},
'not visible': {'total': 0, 'ankle': 0, 'knee': 0, 'hip': 0, 'pelvis': 0,
'thorax': 0, 'neck': 0, 'head': 0, 'wrist': 0, 'elbow': 0,
'shoulder': 0}}
count = copy.deepcopy(correct)
correct_train = copy.deepcopy(correct)
count_train = copy.deepcopy(correct)
idx = 0
for p, g, normalize in zip(pred, gt, normalizing):
for j in range(g.shape[1]):
vis = 'visible'
if g[0,j,0] == 0: ## not in picture!
continue
if g[0,j,2] == 0:
vis = 'not visible'
joint = 'ankle'
if j==1 or j==4:
joint = 'knee'
elif j==2 or j==3:
joint = 'hip'
elif j==6:
joint = 'pelvis'
elif j==7:
joint = 'thorax'
elif j==8:
joint = 'neck'
elif j==9:
joint = 'head'
elif j==10 or j==15:
joint = 'wrist'
elif j==11 or j==14:
joint = 'elbow'
elif j==12 or j==13:
joint = 'shoulder'
if idx >= num_train:
count['all']['total'] += 1
count['all'][joint] += 1
count[vis]['total'] += 1
count[vis][joint] += 1
else:
count_train['all']['total'] += 1
count_train['all'][joint] += 1
count_train[vis]['total'] += 1
count_train[vis][joint] += 1
error = np.linalg.norm(p[0]['keypoints'][j,:2]-g[0,j,:2]) / normalize
if idx >= num_train:
if bound > error:
correct['all']['total'] += 1
correct['all'][joint] += 1
correct[vis]['total'] += 1
correct[vis][joint] += 1
else:
if bound > error:
correct_train['all']['total'] += 1
correct_train['all'][joint] += 1
correct_train[vis]['total'] += 1
correct_train[vis][joint] += 1
idx += 1
## breakdown by validation set / training set
for k in correct:
print(k, ':')
for key in correct[k]:
print('Val PCK @,', bound, ',', key, ':', round(correct[k][key] / max(count[k][key],1), 3), ', count:', count[k][key])
print('Tra PCK @,', bound, ',', key, ':', round(correct_train[k][key] / max(count_train[k][key],1), 3), ', count:', count_train[k][key])
print('\n')
def get_img(config, num_eval=2958, num_train=300):
'''
Load validation and training images
'''
input_res = config['train']['input_res']
output_res = config['train']['output_res']
val_f = h5py.File(os.path.join(ds.annot_dir, 'valid.h5'), 'r')
tr = tqdm.tqdm( range(0, num_train), total = num_train )
## training
train_f = h5py.File(os.path.join(ds.annot_dir, 'train.h5') ,'r')
for i in tr:
path_t = '%s/%s' % (ds.img_dir, train_f['imgname'][i].decode('UTF-8'))
## img
orig_img = cv2.imread(path_t)[:,:,::-1]
c = train_f['center'][i]
s = train_f['scale'][i]
im = utils.img.crop(orig_img, c, s, (input_res, input_res))
## kp
kp = train_f['part'][i]
vis = train_f['visible'][i]
kp2 = np.insert(kp, 2, vis, axis=1)
kps = np.zeros((1, 16, 3))
kps[0] = kp2
## normalize (to make errors more fair on high pixel imgs)
n = train_f['normalize'][i]
yield kps, im, c, s, n
tr2 = tqdm.tqdm( range(0, num_eval), total = num_eval )
## validation
for i in tr2:
path_t = '%s/%s' % (ds.img_dir, val_f['imgname'][i].decode('UTF-8'))
## img
orig_img = cv2.imread(path_t)[:,:,::-1]
c = val_f['center'][i]
s = val_f['scale'][i]
im = utils.img.crop(orig_img, c, s, (input_res, input_res))
## kp
kp = val_f['part'][i]
vis = val_f['visible'][i]
kp2 = np.insert(kp, 2, vis, axis=1)
kps = np.zeros((1, 16, 3))
kps[0] = kp2
## normalize (to make errors more fair on high pixel imgs)
n = val_f['normalize'][i]
yield kps, im, c, s, n
def main():
from train import init
func, config = init()
def runner(imgs):
return func(0, config, 'inference', imgs=torch.Tensor(np.float32(imgs)))['preds']
def do(img, c, s):
ans = inference(img, runner, config, c, s)
if len(ans) > 0:
ans = ans[:,:,:3]
## ans has shape N,16,3 (num preds, joints, x/y/visible)
pred = []
for i in range(ans.shape[0]):
pred.append({'keypoints': ans[i,:,:]})
return pred
gts = []
preds = []
normalizing = []
num_eval = config['inference']['num_eval']
num_train = config['inference']['train_num_eval']
for anns, img, c, s, n in get_img(config, num_eval, num_train):
gts.append(anns)
pred = do(img, c, s)
preds.append(pred)
normalizing.append(n)
mpii_eval(preds, gts, normalizing, num_train)
if __name__ == '__main__':
main()