-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathhuman36m.py
271 lines (214 loc) · 11.6 KB
/
human36m.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
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
import os
from collections import defaultdict
import pickle
import numpy as np
import cv2
import torch
from torch.utils.data import Dataset
from mvn.utils.multiview import Camera
from mvn.utils.img import get_square_bbox, resize_image, crop_image, normalize_image, scale_bbox
from mvn.utils import volumetric
class Human36MMultiViewDataset(Dataset):
"""
Human3.6M for multiview tasks.
"""
def __init__(self,
h36m_root='/Vol1/dbstore/datasets/Human3.6M/processed/',
labels_path='/Vol1/dbstore/datasets/Human3.6M/extra/human36m-multiview-labels-SSDbboxes.npy',
pred_results_path=None,
image_shape=(256, 256),
train=False,
test=False,
retain_every_n_frames_in_test=1,
with_damaged_actions=False,
cuboid_side=2000.0,
scale_bbox=1.5,
norm_image=True,
kind="mpii",
undistort_images=False,
ignore_cameras=[],
crop=True
):
"""
h36m_root:
Path to 'processed/' directory in Human3.6M
labels_path:
Path to 'human36m-multiview-labels.npy' generated by 'generate-labels-npy-multiview.py'
from https://github.sec.samsung.net/RRU8-VIOLET/human36m-preprocessing
retain_every_n_frames_test:
By default, there are 159 181 frames in training set and 26 634 in test (val) set.
With this parameter, test set frames will be evenly skipped frames so that the
test set size is `26634 // retain_every_n_frames_test`.
Use a value of 13 to get 2049 frames in test set.
with_damaged_actions:
If `True`, will include 'S9/[Greeting-2,SittingDown-2,Waiting-1]' in test set.
kind:
Keypoint format, 'mpii' or 'human36m'
ignore_cameras:
A list with indices of cameras to exclude (0 to 3 inclusive)
"""
assert train or test, '`Human36MMultiViewDataset` must be constructed with at least ' \
'one of `test=True` / `train=True`'
assert kind in ("mpii", "human36m")
self.h36m_root = h36m_root
self.labels_path = labels_path
self.image_shape = None if image_shape is None else tuple(image_shape)
self.scale_bbox = scale_bbox
self.norm_image = norm_image
self.cuboid_side = cuboid_side
self.kind = kind
self.undistort_images = undistort_images
self.ignore_cameras = ignore_cameras
self.crop = crop
self.labels = np.load(labels_path, allow_pickle=True).item()
n_cameras = len(self.labels['camera_names'])
assert all(camera_idx in range(n_cameras) for camera_idx in self.ignore_cameras)
train_subjects = ['S1', 'S5', 'S6', 'S7', 'S8']
test_subjects = ['S9', 'S11']
train_subjects = list(self.labels['subject_names'].index(x) for x in train_subjects)
test_subjects = list(self.labels['subject_names'].index(x) for x in test_subjects)
indices = []
if train:
mask = np.isin(self.labels['table']['subject_idx'], train_subjects, assume_unique=True)
indices.append(np.nonzero(mask)[0])
if test:
mask = np.isin(self.labels['table']['subject_idx'], test_subjects, assume_unique=True)
if not with_damaged_actions:
mask_S9 = self.labels['table']['subject_idx'] == self.labels['subject_names'].index('S9')
damaged_actions = 'Greeting-2', 'SittingDown-2', 'Waiting-1'
damaged_actions = [self.labels['action_names'].index(x) for x in damaged_actions]
mask_damaged_actions = np.isin(self.labels['table']['action_idx'], damaged_actions)
mask &= ~(mask_S9 & mask_damaged_actions)
indices.append(np.nonzero(mask)[0][::retain_every_n_frames_in_test])
self.labels['table'] = self.labels['table'][np.concatenate(indices)]
self.num_keypoints = 16 if kind == "mpii" else 17
assert self.labels['table']['keypoints'].shape[1] == 17, "Use a newer 'labels' file"
self.keypoints_3d_pred = None
if pred_results_path is not None:
pred_results = np.load(pred_results_path, allow_pickle=True)
keypoints_3d_pred = pred_results['keypoints_3d'][np.argsort(pred_results['indexes'])]
self.keypoints_3d_pred = keypoints_3d_pred[::retain_every_n_frames_in_test]
assert len(self.keypoints_3d_pred) == len(self)
def __len__(self):
return len(self.labels['table'])
def __getitem__(self, idx):
sample = defaultdict(list) # return value
shot = self.labels['table'][idx]
subject = self.labels['subject_names'][shot['subject_idx']]
action = self.labels['action_names'][shot['action_idx']]
frame_idx = shot['frame_idx']
for camera_idx, camera_name in enumerate(self.labels['camera_names']):
if camera_idx in self.ignore_cameras:
continue
# load bounding box
bbox = shot['bbox_by_camera_tlbr'][camera_idx][[1,0,3,2]] # TLBR to LTRB
bbox_height = bbox[2] - bbox[0]
if bbox_height == 0:
# convention: if the bbox is empty, then this view is missing
continue
# scale the bounding box
bbox = scale_bbox(bbox, self.scale_bbox)
# load image
image_path = os.path.join(
self.h36m_root, subject, action, 'imageSequence' + '-undistorted' * self.undistort_images,
camera_name, 'img_%06d.jpg' % (frame_idx+1))
assert os.path.isfile(image_path), '%s doesn\'t exist' % image_path
image = cv2.imread(image_path)
# load camera
shot_camera = self.labels['cameras'][shot['subject_idx'], camera_idx]
retval_camera = Camera(shot_camera['R'], shot_camera['t'], shot_camera['K'], shot_camera['dist'], camera_name)
if self.crop:
# crop image
image = crop_image(image, bbox)
retval_camera.update_after_crop(bbox)
if self.image_shape is not None:
# resize
image_shape_before_resize = image.shape[:2]
image = resize_image(image, self.image_shape)
retval_camera.update_after_resize(image_shape_before_resize, self.image_shape)
sample['image_shapes_before_resize'].append(image_shape_before_resize)
if self.norm_image:
image = normalize_image(image)
sample['images'].append(image)
sample['detections'].append(bbox + (1.0,)) # TODO add real confidences
sample['cameras'].append(retval_camera)
sample['proj_matrices'].append(retval_camera.projection)
# 3D keypoints
# add dummy confidences
sample['keypoints_3d'] = np.pad(
shot['keypoints'][:self.num_keypoints],
((0,0), (0,1)), 'constant', constant_values=1.0)
# build cuboid
# base_point = sample['keypoints_3d'][6, :3]
# sides = np.array([self.cuboid_side, self.cuboid_side, self.cuboid_side])
# position = base_point - sides / 2
# sample['cuboids'] = volumetric.Cuboid3D(position, sides)
# save sample's index
sample['indexes'] = idx
if self.keypoints_3d_pred is not None:
sample['pred_keypoints_3d'] = self.keypoints_3d_pred[idx]
sample.default_factory = None
return sample
def evaluate_using_per_pose_error(self, per_pose_error, split_by_subject):
def evaluate_by_actions(self, per_pose_error, mask=None):
if mask is None:
mask = np.ones_like(per_pose_error, dtype=bool)
action_scores = {
'Average': {'total_loss': per_pose_error[mask].sum(), 'frame_count': np.count_nonzero(mask)}
}
for action_idx in range(len(self.labels['action_names'])):
action_mask = (self.labels['table']['action_idx'] == action_idx) & mask
action_per_pose_error = per_pose_error[action_mask]
action_scores[self.labels['action_names'][action_idx]] = {
'total_loss': action_per_pose_error.sum(), 'frame_count': len(action_per_pose_error)
}
action_names_without_trials = \
[name[:-2] for name in self.labels['action_names'] if name.endswith('-1')]
for action_name_without_trial in action_names_without_trials:
combined_score = {'total_loss': 0.0, 'frame_count': 0}
for trial in 1, 2:
action_name = '%s-%d' % (action_name_without_trial, trial)
combined_score['total_loss' ] += action_scores[action_name]['total_loss']
combined_score['frame_count'] += action_scores[action_name]['frame_count']
del action_scores[action_name]
action_scores[action_name_without_trial] = combined_score
for k, v in action_scores.items():
action_scores[k] = v['total_loss'] / v['frame_count']
return action_scores
subject_scores = {
'Average': evaluate_by_actions(self, per_pose_error)
}
for subject_idx in range(len(self.labels['subject_names'])):
subject_mask = self.labels['table']['subject_idx'] == subject_idx
subject_scores[self.labels['subject_names'][subject_idx]] = \
evaluate_by_actions(self, per_pose_error, subject_mask)
return subject_scores
def evaluate(self, keypoints_3d_predicted, split_by_subject=False, transfer_cmu_to_human36m=False, transfer_human36m_to_human36m=False):
keypoints_gt = self.labels['table']['keypoints'][:, :self.num_keypoints]
if keypoints_3d_predicted.shape != keypoints_gt.shape:
raise ValueError(
'`keypoints_3d_predicted` shape should be %s, got %s' % \
(keypoints_gt.shape, keypoints_3d_predicted.shape))
if transfer_cmu_to_human36m or transfer_human36m_to_human36m:
human36m_joints = [10, 11, 15, 14, 1, 4]
if transfer_human36m_to_human36m:
cmu_joints = [10, 11, 15, 14, 1, 4]
else:
cmu_joints = [10, 8, 9, 7, 14, 13]
keypoints_gt = keypoints_gt[:, human36m_joints]
keypoints_3d_predicted = keypoints_3d_predicted[:, cmu_joints]
# mean error per 16/17 joints in mm, for each pose
per_pose_error = np.sqrt(((keypoints_gt - keypoints_3d_predicted) ** 2).sum(2)).mean(1)
# relative mean error per 16/17 joints in mm, for each pose
if not (transfer_cmu_to_human36m or transfer_human36m_to_human36m):
root_index = 6 if self.kind == "mpii" else 6
else:
root_index = 0
keypoints_gt_relative = keypoints_gt - keypoints_gt[:, root_index:root_index + 1, :]
keypoints_3d_predicted_relative = keypoints_3d_predicted - keypoints_3d_predicted[:, root_index:root_index + 1, :]
per_pose_error_relative = np.sqrt(((keypoints_gt_relative - keypoints_3d_predicted_relative) ** 2).sum(2)).mean(1)
result = {
'per_pose_error': self.evaluate_using_per_pose_error(per_pose_error, split_by_subject),
'per_pose_error_relative': self.evaluate_using_per_pose_error(per_pose_error_relative, split_by_subject)
}
return result['per_pose_error_relative']['Average']['Average'], result