File size: 12,309 Bytes
d7a991a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import pickle
import shutil
from os.path import join

import cv2
import h5py
import mmcv
import numpy as np
from scipy.io import loadmat

train_subjects = [i for i in range(1, 9)]
test_subjects = [i for i in range(1, 7)]
train_seqs = [1, 2]
train_cams = [0, 1, 2, 4, 5, 6, 7, 8]
train_frame_nums = {
    (1, 1): 6416,
    (1, 2): 12430,
    (2, 1): 6502,
    (2, 2): 6081,
    (3, 1): 12488,
    (3, 2): 12283,
    (4, 1): 6171,
    (4, 2): 6675,
    (5, 1): 12820,
    (5, 2): 12312,
    (6, 1): 6188,
    (6, 2): 6145,
    (7, 1): 6239,
    (7, 2): 6320,
    (8, 1): 6468,
    (8, 2): 6054
}
test_frame_nums = {1: 6151, 2: 6080, 3: 5838, 4: 6007, 5: 320, 6: 492}
train_img_size = (2048, 2048)
root_index = 14
joints_17 = [7, 5, 14, 15, 16, 9, 10, 11, 23, 24, 25, 18, 19, 20, 4, 3, 6]


def get_pose_stats(kps):
    """Get statistic information `mean` and `std` of pose data.

    Args:
        kps (ndarray): keypoints in shape [..., K, C] where K and C is
            the keypoint category number and dimension.
    Returns:
        mean (ndarray): [K, C]
    """
    assert kps.ndim > 2
    K, C = kps.shape[-2:]
    kps = kps.reshape(-1, K, C)
    mean = kps.mean(axis=0)
    std = kps.std(axis=0)
    return mean, std


def get_annotations(joints_2d, joints_3d, scale_factor=1.2):
    """Get annotations, including centers, scales, joints_2d and joints_3d.

    Args:
        joints_2d: 2D joint coordinates in shape [N, K, 2], where N is the
            frame number, K is the joint number.
        joints_3d: 3D joint coordinates in shape [N, K, 3], where N is the
            frame number, K is the joint number.
        scale_factor: Scale factor of bounding box. Default: 1.2.
    Returns:
        centers (ndarray): [N, 2]
        scales (ndarray): [N,]
        joints_2d (ndarray): [N, K, 3]
        joints_3d (ndarray): [N, K, 4]
    """
    # calculate joint visibility
    visibility = (joints_2d[:, :, 0] >= 0) * \
                 (joints_2d[:, :, 0] < train_img_size[0]) * \
                 (joints_2d[:, :, 1] >= 0) * \
                 (joints_2d[:, :, 1] < train_img_size[1])
    visibility = np.array(visibility, dtype=np.float32)[:, :, None]
    joints_2d = np.concatenate([joints_2d, visibility], axis=-1)
    joints_3d = np.concatenate([joints_3d, visibility], axis=-1)

    # calculate bounding boxes
    bboxes = np.stack([
        np.min(joints_2d[:, :, 0], axis=1),
        np.min(joints_2d[:, :, 1], axis=1),
        np.max(joints_2d[:, :, 0], axis=1),
        np.max(joints_2d[:, :, 1], axis=1)
    ],
                      axis=1)
    centers = np.stack([(bboxes[:, 0] + bboxes[:, 2]) / 2,
                        (bboxes[:, 1] + bboxes[:, 3]) / 2],
                       axis=1)
    scales = scale_factor * np.max(bboxes[:, 2:] - bboxes[:, :2], axis=1) / 200

    return centers, scales, joints_2d, joints_3d


def load_trainset(data_root, out_dir):
    """Load training data, create annotation file and camera file.
    Args:
        data_root: Directory of dataset, which is organized in the following
            hierarchy:
                data_root
                |-- train
                    |-- S1
                        |-- Seq1
                        |-- Seq2
                    |-- S2
                    |-- ...
                |-- test
                    |-- TS1
                    |-- TS2
                    |-- ...
        out_dir: Directory to save annotation file.
    """
    _imgnames = []
    _centers = []
    _scales = []
    _joints_2d = []
    _joints_3d = []
    cameras = {}

    img_dir = join(out_dir, 'images')
    os.makedirs(img_dir, exist_ok=True)
    annot_dir = join(out_dir, 'annotations')
    os.makedirs(annot_dir, exist_ok=True)

    for subj in train_subjects:
        for seq in train_seqs:
            seq_path = join(data_root, 'train', f'S{subj}', f'Seq{seq}')
            num_frames = train_frame_nums[(subj, seq)]

            # load camera parametres
            camera_file = join(seq_path, 'camera.calibration')
            with open(camera_file, 'r') as fin:
                lines = fin.readlines()
                for cam in train_cams:
                    K = [float(s) for s in lines[cam * 7 + 5][11:-2].split()]
                    f = np.array([[K[0]], [K[5]]])
                    c = np.array([[K[2]], [K[6]]])
                    RT = np.array(
                        [float(s) for s in lines[cam * 7 + 6][11:-2].split()])
                    RT = np.reshape(RT, (4, 4))
                    R = RT[:3, :3]
                    # convert unit from millimeter to meter
                    T = RT[:3, 3:] * 0.001
                    size = [int(s) for s in lines[cam * 7 + 3][14:].split()]
                    w, h = size
                    cam_param = dict(
                        R=R, T=T, c=c, f=f, w=w, h=h, name=f'train_cam_{cam}')
                    cameras[f'S{subj}_Seq{seq}_Cam{cam}'] = cam_param

            # load annotations
            annot_file = os.path.join(seq_path, 'annot.mat')
            annot2 = loadmat(annot_file)['annot2']
            annot3 = loadmat(annot_file)['annot3']
            for cam in train_cams:
                # load 2D and 3D annotations
                joints_2d = np.reshape(annot2[cam][0][:num_frames],
                                       (num_frames, 28, 2))[:, joints_17]
                joints_3d = np.reshape(annot3[cam][0][:num_frames],
                                       (num_frames, 28, 3))[:, joints_17]
                joints_3d = joints_3d * 0.001
                centers, scales, joints_2d, joints_3d = get_annotations(
                    joints_2d, joints_3d)
                _centers.append(centers)
                _scales.append(scales)
                _joints_2d.append(joints_2d)
                _joints_3d.append(joints_3d)

                # extract frames from video
                video_path = join(seq_path, 'imageSequence',
                                  f'video_{cam}.avi')
                video = mmcv.VideoReader(video_path)
                for i in mmcv.track_iter_progress(range(num_frames)):
                    img = video.read()
                    if img is None:
                        break
                    imgname = f'S{subj}_Seq{seq}_Cam{cam}_{i+1:06d}.jpg'
                    _imgnames.append(imgname)
                    cv2.imwrite(join(img_dir, imgname), img)

    _imgnames = np.array(_imgnames)
    _centers = np.concatenate(_centers)
    _scales = np.concatenate(_scales)
    _joints_2d = np.concatenate(_joints_2d)
    _joints_3d = np.concatenate(_joints_3d)

    out_file = join(annot_dir, 'mpi_inf_3dhp_train.npz')
    np.savez(
        out_file,
        imgname=_imgnames,
        center=_centers,
        scale=_scales,
        part=_joints_2d,
        S=_joints_3d)
    print(f'Create annotation file for trainset: {out_file}. '
          f'{len(_imgnames)} samples in total.')

    out_file = join(annot_dir, 'cameras_train.pkl')
    with open(out_file, 'wb') as fout:
        pickle.dump(cameras, fout)
    print(f'Create camera file for trainset: {out_file}.')

    # get `mean` and `std` of pose data
    _joints_3d = _joints_3d[..., :3]  # remove visibility
    mean_3d, std_3d = get_pose_stats(_joints_3d)

    _joints_2d = _joints_2d[..., :2]  # remove visibility
    mean_2d, std_2d = get_pose_stats(_joints_2d)

    # centered around root
    _joints_3d_rel = _joints_3d - _joints_3d[..., root_index:root_index + 1, :]
    mean_3d_rel, std_3d_rel = get_pose_stats(_joints_3d_rel)
    mean_3d_rel[root_index] = mean_3d[root_index]
    std_3d_rel[root_index] = std_3d[root_index]

    _joints_2d_rel = _joints_2d - _joints_2d[..., root_index:root_index + 1, :]
    mean_2d_rel, std_2d_rel = get_pose_stats(_joints_2d_rel)
    mean_2d_rel[root_index] = mean_2d[root_index]
    std_2d_rel[root_index] = std_2d[root_index]

    stats = {
        'joint3d_stats': {
            'mean': mean_3d,
            'std': std_3d
        },
        'joint2d_stats': {
            'mean': mean_2d,
            'std': std_2d
        },
        'joint3d_rel_stats': {
            'mean': mean_3d_rel,
            'std': std_3d_rel
        },
        'joint2d_rel_stats': {
            'mean': mean_2d_rel,
            'std': std_2d_rel
        }
    }
    for name, stat_dict in stats.items():
        out_file = join(annot_dir, f'{name}.pkl')
        with open(out_file, 'wb') as f:
            pickle.dump(stat_dict, f)
        print(f'Create statistic data file: {out_file}')


def load_testset(data_root, out_dir, valid_only=True):
    """Load testing data, create annotation file and camera file.

    Args:
        data_root: Directory of dataset.
        out_dir: Directory to save annotation file.
        valid_only: Only keep frames with valid_label == 1.
    """
    _imgnames = []
    _centers = []
    _scales = []
    _joints_2d = []
    _joints_3d = []
    cameras = {}

    img_dir = join(out_dir, 'images')
    os.makedirs(img_dir, exist_ok=True)
    annot_dir = join(out_dir, 'annotations')
    os.makedirs(annot_dir, exist_ok=True)

    for subj in test_subjects:
        subj_path = join(data_root, 'test', f'TS{subj}')
        num_frames = test_frame_nums[subj]

        # load annotations
        annot_file = os.path.join(subj_path, 'annot_data.mat')
        with h5py.File(annot_file, 'r') as fin:
            annot2 = np.array(fin['annot2']).reshape((-1, 17, 2))
            annot3 = np.array(fin['annot3']).reshape((-1, 17, 3))
            valid = np.array(fin['valid_frame']).reshape(-1)

        # manually estimate camera intrinsics
        fx, cx = np.linalg.lstsq(
            annot3[:, :, [0, 2]].reshape((-1, 2)),
            (annot2[:, :, 0] * annot3[:, :, 2]).reshape(-1, 1),
            rcond=None)[0].flatten()
        fy, cy = np.linalg.lstsq(
            annot3[:, :, [1, 2]].reshape((-1, 2)),
            (annot2[:, :, 1] * annot3[:, :, 2]).reshape(-1, 1),
            rcond=None)[0].flatten()
        if subj <= 4:
            w, h = 2048, 2048
        else:
            w, h = 1920, 1080
        cameras[f'TS{subj}'] = dict(
            c=np.array([[cx], [cy]]),
            f=np.array([[fx], [fy]]),
            w=w,
            h=h,
            name=f'test_cam_{subj}')

        # get annotations
        if valid_only:
            valid_frames = np.nonzero(valid)[0]
        else:
            valid_frames = np.arange(num_frames)
        joints_2d = annot2[valid_frames, :, :]
        joints_3d = annot3[valid_frames, :, :] * 0.001

        centers, scales, joints_2d, joints_3d = get_annotations(
            joints_2d, joints_3d)
        _centers.append(centers)
        _scales.append(scales)
        _joints_2d.append(joints_2d)
        _joints_3d.append(joints_3d)

        # copy and rename images
        for i in valid_frames:
            imgname = f'TS{subj}_{i+1:06d}.jpg'
            shutil.copyfile(
                join(subj_path, 'imageSequence', f'img_{i+1:06d}.jpg'),
                join(img_dir, imgname))
            _imgnames.append(imgname)

    _imgnames = np.array(_imgnames)
    _centers = np.concatenate(_centers)
    _scales = np.concatenate(_scales)
    _joints_2d = np.concatenate(_joints_2d)
    _joints_3d = np.concatenate(_joints_3d)

    if valid_only:
        out_file = join(annot_dir, 'mpi_inf_3dhp_test_valid.npz')
    else:
        out_file = join(annot_dir, 'mpi_inf_3dhp_test_all.npz')
    np.savez(
        out_file,
        imgname=_imgnames,
        center=_centers,
        scale=_scales,
        part=_joints_2d,
        S=_joints_3d)
    print(f'Create annotation file for testset: {out_file}. '
          f'{len(_imgnames)} samples in total.')

    out_file = join(annot_dir, 'cameras_test.pkl')
    with open(out_file, 'wb') as fout:
        pickle.dump(cameras, fout)
    print(f'Create camera file for testset: {out_file}.')


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('data_root', type=str, help='data root')
    parser.add_argument(
        'out_dir', type=str, help='directory to save annotation files.')
    args = parser.parse_args()
    data_root = args.data_root
    out_dir = args.out_dir

    load_trainset(data_root, out_dir)
    load_testset(data_root, out_dir, valid_only=True)