Master-Shi commited on
Commit
384c96b
·
verified ·
1 Parent(s): 172a29b

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/coco_eval.py +916 -0
  2. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/coco_reindex.py +230 -0
  3. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/__init__.py +1 -0
  4. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/run_ytvis_eval.py +114 -0
  5. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/__init__.py +4 -0
  6. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/_timing.py +68 -0
  7. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/eval.py +395 -0
  8. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/metrics/_base_metric.py +145 -0
  9. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/metrics/count.py +48 -0
  10. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/utils.py +195 -0
  11. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/postprocessors.py +648 -0
  12. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/__init__.py +5 -0
  13. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/_timing.py +69 -0
  14. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/config.py +153 -0
  15. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/eval.py +275 -0
  16. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/metrics/__init__.py +4 -0
  17. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/metrics/_base_metric.py +148 -0
  18. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/metrics/teta.py +399 -0
  19. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/utils.py +46 -0
  20. 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/ytvis_coco_wrapper.py +146 -0
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/coco_eval.py ADDED
@@ -0,0 +1,916 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ """
4
+ COCO evaluator that works in distributed mode.
5
+
6
+ Mostly copy-paste from https://github.com/pytorch/vision/blob/edfd5a7/references/detection/coco_eval.py
7
+ The difference is that there is less copy-pasting from pycocotools
8
+ in the end of the file, as python3 can suppress prints with contextlib
9
+ """
10
+
11
+ import contextlib
12
+ import copy
13
+ import json
14
+ import logging
15
+ import os
16
+ import pickle
17
+ from collections import defaultdict
18
+ from pathlib import Path
19
+
20
+ from typing import Any, List, Optional
21
+
22
+ import numpy as np
23
+
24
+ import pycocotools.mask as mask_utils
25
+ import torch
26
+ from iopath.common.file_io import g_pathmgr
27
+ from pycocotools.coco import COCO
28
+ from pycocotools.cocoeval import COCOeval
29
+
30
+ from sam3.train.masks_ops import rle_encode
31
+
32
+ from sam3.train.utils.distributed import (
33
+ all_gather,
34
+ gather_to_rank_0_via_filesys,
35
+ get_rank,
36
+ is_main_process,
37
+ )
38
+
39
+ RARITY_BUCKETS = {0: "frequent", 1: "common", 2: "medium", 3: "rare"}
40
+
41
+
42
+ class CocoEvaluator:
43
+ def __init__(
44
+ self,
45
+ coco_gt,
46
+ iou_types: List[str],
47
+ useCats: bool,
48
+ dump_dir: Optional[str],
49
+ postprocessor,
50
+ average_by_rarity=False,
51
+ metrics_dump_dir: Optional[str] = None,
52
+ gather_pred_via_filesys=False,
53
+ use_normalized_areas=True,
54
+ maxdets=[1, 10, 100],
55
+ exhaustive_only=False,
56
+ all_exhaustive_only=True,
57
+ ):
58
+ """Online coco evaluator. It will evaluate images as they are generated by the model, then accumulate/summarize at the end
59
+
60
+ Args:
61
+ - coco_gt: COCO api object containing the gt
62
+ - iou_types: can be either "bbox" or "segm"
63
+ - useCats: If true, categories will be used for evaluation
64
+ - dump_dir: if non null, then the predictions will be dumped in that directory
65
+ - postprocessor: Module to convert the model's output into the coco format
66
+ - average_by_rarity: if true then we expect the images information in the gt dataset
67
+ to have a "rarity" field. Then the AP will be computed on all rarity buckets
68
+ individually, then averaged
69
+ - gather_pred_via_filesys: if true, we use the filesystem for collective gathers
70
+ - use_normalized_areas: if true, the areas of the objects in the GT are assumed to be
71
+ normalized by the area of the image. In that case, the size buckets are adjusted
72
+ - maxdets: maximal number of detections to be evaluated on each image.
73
+ - exhaustive_only: If true, we restrict eval only to exhaustive annotations
74
+ - all_exhaustive_only: If true, datapoints are restricted only to those with all exhaustive annotations
75
+
76
+ """
77
+ # coco_gt = copy.deepcopy(coco_gt)
78
+ self.coco_gts = [coco_gt] if not isinstance(coco_gt, list) else coco_gt
79
+ assert len(maxdets) == 3, f"expecting 3 detection threshold, got {len(maxdets)}"
80
+
81
+ self.use_normalized_areas = use_normalized_areas
82
+ self.iou_types = iou_types
83
+ self.useCats = useCats
84
+ self.maxdets = maxdets
85
+ self.dump = None
86
+ self.dump_dir = dump_dir
87
+ if self.dump_dir is not None:
88
+ self.dump = []
89
+ if is_main_process():
90
+ if not os.path.exists(self.dump_dir):
91
+ os.makedirs(self.dump_dir, exist_ok=True)
92
+ logging.info(f"Create the folder: {dump_dir}")
93
+
94
+ self.initialized = False
95
+
96
+ # Whether to gather predictions through filesystem (instead of torch
97
+ # collective ops; requiring a shared filesystem across all ranks)
98
+ self.gather_pred_via_filesys = gather_pred_via_filesys
99
+ self.use_self_evaluate = True # CPP version is disabled
100
+ self.postprocessor = postprocessor
101
+ self.average_by_rarity = average_by_rarity
102
+ self.exhaustive_only = exhaustive_only
103
+ self.all_exhaustive_only = all_exhaustive_only
104
+ self.metrics_dump_dir = metrics_dump_dir
105
+ if self.metrics_dump_dir is not None:
106
+ if is_main_process():
107
+ if not os.path.exists(self.metrics_dump_dir):
108
+ os.makedirs(self.metrics_dump_dir, exist_ok=True)
109
+ logging.info(f"Create the folder: {metrics_dump_dir}")
110
+
111
+ def _lazy_init(self, coco_cls=COCO):
112
+ if self.initialized:
113
+ return
114
+
115
+ self.initialized = True
116
+
117
+ self.coco_gts = [
118
+ coco_cls(g_pathmgr.get_local_path(gt)) if isinstance(gt, str) else gt
119
+ for gt in self.coco_gts
120
+ ]
121
+
122
+ self.reset()
123
+
124
+ self.eval_img_ids = None
125
+
126
+ if self.exhaustive_only:
127
+ exclude_img_ids = set()
128
+ # exclude_img_ids are the ids that are not exhaustively annotated in any of the other gts
129
+ if self.all_exhaustive_only:
130
+ for coco_gt in self.coco_gts[1:]:
131
+ exclude_img_ids = exclude_img_ids.union(
132
+ {
133
+ img["id"]
134
+ for img in coco_gt.dataset["images"]
135
+ if not img["is_instance_exhaustive"]
136
+ }
137
+ )
138
+ # we only eval on instance exhaustive queries
139
+ self.eval_img_ids = [
140
+ img["id"]
141
+ for img in self.coco_gts[0].dataset["images"]
142
+ if (img["is_instance_exhaustive"] and img["id"] not in exclude_img_ids)
143
+ ]
144
+
145
+ self.rarity_buckets = None
146
+ if self.average_by_rarity:
147
+ self.rarity_buckets = defaultdict(list)
148
+ eval_img_ids_set = (
149
+ set(self.eval_img_ids) if self.eval_img_ids is not None else None
150
+ )
151
+ for img in self.coco_gts[0].dataset["images"]:
152
+ if self.eval_img_ids is not None and img["id"] not in eval_img_ids_set:
153
+ continue
154
+ self.rarity_buckets[img["rarity"]].append(img["id"])
155
+ print("Rarity buckets sizes:")
156
+ for k, v in self.rarity_buckets.items():
157
+ print(f"{k}: {len(v)}")
158
+
159
+ def set_sync_device(self, device: torch.device) -> Any:
160
+ self._sync_device = device
161
+
162
+ def _evaluate(self, *args, **kwargs):
163
+ return evaluate(*args, **kwargs)
164
+
165
+ def _loadRes(self, *args, **kwargs):
166
+ return loadRes(*args, **kwargs)
167
+
168
+ def update(self, *args, **kwargs):
169
+ self._lazy_init()
170
+ predictions = self.postprocessor.process_results(*args, **kwargs)
171
+
172
+ img_ids = list(np.unique(list(predictions.keys())))
173
+ self.img_ids.extend(img_ids)
174
+
175
+ for iou_type in self.iou_types:
176
+ results = self.prepare(predictions, iou_type)
177
+ self._dump(results)
178
+
179
+ assert len(self.coco_gts) == len(self.coco_evals)
180
+ all_scorings = []
181
+ for cur_coco_gt, cur_coco_eval in zip(self.coco_gts, self.coco_evals):
182
+ # suppress pycocotools prints
183
+ with open(os.devnull, "w") as devnull:
184
+ with contextlib.redirect_stdout(devnull):
185
+ coco_dt = (
186
+ self._loadRes(cur_coco_gt, results) if results else COCO()
187
+ )
188
+
189
+ coco_eval = cur_coco_eval[iou_type]
190
+
191
+ coco_eval.cocoDt = coco_dt
192
+ coco_eval.params.imgIds = list(img_ids)
193
+ coco_eval.params.useCats = self.useCats
194
+ coco_eval.params.maxDets = self.maxdets
195
+ img_ids, eval_imgs = self._evaluate(coco_eval, self.use_self_evaluate)
196
+ all_scorings.append(eval_imgs)
197
+
198
+ selected = self.select_best_scoring(all_scorings)
199
+ self.eval_imgs[iou_type].append(selected)
200
+
201
+ def select_best_scoring(self, scorings):
202
+ # This function is used for "oracle" type evaluation.
203
+ # It accepts the evaluation results with respect to several ground truths, and picks the best
204
+ if len(scorings) == 1:
205
+ return scorings[0]
206
+
207
+ # Currently we don't support Oracle Phrase AP.
208
+ # To implement it, we likely need to modify the cpp code since the eval_image type is opaque
209
+ raise RuntimeError("Not implemented")
210
+
211
+ def _dump(self, results):
212
+ if self.dump is not None:
213
+ dumped_results = copy.deepcopy(results)
214
+ for r in dumped_results:
215
+ if "bbox" not in self.iou_types and "bbox" in r:
216
+ del r["bbox"]
217
+ elif "bbox" in r:
218
+ r["bbox"] = [round(coord, 5) for coord in r["bbox"]]
219
+ r["score"] = round(r["score"], 5)
220
+ self.dump.extend(dumped_results)
221
+
222
+ def synchronize_between_processes(self):
223
+ self._lazy_init()
224
+ logging.info("Coco evaluator: Synchronizing between processes")
225
+ for iou_type in self.iou_types:
226
+ if len(self.eval_imgs[iou_type]) > 0:
227
+ self.eval_imgs[iou_type] = np.concatenate(self.eval_imgs[iou_type], 2)
228
+ else:
229
+ num_areas = len(self.coco_evals[0][iou_type].params.areaRng)
230
+ # assuming 1 class
231
+ assert not self.useCats
232
+ self.eval_imgs[iou_type] = np.empty((1, num_areas, 0))
233
+ create_common_coco_eval(
234
+ self.coco_evals[0][iou_type],
235
+ self.img_ids,
236
+ self.eval_imgs[iou_type],
237
+ use_self_evaluate=self.use_self_evaluate,
238
+ gather_pred_via_filesys=self.gather_pred_via_filesys,
239
+ metrics_dump_dir=self.metrics_dump_dir,
240
+ )
241
+ if self.dump is not None:
242
+ dumped_file = Path(self.dump_dir) / f"coco_predictions_{get_rank()}.json"
243
+ logging.info(f"COCO evaluator: Dumping local predictions to {dumped_file}")
244
+ with g_pathmgr.open(str(dumped_file), "w") as f:
245
+ json.dump(self.dump, f)
246
+
247
+ # if self.gather_pred_via_filesys:
248
+ # dump = gather_to_rank_0_via_filesys(self.dump)
249
+ # else:
250
+ # dump = all_gather(self.dump, force_cpu=True)
251
+ # self.dump = sum(dump, [])
252
+
253
+ def accumulate(self, imgIds=None):
254
+ self._lazy_init()
255
+ logging.info(
256
+ f"Coco evaluator: Accumulating on {len(imgIds) if imgIds is not None else 'all'} images"
257
+ )
258
+ if not is_main_process():
259
+ return
260
+
261
+ if imgIds is None:
262
+ for coco_eval in self.coco_evals[0].values():
263
+ accumulate(coco_eval, use_self_eval=self.use_self_evaluate)
264
+
265
+ if imgIds is not None:
266
+ imgIds = set(imgIds)
267
+ for coco_eval in self.coco_evals[0].values():
268
+ p = coco_eval.params
269
+ id_mask = np.array([(i in imgIds) for i in p.imgIds], dtype=bool)
270
+ old_img_ids = p.imgIds
271
+ coco_eval.params.imgIds = np.asarray(p.imgIds)[id_mask]
272
+ old_img_evals = coco_eval.evalImgs
273
+ catIds = p.catIds if p.useCats else [-1]
274
+ coco_eval.evalImgs = list(
275
+ np.asarray(coco_eval.evalImgs)
276
+ .reshape(len(catIds), len(p.areaRng), len(old_img_ids))[
277
+ ..., id_mask
278
+ ]
279
+ .flatten()
280
+ )
281
+ accumulate(coco_eval, use_self_eval=self.use_self_evaluate)
282
+ coco_eval.evalImgs = old_img_evals
283
+ coco_eval.params.imgIds = old_img_ids
284
+
285
+ def summarize(self):
286
+ self._lazy_init()
287
+ logging.info("Coco evaluator: Summarizing")
288
+ if not is_main_process():
289
+ return {}
290
+
291
+ outs = {}
292
+ if self.rarity_buckets is None:
293
+ self.accumulate(self.eval_img_ids)
294
+ for iou_type, coco_eval in self.coco_evals[0].items():
295
+ print("IoU metric: {}".format(iou_type))
296
+ summarize(coco_eval)
297
+
298
+ if "bbox" in self.coco_evals[0]:
299
+ for key, value in zip(*self.coco_evals[0]["bbox"].stats):
300
+ outs[f"coco_eval_bbox_{key}"] = value
301
+ if "segm" in self.coco_evals[0]:
302
+ for key, value in zip(*self.coco_evals[0]["segm"].stats):
303
+ outs[f"coco_eval_masks_{key}"] = value
304
+ else:
305
+ total_stats = {}
306
+ all_keys = {}
307
+ for bucket, img_list in self.rarity_buckets.items():
308
+ self.accumulate(imgIds=img_list)
309
+ bucket_name = RARITY_BUCKETS[bucket]
310
+ for iou_type, coco_eval in self.coco_evals[0].items():
311
+ print(f"IoU metric: {iou_type}. Rarity bucket: {bucket_name}")
312
+ summarize(coco_eval)
313
+
314
+ if "bbox" in self.coco_evals[0]:
315
+ if "bbox" not in total_stats:
316
+ total_stats["bbox"] = np.zeros_like(
317
+ self.coco_evals[0]["bbox"].stats[1]
318
+ )
319
+ all_keys["bbox"] = self.coco_evals[0]["bbox"].stats[0]
320
+ total_stats["bbox"] += self.coco_evals[0]["bbox"].stats[1]
321
+ for key, value in zip(*self.coco_evals[0]["bbox"].stats):
322
+ outs[f"coco_eval_bbox_{bucket_name}_{key}"] = value
323
+ if "segm" in self.coco_evals[0]:
324
+ if "segm" not in total_stats:
325
+ total_stats["segm"] = np.zeros_like(
326
+ self.coco_evals[0]["segm"].stats[1]
327
+ )
328
+ all_keys["segm"] = self.coco_evals[0]["segm"].stats[0]
329
+ total_stats["segm"] += self.coco_evals[0]["segm"].stats[1]
330
+ for key, value in zip(*self.coco_evals[0]["segm"].stats):
331
+ outs[f"coco_eval_masks_{bucket_name}_{key}"] = value
332
+
333
+ if "bbox" in total_stats:
334
+ total_stats["bbox"] /= len(self.rarity_buckets)
335
+ for key, value in zip(all_keys["bbox"], total_stats["bbox"]):
336
+ outs[f"coco_eval_bbox_{key}"] = value
337
+ if "segm" in total_stats:
338
+ total_stats["segm"] /= len(self.rarity_buckets)
339
+ for key, value in zip(all_keys["segm"], total_stats["segm"]):
340
+ outs[f"coco_eval_masks_{key}"] = value
341
+
342
+ # if self.dump is not None:
343
+ # assert self.dump_dir is not None
344
+ # logging.info("Coco evaluator: Dumping the global result file to disk")
345
+ # with g_pathmgr.open(str(Path(self.dump_dir) / "coco_eval.json"), "w") as f:
346
+ # json.dump(self.dump, f)
347
+ return outs
348
+
349
+ def compute_synced(self):
350
+ self._lazy_init()
351
+ self.synchronize_between_processes()
352
+ return self.summarize()
353
+
354
+ def compute(self):
355
+ self._lazy_init()
356
+ return {"": 0.0}
357
+
358
+ def reset(self, cocoeval_cls=COCOeval):
359
+ self.coco_evals = [{} for _ in range(len(self.coco_gts))]
360
+ for i, coco_gt in enumerate(self.coco_gts):
361
+ for iou_type in self.iou_types:
362
+ self.coco_evals[i][iou_type] = cocoeval_cls(coco_gt, iouType=iou_type)
363
+ self.coco_evals[i][iou_type].params.useCats = self.useCats
364
+ self.coco_evals[i][iou_type].params.maxDets = self.maxdets
365
+ if self.use_normalized_areas:
366
+ self.coco_evals[i][iou_type].params.areaRng = [
367
+ [0, 1e5],
368
+ [0, 0.001],
369
+ [0.001, 0.01],
370
+ [0.01, 0.1],
371
+ [0.1, 0.5],
372
+ [0.5, 0.95],
373
+ [0.95, 1e5],
374
+ ]
375
+ self.coco_evals[i][iou_type].params.areaRngLbl = [
376
+ "all",
377
+ "tiny",
378
+ "small",
379
+ "medium",
380
+ "large",
381
+ "huge",
382
+ "whole_image",
383
+ ]
384
+
385
+ self.img_ids = []
386
+ self.eval_imgs = {k: [] for k in self.iou_types}
387
+ if self.dump is not None:
388
+ self.dump = []
389
+
390
+ def write(self, stats):
391
+ self._lazy_init()
392
+ """Write the results in the stats dict"""
393
+ if "bbox" in self.coco_evals[0]:
394
+ stats["coco_eval_bbox"] = self.coco_evals[0]["bbox"].stats.tolist()
395
+ if "segm" in self.coco_evals[0]:
396
+ stats["coco_eval_masks"] = self.coco_evals[0]["segm"].stats.tolist()
397
+ return stats
398
+
399
+ def prepare(self, predictions, iou_type):
400
+ self._lazy_init()
401
+ if iou_type == "bbox":
402
+ return self.prepare_for_coco_detection(predictions)
403
+ elif iou_type == "segm":
404
+ return self.prepare_for_coco_segmentation(predictions)
405
+ elif iou_type == "keypoints":
406
+ return self.prepare_for_coco_keypoint(predictions)
407
+ else:
408
+ raise ValueError("Unknown iou type {}".format(iou_type))
409
+
410
+ def prepare_for_coco_detection(self, predictions):
411
+ self._lazy_init()
412
+ coco_results = []
413
+ for original_id, prediction in predictions.items():
414
+ if len(prediction) == 0:
415
+ continue
416
+
417
+ boxes = prediction["boxes"]
418
+ boxes = convert_to_xywh(boxes).tolist()
419
+ scores = prediction["scores"].tolist()
420
+ labels = prediction["labels"].tolist()
421
+
422
+ coco_results.extend(
423
+ [
424
+ {
425
+ "image_id": original_id,
426
+ "category_id": labels[k],
427
+ "bbox": box,
428
+ "score": scores[k],
429
+ }
430
+ for k, box in enumerate(boxes)
431
+ ]
432
+ )
433
+ return coco_results
434
+
435
+ @torch.no_grad()
436
+ def prepare_for_coco_segmentation(self, predictions):
437
+ self._lazy_init()
438
+ coco_results = []
439
+ for original_id, prediction in predictions.items():
440
+ if len(prediction) == 0:
441
+ continue
442
+
443
+ scores = prediction["scores"].tolist()
444
+ labels = prediction["labels"].tolist()
445
+ boundaries, dilated_boundaries = None, None
446
+ if "boundaries" in prediction:
447
+ boundaries = prediction["boundaries"]
448
+ dilated_boundaries = prediction["dilated_boundaries"]
449
+ assert dilated_boundaries is not None
450
+ assert len(scores) == len(boundaries)
451
+
452
+ if "masks_rle" in prediction:
453
+ rles = prediction["masks_rle"]
454
+ areas = []
455
+ for rle in rles:
456
+ cur_area = mask_utils.area(rle)
457
+ h, w = rle["size"]
458
+ areas.append(cur_area / (h * w))
459
+ else:
460
+ masks = prediction["masks"]
461
+
462
+ masks = masks > 0.5
463
+ h, w = masks.shape[-2:]
464
+
465
+ areas = masks.flatten(1).sum(1) / (h * w)
466
+ areas = areas.tolist()
467
+
468
+ rles = rle_encode(masks.squeeze(1))
469
+
470
+ # memory clean
471
+ del masks
472
+ del prediction["masks"]
473
+
474
+ assert len(areas) == len(rles) == len(scores)
475
+ for k, rle in enumerate(rles):
476
+ payload = {
477
+ "image_id": original_id,
478
+ "category_id": labels[k],
479
+ "segmentation": rle,
480
+ "score": scores[k],
481
+ "area": areas[k],
482
+ }
483
+ if boundaries is not None:
484
+ payload["boundary"] = boundaries[k]
485
+ payload["dilated_boundary"] = dilated_boundaries[k]
486
+
487
+ coco_results.append(payload)
488
+
489
+ return coco_results
490
+
491
+ def prepare_for_coco_keypoint(self, predictions):
492
+ self._lazy_init()
493
+ coco_results = []
494
+ for original_id, prediction in predictions.items():
495
+ if len(prediction) == 0:
496
+ continue
497
+
498
+ boxes = prediction["boxes"]
499
+ boxes = convert_to_xywh(boxes).tolist()
500
+ scores = prediction["scores"].tolist()
501
+ labels = prediction["labels"].tolist()
502
+ keypoints = prediction["keypoints"]
503
+ keypoints = keypoints.flatten(start_dim=1).tolist()
504
+
505
+ coco_results.extend(
506
+ [
507
+ {
508
+ "image_id": original_id,
509
+ "category_id": labels[k],
510
+ "keypoints": keypoint,
511
+ "score": scores[k],
512
+ }
513
+ for k, keypoint in enumerate(keypoints)
514
+ ]
515
+ )
516
+ return coco_results
517
+
518
+
519
+ def convert_to_xywh(boxes):
520
+ xmin, ymin, xmax, ymax = boxes.unbind(-1)
521
+ return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=-1)
522
+
523
+
524
+ def merge(img_ids, eval_imgs, gather_pred_via_filesys=False):
525
+ if gather_pred_via_filesys:
526
+ # only gather the predictions to rank 0 (other ranks will receive empty
527
+ # lists for `all_img_ids` and `all_eval_imgs`, which should be OK as
528
+ # merging and evaluation are only done on rank 0)
529
+ all_img_ids = gather_to_rank_0_via_filesys(img_ids)
530
+ all_eval_imgs = gather_to_rank_0_via_filesys(eval_imgs)
531
+ else:
532
+ all_img_ids = all_gather(img_ids, force_cpu=True)
533
+ all_eval_imgs = all_gather(eval_imgs, force_cpu=True)
534
+ if not is_main_process():
535
+ return None, None
536
+
537
+ merged_img_ids = []
538
+ for p in all_img_ids:
539
+ merged_img_ids.extend(p)
540
+
541
+ merged_eval_imgs = []
542
+ for p in all_eval_imgs:
543
+ merged_eval_imgs.append(p)
544
+
545
+ merged_img_ids = np.array(merged_img_ids)
546
+ merged_eval_imgs = np.concatenate(merged_eval_imgs, 2)
547
+
548
+ # keep only unique (and in sorted order) images
549
+ merged_img_ids, idx = np.unique(merged_img_ids, return_index=True)
550
+ merged_eval_imgs = merged_eval_imgs[..., idx]
551
+
552
+ return merged_img_ids, merged_eval_imgs
553
+
554
+
555
+ def create_common_coco_eval(
556
+ coco_eval,
557
+ img_ids,
558
+ eval_imgs,
559
+ use_self_evaluate,
560
+ gather_pred_via_filesys=False,
561
+ metrics_dump_dir=None,
562
+ ):
563
+ img_ids, eval_imgs = merge(img_ids, eval_imgs, gather_pred_via_filesys)
564
+ if not is_main_process():
565
+ return
566
+ if metrics_dump_dir is not None:
567
+ dumped_file = (
568
+ Path(metrics_dump_dir) / f"coco_eval_img_metrics_{get_rank()}.json"
569
+ )
570
+ logging.info(f"COCO evaluator: Dumping local predictions to {dumped_file}")
571
+ with g_pathmgr.open(str(dumped_file), "w") as f:
572
+ json.dump(eval_imgs.squeeze(), f, default=lambda x: x.tolist())
573
+ img_ids = list(img_ids)
574
+
575
+ # If some images were not predicted, we need to create dummy detections for them
576
+ missing_img_ids = set(coco_eval.cocoGt.getImgIds()) - set(img_ids)
577
+ if len(missing_img_ids) > 0:
578
+ print(f"WARNING: {len(missing_img_ids)} images were not predicted!")
579
+ coco_eval.cocoDt = COCO()
580
+ coco_eval.params.imgIds = list(missing_img_ids)
581
+ new_img_ids, new_eval_imgs = evaluate(coco_eval, use_self_evaluate)
582
+ img_ids.extend(new_img_ids)
583
+ eval_imgs = np.concatenate((eval_imgs, new_eval_imgs), axis=2)
584
+
585
+ eval_imgs = list(eval_imgs.flatten())
586
+ assert len(img_ids) == len(coco_eval.cocoGt.getImgIds())
587
+
588
+ coco_eval.evalImgs = eval_imgs
589
+ coco_eval.params.imgIds = img_ids
590
+ coco_eval._paramsEval = copy.deepcopy(coco_eval.params)
591
+
592
+
593
+ #################################################################
594
+ # From pycocotools, just removed the prints and fixed
595
+ # a Python3 bug about unicode not defined
596
+ #################################################################
597
+
598
+
599
+ # Copy of COCO prepare, but doesn't convert anntoRLE
600
+ def segmentation_prepare(self):
601
+ """
602
+ Prepare ._gts and ._dts for evaluation based on params
603
+ :return: None
604
+ """
605
+ p = self.params
606
+ if p.useCats:
607
+ gts = self.cocoGt.loadAnns(
608
+ self.cocoGt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)
609
+ )
610
+ dts = self.cocoDt.loadAnns(
611
+ self.cocoDt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)
612
+ )
613
+ else:
614
+ gts = self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds))
615
+ dts = self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds))
616
+
617
+ for gt in gts:
618
+ gt["ignore"] = gt["ignore"] if "ignore" in gt else 0
619
+ gt["ignore"] = "iscrowd" in gt and gt["iscrowd"]
620
+ if p.iouType == "keypoints":
621
+ gt["ignore"] = (gt["num_keypoints"] == 0) or gt["ignore"]
622
+ self._gts = defaultdict(list) # gt for evaluation
623
+ self._dts = defaultdict(list) # dt for evaluation
624
+ for gt in gts:
625
+ self._gts[gt["image_id"], gt["category_id"]].append(gt)
626
+ for dt in dts:
627
+ self._dts[dt["image_id"], dt["category_id"]].append(dt)
628
+ self.evalImgs = defaultdict(list) # per-image per-category evaluation results
629
+ self.eval = {} # accumulated evaluation results
630
+
631
+
632
+ def evaluate(self, use_self_evaluate):
633
+ """
634
+ Run per image evaluation on given images and store results (a list of dict) in self.evalImgs
635
+ :return: None
636
+ """
637
+ # tic = time.time()
638
+ # print('Running per image evaluation...', use_self_evaluate)
639
+ p = self.params
640
+ # add backward compatibility if useSegm is specified in params
641
+ if p.useSegm is not None:
642
+ p.iouType = "segm" if p.useSegm == 1 else "bbox"
643
+ print(
644
+ "useSegm (deprecated) is not None. Running {} evaluation".format(p.iouType)
645
+ )
646
+ # print('Evaluate annotation type *{}*'.format(p.iouType))
647
+ p.imgIds = list(np.unique(p.imgIds))
648
+ if p.useCats:
649
+ p.catIds = list(np.unique(p.catIds))
650
+ p.maxDets = sorted(p.maxDets)
651
+ self.params = p
652
+
653
+ self._prepare()
654
+ # loop through images, area range, max detection number
655
+ catIds = p.catIds if p.useCats else [-1]
656
+
657
+ if p.iouType == "segm" or p.iouType == "bbox":
658
+ computeIoU = self.computeIoU
659
+ elif p.iouType == "keypoints":
660
+ computeIoU = self.computeOks
661
+ self.ious = {
662
+ (imgId, catId): computeIoU(imgId, catId)
663
+ for imgId in p.imgIds
664
+ for catId in catIds
665
+ }
666
+
667
+ maxDet = p.maxDets[-1]
668
+ if use_self_evaluate:
669
+ evalImgs = [
670
+ self.evaluateImg(imgId, catId, areaRng, maxDet)
671
+ for catId in catIds
672
+ for areaRng in p.areaRng
673
+ for imgId in p.imgIds
674
+ ]
675
+ # this is NOT in the pycocotools code, but could be done outside
676
+ evalImgs = np.asarray(evalImgs).reshape(
677
+ len(catIds), len(p.areaRng), len(p.imgIds)
678
+ )
679
+ return p.imgIds, evalImgs
680
+
681
+ # <<<< Beginning of code differences with original COCO API
682
+ # def convert_instances_to_cpp(instances, is_det=False):
683
+ # # Convert annotations for a list of instances in an image to a format that's fast
684
+ # # to access in C++
685
+ # instances_cpp = []
686
+ # for instance in instances:
687
+ # instance_cpp = _CPP.InstanceAnnotation(
688
+ # int(instance["id"]),
689
+ # instance["score"] if is_det else instance.get("score", 0.0),
690
+ # instance["area"],
691
+ # bool(instance.get("iscrowd", 0)),
692
+ # bool(instance.get("ignore", 0)),
693
+ # )
694
+ # instances_cpp.append(instance_cpp)
695
+ # return instances_cpp
696
+
697
+ # # Convert GT annotations, detections, and IOUs to a format that's fast to access in C++
698
+ # ground_truth_instances = [
699
+ # [convert_instances_to_cpp(self._gts[imgId, catId]) for catId in p.catIds]
700
+ # for imgId in p.imgIds
701
+ # ]
702
+ # detected_instances = [
703
+ # [
704
+ # convert_instances_to_cpp(self._dts[imgId, catId], is_det=True)
705
+ # for catId in p.catIds
706
+ # ]
707
+ # for imgId in p.imgIds
708
+ # ]
709
+ # ious = [[self.ious[imgId, catId] for catId in catIds] for imgId in p.imgIds]
710
+
711
+ # if not p.useCats:
712
+ # # For each image, flatten per-category lists into a single list
713
+ # ground_truth_instances = [
714
+ # [[o for c in i for o in c]] for i in ground_truth_instances
715
+ # ]
716
+ # detected_instances = [[[o for c in i for o in c]] for i in detected_instances]
717
+
718
+ # # Call C++ implementation of self.evaluateImgs()
719
+ # _evalImgs_cpp = _CPP.COCOevalEvaluateImages(
720
+ # p.areaRng, maxDet, p.iouThrs, ious, ground_truth_instances, detected_instances
721
+ # )
722
+
723
+ # self._paramsEval = copy.deepcopy(self.params)
724
+ # evalImgs = np.asarray(_evalImgs_cpp).reshape(
725
+ # len(catIds), len(p.areaRng), len(p.imgIds)
726
+ # )
727
+ # return p.imgIds, evalImgs
728
+
729
+
730
+ #################################################################
731
+ # end of straight copy from pycocotools, just removing the prints
732
+ #################################################################
733
+
734
+
735
+ #################################################################
736
+ # From pycocotools, but disabled mask->box conversion which is
737
+ # pointless
738
+ #################################################################
739
+ def loadRes(self, resFile):
740
+ """
741
+ Load result file and return a result api object.
742
+ :param resFile (str) : file name of result file
743
+ :return: res (obj) : result api object
744
+ """
745
+ res = COCO()
746
+ res.dataset["images"] = [img for img in self.dataset["images"]]
747
+
748
+ if type(resFile) == str:
749
+ anns = json.load(open(resFile))
750
+ elif type(resFile) == np.ndarray:
751
+ anns = self.loadNumpyAnnotations(resFile)
752
+ else:
753
+ anns = resFile
754
+ assert type(anns) == list, "results in not an array of objects"
755
+ annsImgIds = [ann["image_id"] for ann in anns]
756
+ assert set(annsImgIds) == (
757
+ set(annsImgIds) & set(self.getImgIds())
758
+ ), "Results do not correspond to current coco set"
759
+ if "caption" in anns[0]:
760
+ imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
761
+ [ann["image_id"] for ann in anns]
762
+ )
763
+ res.dataset["images"] = [
764
+ img for img in res.dataset["images"] if img["id"] in imgIds
765
+ ]
766
+ for id, ann in enumerate(anns):
767
+ ann["id"] = id + 1
768
+ elif "bbox" in anns[0] and not anns[0]["bbox"] == []:
769
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
770
+ for id, ann in enumerate(anns):
771
+ bb = ann["bbox"]
772
+ x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]]
773
+ if "segmentation" not in ann:
774
+ ann["segmentation"] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
775
+ ann["area"] = bb[2] * bb[3]
776
+ ann["id"] = id + 1
777
+ ann["iscrowd"] = 0
778
+ elif "segmentation" in anns[0]:
779
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
780
+ for id, ann in enumerate(anns):
781
+ # now only support compressed RLE format as segmentation results
782
+ # ann["area"] = mask_util.area(ann["segmentation"])
783
+ # The following lines are disabled because they are pointless
784
+ # if not 'bbox' in ann:
785
+ # ann['bbox'] = maskUtils.toBbox(ann['segmentation'])
786
+ ann["id"] = id + 1
787
+ ann["iscrowd"] = 0
788
+ elif "keypoints" in anns[0]:
789
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
790
+ for id, ann in enumerate(anns):
791
+ s = ann["keypoints"]
792
+ x = s[0::3]
793
+ y = s[1::3]
794
+ x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y)
795
+ ann["area"] = (x1 - x0) * (y1 - y0)
796
+ ann["id"] = id + 1
797
+ ann["bbox"] = [x0, y0, x1 - x0, y1 - y0]
798
+
799
+ res.dataset["annotations"] = anns
800
+ res.createIndex()
801
+ return res
802
+
803
+
804
+ #################################################################
805
+ # end of straight copy from pycocotools
806
+ #################################################################
807
+
808
+
809
+ #################################################################
810
+ # From pycocotools, but added handling of custom area rngs, and returns stat keys
811
+ #################################################################
812
+ def summarize(self):
813
+ """
814
+ Compute and display summary metrics for evaluation results.
815
+ Note this functin can *only* be applied on the default parameter setting
816
+ """
817
+
818
+ def _summarize(ap=1, iouThr=None, areaRng="all", maxDets=100):
819
+ p = self.params
820
+ iStr = " {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}"
821
+ titleStr = "Average Precision" if ap == 1 else "Average Recall"
822
+ typeStr = "(AP)" if ap == 1 else "(AR)"
823
+ iouStr = (
824
+ "{:0.2f}:{:0.2f}".format(p.iouThrs[0], p.iouThrs[-1])
825
+ if iouThr is None
826
+ else "{:0.2f}".format(iouThr)
827
+ )
828
+
829
+ aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]
830
+ mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
831
+ if ap == 1:
832
+ # dimension of precision: [TxRxKxAxM]
833
+ s = self.eval["precision"]
834
+ # IoU
835
+ if iouThr is not None:
836
+ t = np.where(iouThr == p.iouThrs)[0]
837
+ s = s[t]
838
+ s = s[:, :, :, aind, mind]
839
+ else:
840
+ # dimension of recall: [TxKxAxM]
841
+ s = self.eval["recall"]
842
+ if iouThr is not None:
843
+ t = np.where(iouThr == p.iouThrs)[0]
844
+ s = s[t]
845
+ s = s[:, :, aind, mind]
846
+ if len(s[s > -1]) == 0:
847
+ mean_s = -1
848
+ else:
849
+ mean_s = np.mean(s[s > -1])
850
+ print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s))
851
+ return mean_s
852
+
853
+ def _summarizeDets():
854
+ nb_results = 6 + (len(self.params.areaRng) - 1) * 2
855
+ assert len(self.params.areaRng) == len(self.params.areaRngLbl)
856
+ stats = np.zeros((nb_results,))
857
+ keys = ["AP", "AP_50", "AP_75"]
858
+ stats[0] = _summarize(1, maxDets=self.params.maxDets[2])
859
+ stats[1] = _summarize(1, iouThr=0.5, maxDets=self.params.maxDets[2])
860
+ stats[2] = _summarize(1, iouThr=0.75, maxDets=self.params.maxDets[2])
861
+ cur_id = 3
862
+ for area in self.params.areaRngLbl[1:]:
863
+ stats[cur_id] = _summarize(1, areaRng=area, maxDets=self.params.maxDets[2])
864
+ cur_id += 1
865
+ keys.append(f"AP_{area}")
866
+ stats[cur_id] = _summarize(0, maxDets=self.params.maxDets[0])
867
+ cur_id += 1
868
+ stats[cur_id] = _summarize(0, maxDets=self.params.maxDets[1])
869
+ cur_id += 1
870
+ stats[cur_id] = _summarize(0, maxDets=self.params.maxDets[2])
871
+ cur_id += 1
872
+ keys += ["AR", "AR_50", "AR_75"]
873
+
874
+ for area in self.params.areaRngLbl[1:]:
875
+ stats[cur_id] = _summarize(0, areaRng=area, maxDets=self.params.maxDets[2])
876
+ cur_id += 1
877
+ keys.append(f"AR_{area}")
878
+ assert len(stats) == len(keys)
879
+ return keys, stats
880
+
881
+ if not self.eval:
882
+ raise Exception("Please run accumulate() first")
883
+ self.stats = _summarizeDets()
884
+
885
+
886
+ #################################################################
887
+ # end of straight copy from pycocotools
888
+ #################################################################
889
+
890
+
891
+ #################################################################
892
+ # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/evaluation/fast_eval_api.py
893
+ # with slight adjustments
894
+ #################################################################
895
+ def accumulate(self, use_self_eval=False):
896
+ """
897
+ Accumulate per image evaluation results and store the result in self.eval. Does not
898
+ support changing parameter settings from those used by self.evaluate()
899
+ """
900
+ if use_self_eval:
901
+ self.accumulate()
902
+ return
903
+ # CPP code is disabled
904
+ # self.eval = _CPP.COCOevalAccumulate(self.params, self.evalImgs)
905
+
906
+ # # recall is num_iou_thresholds X num_categories X num_area_ranges X num_max_detections
907
+ # self.eval["recall"] = np.array(self.eval["recall"]).reshape(
908
+ # self.eval["counts"][:1] + self.eval["counts"][2:]
909
+ # )
910
+
911
+ # # precision and scores are num_iou_thresholds X num_recall_thresholds X num_categories X
912
+ # # num_area_ranges X num_max_detections
913
+ # self.eval["precision"] = np.array(self.eval["precision"]).reshape(
914
+ # self.eval["counts"]
915
+ # )
916
+ # self.eval["scores"] = np.array(self.eval["scores"]).reshape(self.eval["counts"])
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/coco_reindex.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ """
4
+ Self-contained COCO JSON re-indexing function that creates temporary files.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import tempfile
10
+ from pathlib import Path
11
+ from typing import Any, Dict, List, Optional, Tuple
12
+
13
+
14
+ def reindex_coco_to_temp(input_json_path: str) -> Optional[str]:
15
+ """
16
+ Convert 0-indexed COCO JSON file to 1-indexed and save to temporary location.
17
+
18
+ Args:
19
+ input_json_path: Path to the input COCO JSON file
20
+
21
+ Returns:
22
+ Path to the new 1-indexed JSON file in temporary directory, or None if no conversion needed
23
+
24
+ Raises:
25
+ FileNotFoundError: If input file doesn't exist
26
+ json.JSONDecodeError: If input file is not valid JSON
27
+ ValueError: If input file is not a valid COCO format
28
+ """
29
+
30
+ def is_coco_json(data: Dict[str, Any]) -> bool:
31
+ """Check if data appears to be a COCO format file."""
32
+ if not isinstance(data, dict):
33
+ return False
34
+ # A COCO file should have at least one of these keys
35
+ coco_keys = {"images", "annotations", "categories"}
36
+ return any(key in data for key in coco_keys)
37
+
38
+ def check_zero_indexed(data: Dict[str, Any]) -> Tuple[bool, bool, bool]:
39
+ """
40
+ Check if annotations, images, or categories start from index 0.
41
+
42
+ Returns:
43
+ Tuple of (annotations_zero_indexed, images_zero_indexed, categories_zero_indexed)
44
+ """
45
+ annotations_zero = False
46
+ images_zero = False
47
+ categories_zero = False
48
+
49
+ # Check annotations
50
+ annotations = data.get("annotations", [])
51
+ if annotations and any(ann.get("id", -1) == 0 for ann in annotations):
52
+ annotations_zero = True
53
+
54
+ # Check images
55
+ images = data.get("images", [])
56
+ if images and any(img.get("id", -1) == 0 for img in images):
57
+ images_zero = True
58
+
59
+ # Check categories
60
+ categories = data.get("categories", [])
61
+ if categories and any(cat.get("id", -1) == 0 for cat in categories):
62
+ categories_zero = True
63
+
64
+ return annotations_zero, images_zero, categories_zero
65
+
66
+ def reindex_coco_data(data: Dict[str, Any]) -> Dict[str, Any]:
67
+ """Convert 0-indexed COCO data to 1-indexed."""
68
+ modified_data = data.copy()
69
+
70
+ annotations_zero, images_zero, categories_zero = check_zero_indexed(data)
71
+
72
+ # Create ID mapping for consistency
73
+ image_id_mapping = {}
74
+ category_id_mapping = {}
75
+
76
+ # Process images first (since annotations reference image IDs)
77
+ if images_zero and "images" in modified_data:
78
+ for img in modified_data["images"]:
79
+ old_id = img["id"]
80
+ new_id = old_id + 1
81
+ image_id_mapping[old_id] = new_id
82
+ img["id"] = new_id
83
+
84
+ # Process categories (since annotations reference category IDs)
85
+ if categories_zero and "categories" in modified_data:
86
+ for cat in modified_data["categories"]:
87
+ old_id = cat["id"]
88
+ new_id = old_id + 1
89
+ category_id_mapping[old_id] = new_id
90
+ cat["id"] = new_id
91
+
92
+ # Process annotations
93
+ if "annotations" in modified_data:
94
+ for ann in modified_data["annotations"]:
95
+ # Update annotation ID if needed
96
+ if annotations_zero:
97
+ ann["id"] = ann["id"] + 1
98
+
99
+ # Update image_id reference if images were reindexed
100
+ if images_zero and ann.get("image_id") is not None:
101
+ old_image_id = ann["image_id"]
102
+ if old_image_id in image_id_mapping:
103
+ ann["image_id"] = image_id_mapping[old_image_id]
104
+
105
+ # Update category_id reference if categories were reindexed
106
+ if categories_zero and ann.get("category_id") is not None:
107
+ old_category_id = ann["category_id"]
108
+ if old_category_id in category_id_mapping:
109
+ ann["category_id"] = category_id_mapping[old_category_id]
110
+
111
+ return modified_data
112
+
113
+ # Validate input path
114
+ if not os.path.exists(input_json_path):
115
+ raise FileNotFoundError(f"Input file not found: {input_json_path}")
116
+
117
+ # Load and validate JSON data
118
+ try:
119
+ with open(input_json_path, "r", encoding="utf-8") as f:
120
+ data = json.load(f)
121
+ except json.JSONDecodeError as e:
122
+ raise json.JSONDecodeError(f"Invalid JSON in {input_json_path}: {e}")
123
+
124
+ # Validate COCO format
125
+ if not is_coco_json(data):
126
+ raise ValueError(
127
+ f"File does not appear to be in COCO format: {input_json_path}"
128
+ )
129
+
130
+ # Check if reindexing is needed
131
+ annotations_zero, images_zero, categories_zero = check_zero_indexed(data)
132
+
133
+ if not (annotations_zero or images_zero or categories_zero):
134
+ # No conversion needed - just copy to temp location
135
+ input_path = Path(input_json_path)
136
+ temp_dir = tempfile.mkdtemp()
137
+ temp_filename = f"{input_path.stem}_1_indexed{input_path.suffix}"
138
+ temp_path = os.path.join(temp_dir, temp_filename)
139
+
140
+ with open(temp_path, "w", encoding="utf-8") as f:
141
+ json.dump(data, f, indent=2, ensure_ascii=False)
142
+
143
+ return temp_path
144
+
145
+ # Perform reindexing
146
+ modified_data = reindex_coco_data(data)
147
+
148
+ # Create temporary file
149
+ input_path = Path(input_json_path)
150
+ temp_dir = tempfile.mkdtemp()
151
+ temp_filename = f"{input_path.stem}_1_indexed{input_path.suffix}"
152
+ temp_path = os.path.join(temp_dir, temp_filename)
153
+
154
+ # Write modified data to temporary file
155
+ with open(temp_path, "w", encoding="utf-8") as f:
156
+ json.dump(modified_data, f, indent=2, ensure_ascii=False)
157
+
158
+ return temp_path
159
+
160
+
161
+ # Example usage and test function
162
+ def test_reindex_function():
163
+ """Test the reindex function with a sample COCO file."""
164
+
165
+ # Create a test COCO file
166
+ test_data = {
167
+ "info": {"description": "Test COCO dataset", "version": "1.0", "year": 2023},
168
+ "images": [
169
+ {"id": 0, "width": 640, "height": 480, "file_name": "test1.jpg"},
170
+ {"id": 1, "width": 640, "height": 480, "file_name": "test2.jpg"},
171
+ ],
172
+ "categories": [
173
+ {"id": 0, "name": "person", "supercategory": "person"},
174
+ {"id": 1, "name": "car", "supercategory": "vehicle"},
175
+ ],
176
+ "annotations": [
177
+ {
178
+ "id": 0,
179
+ "image_id": 0,
180
+ "category_id": 0,
181
+ "bbox": [100, 100, 50, 75],
182
+ "area": 3750,
183
+ "iscrowd": 0,
184
+ },
185
+ {
186
+ "id": 1,
187
+ "image_id": 1,
188
+ "category_id": 1,
189
+ "bbox": [200, 150, 120, 80],
190
+ "area": 9600,
191
+ "iscrowd": 0,
192
+ },
193
+ ],
194
+ }
195
+
196
+ # Create temporary test file
197
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
198
+ json.dump(test_data, f, indent=2)
199
+ test_file_path = f.name
200
+
201
+ try:
202
+ # Test the function
203
+ result_path = reindex_coco_to_temp(test_file_path)
204
+ print(f"Original file: {test_file_path}")
205
+ print(f"Converted file: {result_path}")
206
+
207
+ # Load and display the result
208
+ with open(result_path, "r") as f:
209
+ result_data = json.load(f)
210
+
211
+ print("\nConverted data sample:")
212
+ print(f"First image ID: {result_data['images'][0]['id']}")
213
+ print(f"First category ID: {result_data['categories'][0]['id']}")
214
+ print(f"First annotation ID: {result_data['annotations'][0]['id']}")
215
+ print(f"First annotation image_id: {result_data['annotations'][0]['image_id']}")
216
+ print(
217
+ f"First annotation category_id: {result_data['annotations'][0]['category_id']}"
218
+ )
219
+
220
+ # Clean up
221
+ os.unlink(result_path)
222
+ os.rmdir(os.path.dirname(result_path))
223
+
224
+ finally:
225
+ # Clean up test file
226
+ os.unlink(test_file_path)
227
+
228
+
229
+ if __name__ == "__main__":
230
+ test_reindex_function()
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # flake8: noqa
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/run_ytvis_eval.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ """run_youtube_vis.py
4
+ Run example:
5
+ run_youtube_vis.py --USE_PARALLEL False --METRICS HOTA --TRACKERS_TO_EVAL STEm_Seg
6
+ Command Line Arguments: Defaults, # Comments
7
+ Eval arguments:
8
+ 'USE_PARALLEL': False,
9
+ 'NUM_PARALLEL_CORES': 8,
10
+ 'BREAK_ON_ERROR': True, # Raises exception and exits with error
11
+ 'RETURN_ON_ERROR': False, # if not BREAK_ON_ERROR, then returns from function on error
12
+ 'LOG_ON_ERROR': os.path.join(code_path, 'error_log.txt'), # if not None, save any errors into a log file.
13
+ 'PRINT_RESULTS': True,
14
+ 'PRINT_ONLY_COMBINED': False,
15
+ 'PRINT_CONFIG': True,
16
+ 'TIME_PROGRESS': True,
17
+ 'DISPLAY_LESS_PROGRESS': True,
18
+ 'OUTPUT_SUMMARY': True,
19
+ 'OUTPUT_EMPTY_CLASSES': True, # If False, summary files are not output for classes with no detections
20
+ 'OUTPUT_DETAILED': True,
21
+ 'PLOT_CURVES': True,
22
+ Dataset arguments:
23
+ 'GT_FOLDER': os.path.join(code_path, 'data/gt/youtube_vis/youtube_vis_training'), # Location of GT data
24
+ 'TRACKERS_FOLDER': os.path.join(code_path, 'data/trackers/youtube_vis/youtube_vis_training'),
25
+ # Trackers location
26
+ 'OUTPUT_FOLDER': None, # Where to save eval results (if None, same as TRACKERS_FOLDER)
27
+ 'TRACKERS_TO_EVAL': None, # Filenames of trackers to eval (if None, all in folder)
28
+ 'CLASSES_TO_EVAL': None, # Classes to eval (if None, all classes)
29
+ 'SPLIT_TO_EVAL': 'training', # Valid: 'training', 'val'
30
+ 'PRINT_CONFIG': True, # Whether to print current config
31
+ 'OUTPUT_SUB_FOLDER': '', # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER
32
+ 'TRACKER_SUB_FOLDER': 'data', # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER
33
+ 'TRACKER_DISPLAY_NAMES': None, # Names of trackers to display, if None: TRACKERS_TO_EVAL
34
+ Metric arguments:
35
+ 'METRICS': ['TrackMAP', 'HOTA', 'CLEAR', 'Identity']
36
+ """
37
+
38
+ import argparse
39
+ import os
40
+ import sys
41
+ from multiprocessing import freeze_support
42
+
43
+ from . import trackeval
44
+
45
+
46
+ def run_ytvis_eval(args=None, gt_json=None, dt_json=None):
47
+ # Command line interface:
48
+ default_eval_config = trackeval.Evaluator.get_default_eval_config()
49
+ # print only combined since TrackMAP is undefined for per sequence breakdowns
50
+ default_eval_config["PRINT_ONLY_COMBINED"] = True
51
+ default_dataset_config = trackeval.datasets.YouTubeVIS.get_default_dataset_config()
52
+ default_metrics_config = {"METRICS": ["HOTA"]}
53
+ config = {
54
+ **default_eval_config,
55
+ **default_dataset_config,
56
+ **default_metrics_config,
57
+ } # Merge default configs
58
+ parser = argparse.ArgumentParser()
59
+ for setting in config.keys():
60
+ if type(config[setting]) == list or type(config[setting]) == type(None):
61
+ parser.add_argument("--" + setting, nargs="+")
62
+ else:
63
+ parser.add_argument("--" + setting)
64
+ args = parser.parse_args(args).__dict__
65
+ for setting in args.keys():
66
+ if args[setting] is not None:
67
+ if type(config[setting]) == type(True):
68
+ if args[setting] == "True":
69
+ x = True
70
+ elif args[setting] == "False":
71
+ x = False
72
+ else:
73
+ raise Exception(
74
+ "Command line parameter " + setting + "must be True or False"
75
+ )
76
+ elif type(config[setting]) == type(1):
77
+ x = int(args[setting])
78
+ elif type(args[setting]) == type(None):
79
+ x = None
80
+ else:
81
+ x = args[setting]
82
+ config[setting] = x
83
+ eval_config = {k: v for k, v in config.items() if k in default_eval_config.keys()}
84
+ dataset_config = {
85
+ k: v for k, v in config.items() if k in default_dataset_config.keys()
86
+ }
87
+ metrics_config = {
88
+ k: v for k, v in config.items() if k in default_metrics_config.keys()
89
+ }
90
+
91
+ # Run code
92
+ evaluator = trackeval.Evaluator(eval_config)
93
+ # allow directly specifying the GT JSON data and Tracker (result)
94
+ # JSON data as Python objects, without reading from files.
95
+ dataset_config["GT_JSON_OBJECT"] = gt_json
96
+ dataset_config["TRACKER_JSON_OBJECT"] = dt_json
97
+ dataset_list = [trackeval.datasets.YouTubeVIS(dataset_config)]
98
+ metrics_list = []
99
+ # for metric in [trackeval.metrics.TrackMAP, trackeval.metrics.HOTA, trackeval.metrics.CLEAR,
100
+ # trackeval.metrics.Identity]:
101
+ for metric in [trackeval.metrics.HOTA]:
102
+ if metric.get_name() in metrics_config["METRICS"]:
103
+ metrics_list.append(metric())
104
+ if len(metrics_list) == 0:
105
+ raise Exception("No metrics selected for evaluation")
106
+ output_res, output_msg = evaluator.evaluate(dataset_list, metrics_list)
107
+ return output_res, output_msg
108
+
109
+
110
+ if __name__ == "__main__":
111
+ import sys
112
+
113
+ freeze_support()
114
+ run_ytvis_eval(sys.argv[1:])
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ from . import datasets, metrics, utils
4
+ from .eval import Evaluator
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/_timing.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ import inspect
4
+ from functools import wraps
5
+ from time import perf_counter
6
+
7
+ DO_TIMING = False
8
+ DISPLAY_LESS_PROGRESS = False
9
+ timer_dict = {}
10
+ counter = 0
11
+
12
+
13
+ def time(f):
14
+ @wraps(f)
15
+ def wrap(*args, **kw):
16
+ if DO_TIMING:
17
+ # Run function with timing
18
+ ts = perf_counter()
19
+ result = f(*args, **kw)
20
+ te = perf_counter()
21
+ tt = te - ts
22
+
23
+ # Get function name
24
+ arg_names = inspect.getfullargspec(f)[0]
25
+ if arg_names[0] == "self" and DISPLAY_LESS_PROGRESS:
26
+ return result
27
+ elif arg_names[0] == "self":
28
+ method_name = type(args[0]).__name__ + "." + f.__name__
29
+ else:
30
+ method_name = f.__name__
31
+
32
+ # Record accumulative time in each function for analysis
33
+ if method_name in timer_dict.keys():
34
+ timer_dict[method_name] += tt
35
+ else:
36
+ timer_dict[method_name] = tt
37
+
38
+ # If code is finished, display timing summary
39
+ if method_name == "Evaluator.evaluate":
40
+ print("")
41
+ print("Timing analysis:")
42
+ for key, value in timer_dict.items():
43
+ print("%-70s %2.4f sec" % (key, value))
44
+ else:
45
+ # Get function argument values for printing special arguments of interest
46
+ arg_titles = ["tracker", "seq", "cls"]
47
+ arg_vals = []
48
+ for i, a in enumerate(arg_names):
49
+ if a in arg_titles:
50
+ arg_vals.append(args[i])
51
+ arg_text = "(" + ", ".join(arg_vals) + ")"
52
+
53
+ # Display methods and functions with different indentation.
54
+ if arg_names[0] == "self":
55
+ print("%-74s %2.4f sec" % (" " * 4 + method_name + arg_text, tt))
56
+ elif arg_names[0] == "test":
57
+ pass
58
+ else:
59
+ global counter
60
+ counter += 1
61
+ print("%i %-70s %2.4f sec" % (counter, method_name + arg_text, tt))
62
+
63
+ return result
64
+ else:
65
+ # If config["TIME_PROGRESS"] is false, or config["USE_PARALLEL"] is true, run functions normally without timing.
66
+ return f(*args, **kw)
67
+
68
+ return wrap
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/eval.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ import os
4
+ import time
5
+ import traceback
6
+ from functools import partial
7
+ from multiprocessing.pool import Pool
8
+
9
+ import numpy as np
10
+
11
+ from . import _timing, utils
12
+ from .metrics import Count
13
+ from .utils import TrackEvalException
14
+
15
+ try:
16
+ import tqdm
17
+
18
+ TQDM_IMPORTED = True
19
+ except ImportError as _:
20
+ TQDM_IMPORTED = False
21
+
22
+
23
+ class Evaluator:
24
+ """Evaluator class for evaluating different metrics for different datasets"""
25
+
26
+ @staticmethod
27
+ def get_default_eval_config():
28
+ """Returns the default config values for evaluation"""
29
+ code_path = utils.get_code_path()
30
+ default_config = {
31
+ "USE_PARALLEL": False,
32
+ "NUM_PARALLEL_CORES": 8,
33
+ "BREAK_ON_ERROR": True, # Raises exception and exits with error
34
+ "RETURN_ON_ERROR": False, # if not BREAK_ON_ERROR, then returns from function on error
35
+ "LOG_ON_ERROR": os.path.join(
36
+ code_path, "error_log.txt"
37
+ ), # if not None, save any errors into a log file.
38
+ "PRINT_RESULTS": True,
39
+ "PRINT_ONLY_COMBINED": False,
40
+ "PRINT_CONFIG": True,
41
+ "TIME_PROGRESS": True,
42
+ "DISPLAY_LESS_PROGRESS": True,
43
+ "OUTPUT_SUMMARY": True,
44
+ "OUTPUT_EMPTY_CLASSES": True, # If False, summary files are not output for classes with no detections
45
+ "OUTPUT_DETAILED": True,
46
+ "PLOT_CURVES": True,
47
+ }
48
+ return default_config
49
+
50
+ def __init__(self, config=None):
51
+ """Initialise the evaluator with a config file"""
52
+ self.config = utils.init_config(config, self.get_default_eval_config(), "Eval")
53
+ # Only run timing analysis if not run in parallel.
54
+ if self.config["TIME_PROGRESS"] and not self.config["USE_PARALLEL"]:
55
+ _timing.DO_TIMING = True
56
+ if self.config["DISPLAY_LESS_PROGRESS"]:
57
+ _timing.DISPLAY_LESS_PROGRESS = True
58
+
59
+ def _combine_results(
60
+ self,
61
+ res,
62
+ metrics_list,
63
+ metric_names,
64
+ dataset,
65
+ res_field="COMBINED_SEQ",
66
+ target_tag=None,
67
+ ):
68
+ assert res_field.startswith("COMBINED_SEQ")
69
+ # collecting combined cls keys (cls averaged, det averaged, super classes)
70
+ tracker_list, seq_list, class_list = dataset.get_eval_info()
71
+ combined_cls_keys = []
72
+ res[res_field] = {}
73
+
74
+ # narrow the target for evaluation
75
+ if target_tag is not None:
76
+ target_video_ids = [
77
+ annot["video_id"]
78
+ for annot in dataset.gt_data["annotations"]
79
+ if target_tag in annot["tags"]
80
+ ]
81
+ vid2name = {
82
+ video["id"]: video["file_names"][0].split("/")[0]
83
+ for video in dataset.gt_data["videos"]
84
+ }
85
+ target_video_ids = set(target_video_ids)
86
+ target_video = [vid2name[video_id] for video_id in target_video_ids]
87
+
88
+ if len(target_video) == 0:
89
+ raise TrackEvalException(
90
+ "No sequences found with the tag %s" % target_tag
91
+ )
92
+
93
+ target_annotations = [
94
+ annot
95
+ for annot in dataset.gt_data["annotations"]
96
+ if annot["video_id"] in target_video_ids
97
+ ]
98
+ assert all(target_tag in annot["tags"] for annot in target_annotations), (
99
+ f"Not all annotations in the target sequences have the target tag {target_tag}. "
100
+ "We currently only support a target tag at the sequence level, not at the annotation level."
101
+ )
102
+ else:
103
+ target_video = seq_list
104
+
105
+ # combine sequences for each class
106
+ for c_cls in class_list:
107
+ res[res_field][c_cls] = {}
108
+ for metric, metric_name in zip(metrics_list, metric_names):
109
+ curr_res = {
110
+ seq_key: seq_value[c_cls][metric_name]
111
+ for seq_key, seq_value in res.items()
112
+ if not seq_key.startswith("COMBINED_SEQ")
113
+ and seq_key in target_video
114
+ }
115
+ res[res_field][c_cls][metric_name] = metric.combine_sequences(curr_res)
116
+ # combine classes
117
+ if dataset.should_classes_combine:
118
+ combined_cls_keys += [
119
+ "cls_comb_cls_av",
120
+ "cls_comb_det_av",
121
+ "all",
122
+ ]
123
+ res[res_field]["cls_comb_cls_av"] = {}
124
+ res[res_field]["cls_comb_det_av"] = {}
125
+ for metric, metric_name in zip(metrics_list, metric_names):
126
+ cls_res = {
127
+ cls_key: cls_value[metric_name]
128
+ for cls_key, cls_value in res[res_field].items()
129
+ if cls_key not in combined_cls_keys
130
+ }
131
+ res[res_field]["cls_comb_cls_av"][metric_name] = (
132
+ metric.combine_classes_class_averaged(cls_res)
133
+ )
134
+ res[res_field]["cls_comb_det_av"][metric_name] = (
135
+ metric.combine_classes_det_averaged(cls_res)
136
+ )
137
+ # combine classes to super classes
138
+ if dataset.use_super_categories:
139
+ for cat, sub_cats in dataset.super_categories.items():
140
+ combined_cls_keys.append(cat)
141
+ res[res_field][cat] = {}
142
+ for metric, metric_name in zip(metrics_list, metric_names):
143
+ cat_res = {
144
+ cls_key: cls_value[metric_name]
145
+ for cls_key, cls_value in res[res_field].items()
146
+ if cls_key in sub_cats
147
+ }
148
+ res[res_field][cat][metric_name] = (
149
+ metric.combine_classes_det_averaged(cat_res)
150
+ )
151
+ return res, combined_cls_keys
152
+
153
+ def _summarize_results(
154
+ self,
155
+ res,
156
+ tracker,
157
+ metrics_list,
158
+ metric_names,
159
+ dataset,
160
+ res_field,
161
+ combined_cls_keys,
162
+ ):
163
+ config = self.config
164
+ output_fol = dataset.get_output_fol(tracker)
165
+ tracker_display_name = dataset.get_display_name(tracker)
166
+ for c_cls in res[
167
+ res_field
168
+ ].keys(): # class_list + combined classes if calculated
169
+ summaries = []
170
+ details = []
171
+ num_dets = res[res_field][c_cls]["Count"]["Dets"]
172
+ if config["OUTPUT_EMPTY_CLASSES"] or num_dets > 0:
173
+ for metric, metric_name in zip(metrics_list, metric_names):
174
+ # for combined classes there is no per sequence evaluation
175
+ if c_cls in combined_cls_keys:
176
+ table_res = {res_field: res[res_field][c_cls][metric_name]}
177
+ else:
178
+ table_res = {
179
+ seq_key: seq_value[c_cls][metric_name]
180
+ for seq_key, seq_value in res.items()
181
+ }
182
+
183
+ if config["PRINT_RESULTS"] and config["PRINT_ONLY_COMBINED"]:
184
+ dont_print = (
185
+ dataset.should_classes_combine
186
+ and c_cls not in combined_cls_keys
187
+ )
188
+ if not dont_print:
189
+ metric.print_table(
190
+ {res_field: table_res[res_field]},
191
+ tracker_display_name,
192
+ c_cls,
193
+ res_field,
194
+ res_field,
195
+ )
196
+ elif config["PRINT_RESULTS"]:
197
+ metric.print_table(
198
+ table_res, tracker_display_name, c_cls, res_field, res_field
199
+ )
200
+ if config["OUTPUT_SUMMARY"]:
201
+ summaries.append(metric.summary_results(table_res))
202
+ if config["OUTPUT_DETAILED"]:
203
+ details.append(metric.detailed_results(table_res))
204
+ if config["PLOT_CURVES"]:
205
+ metric.plot_single_tracker_results(
206
+ table_res,
207
+ tracker_display_name,
208
+ c_cls,
209
+ output_fol,
210
+ )
211
+ if config["OUTPUT_SUMMARY"]:
212
+ utils.write_summary_results(summaries, c_cls, output_fol)
213
+ if config["OUTPUT_DETAILED"]:
214
+ utils.write_detailed_results(details, c_cls, output_fol)
215
+
216
+ @_timing.time
217
+ def evaluate(self, dataset_list, metrics_list, show_progressbar=False):
218
+ """Evaluate a set of metrics on a set of datasets"""
219
+ config = self.config
220
+ metrics_list = metrics_list + [Count()] # Count metrics are always run
221
+ metric_names = utils.validate_metrics_list(metrics_list)
222
+ dataset_names = [dataset.get_name() for dataset in dataset_list]
223
+ output_res = {}
224
+ output_msg = {}
225
+
226
+ for dataset, dataset_name in zip(dataset_list, dataset_names):
227
+ # Get dataset info about what to evaluate
228
+ output_res[dataset_name] = {}
229
+ output_msg[dataset_name] = {}
230
+ tracker_list, seq_list, class_list = dataset.get_eval_info()
231
+ print(
232
+ "\nEvaluating %i tracker(s) on %i sequence(s) for %i class(es) on %s dataset using the following "
233
+ "metrics: %s\n"
234
+ % (
235
+ len(tracker_list),
236
+ len(seq_list),
237
+ len(class_list),
238
+ dataset_name,
239
+ ", ".join(metric_names),
240
+ )
241
+ )
242
+
243
+ # Evaluate each tracker
244
+ for tracker in tracker_list:
245
+ # if not config['BREAK_ON_ERROR'] then go to next tracker without breaking
246
+ try:
247
+ # Evaluate each sequence in parallel or in series.
248
+ # returns a nested dict (res), indexed like: res[seq][class][metric_name][sub_metric field]
249
+ # e.g. res[seq_0001][pedestrian][hota][DetA]
250
+ print("\nEvaluating %s\n" % tracker)
251
+ time_start = time.time()
252
+ if config["USE_PARALLEL"]:
253
+ if show_progressbar and TQDM_IMPORTED:
254
+ seq_list_sorted = sorted(seq_list)
255
+
256
+ with Pool(config["NUM_PARALLEL_CORES"]) as pool, tqdm.tqdm(
257
+ total=len(seq_list)
258
+ ) as pbar:
259
+ _eval_sequence = partial(
260
+ eval_sequence,
261
+ dataset=dataset,
262
+ tracker=tracker,
263
+ class_list=class_list,
264
+ metrics_list=metrics_list,
265
+ metric_names=metric_names,
266
+ )
267
+ results = []
268
+ for r in pool.imap(
269
+ _eval_sequence, seq_list_sorted, chunksize=20
270
+ ):
271
+ results.append(r)
272
+ pbar.update()
273
+ res = dict(zip(seq_list_sorted, results))
274
+
275
+ else:
276
+ with Pool(config["NUM_PARALLEL_CORES"]) as pool:
277
+ _eval_sequence = partial(
278
+ eval_sequence,
279
+ dataset=dataset,
280
+ tracker=tracker,
281
+ class_list=class_list,
282
+ metrics_list=metrics_list,
283
+ metric_names=metric_names,
284
+ )
285
+ results = pool.map(_eval_sequence, seq_list)
286
+ res = dict(zip(seq_list, results))
287
+ else:
288
+ res = {}
289
+ if show_progressbar and TQDM_IMPORTED:
290
+ seq_list_sorted = sorted(seq_list)
291
+ for curr_seq in tqdm.tqdm(seq_list_sorted):
292
+ res[curr_seq] = eval_sequence(
293
+ curr_seq,
294
+ dataset,
295
+ tracker,
296
+ class_list,
297
+ metrics_list,
298
+ metric_names,
299
+ )
300
+ else:
301
+ for curr_seq in sorted(seq_list):
302
+ res[curr_seq] = eval_sequence(
303
+ curr_seq,
304
+ dataset,
305
+ tracker,
306
+ class_list,
307
+ metrics_list,
308
+ metric_names,
309
+ )
310
+
311
+ # Combine results over all sequences and then over all classes
312
+ res, combined_cls_keys = self._combine_results(
313
+ res, metrics_list, metric_names, dataset, "COMBINED_SEQ"
314
+ )
315
+
316
+ if np.all(
317
+ ["tags" in annot for annot in dataset.gt_data["annotations"]]
318
+ ):
319
+ # Combine results over the challenging sequences and then over all classes
320
+ # currently only support "tracking_challenging_pair"
321
+ res, _ = self._combine_results(
322
+ res,
323
+ metrics_list,
324
+ metric_names,
325
+ dataset,
326
+ "COMBINED_SEQ_CHALLENGING",
327
+ "tracking_challenging_pair",
328
+ )
329
+
330
+ # Print and output results in various formats
331
+ if config["TIME_PROGRESS"]:
332
+ print(
333
+ "\nAll sequences for %s finished in %.2f seconds"
334
+ % (tracker, time.time() - time_start)
335
+ )
336
+
337
+ self._summarize_results(
338
+ res,
339
+ tracker,
340
+ metrics_list,
341
+ metric_names,
342
+ dataset,
343
+ "COMBINED_SEQ",
344
+ combined_cls_keys,
345
+ )
346
+ if "COMBINED_SEQ_CHALLENGING" in res:
347
+ self._summarize_results(
348
+ res,
349
+ tracker,
350
+ metrics_list,
351
+ metric_names,
352
+ dataset,
353
+ "COMBINED_SEQ_CHALLENGING",
354
+ combined_cls_keys,
355
+ )
356
+
357
+ # Output for returning from function
358
+ output_res[dataset_name][tracker] = res
359
+ output_msg[dataset_name][tracker] = "Success"
360
+
361
+ except Exception as err:
362
+ output_res[dataset_name][tracker] = None
363
+ if type(err) == TrackEvalException:
364
+ output_msg[dataset_name][tracker] = str(err)
365
+ else:
366
+ output_msg[dataset_name][tracker] = "Unknown error occurred."
367
+ print("Tracker %s was unable to be evaluated." % tracker)
368
+ print(err)
369
+ traceback.print_exc()
370
+ if config["LOG_ON_ERROR"] is not None:
371
+ with open(config["LOG_ON_ERROR"], "a") as f:
372
+ print(dataset_name, file=f)
373
+ print(tracker, file=f)
374
+ print(traceback.format_exc(), file=f)
375
+ print("\n\n\n", file=f)
376
+ if config["BREAK_ON_ERROR"]:
377
+ raise err
378
+ elif config["RETURN_ON_ERROR"]:
379
+ return output_res, output_msg
380
+
381
+ return output_res, output_msg
382
+
383
+
384
+ @_timing.time
385
+ def eval_sequence(seq, dataset, tracker, class_list, metrics_list, metric_names):
386
+ """Function for evaluating a single sequence"""
387
+
388
+ raw_data = dataset.get_raw_seq_data(tracker, seq)
389
+ seq_res = {}
390
+ for cls in class_list:
391
+ seq_res[cls] = {}
392
+ data = dataset.get_preprocessed_seq_data(raw_data, cls)
393
+ for metric, met_name in zip(metrics_list, metric_names):
394
+ seq_res[cls][met_name] = metric.eval_sequence(data)
395
+ return seq_res
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/metrics/_base_metric.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ import numpy as np
6
+
7
+ from .. import _timing
8
+ from ..utils import TrackEvalException
9
+
10
+
11
+ class _BaseMetric(ABC):
12
+ @abstractmethod
13
+ def __init__(self):
14
+ self.plottable = False
15
+ self.integer_fields = []
16
+ self.float_fields = []
17
+ self.array_labels = []
18
+ self.integer_array_fields = []
19
+ self.float_array_fields = []
20
+ self.fields = []
21
+ self.summary_fields = []
22
+ self.registered = False
23
+
24
+ #####################################################################
25
+ # Abstract functions for subclasses to implement
26
+
27
+ @_timing.time
28
+ @abstractmethod
29
+ def eval_sequence(self, data): ...
30
+
31
+ @abstractmethod
32
+ def combine_sequences(self, all_res): ...
33
+
34
+ @abstractmethod
35
+ def combine_classes_class_averaged(self, all_res, ignore_empty_classes=False): ...
36
+
37
+ @abstractmethod
38
+ def combine_classes_det_averaged(self, all_res): ...
39
+
40
+ def plot_single_tracker_results(self, all_res, tracker, output_folder, cls):
41
+ """Plot results of metrics, only valid for metrics with self.plottable"""
42
+ if self.plottable:
43
+ raise NotImplementedError(
44
+ "plot_results is not implemented for metric %s" % self.get_name()
45
+ )
46
+ else:
47
+ pass
48
+
49
+ #####################################################################
50
+ # Helper functions which are useful for all metrics:
51
+
52
+ @classmethod
53
+ def get_name(cls):
54
+ return cls.__name__
55
+
56
+ @staticmethod
57
+ def _combine_sum(all_res, field):
58
+ """Combine sequence results via sum"""
59
+ return sum([all_res[k][field] for k in all_res.keys()])
60
+
61
+ @staticmethod
62
+ def _combine_weighted_av(all_res, field, comb_res, weight_field):
63
+ """Combine sequence results via weighted average"""
64
+ return sum(
65
+ [all_res[k][field] * all_res[k][weight_field] for k in all_res.keys()]
66
+ ) / np.maximum(1.0, comb_res[weight_field])
67
+
68
+ def print_table(
69
+ self, table_res, tracker, cls, res_field="COMBINED_SEQ", output_lable="COMBINED"
70
+ ):
71
+ """Prints table of results for all sequences"""
72
+ print("")
73
+ metric_name = self.get_name()
74
+ self._row_print(
75
+ [metric_name + ": " + tracker + "-" + cls] + self.summary_fields
76
+ )
77
+ for seq, results in sorted(table_res.items()):
78
+ if seq.startswith("COMBINED_SEQ"):
79
+ continue
80
+ summary_res = self._summary_row(results)
81
+ self._row_print([seq] + summary_res)
82
+ summary_res = self._summary_row(table_res[res_field])
83
+ self._row_print([output_lable] + summary_res)
84
+
85
+ def _summary_row(self, results_):
86
+ vals = []
87
+ for h in self.summary_fields:
88
+ if h in self.float_array_fields:
89
+ vals.append("{0:1.5g}".format(100 * np.mean(results_[h])))
90
+ elif h in self.float_fields:
91
+ vals.append("{0:1.5g}".format(100 * float(results_[h])))
92
+ elif h in self.integer_fields:
93
+ vals.append("{0:d}".format(int(results_[h])))
94
+ else:
95
+ raise NotImplementedError(
96
+ "Summary function not implemented for this field type."
97
+ )
98
+ return vals
99
+
100
+ @staticmethod
101
+ def _row_print(*argv):
102
+ """Prints results in an evenly spaced rows, with more space in first row"""
103
+ if len(argv) == 1:
104
+ argv = argv[0]
105
+ to_print = "%-35s" % argv[0]
106
+ for v in argv[1:]:
107
+ to_print += "%-10s" % str(v)
108
+ print(to_print)
109
+
110
+ def summary_results(self, table_res):
111
+ """Returns a simple summary of final results for a tracker"""
112
+ return dict(
113
+ zip(self.summary_fields, self._summary_row(table_res["COMBINED_SEQ"]))
114
+ )
115
+
116
+ def detailed_results(self, table_res):
117
+ """Returns detailed final results for a tracker"""
118
+ # Get detailed field information
119
+ detailed_fields = self.float_fields + self.integer_fields
120
+ for h in self.float_array_fields + self.integer_array_fields:
121
+ for alpha in [int(100 * x) for x in self.array_labels]:
122
+ detailed_fields.append(h + "___" + str(alpha))
123
+ detailed_fields.append(h + "___AUC")
124
+
125
+ # Get detailed results
126
+ detailed_results = {}
127
+ for seq, res in table_res.items():
128
+ detailed_row = self._detailed_row(res)
129
+ if len(detailed_row) != len(detailed_fields):
130
+ raise TrackEvalException(
131
+ "Field names and data have different sizes (%i and %i)"
132
+ % (len(detailed_row), len(detailed_fields))
133
+ )
134
+ detailed_results[seq] = dict(zip(detailed_fields, detailed_row))
135
+ return detailed_results
136
+
137
+ def _detailed_row(self, res):
138
+ detailed_row = []
139
+ for h in self.float_fields + self.integer_fields:
140
+ detailed_row.append(res[h])
141
+ for h in self.float_array_fields + self.integer_array_fields:
142
+ for i, alpha in enumerate([int(100 * x) for x in self.array_labels]):
143
+ detailed_row.append(res[h][i])
144
+ detailed_row.append(np.mean(res[h]))
145
+ return detailed_row
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/metrics/count.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ from .. import _timing
4
+ from ._base_metric import _BaseMetric
5
+
6
+
7
+ class Count(_BaseMetric):
8
+ """Class which simply counts the number of tracker and gt detections and ids."""
9
+
10
+ def __init__(self, config=None):
11
+ super().__init__()
12
+ self.integer_fields = ["Dets", "GT_Dets", "IDs", "GT_IDs"]
13
+ self.fields = self.integer_fields
14
+ self.summary_fields = self.fields
15
+
16
+ @_timing.time
17
+ def eval_sequence(self, data):
18
+ """Returns counts for one sequence"""
19
+ # Get results
20
+ res = {
21
+ "Dets": data["num_tracker_dets"],
22
+ "GT_Dets": data["num_gt_dets"],
23
+ "IDs": data["num_tracker_ids"],
24
+ "GT_IDs": data["num_gt_ids"],
25
+ "Frames": data["num_timesteps"],
26
+ }
27
+ return res
28
+
29
+ def combine_sequences(self, all_res):
30
+ """Combines metrics across all sequences"""
31
+ res = {}
32
+ for field in self.integer_fields:
33
+ res[field] = self._combine_sum(all_res, field)
34
+ return res
35
+
36
+ def combine_classes_class_averaged(self, all_res, ignore_empty_classes=None):
37
+ """Combines metrics across all classes by averaging over the class values"""
38
+ res = {}
39
+ for field in self.integer_fields:
40
+ res[field] = self._combine_sum(all_res, field)
41
+ return res
42
+
43
+ def combine_classes_det_averaged(self, all_res):
44
+ """Combines metrics across all classes by averaging over the detection values"""
45
+ res = {}
46
+ for field in self.integer_fields:
47
+ res[field] = self._combine_sum(all_res, field)
48
+ return res
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/hota_eval_toolkit/trackeval/utils.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ import argparse
4
+ import csv
5
+ import os
6
+ from collections import OrderedDict
7
+
8
+
9
+ def init_config(config, default_config, name=None):
10
+ """Initialise non-given config values with defaults"""
11
+ if config is None:
12
+ config = default_config
13
+ else:
14
+ for k in default_config.keys():
15
+ if k not in config.keys():
16
+ config[k] = default_config[k]
17
+ if name and config["PRINT_CONFIG"]:
18
+ print("\n%s Config:" % name)
19
+ for c in config.keys():
20
+ print("%-20s : %-30s" % (c, config[c]))
21
+ return config
22
+
23
+
24
+ def update_config(config):
25
+ """
26
+ Parse the arguments of a script and updates the config values for a given value if specified in the arguments.
27
+ :param config: the config to update
28
+ :return: the updated config
29
+ """
30
+ parser = argparse.ArgumentParser()
31
+ for setting in config.keys():
32
+ if type(config[setting]) == list or type(config[setting]) == type(None):
33
+ parser.add_argument("--" + setting, nargs="+")
34
+ else:
35
+ parser.add_argument("--" + setting)
36
+ args = parser.parse_args().__dict__
37
+ for setting in args.keys():
38
+ if args[setting] is not None:
39
+ if type(config[setting]) == type(True):
40
+ if args[setting] == "True":
41
+ x = True
42
+ elif args[setting] == "False":
43
+ x = False
44
+ else:
45
+ raise Exception(
46
+ "Command line parameter " + setting + "must be True or False"
47
+ )
48
+ elif type(config[setting]) == type(1):
49
+ x = int(args[setting])
50
+ elif type(args[setting]) == type(None):
51
+ x = None
52
+ else:
53
+ x = args[setting]
54
+ config[setting] = x
55
+ return config
56
+
57
+
58
+ def get_code_path():
59
+ """Get base path where code is"""
60
+ return os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
61
+
62
+
63
+ def validate_metrics_list(metrics_list):
64
+ """Get names of metric class and ensures they are unique, further checks that the fields within each metric class
65
+ do not have overlapping names.
66
+ """
67
+ metric_names = [metric.get_name() for metric in metrics_list]
68
+ # check metric names are unique
69
+ if len(metric_names) != len(set(metric_names)):
70
+ raise TrackEvalException(
71
+ "Code being run with multiple metrics of the same name"
72
+ )
73
+ fields = []
74
+ for m in metrics_list:
75
+ fields += m.fields
76
+ # check metric fields are unique
77
+ if len(fields) != len(set(fields)):
78
+ raise TrackEvalException(
79
+ "Code being run with multiple metrics with fields of the same name"
80
+ )
81
+ return metric_names
82
+
83
+
84
+ def write_summary_results(summaries, cls, output_folder):
85
+ """Write summary results to file"""
86
+
87
+ fields = sum([list(s.keys()) for s in summaries], [])
88
+ values = sum([list(s.values()) for s in summaries], [])
89
+
90
+ # In order to remain consistent upon new fields being adding, for each of the following fields if they are present
91
+ # they will be output in the summary first in the order below. Any further fields will be output in the order each
92
+ # metric family is called, and within each family either in the order they were added to the dict (python >= 3.6) or
93
+ # randomly (python < 3.6).
94
+ default_order = [
95
+ "HOTA",
96
+ "DetA",
97
+ "AssA",
98
+ "DetRe",
99
+ "DetPr",
100
+ "AssRe",
101
+ "AssPr",
102
+ "LocA",
103
+ "OWTA",
104
+ "HOTA(0)",
105
+ "LocA(0)",
106
+ "HOTALocA(0)",
107
+ "MOTA",
108
+ "MOTP",
109
+ "MODA",
110
+ "CLR_Re",
111
+ "CLR_Pr",
112
+ "MTR",
113
+ "PTR",
114
+ "MLR",
115
+ "CLR_TP",
116
+ "CLR_FN",
117
+ "CLR_FP",
118
+ "IDSW",
119
+ "MT",
120
+ "PT",
121
+ "ML",
122
+ "Frag",
123
+ "sMOTA",
124
+ "IDF1",
125
+ "IDR",
126
+ "IDP",
127
+ "IDTP",
128
+ "IDFN",
129
+ "IDFP",
130
+ "Dets",
131
+ "GT_Dets",
132
+ "IDs",
133
+ "GT_IDs",
134
+ ]
135
+ default_ordered_dict = OrderedDict(
136
+ zip(default_order, [None for _ in default_order])
137
+ )
138
+ for f, v in zip(fields, values):
139
+ default_ordered_dict[f] = v
140
+ for df in default_order:
141
+ if default_ordered_dict[df] is None:
142
+ del default_ordered_dict[df]
143
+ fields = list(default_ordered_dict.keys())
144
+ values = list(default_ordered_dict.values())
145
+
146
+ out_file = os.path.join(output_folder, cls + "_summary.txt")
147
+ os.makedirs(os.path.dirname(out_file), exist_ok=True)
148
+ with open(out_file, "w", newline="") as f:
149
+ writer = csv.writer(f, delimiter=" ")
150
+ writer.writerow(fields)
151
+ writer.writerow(values)
152
+
153
+
154
+ def write_detailed_results(details, cls, output_folder):
155
+ """Write detailed results to file"""
156
+ sequences = details[0].keys()
157
+ fields = ["seq"] + sum([list(s["COMBINED_SEQ"].keys()) for s in details], [])
158
+ out_file = os.path.join(output_folder, cls + "_detailed.csv")
159
+ os.makedirs(os.path.dirname(out_file), exist_ok=True)
160
+ with open(out_file, "w", newline="") as f:
161
+ writer = csv.writer(f)
162
+ writer.writerow(fields)
163
+ for seq in sorted(sequences):
164
+ if seq == "COMBINED_SEQ":
165
+ continue
166
+ writer.writerow([seq] + sum([list(s[seq].values()) for s in details], []))
167
+ writer.writerow(
168
+ ["COMBINED"] + sum([list(s["COMBINED_SEQ"].values()) for s in details], [])
169
+ )
170
+
171
+
172
+ def load_detail(file):
173
+ """Loads detailed data for a tracker."""
174
+ data = {}
175
+ with open(file) as f:
176
+ for i, row_text in enumerate(f):
177
+ row = row_text.replace("\r", "").replace("\n", "").split(",")
178
+ if i == 0:
179
+ keys = row[1:]
180
+ continue
181
+ current_values = row[1:]
182
+ seq = row[0]
183
+ if seq == "COMBINED":
184
+ seq = "COMBINED_SEQ"
185
+ if (len(current_values) == len(keys)) and seq != "":
186
+ data[seq] = {}
187
+ for key, value in zip(keys, current_values):
188
+ data[seq][key] = float(value)
189
+ return data
190
+
191
+
192
+ class TrackEvalException(Exception):
193
+ """Custom exception for catching expected errors."""
194
+
195
+ ...
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/postprocessors.py ADDED
@@ -0,0 +1,648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ """Postprocessors class to transform MDETR output according to the downstream task"""
4
+
5
+ import dataclasses
6
+ import logging
7
+ from collections import defaultdict
8
+ from typing import Dict, List, Optional
9
+
10
+ import numpy as np
11
+ import torch
12
+ from sam3.model import box_ops
13
+ from sam3.model.data_misc import BatchedInferenceMetadata, interpolate
14
+ from sam3.train.masks_ops import rle_encode, robust_rle_encode
15
+ from torch import nn
16
+
17
+
18
+ class PostProcessNullOp(nn.Module):
19
+ def __init__(self, **kwargs):
20
+ super(PostProcessNullOp).__init__()
21
+ pass
22
+
23
+ def forward(self, input):
24
+ pass
25
+
26
+ def process_results(self, **kwargs):
27
+ return kwargs["find_stages"]
28
+
29
+
30
+ class PostProcessImage(nn.Module):
31
+ """This module converts the model's output into the format expected by the coco api"""
32
+
33
+ def __init__(
34
+ self,
35
+ max_dets_per_img: int,
36
+ iou_type="bbox",
37
+ to_cpu: bool = True,
38
+ use_original_ids: bool = False,
39
+ use_original_sizes_box: bool = False,
40
+ use_original_sizes_mask: bool = False,
41
+ convert_mask_to_rle: bool = False,
42
+ always_interpolate_masks_on_gpu: bool = True,
43
+ use_presence: bool = True,
44
+ detection_threshold: float = -1.0,
45
+ ) -> None:
46
+ super().__init__()
47
+ self.max_dets_per_img = max_dets_per_img
48
+ self.iou_type = iou_type
49
+ self.to_cpu = to_cpu
50
+ self.convert_mask_to_rle = convert_mask_to_rle
51
+ self.always_interpolate_masks_on_gpu = always_interpolate_masks_on_gpu
52
+
53
+ self.use_presence = use_presence
54
+ self.detection_threshold = detection_threshold
55
+ self.use_original_ids = use_original_ids
56
+ self.use_original_sizes_box = use_original_sizes_box
57
+ self.use_original_sizes_mask = use_original_sizes_mask
58
+
59
+ @torch.no_grad()
60
+ def forward(
61
+ self,
62
+ outputs,
63
+ target_sizes_boxes,
64
+ target_sizes_masks,
65
+ forced_labels=None,
66
+ consistent=False,
67
+ ret_tensordict: bool = False, # This is experimental
68
+ ):
69
+ """Perform the computation
70
+ Parameters:
71
+ outputs: raw outputs of the model
72
+ target_sizes_boxes: tensor of dimension [batch_size x 2] containing the size of each images of the batch
73
+ For evaluation, this must be the original image size (before any data augmentation)
74
+ For visualization, this should be the image size after data augment, but before padding
75
+ target_sizes_masks: same but used to resize masks
76
+ forced_labels: tensor of dimension [batch_size] containing the label to force for each image of the batch
77
+ This is useful when evaluating the model using standard metrics (eg on COCO, LVIS). In that case,
78
+ we query the model with every possible class label, so we when we pass the predictions to the evaluator,
79
+ we want to make sure that the predicted "class" matches the one that was queried.
80
+ consistent: whether all target sizes are equal
81
+ ret_tensordict: Experimental argument. If true, return a tensordict.TensorDict instead of a list of dictionaries for easier manipulation.
82
+ """
83
+ if ret_tensordict:
84
+ assert (
85
+ consistent is True
86
+ ), "We don't support returning TensorDict if the outputs have different shapes" # NOTE: It's possible but we don't support it.
87
+ assert self.detection_threshold <= 0.0, "TODO: implement?"
88
+ try:
89
+ from tensordict import TensorDict
90
+ except ImportError:
91
+ logging.info(
92
+ "tensordict is not installed. Install by running `pip install tensordict --no-deps`. Falling back by setting `ret_tensordict=False`"
93
+ )
94
+ ret_tensordict = False
95
+
96
+ out_bbox = outputs["pred_boxes"] if "pred_boxes" in outputs else None
97
+ out_logits = outputs["pred_logits"]
98
+ pred_masks = outputs["pred_masks"] if self.iou_type == "segm" else None
99
+ out_probs = out_logits.sigmoid()
100
+ if self.use_presence:
101
+ presence_score = outputs["presence_logit_dec"].sigmoid().unsqueeze(1)
102
+ out_probs = out_probs * presence_score
103
+
104
+ assert target_sizes_boxes.shape[1] == 2
105
+ assert target_sizes_masks.shape[1] == 2
106
+ batch_size = target_sizes_boxes.shape[0]
107
+
108
+ boxes, scores, labels, keep = self._process_boxes_and_labels(
109
+ target_sizes_boxes, forced_labels, out_bbox, out_probs
110
+ )
111
+ assert boxes is None or len(boxes) == batch_size
112
+ out_masks = self._process_masks(
113
+ target_sizes_masks, pred_masks, consistent=consistent, keep=keep
114
+ )
115
+ del pred_masks
116
+
117
+ if boxes is None:
118
+ assert out_masks is not None
119
+ assert not ret_tensordict, "We don't support returning TensorDict if the output does not contain boxes"
120
+ B = len(out_masks)
121
+ boxes = [None] * B
122
+ scores = [None] * B
123
+ labels = [None] * B
124
+
125
+ results = {
126
+ "scores": scores,
127
+ "labels": labels,
128
+ "boxes": boxes,
129
+ }
130
+ if out_masks is not None:
131
+ if self.convert_mask_to_rle:
132
+ results.update(masks_rle=out_masks)
133
+ else:
134
+ results.update(masks=out_masks)
135
+
136
+ if ret_tensordict:
137
+ results = TensorDict(results).auto_batch_size_()
138
+ if self.to_cpu:
139
+ results = results.cpu()
140
+ else:
141
+ # Convert a dictonary of lists/tensors to list of dictionaries
142
+ results = [
143
+ dict(zip(results.keys(), res_tuple))
144
+ for res_tuple in zip(*results.values())
145
+ ]
146
+
147
+ return results
148
+
149
+ def _process_masks(self, target_sizes, pred_masks, consistent=True, keep=None):
150
+ if pred_masks is None:
151
+ return None
152
+ if self.always_interpolate_masks_on_gpu:
153
+ gpu_device = target_sizes.device
154
+ assert gpu_device.type == "cuda"
155
+ pred_masks = pred_masks.to(device=gpu_device)
156
+ if consistent:
157
+ assert keep is None, "TODO: implement?"
158
+ # All masks should have the same shape, expected when processing a batch of size 1
159
+ target_size = target_sizes.unique(dim=0)
160
+ assert target_size.size(0) == 1, "Expecting all target sizes to be equal"
161
+ out_masks = (
162
+ interpolate(
163
+ pred_masks,
164
+ target_size.squeeze().tolist(),
165
+ mode="bilinear",
166
+ align_corners=False,
167
+ ).sigmoid()
168
+ > 0.5
169
+ )
170
+ if self.convert_mask_to_rle:
171
+ raise RuntimeError("TODO: implement?")
172
+ if self.to_cpu:
173
+ out_masks = out_masks.cpu()
174
+ else:
175
+ out_masks = [[]] * len(pred_masks)
176
+
177
+ assert keep is None or len(keep) == len(pred_masks)
178
+ for i, mask in enumerate(pred_masks):
179
+ h, w = target_sizes[i]
180
+ if keep is not None:
181
+ mask = mask[keep[i]]
182
+ # Uses the gpu version fist, moves masks to cpu if it fails"""
183
+ try:
184
+ interpolated = (
185
+ interpolate(
186
+ mask.unsqueeze(1),
187
+ (h, w),
188
+ mode="bilinear",
189
+ align_corners=False,
190
+ ).sigmoid()
191
+ > 0.5
192
+ )
193
+ except Exception as e:
194
+ logging.info("Issue found, reverting to CPU mode!")
195
+ mask_device = mask.device
196
+ mask = mask.cpu()
197
+ interpolated = (
198
+ interpolate(
199
+ mask.unsqueeze(1),
200
+ (h, w),
201
+ mode="bilinear",
202
+ align_corners=False,
203
+ ).sigmoid()
204
+ > 0.5
205
+ )
206
+ interpolated = interpolated.to(mask_device)
207
+
208
+ if self.convert_mask_to_rle:
209
+ out_masks[i] = robust_rle_encode(interpolated.squeeze(1))
210
+ else:
211
+ out_masks[i] = interpolated
212
+ if self.to_cpu:
213
+ out_masks[i] = out_masks[i].cpu()
214
+
215
+ return out_masks
216
+
217
+ def _process_boxes_and_labels(
218
+ self, target_sizes, forced_labels, out_bbox, out_probs
219
+ ):
220
+ if out_bbox is None:
221
+ return None, None, None, None
222
+ assert len(out_probs) == len(target_sizes)
223
+ if self.to_cpu:
224
+ out_probs = out_probs.cpu()
225
+ scores, labels = out_probs.max(-1)
226
+ if forced_labels is None:
227
+ labels = torch.ones_like(labels)
228
+ else:
229
+ labels = forced_labels[:, None].expand_as(labels)
230
+
231
+ # convert to [x0, y0, x1, y1] format
232
+ boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
233
+
234
+ img_h, img_w = target_sizes.unbind(1)
235
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
236
+ boxes = boxes * scale_fct[:, None, :]
237
+
238
+ if self.to_cpu:
239
+ boxes = boxes.cpu()
240
+
241
+ keep = None
242
+ if self.detection_threshold > 0:
243
+ # Filter out the boxes with scores below the detection threshold
244
+ keep = scores > self.detection_threshold
245
+ assert len(keep) == len(boxes) == len(scores) == len(labels)
246
+
247
+ boxes = [b[k.to(b.device)] for b, k in zip(boxes, keep)]
248
+ scores = [s[k.to(s.device)] for s, k in zip(scores, keep)]
249
+ labels = [l[k.to(l.device)] for l, k in zip(labels, keep)]
250
+
251
+ return boxes, scores, labels, keep
252
+
253
+ def process_results(
254
+ self, find_stages, find_metadatas: List[BatchedInferenceMetadata], **kwargs
255
+ ):
256
+ if find_stages.loss_stages is not None:
257
+ find_metadatas = [find_metadatas[i] for i in find_stages.loss_stages]
258
+ assert len(find_stages) == len(find_metadatas)
259
+ results = {}
260
+ for outputs, meta in zip(find_stages, find_metadatas):
261
+ img_size_for_boxes = (
262
+ meta.original_size
263
+ if self.use_original_sizes_box
264
+ else torch.ones_like(meta.original_size)
265
+ )
266
+ img_size_for_masks = (
267
+ meta.original_size
268
+ if self.use_original_sizes_mask
269
+ else torch.ones_like(meta.original_size)
270
+ )
271
+ detection_results = self(
272
+ outputs,
273
+ img_size_for_boxes,
274
+ img_size_for_masks,
275
+ forced_labels=(
276
+ meta.original_category_id if self.use_original_ids else None
277
+ ),
278
+ )
279
+ ids = (
280
+ meta.original_image_id if self.use_original_ids else meta.coco_image_id
281
+ )
282
+ assert len(detection_results) == len(ids)
283
+ for img_id, result in zip(ids, detection_results):
284
+ if img_id.item() not in results:
285
+ results[img_id.item()] = result
286
+ else:
287
+ assert set(results[img_id.item()].keys()) == set(result.keys())
288
+ for k in result.keys():
289
+ if isinstance(result[k], torch.Tensor):
290
+ results[img_id.item()][k] = torch.cat(
291
+ [results[img_id.item()][k], result[k]], dim=0
292
+ )
293
+ elif isinstance(result[k], list):
294
+ results[img_id.item()][k] += result[k]
295
+ else:
296
+ raise NotImplementedError(
297
+ f"Unexpected type {type(result[k])} in result."
298
+ )
299
+ # Prune the results to the max number of detections per image.
300
+ for img_id, result in results.items():
301
+ if (
302
+ self.max_dets_per_img > 0
303
+ and len(result["scores"]) > self.max_dets_per_img
304
+ ):
305
+ _, topk_indexes = torch.topk(
306
+ result["scores"], self.max_dets_per_img, dim=0
307
+ )
308
+ if self.to_cpu:
309
+ topk_indexes = topk_indexes.cpu()
310
+ for k in result.keys():
311
+ if isinstance(results[img_id][k], list):
312
+ results[img_id][k] = [
313
+ results[img_id][k][i] for i in topk_indexes.tolist()
314
+ ]
315
+ else:
316
+ results[img_id][k] = results[img_id][k].to(topk_indexes.device)[
317
+ topk_indexes
318
+ ]
319
+
320
+ return results
321
+
322
+
323
+ class PostProcessAPIVideo(PostProcessImage):
324
+ """This module converts the video model's output into the format expected by the YT-VIS api"""
325
+
326
+ def __init__(
327
+ self,
328
+ *args,
329
+ to_cpu: bool = True,
330
+ convert_mask_to_rle: bool = False,
331
+ always_interpolate_masks_on_gpu: bool = True,
332
+ prob_thresh: float = 0.5,
333
+ use_presence: bool = False,
334
+ **kwargs,
335
+ ):
336
+ super().__init__(
337
+ *args,
338
+ # Here we always set `convert_mask_to_rle=False` in the base `PostProcessAPI` class
339
+ # (so that its `_process_masks` won't return a list of RLEs). If we want to return
340
+ # RLEs for video masklets, we handle it in this `PostProcessAPIVideo` class instead.
341
+ convert_mask_to_rle=False,
342
+ # Here we always set `to_cpu=False` in the base `PostProcessAPI` class (so that
343
+ # the interpolated masks won't be automatically moved back to CPU). We will handle
344
+ # it in this `PostProcessAPIVideo` class instead.
345
+ always_interpolate_masks_on_gpu=always_interpolate_masks_on_gpu,
346
+ use_presence=use_presence,
347
+ **kwargs,
348
+ )
349
+ # Expected keys in the output dict to postprocess
350
+ self.EXPECTED_KEYS = [
351
+ "pred_logits",
352
+ "pred_boxes",
353
+ "pred_masks",
354
+ ]
355
+ # Whether to post-process video masklets (under packed representation) into RLE format
356
+ self.convert_mask_to_rle_for_video = convert_mask_to_rle
357
+ self.to_cpu_for_video = to_cpu
358
+ self.prob_thresh = prob_thresh
359
+
360
+ def process_results(
361
+ self, find_stages, find_metadatas: List[BatchedInferenceMetadata], **kwargs
362
+ ):
363
+ """
364
+ Tracking Postprocessor for SAM 3 video model.
365
+ This function takes in the output of the SAM 3 video model and processes it to extract all the tracklet predictions.
366
+ Args:
367
+ find_stages: A list of tensors representing the output of the SAM 3 video model.
368
+ find_metadatas: A list of BatchedInferenceMetadata objects containing metadata about each frame.
369
+ **kwargs: Additional keyword arguments.
370
+ Returns:
371
+ A dictionary of predcitions with video_id as key.
372
+ """
373
+
374
+ # Import tensordict here to avoid global dependency.
375
+ try:
376
+ from tensordict import TensorDict
377
+ except ImportError as e:
378
+ logging.error(
379
+ "tensordict is not installed, please install by running `pip install tensordict --no-deps`"
380
+ )
381
+ raise e
382
+ # Notes and assumptions:
383
+ # 1- This postprocessor assumes results only for a single video.
384
+ # 2- There are N stage outputs corresponding to N video frames
385
+ # 3- Each stage outputs contains PxQ preds, where P is number of prompts and Q is number of object queries. The output should also contain the tracking object ids corresponding to each object query.
386
+ # 4- The tracking object id has a default value of -1, indicating that the object query is not tracking any object in the frame, and hence its predictions can be ingored for a given frame.
387
+ # 5- Some objects may be tracked in a subset of frames only. So, we first extract the predictions in a packed representation (for efficient postprocessing -- specially memory)
388
+ # and then we convert the packed representation into a padded one, where we zero pad boxes/masks for objects that are not tracked in some frames.
389
+ # 6- We refer to objects by an object id, which is a tuple (prompt_idx, obj_id)
390
+
391
+ assert len(find_stages) > 0, "There is nothing to postprocess?"
392
+ PROMPT_AXIS, OBJ_QUERY_AXIS = (0, 1)
393
+ NO_OBJ_ID = -1
394
+ # Maps object ID -> [indices in packed tensor]
395
+ tracked_objects_packed_idx = defaultdict(list)
396
+ # Maps object ID -> [indices in padded tensor (abs frame index)]
397
+ tracked_objects_frame_idx = defaultdict(list)
398
+ total_num_preds = 0
399
+ # This will hold the packed representation of predictions.
400
+ vid_preds_packed: List[TensorDict] = []
401
+ vid_masklets_rle_packed: List[Optional[Dict]] = []
402
+ video_id = -1 # We assume single video postprocessing, this ID should be unique in the datapoint.
403
+
404
+ for frame_idx, (frame_outs, meta) in enumerate(
405
+ zip(find_stages, find_metadatas)
406
+ ):
407
+ # only store keys we need to extract the results
408
+ frame_outs_td = TensorDict(
409
+ {k: frame_outs[k] for k in self.EXPECTED_KEYS}
410
+ ).auto_batch_size_() # Shape is [P,Q,...]
411
+ meta_td = TensorDict(
412
+ dataclasses.asdict(meta)
413
+ ).auto_batch_size_() # Shape is [P,...]
414
+ unique_vid_id = meta.original_image_id.unique()
415
+ assert unique_vid_id.size(0) == 1
416
+ if video_id == -1:
417
+ video_id = unique_vid_id.item()
418
+ else:
419
+ assert (
420
+ video_id == unique_vid_id.item()
421
+ ), "We can only postprocess one video per datapoint"
422
+ # keeping track of which objects appear in the current frame
423
+ obj_ids_per_frame = frame_outs["pred_object_ids"]
424
+ assert obj_ids_per_frame.size(-1) == frame_outs["pred_logits"].size(-2)
425
+ if self.prob_thresh is not None:
426
+ # only keep the predictions on this frame with probability above the threshold
427
+ # (remove those predictions during the keep-alive period of a tracking query,
428
+ # where its "pred_object_ids" is still the tracked object ID rather than -1)
429
+ pred_probs = frame_outs["pred_logits"].sigmoid().squeeze(-1)
430
+ obj_ids_per_frame = torch.where(
431
+ pred_probs >= self.prob_thresh, obj_ids_per_frame, NO_OBJ_ID
432
+ )
433
+ tracked_obj_ids_idx = torch.where(obj_ids_per_frame != NO_OBJ_ID)
434
+ # Object id is a tuple of (prompt_idx, obj_id). This is because the model can assign same obj_id for two different prompts.
435
+ tracked_obj_ids = [
436
+ (p_id.item(), obj_ids_per_frame[p_id, q_id].item())
437
+ for p_id, q_id in zip(
438
+ tracked_obj_ids_idx[PROMPT_AXIS],
439
+ tracked_obj_ids_idx[OBJ_QUERY_AXIS],
440
+ )
441
+ ]
442
+ if len(tracked_obj_ids) == 0:
443
+ continue
444
+ # For each object, we keep track of the packed and padded (frame index) indices
445
+ for oid in tracked_obj_ids:
446
+ tracked_objects_packed_idx[oid].append(total_num_preds)
447
+ tracked_objects_frame_idx[oid].append(frame_idx)
448
+ total_num_preds += 1
449
+
450
+ # Since we have P*Q masks per frame, mask interpolation is the GPU memory bottleneck or time bottleneck in case of cpu processing.
451
+ # Instead, we first extract results only for tracked objects, reducing the number of masks to K = sum_i(tracked_objs_per_ith_prompt), hopefully <<< P*Q
452
+ tracked_objs_outs_td = frame_outs_td[
453
+ tracked_obj_ids_idx
454
+ ] # [P,Q,...] --> [K,...]
455
+ meta_td = meta_td[tracked_obj_ids_idx[PROMPT_AXIS].cpu()]
456
+ if self.always_interpolate_masks_on_gpu:
457
+ gpu_device = meta_td["original_size"].device
458
+ assert gpu_device.type == "cuda"
459
+ tracked_objs_outs_td = tracked_objs_outs_td.to(device=gpu_device)
460
+ frame_results_td = self(
461
+ tracked_objs_outs_td.unsqueeze(1),
462
+ (
463
+ meta_td["original_size"]
464
+ if self.use_original_sizes
465
+ else torch.ones_like(meta_td["original_size"])
466
+ ),
467
+ forced_labels=(
468
+ meta_td["original_category_id"] if self.use_original_ids else None
469
+ ),
470
+ consistent=True,
471
+ ret_tensordict=True,
472
+ ).squeeze(1)
473
+ del tracked_objs_outs_td
474
+
475
+ # Optionally, remove "masks" from output tensor dict and directly encode them
476
+ # to RLE format under packed representations
477
+ if self.convert_mask_to_rle_for_video:
478
+ interpolated_binary_masks = frame_results_td.pop("masks")
479
+ rle_list = rle_encode(interpolated_binary_masks, return_areas=True)
480
+ vid_masklets_rle_packed.extend(rle_list)
481
+ # Optionally, move output TensorDict to CPU (do this after RLE encoding step above)
482
+ if self.to_cpu_for_video:
483
+ frame_results_td = frame_results_td.cpu()
484
+ vid_preds_packed.append(frame_results_td)
485
+
486
+ if len(vid_preds_packed) == 0:
487
+ logging.debug(f"Video {video_id} has no predictions")
488
+ return {video_id: []}
489
+
490
+ vid_preds_packed = torch.cat(vid_preds_packed, dim=0)
491
+ ############### Construct a padded representation of the predictions ###############
492
+ num_preds = len(tracked_objects_packed_idx)
493
+ num_frames = len(find_stages)
494
+ # We zero pad any missing prediction
495
+ # NOTE: here, we also have padded tensors for "scores" and "labels", but we overwrite them later.
496
+ padded_frames_results = TensorDict(
497
+ {
498
+ k: torch.zeros(
499
+ num_preds, num_frames, *v.shape[1:], device=v.device, dtype=v.dtype
500
+ )
501
+ for k, v in vid_preds_packed.items()
502
+ },
503
+ batch_size=[
504
+ num_preds,
505
+ num_frames,
506
+ ],
507
+ )
508
+ padded_frames_results["scores"][...] = -1e8 # a very low score for empty object
509
+ # Track scores and labels of each pred tracklet, only for frames where the model was able to track that object
510
+ tracklet_scores = []
511
+ tracklet_labels = []
512
+ # Optionally, fill the list of RLEs for masklets
513
+ # note: only frames with actual predicted masks (in packed format) will be
514
+ # filled with RLEs; the rest will remains None in results["masks_rle"]
515
+ if self.convert_mask_to_rle_for_video:
516
+ vid_masklets_rle_padded = [[None] * num_frames for _ in range(num_preds)]
517
+ for o_idx, oid in enumerate(tracked_objects_packed_idx):
518
+ oid2packed_idx = tracked_objects_packed_idx[oid]
519
+ oid2padded_idx = tracked_objects_frame_idx[oid]
520
+ obj_packed_results = vid_preds_packed[oid2packed_idx]
521
+ padded_frames_results[o_idx][oid2padded_idx] = obj_packed_results
522
+ if self.convert_mask_to_rle_for_video:
523
+ for packed_idx, padded_idx in zip(oid2packed_idx, oid2padded_idx):
524
+ vid_masklets_rle_padded[o_idx][padded_idx] = (
525
+ vid_masklets_rle_packed[packed_idx]
526
+ )
527
+ # NOTE: We need a single confidence score per tracklet for the mAP metric.
528
+ # We use the average confidence score across time. (How does this impact AP?)
529
+ tracklet_scores.append(obj_packed_results["scores"].mean())
530
+ # We also need to have a unique category Id per tracklet.
531
+ # This is not a problem for phrase AP, however, for mAP we do majority voting across time.
532
+ tracklet_labels.append(obj_packed_results["labels"].mode()[0])
533
+
534
+ results = padded_frames_results.to_dict()
535
+ results["scores"] = torch.stack(tracklet_scores, dim=0)
536
+ results["labels"] = torch.stack(tracklet_labels, dim=0)
537
+ if self.convert_mask_to_rle_for_video:
538
+ results["masks_rle"] = vid_masklets_rle_padded
539
+ # we keep the frame-level scores since it's needed by some evaluation scripts
540
+ results["per_frame_scores"] = padded_frames_results["scores"]
541
+
542
+ return {video_id: results}
543
+
544
+
545
+ class PostProcessTracking(PostProcessImage):
546
+ """This module converts the model's output into the format expected by the coco api"""
547
+
548
+ def __init__(
549
+ self,
550
+ max_dets_per_img: int,
551
+ iou_type="bbox",
552
+ force_single_mask: bool = False,
553
+ **kwargs,
554
+ ) -> None:
555
+ super().__init__(max_dets_per_img=max_dets_per_img, iou_type=iou_type, **kwargs)
556
+ self.force_single_mask = force_single_mask
557
+
558
+ def process_results(
559
+ self, find_stages, find_metadatas: BatchedInferenceMetadata, **kwargs
560
+ ):
561
+ assert len(find_stages) == len(find_metadatas)
562
+ results = {}
563
+ for outputs, meta in zip(find_stages, find_metadatas):
564
+ if self.force_single_mask:
565
+ scores, labels = outputs["pred_logits"].max(-1)
566
+ m = []
567
+ for i in range(len(outputs["pred_masks"])):
568
+ score, idx = scores[i].max(0)
569
+ m.append(outputs["pred_masks"][i][idx])
570
+ outputs["pred_masks"] = torch.stack(m, 0).unsqueeze(1)
571
+ detection_results = self(outputs, meta.original_size, consistent=False)
572
+ assert len(detection_results) == len(meta.coco_image_id)
573
+ results.update(
574
+ {
575
+ (media_id.item(), object_id.item(), frame_index.item()): result
576
+ for media_id, object_id, frame_index, result in zip(
577
+ meta.original_image_id,
578
+ meta.object_id,
579
+ meta.frame_index,
580
+ detection_results,
581
+ )
582
+ }
583
+ )
584
+ return results
585
+
586
+
587
+ class PostProcessCounting(nn.Module):
588
+ """This module converts the model's output to be evaluated for counting tasks"""
589
+
590
+ def __init__(
591
+ self,
592
+ use_original_ids: bool = False,
593
+ threshold: float = 0.5,
594
+ use_presence: bool = False,
595
+ ) -> None:
596
+ """
597
+ Args:
598
+ use_original_ids: whether to use the original image ids or the coco ids
599
+ threshold: threshold for counting (values above this are counted)
600
+ """
601
+ super().__init__()
602
+ self.use_original_ids = use_original_ids
603
+ self.threshold = threshold
604
+ self.use_presence = use_presence
605
+
606
+ def forward(self, outputs, target_sizes):
607
+ """Perform the computation
608
+ Parameters:
609
+ outputs: raw outputs of the model
610
+ target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch
611
+ """
612
+ # Extract scores from model outputs and apply sigmoid
613
+ scores = torch.sigmoid(outputs["pred_logits"]).squeeze(-1) # [B, N]
614
+ if self.use_presence:
615
+ presence_score = outputs["presence_logit_dec"].sigmoid()
616
+ if presence_score.ndim == 1:
617
+ presence_score = presence_score.unsqueeze(1) # [B, 1]
618
+ scores = scores * presence_score # [B, N]
619
+
620
+ # Calculate counts by summing values above threshold
621
+ counts = (scores > self.threshold).float().sum(dim=1)
622
+
623
+ assert len(counts) == len(target_sizes)
624
+ results = []
625
+ for count in counts:
626
+ results.append({"count": count.item()})
627
+
628
+ return results
629
+
630
+ @torch.no_grad()
631
+ def process_results(
632
+ self, find_stages, find_metadatas: List[BatchedInferenceMetadata], **kwargs
633
+ ):
634
+ assert len(find_stages) == len(find_metadatas)
635
+ results = {}
636
+ for outputs, meta in zip(find_stages, find_metadatas):
637
+ detection_results = self(
638
+ outputs,
639
+ meta.original_size,
640
+ )
641
+ ids = (
642
+ meta.original_image_id if self.use_original_ids else meta.coco_image_id
643
+ )
644
+ assert len(detection_results) == len(ids)
645
+ for img_id, result in zip(ids, detection_results):
646
+ results[img_id.item()] = result
647
+
648
+ return results
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ from . import config, datasets, metrics, utils
5
+ from .eval import Evaluator
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/_timing.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ import inspect
5
+ from functools import wraps
6
+ from time import perf_counter
7
+
8
+ DO_TIMING = False
9
+ DISPLAY_LESS_PROGRESS = False
10
+ timer_dict = {}
11
+ counter = 0
12
+
13
+
14
+ def time(f):
15
+ @wraps(f)
16
+ def wrap(*args, **kw):
17
+ if DO_TIMING:
18
+ # Run function with timing
19
+ ts = perf_counter()
20
+ result = f(*args, **kw)
21
+ te = perf_counter()
22
+ tt = te - ts
23
+
24
+ # Get function name
25
+ arg_names = inspect.getfullargspec(f)[0]
26
+ if arg_names[0] == "self" and DISPLAY_LESS_PROGRESS:
27
+ return result
28
+ elif arg_names[0] == "self":
29
+ method_name = type(args[0]).__name__ + "." + f.__name__
30
+ else:
31
+ method_name = f.__name__
32
+
33
+ # Record accumulative time in each function for analysis
34
+ if method_name in timer_dict.keys():
35
+ timer_dict[method_name] += tt
36
+ else:
37
+ timer_dict[method_name] = tt
38
+
39
+ # If code is finished, display timing summary
40
+ if method_name == "Evaluator.evaluate":
41
+ print("")
42
+ print("Timing analysis:")
43
+ for key, value in timer_dict.items():
44
+ print("%-70s %2.4f sec" % (key, value))
45
+ else:
46
+ # Get function argument values for printing special arguments of interest
47
+ arg_titles = ["tracker", "seq", "cls"]
48
+ arg_vals = []
49
+ for i, a in enumerate(arg_names):
50
+ if a in arg_titles:
51
+ arg_vals.append(args[i])
52
+ arg_text = "(" + ", ".join(arg_vals) + ")"
53
+
54
+ # Display methods and functions with different indentation.
55
+ if arg_names[0] == "self":
56
+ print("%-74s %2.4f sec" % (" " * 4 + method_name + arg_text, tt))
57
+ elif arg_names[0] == "test":
58
+ pass
59
+ else:
60
+ global counter
61
+ counter += 1
62
+ print("%i %-70s %2.4f sec" % (counter, method_name + arg_text, tt))
63
+
64
+ return result
65
+ else:
66
+ # If config["TIME_PROGRESS"] is false, or config["USE_PARALLEL"] is true, run functions normally without timing.
67
+ return f(*args, **kw)
68
+
69
+ return wrap
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/config.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ """Config."""
5
+ import argparse
6
+ import os
7
+
8
+
9
+ def parse_configs():
10
+ """Parse command line."""
11
+ default_eval_config = get_default_eval_config()
12
+ default_eval_config["DISPLAY_LESS_PROGRESS"] = True
13
+ default_dataset_config = get_default_dataset_config()
14
+ default_metrics_config = {"METRICS": ["TETA"]}
15
+ config = {
16
+ **default_eval_config,
17
+ **default_dataset_config,
18
+ **default_metrics_config,
19
+ }
20
+ parser = argparse.ArgumentParser()
21
+ for setting in config.keys():
22
+ if type(config[setting]) == list or type(config[setting]) == type(None):
23
+ parser.add_argument("--" + setting, nargs="+")
24
+ else:
25
+ parser.add_argument("--" + setting)
26
+ args = parser.parse_args().__dict__
27
+ for setting in args.keys():
28
+ if args[setting] is not None:
29
+ if type(config[setting]) == type(True):
30
+ if args[setting] == "True":
31
+ x = True
32
+ elif args[setting] == "False":
33
+ x = False
34
+ else:
35
+ raise Exception(
36
+ f"Command line parameter {setting} must be True/False"
37
+ )
38
+ elif type(config[setting]) == type(1):
39
+ x = int(args[setting])
40
+ elif type(args[setting]) == type(None):
41
+ x = None
42
+ else:
43
+ x = args[setting]
44
+ config[setting] = x
45
+ eval_config = {k: v for k, v in config.items() if k in default_eval_config.keys()}
46
+ dataset_config = {
47
+ k: v for k, v in config.items() if k in default_dataset_config.keys()
48
+ }
49
+ metrics_config = {
50
+ k: v for k, v in config.items() if k in default_metrics_config.keys()
51
+ }
52
+
53
+ return eval_config, dataset_config, metrics_config
54
+
55
+
56
+ def get_default_eval_config():
57
+ """Returns the default config values for evaluation."""
58
+ code_path = get_code_path()
59
+ default_config = {
60
+ "USE_PARALLEL": True,
61
+ "NUM_PARALLEL_CORES": 8,
62
+ "BREAK_ON_ERROR": True,
63
+ "RETURN_ON_ERROR": False,
64
+ "LOG_ON_ERROR": os.path.join(code_path, "error_log.txt"),
65
+ "PRINT_RESULTS": True,
66
+ "PRINT_ONLY_COMBINED": True,
67
+ "PRINT_CONFIG": True,
68
+ "TIME_PROGRESS": True,
69
+ "DISPLAY_LESS_PROGRESS": True,
70
+ "OUTPUT_SUMMARY": True,
71
+ "OUTPUT_EMPTY_CLASSES": True,
72
+ "OUTPUT_TEM_RAW_DATA": True,
73
+ "OUTPUT_PER_SEQ_RES": True,
74
+ }
75
+ return default_config
76
+
77
+
78
+ def get_default_dataset_config():
79
+ """Default class config values"""
80
+ code_path = get_code_path()
81
+ default_config = {
82
+ "GT_FOLDER": os.path.join(
83
+ code_path, "data/gt/tao/tao_training"
84
+ ), # Location of GT data
85
+ "TRACKERS_FOLDER": os.path.join(
86
+ code_path, "data/trackers/tao/tao_training"
87
+ ), # Trackers location
88
+ "OUTPUT_FOLDER": None, # Where to save eval results (if None, same as TRACKERS_FOLDER)
89
+ "TRACKERS_TO_EVAL": ['TETer'], # Filenames of trackers to eval (if None, all in folder)
90
+ "CLASSES_TO_EVAL": None, # Classes to eval (if None, all classes)
91
+ "SPLIT_TO_EVAL": "training", # Valid: 'training', 'val'
92
+ "PRINT_CONFIG": True, # Whether to print current config
93
+ "TRACKER_SUB_FOLDER": "data", # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER
94
+ "OUTPUT_SUB_FOLDER": "", # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER
95
+ "TRACKER_DISPLAY_NAMES": None, # Names of trackers to display, if None: TRACKERS_TO_EVAL
96
+ "MAX_DETECTIONS": 0, # Number of maximal allowed detections per image (0 for unlimited)
97
+ "USE_MASK": False, # Whether to use mask data for evaluation
98
+ }
99
+ return default_config
100
+
101
+
102
+ def init_config(config, default_config, name=None):
103
+ """Initialize non-given config values with defaults."""
104
+ if config is None:
105
+ config = default_config
106
+ else:
107
+ for k in default_config.keys():
108
+ if k not in config.keys():
109
+ config[k] = default_config[k]
110
+ if name and config["PRINT_CONFIG"]:
111
+ print("\n%s Config:" % name)
112
+ for c in config.keys():
113
+ print("%-20s : %-30s" % (c, config[c]))
114
+ return config
115
+
116
+
117
+ def update_config(config):
118
+ """
119
+ Parse the arguments of a script and updates the config values for a given value if specified in the arguments.
120
+ :param config: the config to update
121
+ :return: the updated config
122
+ """
123
+ parser = argparse.ArgumentParser()
124
+ for setting in config.keys():
125
+ if type(config[setting]) == list or type(config[setting]) == type(None):
126
+ parser.add_argument("--" + setting, nargs="+")
127
+ else:
128
+ parser.add_argument("--" + setting)
129
+ args = parser.parse_args().__dict__
130
+ for setting in args.keys():
131
+ if args[setting] is not None:
132
+ if type(config[setting]) == type(True):
133
+ if args[setting] == "True":
134
+ x = True
135
+ elif args[setting] == "False":
136
+ x = False
137
+ else:
138
+ raise Exception(
139
+ "Command line parameter " + setting + "must be True or False"
140
+ )
141
+ elif type(config[setting]) == type(1):
142
+ x = int(args[setting])
143
+ elif type(args[setting]) == type(None):
144
+ x = None
145
+ else:
146
+ x = args[setting]
147
+ config[setting] = x
148
+ return config
149
+
150
+
151
+ def get_code_path():
152
+ """Get base path where code is"""
153
+ return os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/eval.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ import copy
5
+ import os
6
+ import pickle
7
+ import time
8
+ import traceback
9
+ from functools import partial
10
+ from multiprocessing.pool import Pool
11
+
12
+ import numpy as np
13
+
14
+ from . import _timing, utils
15
+ from .config import get_default_eval_config, init_config
16
+ from .utils import TrackEvalException
17
+
18
+
19
+ class Evaluator:
20
+ """Evaluator class for evaluating different metrics for each datasets."""
21
+
22
+ def __init__(self, config=None):
23
+ """Initialize the evaluator with a config file."""
24
+ self.config = init_config(config, get_default_eval_config(), "Eval")
25
+ # Only run timing analysis if not run in parallel.
26
+ if self.config["TIME_PROGRESS"] and not self.config["USE_PARALLEL"]:
27
+ _timing.DO_TIMING = True
28
+ if self.config["DISPLAY_LESS_PROGRESS"]:
29
+ _timing.DISPLAY_LESS_PROGRESS = True
30
+
31
+ @_timing.time
32
+ def evaluate(self, dataset_list, metrics_list):
33
+ """Evaluate a set of metrics on a set of datasets."""
34
+ config = self.config
35
+ metrics_list = metrics_list
36
+ metric_names = utils.validate_metrics_list(metrics_list)
37
+ dataset_names = [dataset.get_name() for dataset in dataset_list]
38
+ output_res = {}
39
+ output_msg = {}
40
+
41
+ for dataset, dname in zip(dataset_list, dataset_names):
42
+ # Get dataset info about what to evaluate
43
+ output_res[dname] = {}
44
+ output_msg[dname] = {}
45
+ tracker_list, seq_list, class_list = dataset.get_eval_info()
46
+ print(
47
+ f"\nEvaluating {len(tracker_list)} tracker(s) on "
48
+ f"{len(seq_list)} sequence(s) for {len(class_list)} class(es)"
49
+ f" on {dname} dataset using the following "
50
+ f'metrics: {", ".join(metric_names)}\n'
51
+ )
52
+
53
+ # Evaluate each tracker
54
+ for tracker in tracker_list:
55
+ try:
56
+ output_res, output_msg = self.evaluate_tracker(
57
+ tracker,
58
+ dataset,
59
+ dname,
60
+ class_list,
61
+ metrics_list,
62
+ metric_names,
63
+ seq_list,
64
+ output_res,
65
+ output_msg,
66
+ )
67
+ except Exception as err:
68
+ output_res[dname][tracker] = None
69
+ if type(err) == TrackEvalException:
70
+ output_msg[dname][tracker] = str(err)
71
+ else:
72
+ output_msg[dname][tracker] = "Unknown error occurred."
73
+ print("Tracker %s was unable to be evaluated." % tracker)
74
+ print(err)
75
+ traceback.print_exc()
76
+ if config["LOG_ON_ERROR"] is not None:
77
+ with open(config["LOG_ON_ERROR"], "a") as f:
78
+ print(dname, file=f)
79
+ print(tracker, file=f)
80
+ print(traceback.format_exc(), file=f)
81
+ print("\n\n\n", file=f)
82
+ if config["BREAK_ON_ERROR"]:
83
+ raise err
84
+ elif config["RETURN_ON_ERROR"]:
85
+ return output_res, output_msg
86
+
87
+ return output_res, output_msg
88
+
89
+ def evaluate_tracker(
90
+ self,
91
+ tracker,
92
+ dataset,
93
+ dname,
94
+ class_list,
95
+ metrics_list,
96
+ metric_names,
97
+ seq_list,
98
+ output_res,
99
+ output_msg,
100
+ ):
101
+ """Evaluate each sequence in parallel or in series."""
102
+ print("\nEvaluating %s\n" % tracker)
103
+ time_start = time.time()
104
+ config = self.config
105
+ if config["USE_PARALLEL"]:
106
+ with Pool(config["NUM_PARALLEL_CORES"]) as pool:
107
+ _eval_sequence = partial(
108
+ eval_sequence,
109
+ dataset=dataset,
110
+ tracker=tracker,
111
+ class_list=class_list,
112
+ metrics_list=metrics_list,
113
+ metric_names=metric_names,
114
+ )
115
+ results = pool.map(_eval_sequence, seq_list)
116
+ res = dict(zip(seq_list, results))
117
+ else:
118
+ res = {}
119
+ for curr_seq in sorted(seq_list):
120
+ res[curr_seq] = eval_sequence(
121
+ curr_seq, dataset, tracker, class_list, metrics_list, metric_names
122
+ )
123
+
124
+
125
+ # collecting combined cls keys (cls averaged, det averaged, super classes)
126
+ cls_keys = []
127
+ res["COMBINED_SEQ"] = {}
128
+ # combine sequences for each class
129
+ for c_cls in class_list:
130
+ res["COMBINED_SEQ"][c_cls] = {}
131
+ for metric, mname in zip(metrics_list, metric_names):
132
+ curr_res = {
133
+ seq_key: seq_value[c_cls][mname]
134
+ for seq_key, seq_value in res.items()
135
+ if seq_key != "COMBINED_SEQ"
136
+ }
137
+ # combine results over all sequences and then over all classes
138
+ res["COMBINED_SEQ"][c_cls][mname] = metric.combine_sequences(curr_res)
139
+
140
+ # combine classes
141
+ if dataset.should_classes_combine:
142
+ if config["OUTPUT_PER_SEQ_RES"]:
143
+ video_keys = res.keys()
144
+ else:
145
+ video_keys = ["COMBINED_SEQ"]
146
+ for v_key in video_keys:
147
+ cls_keys += ["average"]
148
+ res[v_key]["average"] = {}
149
+ for metric, mname in zip(metrics_list, metric_names):
150
+ cls_res = {
151
+ cls_key: cls_value[mname]
152
+ for cls_key, cls_value in res[v_key].items()
153
+ if cls_key not in cls_keys
154
+ }
155
+ res[v_key]["average"][
156
+ mname
157
+ ] = metric.combine_classes_class_averaged(
158
+ cls_res, ignore_empty=True
159
+ )
160
+
161
+ # combine classes to super classes
162
+ if dataset.use_super_categories:
163
+ for cat, sub_cats in dataset.super_categories.items():
164
+ cls_keys.append(cat)
165
+ res["COMBINED_SEQ"][cat] = {}
166
+ for metric, mname in zip(metrics_list, metric_names):
167
+ cat_res = {
168
+ cls_key: cls_value[mname]
169
+ for cls_key, cls_value in res["COMBINED_SEQ"].items()
170
+ if cls_key in sub_cats
171
+ }
172
+ res["COMBINED_SEQ"][cat][
173
+ mname
174
+ ] = metric.combine_classes_det_averaged(cat_res)
175
+ # Print and output results in various formats
176
+ if config["TIME_PROGRESS"]:
177
+ print(
178
+ f"\nAll sequences for {tracker} finished in"
179
+ f" {time.time() - time_start} seconds"
180
+ )
181
+ output_fol = dataset.get_output_fol(tracker)
182
+ os.makedirs(output_fol, exist_ok=True)
183
+
184
+ # take a mean of each field of each thr
185
+ if config["OUTPUT_PER_SEQ_RES"]:
186
+ all_res = copy.deepcopy(res)
187
+ summary_keys = res.keys()
188
+ else:
189
+ all_res = copy.deepcopy(res["COMBINED_SEQ"])
190
+ summary_keys = ["COMBINED_SEQ"]
191
+ thr_key_list = [50]
192
+ for s_key in summary_keys:
193
+ for metric, mname in zip(metrics_list, metric_names):
194
+ if mname != "TETA":
195
+ if s_key == "COMBINED_SEQ":
196
+ metric.print_table(
197
+ {"COMBINED_SEQ": res["COMBINED_SEQ"][cls_keys[0]][mname]},
198
+ tracker,
199
+ cls_keys[0],
200
+ )
201
+ continue
202
+
203
+ for c_cls in res[s_key].keys():
204
+ for thr in thr_key_list:
205
+ all_res[s_key][c_cls][mname][thr] = metric._summary_row(
206
+ res[s_key][c_cls][mname][thr]
207
+ )
208
+ x = (
209
+ np.array(list(all_res[s_key][c_cls]["TETA"].values()))
210
+ .astype("float")
211
+ .mean(axis=0)
212
+ )
213
+ all_res_summary = list(x.round(decimals=2).astype("str"))
214
+ all_res[s_key][c_cls][mname]["ALL"] = all_res_summary
215
+ if config["OUTPUT_SUMMARY"] and s_key == "COMBINED_SEQ":
216
+ for t in thr_key_list:
217
+ metric.print_summary_table(
218
+ all_res[s_key][cls_keys[0]][mname][t],
219
+ t,
220
+ tracker,
221
+ cls_keys[0],
222
+ )
223
+
224
+ if config["OUTPUT_TEM_RAW_DATA"]:
225
+ out_file = os.path.join(output_fol, "teta_summary_results.pth")
226
+ pickle.dump(all_res, open(out_file, "wb"))
227
+ print("Saved the TETA summary results.")
228
+
229
+ # output
230
+ output_res[dname][mname] = all_res[s_key][cls_keys[0]][mname][t]
231
+ output_msg[dname][tracker] = "Success"
232
+
233
+ return output_res, output_msg
234
+
235
+
236
+ @_timing.time
237
+ def eval_sequence(seq, dataset, tracker, class_list, metrics_list, metric_names):
238
+ """Function for evaluating a single sequence."""
239
+ raw_data = dataset.get_raw_seq_data(tracker, seq)
240
+ seq_res = {}
241
+
242
+ if "TETA" in metric_names:
243
+ thresholds = [50]
244
+ data_all_class = dataset.get_preprocessed_seq_data(
245
+ raw_data, "all", thresholds=thresholds
246
+ )
247
+ teta = metrics_list[metric_names.index("TETA")]
248
+ assignment = teta.compute_global_assignment(data_all_class)
249
+
250
+ # create a dict to save Cls_FP for each class in different thr.
251
+ cls_fp = {
252
+ key: {
253
+ cls: np.zeros((len(np.arange(0.5, 0.99, 0.05)))) for cls in class_list
254
+ }
255
+ for key in thresholds
256
+ }
257
+
258
+ for cls in class_list:
259
+ seq_res[cls] = {}
260
+ data = dataset.get_preprocessed_seq_data(raw_data, cls, assignment, thresholds)
261
+
262
+ for metric, mname in zip(metrics_list, metric_names):
263
+ if mname == "TETA":
264
+ seq_res[cls][mname], cls_fp, _ = metric.eval_sequence(
265
+ data, cls, dataset.clsid2cls_name, cls_fp
266
+ )
267
+ else:
268
+ seq_res[cls][mname] = metric.eval_sequence(data)
269
+
270
+ if "TETA" in metric_names:
271
+ for thr in thresholds:
272
+ for cls in class_list:
273
+ seq_res[cls]["TETA"][thr]["Cls_FP"] += cls_fp[thr][cls]
274
+
275
+ return seq_res
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/metrics/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ from .teta import TETA
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/metrics/_base_metric.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ from abc import ABC, abstractmethod
5
+
6
+ import numpy as np
7
+
8
+ from .. import _timing
9
+ from ..utils import TrackEvalException
10
+
11
+
12
+ class _BaseMetric(ABC):
13
+ @abstractmethod
14
+ def __init__(self):
15
+ self.plottable = False
16
+ self.integer_fields = []
17
+ self.float_fields = []
18
+ self.array_labels = []
19
+ self.integer_array_fields = []
20
+ self.float_array_fields = []
21
+ self.fields = []
22
+ self.summary_fields = []
23
+ self.registered = False
24
+
25
+ #####################################################################
26
+ # Abstract functions for subclasses to implement
27
+
28
+ @_timing.time
29
+ @abstractmethod
30
+ def eval_sequence(self, data):
31
+ ...
32
+
33
+ @abstractmethod
34
+ def combine_sequences(self, all_res):
35
+ ...
36
+
37
+ @abstractmethod
38
+ def combine_classes_class_averaged(self, all_res, ignore_empty=False):
39
+ ...
40
+
41
+ @abstractmethod
42
+ def combine_classes_det_averaged(self, all_res):
43
+ ...
44
+
45
+ def plot_single_tracker_results(self, all_res, tracker, output_folder, cls):
46
+ """Plot results, only valid for metrics with self.plottable."""
47
+ if self.plottable:
48
+ raise NotImplementedError(
49
+ f"plot_results is not implemented for metric {self.get_name()}"
50
+ )
51
+ else:
52
+ pass
53
+
54
+ #####################################################################
55
+ # Helper functions which are useful for all metrics:
56
+
57
+ @classmethod
58
+ def get_name(cls):
59
+ return cls.__name__
60
+
61
+ @staticmethod
62
+ def _combine_sum(all_res, field):
63
+ """Combine sequence results via sum"""
64
+ return sum([all_res[k][field] for k in all_res.keys()])
65
+
66
+ @staticmethod
67
+ def _combine_weighted_av(all_res, field, comb_res, weight_field):
68
+ """Combine sequence results via weighted average."""
69
+ return sum(
70
+ [all_res[k][field] * all_res[k][weight_field] for k in all_res.keys()]
71
+ ) / np.maximum(1.0, comb_res[weight_field])
72
+
73
+ def print_table(self, table_res, tracker, cls):
74
+ """Print table of results for all sequences."""
75
+ print("")
76
+ metric_name = self.get_name()
77
+ self._row_print(
78
+ [metric_name + ": " + tracker + "-" + cls] + self.summary_fields
79
+ )
80
+ for seq, results in sorted(table_res.items()):
81
+ if seq == "COMBINED_SEQ":
82
+ continue
83
+ summary_res = self._summary_row(results)
84
+ self._row_print([seq] + summary_res)
85
+ summary_res = self._summary_row(table_res["COMBINED_SEQ"])
86
+ self._row_print(["COMBINED"] + summary_res)
87
+
88
+ def _summary_row(self, results_):
89
+ vals = []
90
+ for h in self.summary_fields:
91
+ if h in self.float_array_fields:
92
+ vals.append("{0:1.5g}".format(100 * np.mean(results_[h])))
93
+ elif h in self.float_fields:
94
+ vals.append("{0:1.5g}".format(100 * float(results_[h])))
95
+ elif h in self.integer_fields:
96
+ vals.append("{0:d}".format(int(results_[h])))
97
+ else:
98
+ raise NotImplementedError(
99
+ "Summary function not implemented for this field type."
100
+ )
101
+ return vals
102
+
103
+ @staticmethod
104
+ def _row_print(*argv):
105
+ """Print results in evenly spaced rows, with more space in first row."""
106
+ if len(argv) == 1:
107
+ argv = argv[0]
108
+ to_print = "%-35s" % argv[0]
109
+ for v in argv[1:]:
110
+ to_print += "%-10s" % str(v)
111
+ print(to_print)
112
+
113
+ def summary_results(self, table_res):
114
+ """Return a simple summary of final results for a tracker."""
115
+ return dict(
116
+ zip(self.summary_fields, self._summary_row(table_res["COMBINED_SEQ"]),)
117
+ )
118
+
119
+ def detailed_results(self, table_res):
120
+ """Return detailed final results for a tracker."""
121
+ # Get detailed field information
122
+ detailed_fields = self.float_fields + self.integer_fields
123
+ for h in self.float_array_fields + self.integer_array_fields:
124
+ for alpha in [int(100 * x) for x in self.array_labels]:
125
+ detailed_fields.append(h + "___" + str(alpha))
126
+ detailed_fields.append(h + "___AUC")
127
+
128
+ # Get detailed results
129
+ detailed_results = {}
130
+ for seq, res in table_res.items():
131
+ detailed_row = self._detailed_row(res)
132
+ if len(detailed_row) != len(detailed_fields):
133
+ raise TrackEvalException(
134
+ f"Field names and data have different sizes "
135
+ f"({len(detailed_row)} and {len(detailed_fields)})"
136
+ )
137
+ detailed_results[seq] = dict(zip(detailed_fields, detailed_row))
138
+ return detailed_results
139
+
140
+ def _detailed_row(self, res):
141
+ detailed_row = []
142
+ for h in self.float_fields + self.integer_fields:
143
+ detailed_row.append(res[h])
144
+ for h in self.float_array_fields + self.integer_array_fields:
145
+ for i, _ in enumerate([int(100 * x) for x in self.array_labels]):
146
+ detailed_row.append(res[h][i])
147
+ detailed_row.append(np.mean(res[h]))
148
+ return detailed_row
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/metrics/teta.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ """Track Every Thing Accuracy metric."""
5
+
6
+ import numpy as np
7
+ from scipy.optimize import linear_sum_assignment
8
+
9
+ from .. import _timing
10
+ from ._base_metric import _BaseMetric
11
+
12
+ EPS = np.finfo("float").eps # epsilon
13
+
14
+
15
+ class TETA(_BaseMetric):
16
+ """TETA metric."""
17
+
18
+ def __init__(self, exhaustive=False, config=None):
19
+ """Initialize metric."""
20
+ super().__init__()
21
+ self.plottable = True
22
+ self.array_labels = np.arange(0.0, 0.99, 0.05)
23
+ self.cls_array_labels = np.arange(0.5, 0.99, 0.05)
24
+
25
+ self.integer_array_fields = [
26
+ "Loc_TP",
27
+ "Loc_FN",
28
+ "Loc_FP",
29
+ "Cls_TP",
30
+ "Cls_FN",
31
+ "Cls_FP",
32
+ ]
33
+ self.float_array_fields = (
34
+ ["TETA", "LocA", "AssocA", "ClsA"]
35
+ + ["LocRe", "LocPr"]
36
+ + ["AssocRe", "AssocPr"]
37
+ + ["ClsRe", "ClsPr"]
38
+ )
39
+ self.fields = self.float_array_fields + self.integer_array_fields
40
+ self.summary_fields = self.float_array_fields
41
+ self.exhaustive = exhaustive
42
+
43
+ def compute_global_assignment(self, data_thr, alpha=0.5):
44
+ """Compute global assignment of TP."""
45
+ res = {
46
+ thr: {t: {} for t in range(data_thr[thr]["num_timesteps"])}
47
+ for thr in data_thr
48
+ }
49
+
50
+ for thr in data_thr:
51
+ data = data_thr[thr]
52
+ # return empty result if tracker or gt sequence is empty
53
+ if data["num_tk_overlap_dets"] == 0 or data["num_gt_dets"] == 0:
54
+ return res
55
+
56
+ # global alignment score
57
+ ga_score, _, _ = self.compute_global_alignment_score(data)
58
+
59
+ # calculate scores for each timestep
60
+ for t, (gt_ids_t, tk_ids_t) in enumerate(
61
+ zip(data["gt_ids"], data["tk_ids"])
62
+ ):
63
+ # get matches optimizing for TETA
64
+ amatch_rows, amatch_cols = self.compute_matches(
65
+ data, t, ga_score, gt_ids_t, tk_ids_t, alpha=alpha
66
+ )
67
+ gt_ids = [data["gt_id_map"][tid] for tid in gt_ids_t[amatch_rows[0]]]
68
+ matched_ids = [
69
+ data["tk_id_map"][tid] for tid in tk_ids_t[amatch_cols[0]]
70
+ ]
71
+ res[thr][t] = dict(zip(gt_ids, matched_ids))
72
+
73
+ return res
74
+
75
+ def eval_sequence_single_thr(self, data, cls, cid2clsname, cls_fp_thr, thr):
76
+ """Computes TETA metric for one threshold for one sequence."""
77
+ res = {}
78
+ class_info_list = []
79
+ for field in self.float_array_fields + self.integer_array_fields:
80
+ if field.startswith("Cls"):
81
+ res[field] = np.zeros(len(self.cls_array_labels), dtype=float)
82
+ else:
83
+ res[field] = np.zeros((len(self.array_labels)), dtype=float)
84
+
85
+ # return empty result if tracker or gt sequence is empty
86
+ if data["num_tk_overlap_dets"] == 0:
87
+ res["Loc_FN"] = data["num_gt_dets"] * np.ones(
88
+ (len(self.array_labels)), dtype=float
89
+ )
90
+ if self.exhaustive:
91
+ cls_fp_thr[cls] = data["num_tk_cls_dets"] * np.ones(
92
+ (len(self.cls_array_labels)), dtype=float
93
+ )
94
+ res = self._compute_final_fields(res)
95
+ return res, cls_fp_thr, class_info_list
96
+
97
+ if data["num_gt_dets"] == 0:
98
+ if self.exhaustive:
99
+ cls_fp_thr[cls] = data["num_tk_cls_dets"] * np.ones(
100
+ (len(self.cls_array_labels)), dtype=float
101
+ )
102
+ res = self._compute_final_fields(res)
103
+ return res, cls_fp_thr, class_info_list
104
+
105
+ # global alignment score
106
+ ga_score, gt_id_count, tk_id_count = self.compute_global_alignment_score(data)
107
+ matches_counts = [np.zeros_like(ga_score) for _ in self.array_labels]
108
+
109
+ # calculate scores for each timestep
110
+ for t, (gt_ids_t, tk_ids_t, tk_overlap_ids_t, tk_cls_ids_t) in enumerate(
111
+ zip(
112
+ data["gt_ids"],
113
+ data["tk_ids"],
114
+ data["tk_overlap_ids"],
115
+ data["tk_class_eval_tk_ids"],
116
+ )
117
+ ):
118
+ # deal with the case that there are no gt_det/tk_det in a timestep
119
+ if len(gt_ids_t) == 0:
120
+ if self.exhaustive:
121
+ cls_fp_thr[cls] += len(tk_cls_ids_t)
122
+ continue
123
+
124
+ # get matches optimizing for TETA
125
+ amatch_rows, amatch_cols = self.compute_matches(
126
+ data, t, ga_score, gt_ids_t, tk_ids_t, list(self.array_labels)
127
+ )
128
+
129
+ # map overlap_ids to original ids.
130
+ if len(tk_overlap_ids_t) != 0:
131
+ sorter = np.argsort(tk_ids_t)
132
+ indexes = sorter[
133
+ np.searchsorted(tk_ids_t, tk_overlap_ids_t, sorter=sorter)
134
+ ]
135
+ sim_t = data["sim_scores"][t][:, indexes]
136
+ fpl_candidates = tk_overlap_ids_t[(sim_t >= (thr / 100)).any(axis=0)]
137
+ fpl_candidates_ori_ids_t = np.array(
138
+ [data["tk_id_map"][tid] for tid in fpl_candidates]
139
+ )
140
+ else:
141
+ fpl_candidates_ori_ids_t = []
142
+
143
+ if self.exhaustive:
144
+ cls_fp_thr[cls] += len(tk_cls_ids_t) - len(tk_overlap_ids_t)
145
+
146
+ # calculate and accumulate basic statistics
147
+ for a, alpha in enumerate(self.array_labels):
148
+ match_row, match_col = amatch_rows[a], amatch_cols[a]
149
+ num_matches = len(match_row)
150
+ matched_ori_ids = set(
151
+ [data["tk_id_map"][tid] for tid in tk_ids_t[match_col]]
152
+ )
153
+ match_tk_cls = data["tk_classes"][t][match_col]
154
+ wrong_tk_cls = match_tk_cls[match_tk_cls != data["gt_classes"][t]]
155
+
156
+ num_class_and_det_matches = np.sum(
157
+ match_tk_cls == data["gt_classes"][t]
158
+ )
159
+
160
+ if alpha >= 0.5:
161
+ for cid in wrong_tk_cls:
162
+ if cid in cid2clsname:
163
+ cname = cid2clsname[cid]
164
+ cls_fp_thr[cname][a - 10] += 1
165
+ res["Cls_TP"][a - 10] += num_class_and_det_matches
166
+ res["Cls_FN"][a - 10] += num_matches - num_class_and_det_matches
167
+
168
+ res["Loc_TP"][a] += num_matches
169
+ res["Loc_FN"][a] += len(gt_ids_t) - num_matches
170
+ res["Loc_FP"][a] += len(set(fpl_candidates_ori_ids_t) - matched_ori_ids)
171
+
172
+ if num_matches > 0:
173
+ matches_counts[a][gt_ids_t[match_row], tk_ids_t[match_col]] += 1
174
+
175
+ # calculate AssocA, AssocRe, AssocPr
176
+ self.compute_association_scores(res, matches_counts, gt_id_count, tk_id_count)
177
+
178
+ # calculate final scores
179
+ res = self._compute_final_fields(res)
180
+ return res, cls_fp_thr, class_info_list
181
+
182
+ def compute_global_alignment_score(self, data):
183
+ """Computes global alignment score."""
184
+ num_matches = np.zeros((data["num_gt_ids"], data["num_tk_ids"]))
185
+ gt_id_count = np.zeros((data["num_gt_ids"], 1))
186
+ tk_id_count = np.zeros((1, data["num_tk_ids"]))
187
+
188
+ # loop through each timestep and accumulate global track info.
189
+ for t, (gt_ids_t, tk_ids_t) in enumerate(zip(data["gt_ids"], data["tk_ids"])):
190
+ # count potential matches between ids in each time step
191
+ # these are normalized, weighted by match similarity
192
+ sim = data["sim_scores"][t]
193
+ sim_iou_denom = sim.sum(0, keepdims=True) + sim.sum(1, keepdims=True) - sim
194
+ sim_iou = np.zeros_like(sim)
195
+ mask = sim_iou_denom > (0 + EPS)
196
+ sim_iou[mask] = sim[mask] / sim_iou_denom[mask]
197
+ num_matches[gt_ids_t[:, None], tk_ids_t[None, :]] += sim_iou
198
+
199
+ # calculate total number of dets for each gt_id and tk_id.
200
+ gt_id_count[gt_ids_t] += 1
201
+ tk_id_count[0, tk_ids_t] += 1
202
+
203
+ # Calculate overall Jaccard alignment score between IDs
204
+ ga_score = num_matches / (gt_id_count + tk_id_count - num_matches)
205
+ return ga_score, gt_id_count, tk_id_count
206
+
207
+ def compute_matches(self, data, t, ga_score, gt_ids, tk_ids, alpha):
208
+ """Compute matches based on alignment score."""
209
+ sim = data["sim_scores"][t]
210
+ score_mat = ga_score[gt_ids[:, None], tk_ids[None, :]] * sim
211
+ # Hungarian algorithm to find best matches
212
+ match_rows, match_cols = linear_sum_assignment(-score_mat)
213
+
214
+ if not isinstance(alpha, list):
215
+ alpha = [alpha]
216
+ alpha_match_rows, alpha_match_cols = [], []
217
+ for a in alpha:
218
+ matched_mask = sim[match_rows, match_cols] >= a - EPS
219
+ alpha_match_rows.append(match_rows[matched_mask])
220
+ alpha_match_cols.append(match_cols[matched_mask])
221
+ return alpha_match_rows, alpha_match_cols
222
+
223
+ def compute_association_scores(self, res, matches_counts, gt_id_count, tk_id_count):
224
+ """Calculate association scores for each alpha.
225
+
226
+ First calculate scores per gt_id/tk_id combo,
227
+ and then average over the number of detections.
228
+ """
229
+ for a, _ in enumerate(self.array_labels):
230
+ matches_count = matches_counts[a]
231
+ ass_a = matches_count / np.maximum(
232
+ 1, gt_id_count + tk_id_count - matches_count
233
+ )
234
+ res["AssocA"][a] = np.sum(matches_count * ass_a) / np.maximum(
235
+ 1, res["Loc_TP"][a]
236
+ )
237
+ ass_re = matches_count / np.maximum(1, gt_id_count)
238
+ res["AssocRe"][a] = np.sum(matches_count * ass_re) / np.maximum(
239
+ 1, res["Loc_TP"][a]
240
+ )
241
+ ass_pr = matches_count / np.maximum(1, tk_id_count)
242
+ res["AssocPr"][a] = np.sum(matches_count * ass_pr) / np.maximum(
243
+ 1, res["Loc_TP"][a]
244
+ )
245
+
246
+ @_timing.time
247
+ def eval_sequence(self, data, cls, cls_id_name_mapping, cls_fp):
248
+ """Evaluate a single sequence across all thresholds."""
249
+ res = {}
250
+ class_info_dict = {}
251
+
252
+ for thr in data:
253
+ res[thr], cls_fp[thr], cls_info = self.eval_sequence_single_thr(
254
+ data[thr], cls, cls_id_name_mapping, cls_fp[thr], thr
255
+ )
256
+ class_info_dict[thr] = cls_info
257
+
258
+ return res, cls_fp, class_info_dict
259
+
260
+ def combine_sequences(self, all_res):
261
+ """Combines metrics across all sequences."""
262
+ data = {}
263
+ res = {}
264
+
265
+ if all_res:
266
+ thresholds = list(list(all_res.values())[0].keys())
267
+ else:
268
+ thresholds = [50]
269
+ for thr in thresholds:
270
+ data[thr] = {}
271
+ for seq_key in all_res:
272
+ data[thr][seq_key] = all_res[seq_key][thr]
273
+ for thr in thresholds:
274
+ res[thr] = self._combine_sequences_thr(data[thr])
275
+
276
+ return res
277
+
278
+ def _combine_sequences_thr(self, all_res):
279
+ """Combines sequences over each threshold."""
280
+ res = {}
281
+ for field in self.integer_array_fields:
282
+ res[field] = self._combine_sum(all_res, field)
283
+ for field in ["AssocRe", "AssocPr", "AssocA"]:
284
+ res[field] = self._combine_weighted_av(
285
+ all_res, field, res, weight_field="Loc_TP"
286
+ )
287
+ res = self._compute_final_fields(res)
288
+ return res
289
+
290
+ def combine_classes_class_averaged(self, all_res, ignore_empty=False):
291
+ """Combines metrics across all classes by averaging over classes.
292
+
293
+ If 'ignore_empty' is True, then it only sums over classes
294
+ with at least one gt or predicted detection.
295
+ """
296
+ data = {}
297
+ res = {}
298
+ if all_res:
299
+ thresholds = list(list(all_res.values())[0].keys())
300
+ else:
301
+ thresholds = [50]
302
+ for thr in thresholds:
303
+ data[thr] = {}
304
+ for cls_key in all_res:
305
+ data[thr][cls_key] = all_res[cls_key][thr]
306
+ for thr in data:
307
+ res[thr] = self._combine_classes_class_averaged_thr(
308
+ data[thr], ignore_empty=ignore_empty
309
+ )
310
+ return res
311
+
312
+ def _combine_classes_class_averaged_thr(self, all_res, ignore_empty=False):
313
+ """Combines classes over each threshold."""
314
+ res = {}
315
+
316
+ def check_empty(val):
317
+ """Returns True if empty."""
318
+ return not (val["Loc_TP"] + val["Loc_FN"] + val["Loc_FP"] > 0 + EPS).any()
319
+
320
+ for field in self.integer_array_fields:
321
+ if ignore_empty:
322
+ res_field = {k: v for k, v in all_res.items() if not check_empty(v)}
323
+ else:
324
+ res_field = {k: v for k, v in all_res.items()}
325
+ res[field] = self._combine_sum(res_field, field)
326
+
327
+ for field in self.float_array_fields:
328
+ if ignore_empty:
329
+ res_field = [v[field] for v in all_res.values() if not check_empty(v)]
330
+ else:
331
+ res_field = [v[field] for v in all_res.values()]
332
+ res[field] = np.mean(res_field, axis=0)
333
+ return res
334
+
335
+ def combine_classes_det_averaged(self, all_res):
336
+ """Combines metrics across all classes by averaging over detections."""
337
+ data = {}
338
+ res = {}
339
+ if all_res:
340
+ thresholds = list(list(all_res.values())[0].keys())
341
+ else:
342
+ thresholds = [50]
343
+ for thr in thresholds:
344
+ data[thr] = {}
345
+ for cls_key in all_res:
346
+ data[thr][cls_key] = all_res[cls_key][thr]
347
+ for thr in data:
348
+ res[thr] = self._combine_classes_det_averaged_thr(data[thr])
349
+ return res
350
+
351
+ def _combine_classes_det_averaged_thr(self, all_res):
352
+ """Combines detections over each threshold."""
353
+ res = {}
354
+ for field in self.integer_array_fields:
355
+ res[field] = self._combine_sum(all_res, field)
356
+ for field in ["AssocRe", "AssocPr", "AssocA"]:
357
+ res[field] = self._combine_weighted_av(
358
+ all_res, field, res, weight_field="Loc_TP"
359
+ )
360
+ res = self._compute_final_fields(res)
361
+ return res
362
+
363
+ @staticmethod
364
+ def _compute_final_fields(res):
365
+ """Calculate final metric values.
366
+
367
+ This function is used both for both per-sequence calculation,
368
+ and in combining values across sequences.
369
+ """
370
+ # LocA
371
+ res["LocRe"] = res["Loc_TP"] / np.maximum(1, res["Loc_TP"] + res["Loc_FN"])
372
+ res["LocPr"] = res["Loc_TP"] / np.maximum(1, res["Loc_TP"] + res["Loc_FP"])
373
+ res["LocA"] = res["Loc_TP"] / np.maximum(
374
+ 1, res["Loc_TP"] + res["Loc_FN"] + res["Loc_FP"]
375
+ )
376
+
377
+ # ClsA
378
+ res["ClsRe"] = res["Cls_TP"] / np.maximum(1, res["Cls_TP"] + res["Cls_FN"])
379
+ res["ClsPr"] = res["Cls_TP"] / np.maximum(1, res["Cls_TP"] + res["Cls_FP"])
380
+ res["ClsA"] = res["Cls_TP"] / np.maximum(
381
+ 1, res["Cls_TP"] + res["Cls_FN"] + res["Cls_FP"]
382
+ )
383
+
384
+ res["ClsRe"] = np.mean(res["ClsRe"])
385
+ res["ClsPr"] = np.mean(res["ClsPr"])
386
+ res["ClsA"] = np.mean(res["ClsA"])
387
+
388
+ res["TETA"] = (res["LocA"] + res["AssocA"] + res["ClsA"]) / 3
389
+
390
+ return res
391
+
392
+ def print_summary_table(self, thr_res, thr, tracker, cls):
393
+ """Prints summary table of results."""
394
+ print("")
395
+ metric_name = self.get_name()
396
+ self._row_print(
397
+ [f"{metric_name}{str(thr)}: {tracker}-{cls}"] + self.summary_fields
398
+ )
399
+ self._row_print(["COMBINED"] + thr_res)
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/teta_eval_toolkit/utils.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ import csv
5
+ import os
6
+ from collections import OrderedDict
7
+
8
+
9
+ def validate_metrics_list(metrics_list):
10
+ """Get names of metric class and ensures they are unique, further checks that the fields within each metric class
11
+ do not have overlapping names.
12
+ """
13
+ metric_names = [metric.get_name() for metric in metrics_list]
14
+ # check metric names are unique
15
+ if len(metric_names) != len(set(metric_names)):
16
+ raise TrackEvalException(
17
+ "Code being run with multiple metrics of the same name"
18
+ )
19
+ fields = []
20
+ for m in metrics_list:
21
+ fields += m.fields
22
+ # check metric fields are unique
23
+ if len(fields) != len(set(fields)):
24
+ raise TrackEvalException(
25
+ "Code being run with multiple metrics with fields of the same name"
26
+ )
27
+ return metric_names
28
+
29
+
30
+ def get_track_id_str(ann):
31
+ """Get name of track ID in annotation."""
32
+ if "track_id" in ann:
33
+ tk_str = "track_id"
34
+ elif "instance_id" in ann:
35
+ tk_str = "instance_id"
36
+ elif "scalabel_id" in ann:
37
+ tk_str = "scalabel_id"
38
+ else:
39
+ assert False, "No track/instance ID."
40
+ return tk_str
41
+
42
+
43
+ class TrackEvalException(Exception):
44
+ """Custom exception for catching expected errors."""
45
+
46
+ ...
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/eval/ytvis_coco_wrapper.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+ # (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
3
+
4
+ import copy
5
+ import json
6
+ import logging
7
+
8
+ import numpy as np
9
+ import pycocotools.mask as mask_util
10
+ from pycocotools.coco import COCO
11
+ from typing_extensions import override
12
+
13
+
14
+ class YTVIS(COCO):
15
+ """
16
+ Helper class for reading YT-VIS annotations
17
+ """
18
+
19
+ @override
20
+ def __init__(self, annotation_file: str = None, ignore_gt_cats: bool = True):
21
+ """
22
+ Args:
23
+ annotation_file: Path to the annotation file
24
+ ignore_gt_cats: If True, we ignore the ground truth categories and replace them with a dummy "object" category. This is useful for Phrase AP evaluation.
25
+ """
26
+ self.ignore_gt_cats = ignore_gt_cats
27
+ super().__init__(annotation_file=annotation_file)
28
+
29
+ @override
30
+ def createIndex(self):
31
+ # We rename some keys to match the COCO format before creating the index.
32
+ if "annotations" in self.dataset:
33
+ for ann in self.dataset["annotations"]:
34
+ if "video_id" in ann:
35
+ ann["image_id"] = int(ann.pop("video_id"))
36
+ if self.ignore_gt_cats:
37
+ ann["category_id"] = -1
38
+ else:
39
+ ann["category_id"] = int(ann["category_id"])
40
+ if "bboxes" in ann:
41
+ # note that in some datasets we load under this YTVIS class,
42
+ # some "bboxes" could be None for when the GT object is invisible,
43
+ # so we replace them with [0, 0, 0, 0]
44
+ ann["bboxes"] = [
45
+ bbox if bbox is not None else [0, 0, 0, 0]
46
+ for bbox in ann["bboxes"]
47
+ ]
48
+ if "areas" in ann:
49
+ # similar to "bboxes", some areas could be None for when the GT
50
+ # object is invisible, so we replace them with 0
51
+ areas = [a if a is not None else 0 for a in ann["areas"]]
52
+ # Compute average area of tracklet
53
+ ann["area"] = np.mean(areas)
54
+ if "videos" in self.dataset:
55
+ for vid in self.dataset["videos"]:
56
+ vid["id"] = int(vid["id"])
57
+ self.dataset["images"] = self.dataset.pop("videos")
58
+
59
+ if self.ignore_gt_cats:
60
+ self.dataset["categories"] = [
61
+ {"supercategory": "object", "id": -1, "name": "object"}
62
+ ]
63
+ else:
64
+ for cat in self.dataset["categories"]:
65
+ cat["id"] = int(cat["id"])
66
+ super().createIndex()
67
+
68
+ @override
69
+ def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None):
70
+ if len(areaRng) > 0:
71
+ logging.warning(
72
+ "Note that we filter out objects based on their *average* area across the video, not per frame area"
73
+ )
74
+
75
+ return super().getAnnIds(imgIds=imgIds, catIds=catIds, iscrowd=iscrowd)
76
+
77
+ @override
78
+ def showAnns(self, anns, draw_bbox=False):
79
+ raise NotImplementedError("Showing annotations is not supported")
80
+
81
+ @override
82
+ def loadRes(self, resFile):
83
+ # Adapted from COCO.loadRes to support tracklets/masklets
84
+ res = YTVIS(ignore_gt_cats=self.ignore_gt_cats)
85
+ res.dataset["images"] = [img for img in self.dataset["images"]]
86
+
87
+ if type(resFile) == str:
88
+ with open(resFile) as f:
89
+ anns = json.load(f)
90
+ elif type(resFile) == np.ndarray:
91
+ anns = self.loadNumpyAnnotations(resFile)
92
+ else:
93
+ anns = resFile
94
+ assert type(anns) == list, "results is not an array of objects"
95
+ annsImgIds = [ann["image_id"] for ann in anns]
96
+ assert set(annsImgIds) == (
97
+ set(annsImgIds) & set(self.getImgIds())
98
+ ), "Results do not correspond to current coco set"
99
+ if "bboxes" in anns[0] and not anns[0]["bboxes"] == []:
100
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
101
+ for id, ann in enumerate(anns):
102
+ bbs = [(bb if bb is not None else [0, 0, 0, 0]) for bb in ann["bboxes"]]
103
+ xxyy = [[bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]] for bb in bbs]
104
+ if not "segmentations" in ann:
105
+ ann["segmentations"] = [
106
+ [[x1, y1, x1, y2, x2, y2, x2, y1]] for (x1, x2, y1, y2) in xxyy
107
+ ]
108
+ ann["areas"] = [bb[2] * bb[3] for bb in bbs]
109
+ # NOTE: We also compute average area of a tracklet across video, allowing us to compute area based mAP.
110
+ ann["area"] = np.mean(ann["areas"])
111
+ ann["id"] = id + 1
112
+ ann["iscrowd"] = 0
113
+ elif "segmentations" in anns[0]:
114
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
115
+ for id, ann in enumerate(anns):
116
+ ann["bboxes"] = [
117
+ mask_util.toBbox(segm) for segm in ann["segmentations"]
118
+ ]
119
+ if "areas" not in ann:
120
+ ann["areas"] = [
121
+ mask_util.area(segm) for segm in ann["segmentations"]
122
+ ]
123
+ # NOTE: We also compute average area of a tracklet across video, allowing us to compute area based mAP.
124
+ ann["area"] = np.mean(ann["areas"])
125
+ ann["id"] = id + 1
126
+ ann["iscrowd"] = 0
127
+
128
+ res.dataset["annotations"] = anns
129
+ res.createIndex()
130
+ return res
131
+
132
+ @override
133
+ def download(self, tarDir=None, imgIds=[]):
134
+ raise NotImplementedError
135
+
136
+ @override
137
+ def loadNumpyAnnotations(self, data):
138
+ raise NotImplementedError("We don't support numpy annotations for now")
139
+
140
+ @override
141
+ def annToRLE(self, ann):
142
+ raise NotImplementedError("We expect masks to be already in RLE format")
143
+
144
+ @override
145
+ def annToMask(self, ann):
146
+ raise NotImplementedError("We expect masks to be already in RLE format")