目标检测性能指标代码
时间: 2023-11-12 12:56:42 浏览: 42
目标检测的性能指标包括精度和速度两个方面。常用的精度指标有mAP(mean average precision)、PR曲线、ROC曲线等;常用的速度指标有FPS(frames per second,每秒处理帧数)、推理时间等。以下是使用Python和OpenCV计算mAP的示例代码:
```python
import numpy as np
def calculate_iou(box1, box2):
x1, y1, w1, h1 = box1
x2, y2, w2, h2 = box2
xi1 = max(x1, x2)
yi1 = max(y1, y2)
xi2 = min(x1 + w1, x2 + w2)
yi2 = min(y1 + h1, y2 + h2)
iw = max(xi2 - xi1, 0)
ih = max(yi2 - yi1, 0)
ua = (w1 * h1 + w2 * h2 - iw * ih)
iou = iw * ih / ua
return iou
def calculate_ap(gt_boxes, pred_boxes, iou_threshold=0.5):
tp = [0] * len(pred_boxes)
fp = [0] * len(pred_boxes)
gt_detected = [False] * len(gt_boxes)
pred_scores = [box[0] for box in pred_boxes]
order = np.argsort(pred_scores)[::-1]
for i in order:
_, pred_box, pred_class = pred_boxes[i]
max_iou = -float('inf')
max_idx = -1
for j, gt_box in enumerate(gt_boxes):
if pred_class != gt_box[0]:
continue
iou = calculate_iou(pred_box, gt_box[1:])
if iou > max_iou:
max_iou = iou
max_idx = j
if max_iou >= iou_threshold:
if not gt_detected[max_idx]:
tp[i] = 1
gt_detected[max_idx] = True
else:
fp[i] = 1
else:
fp[i] = 1
tp_acc = np.cumsum(tp)
fp_acc = np.cumsum(fp)
recall = tp_acc / len(gt_boxes)
precision = tp_acc / (tp_acc + fp_acc)
ap = 0
for t in np.arange(0, 1.1, 0.1):
if np.sum(recall >= t) == 0:
p = 0
else:
p = np.max(precision[recall >= t])
ap += p / 11
return ap
def calculate_map(gt_boxes_list, pred_boxes_list, iou_threshold=0.5):
aps = []
for c in range(len(gt_boxes_list)):
gt_boxes = gt_boxes_list[c]
pred_boxes = pred_boxes_list[c]
ap = calculate_ap(gt_boxes, pred_boxes, iou_threshold)
aps.append(ap)
map = sum(aps) / len(aps)
return map
```