import numpy as np
from pycocotools.cocoeval import COCOeval# 自定义COCOeval类,继承自COCOeval
class CustomCOCOeval(COCOeval):# 重写computeIoU方法def computeIoU(self, imgId, catId):p = self.paramsif p.useCats:gt = self._gts[imgId, catId]dt = self._dts[imgId, catId]else:gt = [g for cId in p.catIds for g in self._gts[imgId, cId]]dt = [d for cId in p.catIds for d in self._dts[imgId, cId]]if len(gt) == 0 and len(dt) == 0:return []ious = np.zeros((len(dt), len(gt)))for j, gt_obj in enumerate(gt):gx, gy, gwidth, gheight = gt_obj['bbox']gx2, gy2 = gx + gwidth, gy + gheightgt_area = gwidth * gheightfor i, dt_obj in enumerate(dt):dx, dy, dwidth, dheight = dt_obj['bbox']dx2, dy2 = dx + dwidth, dy + dheightdt_area = dwidth * dheightinter_w = min(dx2, gx2) - max(dx, gx)inter_h = min(dy2, gy2) - max(dy, gy)if inter_w <= 0 or inter_h <= 0:continueinter_area = inter_w * inter_hunion_area = dt_area + gt_area - inter_areaious[i, j] = inter_area / union_areareturn ious# 使用自定义的COCOeval进行评估
def evaluate_model(coco_gt, coco_dt):coco_eval = CustomCOCOeval(coco_gt, coco_dt, 'keypoints')coco_eval.evaluate()coco_eval.accumulate()coco_eval.summarize()return coco_eval.stats# 示例:加载你的COCO格式的ground truth和detection结果
# coco_gt = COCO("path/to/ground_truth.json")
# coco_dt = coco_gt.loadRes("path/to/detections.json")# 调用评估函数
# stats = evaluate_model(coco_gt, coco_dt)
# print(stats)