Spaces:
Sleeping
Sleeping
File size: 52,382 Bytes
d7e58f0 |
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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 |
import logging
import pickle
from enum import Enum
from math import ceil
from typing import Any, List, Optional, TypeVar, Union, overload
import numpy as np
import torch
from mmcv.utils import print_log
from detrsmpl.utils.path_utils import (
Existence,
check_path_existence,
check_path_suffix,
)
# In T = TypeVar('T'), T can be anything.
# See definition of typing.TypeVar for details.
_T1 = TypeVar('_T1')
_KT = TypeVar('_KT')
_VT = TypeVar('_VT')
_HumanData = TypeVar('_HumanData')
_CPU_DEVICE = torch.device('cpu')
_HumanData_SUPPORTED_KEYS = {
'image_path': {
'type': list,
},
'image_id': {
'type': list,
},
'bbox_xywh': {
'type': np.ndarray,
'shape': (-1, 5),
'dim': 0
},
'config': {
'type': str,
'dim': None
},
'keypoints2d': {
'type': np.ndarray,
'shape': (-1, -1, 3),
'dim': 0
},
'keypoints3d': {
'type': np.ndarray,
'shape': (-1, -1, 4),
'dim': 0
},
'smpl': {
'type': dict,
'slice_key': 'betas',
'dim': 0
},
'smplh': {
'type': dict,
'slice_key': 'betas',
'dim': 0
},
'smplx': {
'type': dict,
'slice_key': 'betas',
'dim': 0
},
'meta': {
'type': dict,
},
'keypoints2d_mask': {
'type': np.ndarray,
'shape': (-1, ),
'dim': None
},
'keypoints2d_convention': {
'type': str,
'dim': None
},
'keypoints3d_mask': {
'type': np.ndarray,
'shape': (-1, ),
'dim': None
},
'keypoints3d_convention': {
'type': str,
'dim': None
},
'vertices': {
'type': np.ndarray,
'shape': (-1, ),
'dim': None
},
'focal_length': {
'type': np.ndarray,
'shape': (-1, ),
'dim': 0
},
'principal_point': {
'type': np.ndarray,
'shape': (-1, ),
'dim': 0
},
'misc': {
'type': dict,
},
}
class _KeyCheck(Enum):
PASS = 0
WARN = 1
ERROR = 2
class HumanData(dict):
logger = None
SUPPORTED_KEYS = _HumanData_SUPPORTED_KEYS
WARNED_KEYS = []
def __new__(cls: _HumanData, *args: Any, **kwargs: Any) -> _HumanData:
"""New an instance of HumanData.
Args:
cls (HumanData): HumanData class.
Returns:
HumanData: An instance of HumanData.
"""
ret_human_data = super().__new__(cls, args, kwargs)
setattr(ret_human_data, '__data_len__', -1)
setattr(ret_human_data, '__key_strict__', False)
setattr(ret_human_data, '__keypoints_compressed__', False)
return ret_human_data
@classmethod
def set_logger(cls, logger: Union[logging.Logger, str, None] = None):
"""Set logger of HumanData class.
Args:
logger (logging.Logger | str | None, optional):
The way to print summary.
See `mmcv.utils.print_log()` for details.
Defaults to None.
"""
cls.logger = logger
@classmethod
def fromfile(cls, npz_path: str) -> _HumanData:
"""Construct a HumanData instance from an npz file.
Args:
npz_path (str):
Path to a dumped npz file.
Returns:
HumanData:
A HumanData instance load from file.
"""
ret_human_data = cls()
ret_human_data.load(npz_path)
return ret_human_data
@classmethod
def new(cls,
source_dict: dict = None,
key_strict: bool = False) -> _HumanData:
"""Construct a HumanData instance from a dict.
Args:
source_dict (dict, optional):
A dict with items in HumanData fashion.
Defaults to None.
key_strict (bool, optional):
Whether to raise error when setting unsupported keys.
Defaults to False.
Returns:
HumanData:
A HumanData instance.
"""
if source_dict is None:
ret_human_data = cls()
else:
ret_human_data = cls(source_dict)
ret_human_data.set_key_strict(key_strict)
return ret_human_data
def get_key_strict(self) -> bool:
"""Get value of attribute key_strict.
Returns:
bool:
Whether to raise error when setting unsupported keys.
"""
return self.__key_strict__
def set_key_strict(self, value: bool):
"""Set value of attribute key_strict.
Args:
value (bool, optional):
Whether to raise error when setting unsupported keys.
Defaults to True.
"""
former__key_strict__ = self.__key_strict__
self.__key_strict__ = value
if former__key_strict__ is False and \
value is True:
self.pop_unsupported_items()
def check_keypoints_compressed(self) -> bool:
"""Check whether the keypoints are compressed.
Returns:
bool:
Whether the keypoints are compressed.
"""
return self.__keypoints_compressed__
def load(self, npz_path: str):
"""Load data from npz_path and update them to self.
Args:
npz_path (str):
Path to a dumped npz file.
"""
supported_keys = self.__class__.SUPPORTED_KEYS
with np.load(npz_path, allow_pickle=True) as npz_file:
tmp_data_dict = dict(npz_file)
for key, value in list(tmp_data_dict.items()):
if isinstance(value, np.ndarray) and\
len(value.shape) == 0:
# value is not an ndarray before dump
value = value.item()
elif key in supported_keys and\
type(value) != supported_keys[key]['type']:
value = supported_keys[key]['type'](value)
if value is None:
tmp_data_dict.pop(key)
elif key == '__key_strict__' or \
key == '__data_len__' or\
key == '__keypoints_compressed__':
self.__setattr__(key, value)
# pop the attributes to keep dict clean
tmp_data_dict.pop(key)
elif key == 'bbox_xywh' and value.shape[1] == 4:
value = np.hstack([value, np.ones([value.shape[0], 1])])
tmp_data_dict[key] = value
else:
tmp_data_dict[key] = value
self.update(tmp_data_dict)
self.__set_default_values__()
def dump(self, npz_path: str, overwrite: bool = True):
"""Dump keys and items to an npz file.
Args:
npz_path (str):
Path to a dumped npz file.
overwrite (bool, optional):
Whether to overwrite if there is already a file.
Defaults to True.
Raises:
ValueError:
npz_path does not end with '.npz'.
FileExistsError:
When overwrite is False and file exists.
"""
if not check_path_suffix(npz_path, ['.npz']):
raise ValueError('Not an npz file.')
if not overwrite:
if check_path_existence(npz_path, 'file') == Existence.FileExist:
raise FileExistsError
dict_to_dump = {
'__key_strict__': self.__key_strict__,
'__data_len__': self.__data_len__,
'__keypoints_compressed__': self.__keypoints_compressed__,
}
dict_to_dump.update(self)
np.savez_compressed(npz_path, **dict_to_dump)
def get_sliced_cache(self, slice_size=10) -> List:
"""Slice the whole HumanData into pieces for HumanDataCacheWriter.
Args:
slice_size (int, optional):
The length of each unit in HumanData cache.
Defaults to 10.
Returns:
List:
Two dicts for HumanDataCacheWriter.
Init HumanDataCacheWriter by HumanDataCacheWriter(**Returns[0])
and set data by
human_data_cache_writer.update_sliced_dict(Returns[1]).
"""
keypoints_info = {}
non_sliced_data = {}
sliced_data = {}
slice_num = ceil(self.__data_len__ / slice_size)
for slice_index in range(slice_num):
sliced_data[str(slice_index)] = {}
dim_dict = self.__get_slice_dim__()
for key, dim in dim_dict.items():
# no dim to slice
if dim is None:
if key.startswith('keypoints') and\
(key.endswith('_mask') or
key.endswith('_convention')):
keypoints_info[key] = self[key]
else:
non_sliced_data[key] = self[key]
elif isinstance(dim, dict):
value_dict = self.get_raw_value(key)
non_sliced_sub_dict = {}
for sub_key in value_dict.keys():
sub_value = value_dict[sub_key]
if dim[sub_key] is None:
non_sliced_sub_dict[sub_key] = sub_value
else:
sub_dim = dim[sub_key]
for slice_index in range(slice_num):
slice_start = slice_index * slice_size
slice_end = min((slice_index + 1) * slice_size,
self.__data_len__)
slice_range = slice(slice_start, slice_end)
sliced_sub_value = \
HumanData.__get_sliced_result__(
sub_value, sub_dim, slice_range
)
if key not in sliced_data[str(slice_index)]:
sliced_data[str(slice_index)][key] = {}
sliced_data[str(slice_index)][key][sub_key] = \
sliced_sub_value
if len(non_sliced_sub_dict) > 0:
non_sliced_data[key] = non_sliced_sub_dict
else:
value = self.get_raw_value(key)
# slice as ndarray
if isinstance(value, np.ndarray):
slice_list = [
slice(None),
] * len(value.shape)
for slice_index in range(slice_num):
slice_start = slice_index * slice_size
slice_end = min((slice_index + 1) * slice_size,
self.__data_len__)
slice_list[dim] = slice(slice_start, slice_end)
sliced_value = value[tuple(slice_list)]
sliced_data[str(slice_index)][key] = sliced_value
# slice as list/tuple
else:
for slice_index in range(slice_num):
slice_start = slice_index * slice_size
slice_end = min((slice_index + 1) * slice_size,
self.__data_len__)
sliced_value = value[slice(slice_start, slice_end)]
sliced_data[str(slice_index)][key] = sliced_value
writer_args_dict = {
'slice_size': slice_size,
'keypoints_info': keypoints_info,
'data_len': self.data_len,
'non_sliced_data': non_sliced_data,
'key_strict': self.get_key_strict()
}
return writer_args_dict, sliced_data
def to(self,
device: Optional[Union[torch.device, str]] = _CPU_DEVICE,
dtype: Optional[torch.dtype] = None,
non_blocking: Optional[bool] = False,
copy: Optional[bool] = False,
memory_format: Optional[torch.memory_format] = None) -> dict:
"""Convert values in numpy.ndarray type to torch.Tensor, and move
Tensors to the target device. All keys will exist in the returned dict.
Args:
device (Union[torch.device, str], optional):
A specified device. Defaults to CPU_DEVICE.
dtype (torch.dtype, optional):
The data type of the expected torch.Tensor.
If dtype is None, it is decided according to numpy.ndarry.
Defaults to None.
non_blocking (bool, optional):
When non_blocking, tries to convert asynchronously with
respect to the host if possible, e.g.,
converting a CPU Tensor with pinned memory to a CUDA Tensor.
Defaults to False.
copy (bool, optional):
When copy is set, a new Tensor is created even when
the Tensor already matches the desired conversion.
No matter what value copy is, Tensor constructed from numpy
will not share the same memory with the source numpy.ndarray.
Defaults to False.
memory_format (torch.memory_format, optional):
The desired memory format of returned Tensor.
Not supported by pytorch-cpu.
Defaults to None.
Returns:
dict:
A dict with all numpy.ndarray values converted into
torch.Tensor and all Tensors moved to the target device.
"""
ret_dict = {}
for key in self.keys():
raw_value = self.get_raw_value(key)
tensor_value = None
if isinstance(raw_value, np.ndarray):
tensor_value = torch.from_numpy(raw_value).clone()
elif isinstance(raw_value, torch.Tensor):
tensor_value = raw_value
if tensor_value is None:
ret_dict[key] = raw_value
else:
if memory_format is None:
ret_dict[key] = \
tensor_value.to(device, dtype,
non_blocking, copy)
else:
ret_dict[key] = \
tensor_value.to(device, dtype,
non_blocking, copy,
memory_format=memory_format)
return ret_dict
def __getitem__(self, key: _KT) -> _VT:
"""Get value defined by HumanData. This function will be called by
self[key]. In keypoints_compressed mode, if the key contains
'keypoints', an array with zero-padding at absent keypoint will be
returned. Call self.get_raw_value(k) to get value without padding.
Args:
key (_KT):
Key in HumanData.
Returns:
_VT:
Value to the key.
"""
value = super().__getitem__(key)
if self.__keypoints_compressed__:
mask_key = f'{key}_mask'
if key in self and \
isinstance(value, np.ndarray) and \
'keypoints' in key and \
mask_key in self:
mask_array = np.asarray(super().__getitem__(mask_key))
value = \
self.__class__.__add_zero_pad__(value, mask_array)
return value
def get_raw_value(self, key: _KT) -> _VT:
"""Get raw value from the dict. It acts the same as
dict.__getitem__(k).
Args:
key (_KT):
Key in dict.
Returns:
_VT:
Value to the key.
"""
value = super().__getitem__(key)
return value
def get_value_in_shape(self,
key: _KT,
shape: Union[list, tuple],
padding_constant: int = 0) -> np.ndarray:
"""Get value in a specific shape. For each dim, if the required shape
is smaller than current shape, ndarray will be sliced. Otherwise, it
will be padded with padding_constant at the end.
Args:
key (_KT):
Key in dict. The value of this key must be
an instance of numpy.ndarray.
shape (Union[list, tuple]):
Shape of the returned array. Its length
must be equal to value.ndim. Set -1 for
a dimension if you do not want to edit it.
padding_constant (int, optional):
The value to set the padded values for each axis.
Defaults to 0.
Raises:
ValueError:
A value in shape is neither positive integer nor -1.
Returns:
np.ndarray:
An array in required shape.
"""
value = self.get_raw_value(key)
assert isinstance(value, np.ndarray)
assert value.ndim == len(shape)
pad_width_list = []
slice_list = []
for dim_index in range(len(shape)):
if shape[dim_index] == -1:
# no pad or slice
pad_width_list.append((0, 0))
slice_list.append(slice(None))
elif shape[dim_index] > 0:
# valid shape value
wid = shape[dim_index] - value.shape[dim_index]
if wid > 0:
pad_width_list.append((0, wid))
else:
pad_width_list.append((0, 0))
slice_list.append(slice(0, shape[dim_index]))
else:
# invalid
raise ValueError
pad_value = np.pad(value,
pad_width=pad_width_list,
mode='constant',
constant_values=padding_constant)
return pad_value[tuple(slice_list)]
@overload
def get_slice(self, stop: int):
"""Slice [0, stop, 1] of all sliceable values."""
...
@overload
def get_slice(self, start: int, stop: int):
"""Slice [start, stop, 1] of all sliceable values."""
...
@overload
def get_slice(self, start: int, stop: int, step: int):
"""Slice [start, stop, step] of all sliceable values."""
...
def get_slice(self,
arg_0: int,
arg_1: Union[int, Any] = None,
step: int = 1) -> _HumanData:
"""Slice all sliceable values along major_dim dimension.
Args:
arg_0 (int):
When arg_1 is None, arg_0 is stop and start=0.
When arg_1 is not None, arg_0 is start.
arg_1 (Union[int, Any], optional):
None or where to stop.
Defaults to None.
step (int, optional):
Length of step. Defaults to 1.
Returns:
HumanData:
A new HumanData instance with sliced values.
"""
ret_human_data = \
HumanData.new(key_strict=self.get_key_strict())
if arg_1 is None:
start = 0
stop = arg_0
else:
start = arg_0
stop = arg_1
slice_index = slice(start, stop, step)
dim_dict = self.__get_slice_dim__()
for key, dim in dim_dict.items():
# keys not expected be sliced
if dim is None:
ret_human_data[key] = self[key]
elif isinstance(dim, dict):
value_dict = self.get_raw_value(key)
sliced_dict = {}
for sub_key in value_dict.keys():
sub_value = value_dict[sub_key]
if dim[sub_key] is None:
sliced_dict[sub_key] = sub_value
else:
sub_dim = dim[sub_key]
sliced_sub_value = \
HumanData.__get_sliced_result__(
sub_value, sub_dim, slice_index)
sliced_dict[sub_key] = sliced_sub_value
ret_human_data[key] = sliced_dict
else:
value = self[key]
sliced_value = \
HumanData.__get_sliced_result__(
value, dim, slice_index)
ret_human_data[key] = sliced_value
# check keypoints compressed
if self.check_keypoints_compressed():
ret_human_data.compress_keypoints_by_mask()
return ret_human_data
def __get_slice_dim__(self) -> dict:
"""For each key in this HumanData, get the dimension for slicing. 0 for
default, if no other value specified.
Returns:
dict:
Keys are self.keys().
Values indicate where to slice.
None for not expected to be sliced or
failed.
"""
supported_keys = self.__class__.SUPPORTED_KEYS
ret_dict = {}
for key in self.keys():
# keys not expected be sliced
if key in supported_keys and \
'dim' in supported_keys[key] and \
supported_keys[key]['dim'] is None:
ret_dict[key] = None
else:
value = self[key]
if isinstance(value, dict) and len(value) > 0:
ret_dict[key] = {}
for sub_key in value.keys():
try:
sub_value_len = len(value[sub_key])
if sub_value_len != self.__data_len__:
ret_dict[key][sub_key] = None
elif 'dim' in value:
ret_dict[key][sub_key] = value['dim']
else:
ret_dict[key][sub_key] = 0
except TypeError:
ret_dict[key][sub_key] = None
continue
# instance cannot be sliced without len method
try:
value_len = len(value)
except TypeError:
ret_dict[key] = None
continue
# slice on dim 0 by default
slice_dim = 0
if key in supported_keys and \
'dim' in supported_keys[key]:
slice_dim = \
supported_keys[key]['dim']
data_len = value_len if slice_dim == 0 \
else value.shape[slice_dim]
# dim not for slice
if data_len != self.__data_len__:
ret_dict[key] = None
continue
else:
ret_dict[key] = slice_dim
return ret_dict
def __setitem__(self, key: _KT, val: _VT) -> None:
"""Set self[key] to value. Only be called when using
human_data[key] = val. Methods like update won't call __setitem__.
In keypoints_compressed mode, if the key contains 'keypoints',
and f'{key}_mask' is in self.keys(), invalid zeros
will be removed before setting value.
Args:
key (_KT):
Key in HumanData.
Better be an element in HumanData.SUPPORTED_KEYS.
If not, an Error will be raised in key_strict mode.
val (_VT):
Value to the key.
Raises:
KeyError:
self.get_key_strict() is True and
key cannot be found in
HumanData.SUPPORTED_KEYS.
ValueError:
Value is supported but doesn't match definition.
ValueError:
self.check_keypoints_compressed() is True and
mask of a keypoint item is missing.
"""
self.__check_key__(key)
self.__check_value__(key, val)
# if it can be compressed by mask
if self.__keypoints_compressed__:
class_logger = self.__class__.logger
if 'keypoints' in key and \
'_mask' in key:
msg = 'Mask cannot be modified ' +\
'in keypoints_compressed mode.'
print_log(msg=msg, logger=class_logger, level=logging.WARN)
return
elif isinstance(val, np.ndarray) and \
'keypoints' in key and \
'_mask' not in key:
mask_key = f'{key}_mask'
if mask_key in self:
mask_array = np.asarray(super().__getitem__(mask_key))
val = \
self.__class__.__remove_zero_pad__(val, mask_array)
else:
msg = f'Mask for {key} has not been set.' +\
f' Please set {mask_key} before compression.'
print_log(msg=msg,
logger=class_logger,
level=logging.ERROR)
raise ValueError
dict.__setitem__(self, key, val)
def set_raw_value(self, key: _KT, val: _VT) -> None:
"""Set the raw value of self[key] to val after key check. It acts the
same as dict.__setitem__(self, key, val) if the key satisfied
constraints.
Args:
key (_KT):
Key in dict.
val (_VT):
Value to the key.
Raises:
KeyError:
self.get_key_strict() is True and
key cannot be found in
HumanData.SUPPORTED_KEYS.
ValueError:
Value is supported but doesn't match definition.
"""
self.__check_key__(key)
self.__check_value__(key, val)
dict.__setitem__(self, key, val)
def pop_unsupported_items(self) -> None:
"""Find every item with a key not in HumanData.SUPPORTED_KEYS, and pop
it to save memory."""
for key in list(self.keys()):
if key not in self.__class__.SUPPORTED_KEYS:
self.pop(key)
def __check_key__(self, key: Any) -> _KeyCheck:
"""Check whether the key matches definition in
HumanData.SUPPORTED_KEYS.
Args:
key (Any):
Key in HumanData.
Returns:
_KeyCheck:
PASS, WARN or ERROR.
Raises:
KeyError:
self.get_key_strict() is True and
key cannot be found in
HumanData.SUPPORTED_KEYS.
"""
ret_key_check = _KeyCheck.PASS
if self.get_key_strict():
if key not in self.__class__.SUPPORTED_KEYS:
ret_key_check = _KeyCheck.ERROR
else:
if key not in self.__class__.SUPPORTED_KEYS and \
key not in self.__class__.WARNED_KEYS:
# log warning message at the first time
ret_key_check = _KeyCheck.WARN
self.__class__.WARNED_KEYS.append(key)
if ret_key_check == _KeyCheck.ERROR:
raise KeyError(self.__class__.__get_key_error_msg__(key))
elif ret_key_check == _KeyCheck.WARN:
class_logger = self.__class__.logger
if class_logger == 'silent':
pass
else:
print_log(msg=self.__class__.__get_key_warn_msg__(key),
logger=class_logger,
level=logging.WARN)
return ret_key_check
def __check_value__(self, key: Any, val: Any) -> bool:
"""Check whether the value matches definition in
HumanData.SUPPORTED_KEYS.
Args:
key (Any):
Key in HumanData.
val (Any):
Value to the key.
Returns:
bool:
True for matched, ortherwise False.
Raises:
ValueError:
Value is supported but doesn't match definition.
"""
ret_bool = self.__check_value_type__(key, val) and\
self.__check_value_shape__(key, val) and\
self.__check_value_len__(key, val)
if not ret_bool:
raise ValueError(self.__class__.__get_value_error_msg__())
return ret_bool
def __check_value_type__(self, key: Any, val: Any) -> bool:
"""Check whether the type of val matches definition in
HumanData.SUPPORTED_KEYS.
Args:
key (Any):
Key in HumanData.
val (Any):
Value to the key.
Returns:
bool:
If type doesn't match, return False.
Else return True.
"""
ret_bool = True
supported_keys = self.__class__.SUPPORTED_KEYS
# check definition
if key in supported_keys:
# check type
if type(val) != supported_keys[key]['type']:
ret_bool = False
if not ret_bool:
expected_type = supported_keys[key]['type']
err_msg = 'Type check Failed:\n'
err_msg += f'key={str(key)}\n'
err_msg += f'type(val)={type(val)}\n'
err_msg += f'expected type={expected_type}\n'
print_log(msg=err_msg,
logger=self.__class__.logger,
level=logging.ERROR)
return ret_bool
def __check_value_shape__(self, key: Any, val: Any) -> bool:
"""Check whether the shape of val matches definition in
HumanData.SUPPORTED_KEYS.
Args:
key (Any):
Key in HumanData.
val (Any):
Value to the key.
Returns:
bool:
If expected shape is defined and doesn't match,
return False.
Else return True.
"""
ret_bool = True
supported_keys = self.__class__.SUPPORTED_KEYS
# check definition
if key in supported_keys:
# check shape
if 'shape' in supported_keys[key]:
val_shape = val.shape
for shape_ind in range(len(supported_keys[key]['shape'])):
# length not match
if shape_ind >= len(val_shape):
ret_bool = False
break
expect_val = supported_keys[key]['shape'][shape_ind]
# value not match
if expect_val > 0 and \
expect_val != val_shape[shape_ind]:
ret_bool = False
break
if not ret_bool:
expected_shape = str(supported_keys[key]['shape'])
expected_shape = expected_shape.replace('-1', 'Any')
err_msg = 'Shape check Failed:\n'
err_msg += f'key={str(key)}\n'
err_msg += f'val.shape={val_shape}\n'
err_msg += f'expected shape={expected_shape}\n'
print_log(msg=err_msg,
logger=self.__class__.logger,
level=logging.ERROR)
return ret_bool
@property
def data_len(self) -> int:
"""Get the temporal length of this HumanData instance.
Returns:
int:
Number of frames related to this instance.
"""
return self.__data_len__
@data_len.setter
def data_len(self, value: int):
"""Set the temporal length of this HumanData instance.
Args:
value (int):
Number of frames related to this instance.
"""
self.__data_len__ = value
def __check_value_len__(self, key: Any, val: Any) -> bool:
"""Check whether the temporal length of val matches other values.
Args:
key (Any):
Key in HumanData.
val (Any):
Value to the key.
Returns:
bool:
If temporal dim is defined and temporal length doesn't match,
return False.
Else return True.
"""
ret_bool = True
supported_keys = self.__class__.SUPPORTED_KEYS
# check definition
if key in supported_keys:
# check temporal length
if 'dim' in supported_keys[key] and \
supported_keys[key]['dim'] is not None:
val_slice_dim = supported_keys[key]['dim']
if supported_keys[key]['type'] == dict:
slice_key = supported_keys[key]['slice_key']
val_data_len = val[slice_key].shape[val_slice_dim]
else:
val_data_len = val.shape[val_slice_dim]
if self.data_len < 0:
# no data_len yet, assign a new one
self.data_len = val_data_len
else:
# check if val_data_len matches recorded data_len
if self.data_len != val_data_len:
ret_bool = False
if not ret_bool:
err_msg = 'Temporal check Failed:\n'
err_msg += f'key={str(key)}\n'
err_msg += f'val\'s data_len={val_data_len}\n'
err_msg += f'expected data_len={self.data_len}\n'
print_log(msg=err_msg,
logger=self.__class__.logger,
level=logging.ERROR)
return ret_bool
def generate_mask_from_confidence(self, keys=None) -> None:
"""Generate mask from keypoints' confidence. Keypoints that have zero
confidence in all occurrences will have a zero mask. Note that the last
value of the keypoint is assumed to be confidence.
Args:
keys: None, str, or list of str.
None: all keys with `keypoint` in it will have mask
generated from their confidence.
str: key of the keypoint, the mask has name f'{key}_name'
list of str: a list of keys of the keypoints.
Generate mask for multiple keypoints.
Defaults to None.
Returns:
None
Raises:
KeyError:
A key is not not found
"""
if keys is None:
keys = []
for key in self.keys():
val = self.get_raw_value(key)
if isinstance(val, np.ndarray) and \
'keypoints' in key and \
'_mask' not in key:
keys.append(key)
elif isinstance(keys, str):
keys = [keys]
elif isinstance(keys, list):
for key in keys:
assert isinstance(key, str)
else:
raise TypeError(f'`Keys` must be None, str, or list of str, '
f'got {type(keys)}.')
update_dict = {}
for kpt_key in keys:
kpt_array = self.get_raw_value(kpt_key)
num_joints = kpt_array.shape[-2]
# if all conf of a joint are zero, this joint is masked
joint_conf = kpt_array[..., -1].reshape(-1, num_joints)
mask_array = (joint_conf > 0).astype(np.uint8).max(axis=0)
assert len(mask_array) == num_joints
# generate mask
update_dict[f'{kpt_key}_mask'] = mask_array
self.update(update_dict)
def compress_keypoints_by_mask(self) -> None:
"""If a key contains 'keypoints', and f'{key}_mask' is in self.keys(),
invalid zeros will be removed and f'{key}_mask' will be locked.
Raises:
KeyError:
A key contains 'keypoints' has been found
but its corresponding mask is missing.
"""
assert self.__keypoints_compressed__ is False
key_pairs = []
for key in self.keys():
mask_key = f'{key}_mask'
val = self.get_raw_value(key)
if isinstance(val, np.ndarray) and \
'keypoints' in key and \
'_mask' not in key and 'has' not in key:
if mask_key in self:
key_pairs.append([key, mask_key])
else:
msg = f'Mask for {key} has not been set.' +\
f'Please set {mask_key} before compression.'
raise KeyError(msg)
compressed_dict = {}
for kpt_key, mask_key in key_pairs:
kpt_array = self.get_raw_value(kpt_key)
mask_array = np.asarray(self.get_raw_value(mask_key))
compressed_kpt = \
self.__class__.__remove_zero_pad__(kpt_array, mask_array)
compressed_dict[kpt_key] = compressed_kpt
# set value after all pairs are compressed
self.update(compressed_dict)
self.__keypoints_compressed__ = True
def decompress_keypoints(self) -> None:
"""If a key contains 'keypoints', and f'{key}_mask' is in self.keys(),
invalid zeros will be inserted to the right places and f'{key}_mask'
will be unlocked.
Raises:
KeyError:
A key contains 'keypoints' has been found
but its corresponding mask is missing.
"""
assert self.__keypoints_compressed__ is True
key_pairs = []
for key in self.keys():
mask_key = f'{key}_mask'
val = self.get_raw_value(key)
if isinstance(val, np.ndarray) and \
'keypoints' in key and \
'_mask' not in key:
if mask_key in self:
key_pairs.append([key, mask_key])
else:
class_logger = self.__class__.logger
msg = f'Mask for {key} has not been found.' +\
f'Please remove {key} before decompression.'
print_log(msg=msg,
logger=class_logger,
level=logging.ERROR)
raise KeyError
decompressed_dict = {}
for kpt_key, mask_key in key_pairs:
mask_array = np.asarray(self.get_raw_value(mask_key))
compressed_kpt = self.get_raw_value(kpt_key)
kpt_array = \
self.__class__.__add_zero_pad__(compressed_kpt, mask_array)
decompressed_dict[kpt_key] = kpt_array
# set value after all pairs are decompressed
self.update(decompressed_dict)
self.__keypoints_compressed__ = False
def dump_by_pickle(self, pkl_path: str, overwrite: bool = True) -> None:
"""Dump keys and items to a pickle file. It's a secondary dump method,
when a HumanData instance is too large to be dumped by self.dump()
Args:
pkl_path (str):
Path to a dumped pickle file.
overwrite (bool, optional):
Whether to overwrite if there is already a file.
Defaults to True.
Raises:
ValueError:
npz_path does not end with '.pkl'.
FileExistsError:
When overwrite is False and file exists.
"""
if not check_path_suffix(pkl_path, ['.pkl']):
raise ValueError('Not an pkl file.')
if not overwrite:
if check_path_existence(pkl_path, 'file') == Existence.FileExist:
raise FileExistsError
dict_to_dump = {
'__key_strict__': self.__key_strict__,
'__data_len__': self.__data_len__,
'__keypoints_compressed__': self.__keypoints_compressed__,
}
dict_to_dump.update(self)
with open(pkl_path, 'wb') as f_writeb:
pickle.dump(dict_to_dump,
f_writeb,
protocol=pickle.HIGHEST_PROTOCOL)
def load_by_pickle(self, pkl_path: str) -> None:
"""Load data from pkl_path and update them to self.
When a HumanData Instance was dumped by
self.dump_by_pickle(), use this to load.
Args:
npz_path (str):
Path to a dumped npz file.
"""
with open(pkl_path, 'rb') as f_readb:
tmp_data_dict = pickle.load(f_readb)
for key, value in list(tmp_data_dict.items()):
if value is None:
tmp_data_dict.pop(key)
elif key == '__key_strict__' or \
key == '__data_len__' or\
key == '__keypoints_compressed__':
self.__setattr__(key, value)
# pop the attributes to keep dict clean
tmp_data_dict.pop(key)
elif key == 'bbox_xywh' and value.shape[1] == 4:
value = np.hstack([value, np.ones([value.shape[0], 1])])
tmp_data_dict[key] = value
else:
tmp_data_dict[key] = value
self.update(tmp_data_dict)
self.__set_default_values__()
def __set_default_values__(self) -> None:
"""For older versions of HumanData, call this method to apply missing
values (also attributes)."""
supported_keys = self.__class__.SUPPORTED_KEYS
if self.__data_len__ == -1:
for key in supported_keys:
if key in self and \
'dim' in supported_keys[key] and\
supported_keys[key]['dim'] is not None:
if 'slice_key' in supported_keys[key] and\
supported_keys[key]['type'] == dict:
sub_key = supported_keys[key]['slice_key']
slice_dim = supported_keys[key]['dim']
self.__data_len__ = \
self[key][sub_key].shape[slice_dim]
else:
slice_dim = supported_keys[key]['dim']
self.__data_len__ = self[key].shape[slice_dim]
break
for key in list(self.keys()):
convention_key = f'{key}_convention'
if key.startswith('keypoints') and \
not key.endswith('_mask') and \
not key.endswith('_convention') and \
convention_key not in self:
self[convention_key] = 'human_data'
@classmethod
def concatenate(cls, human_data_0: _HumanData,
human_data_1: _HumanData) -> _HumanData:
"""Concatenate two human_data. All keys will be kept it the returned
human_data. If either value from human_data_0 or human_data_1 matches
data_len from its HumanData, the two values will be concatenated as a
single value. If not, postfix will be added to the key to specify
source of the value.
Args:
human_data_0 (_HumanData)
human_data_1 (_HumanData)
Returns:
_HumanData:
A new human_data instance with all concatenated data.
"""
ret_human_data = cls.new(key_strict=False)
set_0 = set(human_data_0.keys())
set_1 = set(human_data_1.keys())
common_keys = set_0.intersection(set_1)
dim_dict_0 = human_data_0.__get_slice_dim__()
dim_dict_1 = human_data_1.__get_slice_dim__()
for key in common_keys:
value_0 = human_data_0[key]
value_1 = human_data_1[key]
# align type
value_0 = list(value_0) if isinstance(value_0, tuple)\
else value_0
value_1 = list(value_1) if isinstance(value_1, tuple)\
else value_1
assert type(value_0) == type(value_1)
# align convention
if key.startswith('keypoints') and\
key.endswith('_convention'):
assert value_0 == value_1
ret_human_data[key] = value_0
continue
# mask_0 and mask_1
elif key.startswith('keypoints') and\
key.endswith('_mask'):
new_mask = value_0 * value_1
ret_human_data[key] = new_mask
continue
# go through the sub dict
if isinstance(value_0, dict):
sub_dict = {}
for sub_key, sub_value_0 in value_0.items():
# only found in value_0
if sub_key not in value_1:
sub_dict[sub_key] = sub_value_0
# found in both values
else:
sub_value_1 = value_1[sub_key]
concat_sub_dict = cls.__concat_value__(
key=sub_key,
value_0=sub_value_0,
dim_0=dim_dict_0[key][sub_key],
value_1=sub_value_1,
dim_1=dim_dict_1[key][sub_key])
sub_dict.update(concat_sub_dict)
for sub_key, sub_value_1 in value_1.items():
if sub_key not in value_0:
sub_dict[sub_key] = sub_value_1
ret_human_data[key] = sub_dict
# try concat
else:
concat_dict = cls.__concat_value__(key=key,
value_0=value_0,
dim_0=dim_dict_0[key],
value_1=value_1,
dim_1=dim_dict_1[key])
ret_human_data.update(concat_dict)
# check exclusive keys
for key, value in human_data_0.items():
if key not in common_keys:
# value not for concat and slice
if dim_dict_0[key] is None:
ret_human_data[key] = value
# value aligned with data_len of HumanData_0
else:
ret_human_data[f'{key}_0'] = value
for key, value in human_data_1.items():
if key not in common_keys:
# same as above
if dim_dict_1[key] is None:
ret_human_data[key] = value
else:
ret_human_data[f'{key}_1'] = value
return ret_human_data
@classmethod
def __concat_value__(cls, key: Any, value_0: Any, value_1: Any,
dim_0: Union[None, int], dim_1: Union[None,
int]) -> dict:
"""Concat two values from two different HumanData.
Args:
key (Any):
The common key of the two values.
value_0 (Any):
Value from 0.
value_1 (Any):
Value from 1.
dim_0 (Union[None, int]):
The dim for concat and slice. None for N/A.
dim_1 (Union[None, int]):
The dim for concat and slice. None for N/A.
Returns:
dict:
Dict for concatenated result.
"""
ret_dict = {}
if dim_0 is None or dim_1 is None:
ret_dict[f'{key}_0'] = value_0
ret_dict[f'{key}_1'] = value_1
elif isinstance(value_0, list):
ret_dict[key] = value_0 + value_1
# elif isinstance(value_0, np.ndarray):
else:
ret_dict[key] = np.concatenate((value_0, value_1), axis=dim_0)
return ret_dict
@classmethod
def __add_zero_pad__(cls, compressed_array: np.ndarray,
mask_array: np.ndarray) -> np.ndarray:
"""Pad zeros to a compressed keypoints array.
Args:
compressed_array (np.ndarray):
A compressed keypoints array.
mask_array (np.ndarray):
The mask records compression relationship.
Returns:
np.ndarray:
A keypoints array in full-size.
"""
assert mask_array.sum() == compressed_array.shape[1]
data_len, _, dim = compressed_array.shape
mask_len = mask_array.shape[0]
ret_value = np.zeros(shape=[data_len, mask_len, dim],
dtype=compressed_array.dtype)
valid_mask_index = np.where(mask_array == 1)[0]
ret_value[:, valid_mask_index, :] = compressed_array
return ret_value
@classmethod
def __remove_zero_pad__(cls, zero_pad_array: np.ndarray,
mask_array: np.ndarray) -> np.ndarray:
"""Remove zero-padding from a full-size keypoints array.
Args:
zero_pad_array (np.ndarray):
A keypoints array in full-size.
mask_array (np.ndarray):
The mask records compression relationship.
Returns:
np.ndarray:
A compressed keypoints array.
"""
assert mask_array.shape[0] == zero_pad_array.shape[1]
valid_mask_index = np.where(mask_array == 1)[0]
ret_value = np.take(zero_pad_array, valid_mask_index, axis=1)
return ret_value
@classmethod
def __get_key_warn_msg__(cls, key: Any) -> str:
"""Get the warning message when a key fails the check.
Args:
key (Any):
The key with wrong.
Returns:
str:
The warning message.
"""
class_name = cls.__name__
warn_message = \
f'{key} is absent in' +\
f' {class_name}.SUPPORTED_KEYS.\n'
suggestion_message = \
'Ignore this if you know exactly' +\
' what you are doing.\n' +\
'Otherwise, Call self.set_key_strict(True)' +\
' to avoid wrong keys.\n'
return warn_message + suggestion_message
@classmethod
def __get_key_error_msg__(cls, key: Any) -> str:
"""Get the error message when a key fails the check.
Args:
key (Any):
The key with wrong.
Returns:
str:
The error message.
"""
class_name = cls.__name__
absent_message = \
f'{key} is absent in' +\
f' {class_name}.SUPPORTED_KEYS.\n'
suggestion_message = \
'Call self.set_key_strict(False)' +\
' to allow unsupported keys.\n'
return absent_message + suggestion_message
@classmethod
def __get_value_error_msg__(cls) -> str:
"""Get the error message when a value fails the check.
Returns:
str:
The error message.
"""
error_message = \
'An supported value doesn\'t ' +\
'match definition.\n'
suggestion_message = \
'See error log for details.\n'
return error_message + suggestion_message
@classmethod
def __get_sliced_result__(
cls, input_data: Union[np.ndarray, list, tuple], slice_dim: int,
slice_range: slice) -> Union[np.ndarray, list, tuple]:
"""Slice input_data along slice_dim with slice_range.
Args:
input_data (Union[np.ndarray, list, tuple]):
Data to be sliced.
slice_dim (int):
Dimension to be sliced.
slice_range (slice):
An instance of class slice.
Returns:
Union[np.ndarray, list, tuple]:
A slice of input_data.
"""
if isinstance(input_data, np.ndarray):
slice_list = [
slice(None),
] * len(input_data.shape)
slice_list[slice_dim] = slice_range
sliced_data = input_data[tuple(slice_list)]
else:
sliced_data = \
input_data[slice_range]
return sliced_data
|