代码资源:IoU_P_R.py


1. 基础概念

1.1 TP、TN、FP、FN

在这里插入图片描述

1.2 IoU

在这里插入图片描述

1.3 Precision(P)、Recall(R)、F1-score

  • 查准率 Precision(P): P = T P T P + F P P=\frac{TP}{TP+FP} P=TP+FPTP
  • 查全率 Recall(R): R = T P T P + F N R=\frac{TP}{TP+FN} R=TP+FNTP
  • F1-score: F 1 = 2 × P × R P + R \begin{aligned} &F_1=\frac{2\times P\times R}{{P+R}} \end{aligned} F1=P+R2×P×R

根据IoU可以计算Precision(P)、Recall(R),若真实框和预测框的IoU大于IoU阈值,则视为TP,否则视为FP,则FN=真实框数-TP

2. python代码

# Calculate precision and recall for object detection
def calculate_precision_recall(detected_boxes, true_boxes, iou_threshold):
    """
    Calculate precision and recall for object detection
    :param detected_boxes: list of detected bounding boxes in format [xmin, ymin, xmax, ymax]
    :param true_boxes: list of true bounding boxes in format [xmin, ymin, xmax, ymax]
    :param iou_threshold: intersection over union threshold for matching detected and true boxes
    :return: precision and recall
    """
    num_true_boxes = len(true_boxes)
    true_positives = 0
    for true_box in true_boxes:
        max_iou = 0
        for detected_box in detected_boxes:
            iou = calculate_iou(detected_box, true_box)
            if iou > max_iou:
                max_iou = iou
            if max_iou >= iou_threshold:
                true_positives += 1
                break
    false_positives = len(detected_boxes) - true_positives
    false_negatives = num_true_boxes - true_positives
    precision = true_positives / (true_positives + false_positives)
    recall = true_positives / (true_positives + false_negatives)
    print('TP: ', true_positives)
    print('FP: ', false_positives)
    print('FN: ', false_negatives)
    return precision, recall


def calculate_iou(box1, box2):
    """
    Calculate intersection over union (IoU) between two bounding boxes
    :param box1: bounding box in format [xmin, ymin, xmax, ymax]
    :param box2: bounding box in format [xmin, ymin, xmax, ymax]
    :return: IoU between box1 and box2
    """
    x1 = max(box1[0], box2[0])
    y1 = max(box1[1], box2[1])
    x2 = min(box1[2], box2[2])
    y2 = min(box1[3], box2[3])
    intersection = max(0, x2 - x1) * max(0, y2 - y1)
    area_box1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
    area_box2 = (box2[2] - box2[0]) * (box2[3] - box2[1])
    union = area_box1 + area_box2 - intersection
    iou = intersection / union
    return iou

3. 总结

  • 本文介绍了用python计算目标检测中的IoU以及TP、FP、FN、precision、recall等指标的方法和原理。
  • IoU是交并比,表示预测框和真实框之间的重叠程度,用交集面积除以并集面积得到。
  • TP、TN、FP、FN分别表示真正例、真负例、假正例和假负例,用于评估分类器的正确性。
  • Precision是预测为正例的样本中的准确率,Recall是预测正确的正例占所有正例的比例,二者需要综合考虑。
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐