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

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

Comments

Loading...