lapa2coco.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import json
  3. import os
  4. import os.path as osp
  5. import time
  6. import cv2
  7. import mmengine
  8. import numpy as np
  9. def default_dump(obj):
  10. """Convert numpy classes to JSON serializable objects."""
  11. if isinstance(obj, (np.integer, np.floating, np.bool_)):
  12. return obj.item()
  13. elif isinstance(obj, np.ndarray):
  14. return obj.tolist()
  15. else:
  16. return obj
  17. def convert_labpa_to_coco(ann_dir, out_file):
  18. annotations = []
  19. images = []
  20. cnt = 0
  21. if 'trainval' in ann_dir:
  22. ann_dir_list = ['train', 'val']
  23. else:
  24. ann_dir_list = [ann_dir]
  25. for tv in ann_dir_list:
  26. ann_dir = 'data/LaPa/' + tv
  27. landmark_dir = osp.join(ann_dir, 'landmarks')
  28. ann_list = os.listdir(landmark_dir)
  29. img_dir = osp.join(ann_dir, 'images')
  30. for idx, ann_file in enumerate(mmengine.track_iter_progress(ann_list)):
  31. cnt += 1
  32. ann_path = osp.join(landmark_dir, ann_file)
  33. file_name = ann_file[:-4] + '.jpg'
  34. img_path = osp.join(img_dir, file_name)
  35. data_info = open(ann_path).readlines()
  36. img = cv2.imread(img_path)
  37. keypoints = []
  38. for line in data_info[1:]:
  39. x, y = line.strip().split(' ')
  40. x, y = float(x), float(y)
  41. keypoints.append([x, y, 2])
  42. keypoints = np.array(keypoints)
  43. x1, y1, _ = np.amin(keypoints, axis=0)
  44. x2, y2, _ = np.amax(keypoints, axis=0)
  45. w, h = x2 - x1, y2 - y1
  46. bbox = [x1, y1, w, h]
  47. image = {}
  48. image['id'] = cnt
  49. image['file_name'] = f'{tv}/images/{file_name}'
  50. image['height'] = img.shape[0]
  51. image['width'] = img.shape[1]
  52. images.append(image)
  53. ann = {}
  54. ann['keypoints'] = keypoints.reshape(-1).tolist()
  55. ann['image_id'] = cnt
  56. ann['id'] = cnt
  57. ann['num_keypoints'] = len(keypoints)
  58. ann['bbox'] = bbox
  59. ann['iscrowd'] = 0
  60. ann['area'] = int(ann['bbox'][2] * ann['bbox'][3])
  61. ann['category_id'] = 1
  62. annotations.append(ann)
  63. cocotype = {}
  64. cocotype['info'] = {}
  65. cocotype['info']['description'] = 'LaPa Generated by MMPose Team'
  66. cocotype['info']['version'] = 1.0
  67. cocotype['info']['year'] = time.strftime('%Y', time.localtime())
  68. cocotype['info']['date_created'] = time.strftime('%Y/%m/%d',
  69. time.localtime())
  70. cocotype['images'] = images
  71. cocotype['annotations'] = annotations
  72. cocotype['categories'] = [{
  73. 'supercategory': 'person',
  74. 'id': 1,
  75. 'name': 'face',
  76. 'keypoints': [],
  77. 'skeleton': []
  78. }]
  79. json.dump(
  80. cocotype,
  81. open(out_file, 'w'),
  82. ensure_ascii=False,
  83. default=default_dump)
  84. print(f'done {out_file}')
  85. if __name__ == '__main__':
  86. if not osp.exists('data/LaPa/annotations'):
  87. os.makedirs('data/LaPa/annotations')
  88. for tv in ['val', 'test', 'train', 'trainval']:
  89. print(f'processing {tv}')
  90. convert_labpa_to_coco(tv, f'data/LaPa/annotations/lapa_{tv}.json')