Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

pose_estimation_metrics_test.py 11 KB

You have to be logged in to leave a comment. Sign In
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
  1. import collections
  2. import os.path
  3. import random
  4. import tempfile
  5. import unittest
  6. from pprint import pprint
  7. from typing import List, Tuple
  8. import json_tricks as json
  9. import numpy as np
  10. import torch.cuda
  11. from pycocotools.coco import COCO
  12. from pycocotools.cocoeval import COCOeval
  13. from super_gradients.training.datasets.pose_estimation_datasets.coco_utils import (
  14. remove_duplicate_annotations,
  15. make_keypoints_outside_image_invisible,
  16. remove_crowd_annotations,
  17. )
  18. from super_gradients.training.metrics.pose_estimation_metrics import PoseEstimationMetrics
  19. class TestPoseEstimationMetrics(unittest.TestCase):
  20. def _load_coco_groundtruth(self, with_crowd: bool, with_duplicates: bool, with_invisible_keypoitns: bool):
  21. gt_annotations_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data/coco2017/annotations/person_keypoints_val2017.json")
  22. assert os.path.isfile(gt_annotations_path)
  23. gt = COCO(gt_annotations_path)
  24. if not with_duplicates:
  25. gt = remove_duplicate_annotations(gt)
  26. if not with_invisible_keypoitns:
  27. gt = make_keypoints_outside_image_invisible(gt)
  28. if not with_crowd:
  29. gt = remove_crowd_annotations(gt)
  30. return gt
  31. def _internal_compare_method(self, with_crowd: bool, with_duplicates: bool, with_invisible_keypoitns: bool, device: str):
  32. random.seed(0)
  33. np.random.seed(0)
  34. # Load groundtruth annotations
  35. gt = self._load_coco_groundtruth(with_crowd, with_duplicates, with_invisible_keypoitns)
  36. # Generate predictions by randomly dropping some instances and adding noise to remaining poses
  37. (
  38. predicted_poses,
  39. predicted_scores,
  40. groundtruths_poses,
  41. groundtruths_iscrowd,
  42. groundtruths_areas,
  43. groundtruths_bboxes,
  44. image_ids,
  45. ) = self.generate_noised_predictions(gt, instance_drop_probability=0.1, pose_offset=1)
  46. # Compute metrics using SG implementation
  47. def convert_predictions_to_target_format(preds):
  48. # This is out predictions decode function. Here it's no-op since we pass decoded predictions as the input
  49. # but in real life this post-processing callback should be doing actual pose decoding & NMS
  50. return preds
  51. sg_metrics = PoseEstimationMetrics(
  52. post_prediction_callback=convert_predictions_to_target_format,
  53. num_joints=17,
  54. max_objects_per_image=20,
  55. iou_thresholds_to_report=(0.5, 0.75),
  56. ).to(device)
  57. sg_metrics.update(
  58. preds=(predicted_poses, predicted_scores),
  59. target=None,
  60. gt_joints=groundtruths_poses,
  61. gt_iscrowd=groundtruths_iscrowd,
  62. gt_areas=groundtruths_areas,
  63. gt_bboxes=groundtruths_bboxes,
  64. )
  65. actual_metrics = sg_metrics.compute()
  66. pprint(actual_metrics)
  67. coco_pred = self._coco_convert_predictions_to_dict(predicted_poses, predicted_scores, image_ids)
  68. with tempfile.TemporaryDirectory() as td:
  69. res_file = os.path.join(td, "keypoints_coco2017_results.json")
  70. with open(res_file, "w") as f:
  71. json.dump(coco_pred, f, sort_keys=True, indent=4)
  72. coco_dt = self._load_coco_groundtruth(with_crowd, with_duplicates, with_invisible_keypoitns)
  73. coco_dt = coco_dt.loadRes(res_file)
  74. coco_evaluator = COCOeval(gt, coco_dt, iouType="keypoints")
  75. coco_evaluator.evaluate() # run per image evaluation
  76. coco_evaluator.accumulate() # accumulate per image results
  77. coco_evaluator.summarize() # display summary metrics of results
  78. expected_metrics = coco_evaluator.stats
  79. self.assertAlmostEquals(expected_metrics[0], actual_metrics["AP"], delta=0.002)
  80. self.assertAlmostEquals(expected_metrics[5], actual_metrics["AR"], delta=0.002)
  81. def test_compare_pycocotools_with_our_implementation_no_crowd(self):
  82. for device in ["cuda", "cpu"] if torch.cuda.is_available() else ["cpu"]:
  83. self._internal_compare_method(False, True, True, device)
  84. def test_compare_pycocotools_with_our_implementation_no_duplicates(self):
  85. for device in ["cuda", "cpu"] if torch.cuda.is_available() else ["cpu"]:
  86. self._internal_compare_method(True, False, True, device)
  87. def test_compare_pycocotools_with_our_implementation_no_invisible(self):
  88. for device in ["cuda", "cpu"] if torch.cuda.is_available() else ["cpu"]:
  89. self._internal_compare_method(True, True, False, device)
  90. def test_metric_works_on_empty_predictions(self):
  91. # Compute metrics using SG implementation
  92. def convert_predictions_to_target_format(preds):
  93. # This is out predictions decode function. Here it's no-op since we pass decoded predictions as the input
  94. # but in real life this post-processing callback should be doing actual pose decoding & NMS
  95. return preds
  96. sg_metrics = PoseEstimationMetrics(
  97. post_prediction_callback=convert_predictions_to_target_format,
  98. num_joints=17,
  99. max_objects_per_image=20,
  100. iou_thresholds=None,
  101. oks_sigmas=None,
  102. )
  103. actual_metrics = sg_metrics.compute()
  104. pprint(actual_metrics)
  105. self.assertEqual(-1, actual_metrics["AP"])
  106. self.assertEqual(-1, actual_metrics["AR"])
  107. def generate_noised_predictions(self, coco: COCO, instance_drop_probability: float, pose_offset: float) -> Tuple[List, List, List]:
  108. """
  109. :param coco:
  110. :return: List of tuples (poses, image_id)
  111. """
  112. image_ids = []
  113. predicted_poses = []
  114. predicted_scores = []
  115. groundtruths_poses = []
  116. groundtruths_iscrowd = []
  117. groundtruths_areas = []
  118. groundtruths_bboxes = []
  119. for image_id, image_info in coco.imgs.items():
  120. image_id_int = int(image_id)
  121. image_width = image_info["width"]
  122. image_height = image_info["height"]
  123. ann_ids = coco.getAnnIds(imgIds=image_id_int)
  124. anns = coco.loadAnns(ann_ids)
  125. image_pred_keypoints = []
  126. image_gt_keypoints = []
  127. image_gt_iscrowd = []
  128. image_gt_areas = []
  129. image_gt_bboxes = []
  130. for ann in anns:
  131. gt_keypoints = np.array(ann["keypoints"]).reshape(-1, 3).astype(np.float32)
  132. image_gt_keypoints.append(gt_keypoints)
  133. image_gt_iscrowd.append(ann["iscrowd"])
  134. image_gt_areas.append(ann["area"])
  135. image_gt_bboxes.append(ann["bbox"])
  136. if np.random.rand() < instance_drop_probability:
  137. continue
  138. keypoints = gt_keypoints.copy()
  139. if pose_offset > 0:
  140. keypoints[:, 0] += (2 * np.random.randn() - 1) * pose_offset
  141. keypoints[:, 1] += (2 * np.random.randn() - 1) * pose_offset
  142. keypoints[:, 0] = np.clip(keypoints[:, 0], 0, image_width)
  143. keypoints[:, 1] = np.clip(keypoints[:, 1], 0, image_height)
  144. # Apply random score for visible keypoints
  145. keypoints[:, 2] = (keypoints[:, 2] > 0) * np.random.randn(len(keypoints))
  146. image_pred_keypoints.append(keypoints)
  147. image_ids.append(image_id_int)
  148. predicted_poses.append(image_pred_keypoints)
  149. predicted_scores.append(np.random.rand(len(image_pred_keypoints)))
  150. groundtruths_poses.append(image_gt_keypoints)
  151. groundtruths_iscrowd.append(np.array(image_gt_iscrowd, dtype=bool))
  152. groundtruths_areas.append(np.array(image_gt_areas))
  153. groundtruths_bboxes.append(np.array(image_gt_bboxes))
  154. return predicted_poses, predicted_scores, groundtruths_poses, groundtruths_iscrowd, groundtruths_areas, groundtruths_bboxes, image_ids
  155. def _coco_convert_predictions_to_dict(self, predicted_poses, predicted_scores, image_ids):
  156. kpts = collections.defaultdict(list)
  157. for poses, scores, image_id_int in zip(predicted_poses, predicted_scores, image_ids):
  158. for person_index, kpt in enumerate(poses):
  159. area = (np.max(kpt[:, 0]) - np.min(kpt[:, 0])) * (np.max(kpt[:, 1]) - np.min(kpt[:, 1]))
  160. kpt = self._coco_process_keypoints(kpt)
  161. kpts[image_id_int].append({"keypoints": kpt[:, 0:3], "score": float(scores[person_index]), "image": image_id_int, "area": area})
  162. oks_nmsed_kpts = []
  163. # image x person x (keypoints)
  164. for img in kpts.keys():
  165. # person x (keypoints)
  166. img_kpts = kpts[img]
  167. # person x (keypoints)
  168. # do not use nms, keep all detections
  169. keep = []
  170. if len(keep) == 0:
  171. oks_nmsed_kpts.append(img_kpts)
  172. else:
  173. oks_nmsed_kpts.append([img_kpts[_keep] for _keep in keep])
  174. classes = ["__background__", "person"]
  175. _class_to_coco_ind = {cls: i for i, cls in enumerate(classes)}
  176. data_pack = [
  177. {"cat_id": _class_to_coco_ind[cls], "cls_ind": cls_ind, "cls": cls, "ann_type": "keypoints", "keypoints": oks_nmsed_kpts}
  178. for cls_ind, cls in enumerate(classes)
  179. if not cls == "__background__"
  180. ]
  181. results = self._coco_keypoint_results_one_category_kernel(data_pack[0], num_joints=17)
  182. return results
  183. def _coco_keypoint_results_one_category_kernel(self, data_pack, num_joints: int):
  184. cat_id = data_pack["cat_id"]
  185. keypoints = data_pack["keypoints"]
  186. cat_results = []
  187. for img_kpts in keypoints:
  188. if len(img_kpts) == 0:
  189. continue
  190. _key_points = np.array([img_kpts[k]["keypoints"] for k in range(len(img_kpts))])
  191. key_points = np.zeros((_key_points.shape[0], num_joints * 3), dtype=np.float32)
  192. for ipt in range(num_joints):
  193. key_points[:, ipt * 3 + 0] = _key_points[:, ipt, 0]
  194. key_points[:, ipt * 3 + 1] = _key_points[:, ipt, 1]
  195. # keypoints score.
  196. key_points[:, ipt * 3 + 2] = _key_points[:, ipt, 2]
  197. for k in range(len(img_kpts)):
  198. kpt = key_points[k].reshape((num_joints, 3))
  199. left_top = np.amin(kpt, axis=0)
  200. right_bottom = np.amax(kpt, axis=0)
  201. w = right_bottom[0] - left_top[0]
  202. h = right_bottom[1] - left_top[1]
  203. cat_results.append(
  204. {
  205. "image_id": img_kpts[k]["image"],
  206. "category_id": cat_id,
  207. "keypoints": list(key_points[k]),
  208. "score": img_kpts[k]["score"],
  209. "bbox": list([left_top[0], left_top[1], w, h]),
  210. }
  211. )
  212. return cat_results
  213. def _coco_process_keypoints(self, keypoints):
  214. tmp = keypoints.copy()
  215. if keypoints[:, 2].max() > 0:
  216. num_keypoints = keypoints.shape[0]
  217. for i in range(num_keypoints):
  218. tmp[i][0:3] = [float(keypoints[i][0]), float(keypoints[i][1]), float(keypoints[i][2])]
  219. return tmp
  220. if __name__ == "__main__":
  221. unittest.main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...