pose3d_cmb.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. this code is base on https://github.com/open-mmlab/mmpose
  16. """
  17. import os
  18. import cv2
  19. import numpy as np
  20. import json
  21. import copy
  22. import pycocotools
  23. from pycocotools.coco import COCO
  24. from .dataset import DetDataset
  25. from ppdet.core.workspace import register, serializable
  26. @serializable
  27. class Pose3DDataset(DetDataset):
  28. """Pose3D Dataset class.
  29. Args:
  30. dataset_dir (str): Root path to the dataset.
  31. anno_list (list of str): each of the element is a relative path to the annotation file.
  32. image_dirs (list of str): each of path is a relative path where images are held.
  33. transform (composed(operators)): A sequence of data transforms.
  34. test_mode (bool): Store True when building test or
  35. validation dataset. Default: False.
  36. 24 joints order:
  37. 0-2: 'R_Ankle', 'R_Knee', 'R_Hip',
  38. 3-5:'L_Hip', 'L_Knee', 'L_Ankle',
  39. 6-8:'R_Wrist', 'R_Elbow', 'R_Shoulder',
  40. 9-11:'L_Shoulder','L_Elbow','L_Wrist',
  41. 12-14:'Neck','Top_of_Head','Pelvis',
  42. 15-18:'Thorax','Spine','Jaw','Head',
  43. 19-23:'Nose','L_Eye','R_Eye','L_Ear','R_Ear'
  44. """
  45. def __init__(self,
  46. dataset_dir,
  47. image_dirs,
  48. anno_list,
  49. transform=[],
  50. num_joints=24,
  51. test_mode=False):
  52. super().__init__(dataset_dir, image_dirs, anno_list)
  53. self.image_info = {}
  54. self.ann_info = {}
  55. self.num_joints = num_joints
  56. self.transform = transform
  57. self.test_mode = test_mode
  58. self.img_ids = []
  59. self.dataset_dir = dataset_dir
  60. self.image_dirs = image_dirs
  61. self.anno_list = anno_list
  62. def get_mask(self, mvm_percent=0.3):
  63. num_joints = self.num_joints
  64. mjm_mask = np.ones((num_joints, 1)).astype(np.float32)
  65. if self.test_mode == False:
  66. pb = np.random.random_sample()
  67. masked_num = int(
  68. pb * mvm_percent *
  69. num_joints) # at most x% of the joints could be masked
  70. indices = np.random.choice(
  71. np.arange(num_joints), replace=False, size=masked_num)
  72. mjm_mask[indices, :] = 0.0
  73. mvm_mask = np.ones((10, 1)).astype(np.float32)
  74. if self.test_mode == False:
  75. num_vertices = 10
  76. pb = np.random.random_sample()
  77. masked_num = int(
  78. pb * mvm_percent *
  79. num_vertices) # at most x% of the vertices could be masked
  80. indices = np.random.choice(
  81. np.arange(num_vertices), replace=False, size=masked_num)
  82. mvm_mask[indices, :] = 0.0
  83. mjm_mask = np.concatenate([mjm_mask, mvm_mask], axis=0)
  84. return mjm_mask
  85. def filterjoints(self, x):
  86. if self.num_joints == 24:
  87. return x
  88. elif self.num_joints == 14:
  89. return x[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 18], :]
  90. elif self.num_joints == 17:
  91. return x[
  92. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 18, 19], :]
  93. else:
  94. raise ValueError(
  95. "unsupported joint numbers, only [24 or 17 or 14] is supported!")
  96. def parse_dataset(self):
  97. print("Loading annotations..., please wait")
  98. self.annos = []
  99. im_id = 0
  100. for idx, annof in enumerate(self.anno_list):
  101. img_prefix = os.path.join(self.dataset_dir, self.image_dirs[idx])
  102. dataf = os.path.join(self.dataset_dir, annof)
  103. with open(dataf, 'r') as rf:
  104. anno_data = json.load(rf)
  105. annos = anno_data['data']
  106. new_annos = []
  107. print("{} has annos numbers: {}".format(dataf, len(annos)))
  108. for anno in annos:
  109. new_anno = {}
  110. new_anno['im_id'] = im_id
  111. im_id += 1
  112. imagename = anno['imageName']
  113. if imagename.startswith("COCO_train2014_"):
  114. imagename = imagename[len("COCO_train2014_"):]
  115. elif imagename.startswith("COCO_val2014_"):
  116. imagename = imagename[len("COCO_val2014_"):]
  117. imagename = os.path.join(img_prefix, imagename)
  118. if not os.path.exists(imagename):
  119. if "train2017" in imagename:
  120. imagename = imagename.replace("train2017",
  121. "val2017")
  122. if not os.path.exists(imagename):
  123. print("cannot find imagepath:{}".format(
  124. imagename))
  125. continue
  126. else:
  127. print("cannot find imagepath:{}".format(imagename))
  128. continue
  129. new_anno['imageName'] = imagename
  130. new_anno['bbox_center'] = anno['bbox_center']
  131. new_anno['bbox_scale'] = anno['bbox_scale']
  132. new_anno['joints_2d'] = np.array(anno[
  133. 'gt_keypoint_2d']).astype(np.float32)
  134. if new_anno['joints_2d'].shape[0] == 49:
  135. #if the joints_2d is in SPIN format(which generated by eft), choose the last 24 public joints
  136. #for detail please refer: https://github.com/nkolot/SPIN/blob/master/constants.py
  137. new_anno['joints_2d'] = new_anno['joints_2d'][25:]
  138. new_anno['joints_3d'] = np.array(anno[
  139. 'pose3d'])[:, :3].astype(np.float32)
  140. new_anno['mjm_mask'] = self.get_mask()
  141. if not 'has_3d_joints' in anno:
  142. new_anno['has_3d_joints'] = int(1)
  143. new_anno['has_2d_joints'] = int(1)
  144. else:
  145. new_anno['has_3d_joints'] = int(anno['has_3d_joints'])
  146. new_anno['has_2d_joints'] = int(anno['has_2d_joints'])
  147. new_anno['joints_2d'] = self.filterjoints(new_anno[
  148. 'joints_2d'])
  149. self.annos.append(new_anno)
  150. del annos
  151. def __len__(self):
  152. """Get dataset length."""
  153. return len(self.annos)
  154. def _get_imganno(self, idx):
  155. """Get anno for a single image."""
  156. return self.annos[idx]
  157. def __getitem__(self, idx):
  158. """Prepare image for training given the index."""
  159. records = copy.deepcopy(self._get_imganno(idx))
  160. imgpath = records['imageName']
  161. assert os.path.exists(imgpath), "cannot find image {}".format(imgpath)
  162. records['image'] = cv2.imread(imgpath)
  163. records['image'] = cv2.cvtColor(records['image'], cv2.COLOR_BGR2RGB)
  164. records = self.transform(records)
  165. return records
  166. def check_or_download_dataset(self):
  167. alldatafind = True
  168. for image_dir in self.image_dirs:
  169. image_dir = os.path.join(self.dataset_dir, image_dir)
  170. if not os.path.isdir(image_dir):
  171. print("dataset [{}] is not found".format(image_dir))
  172. alldatafind = False
  173. if not alldatafind:
  174. raise ValueError(
  175. "Some dataset is not valid and cannot download automatically now, please prepare the dataset first"
  176. )