使用 Python 实现计算交并比(IoU)的代码示例:

两个矩形框的交集/并集

 IOU=(A)/(A+B+C)

1. 这个代码可以计算一个框与其他几个框的iou

import torch
from torchvision import transforms
t=transforms.Compose([
    transforms.ToTensor()
])
#写iou,这个要考
def bb_box(box,boxes):
    box_areas=(box[2]-box[0])*(box[3]-box[1])
    boxes_areas=(boxes[:,2]-boxes[:,0])*(boxes[:,3]-boxes[:,1])
    l_x=torch.maximum(box[0],boxes[:,0])
    l_y=torch.maximum(box[1],boxes[:,1])
    r_x=torch.minimum(box[2],boxes[:,2])
    r_y=torch.minimum(box[3],boxes[:,3])
    h=torch.maximum(torch.tensor(0),r_y-l_y)
    w=torch.maximum(torch.tensor(0),r_x-l_x)
    inter_area=w*h
    iou_val=inter_area/(box_areas+boxes_areas-inter_area)
    return iou_val
if __name__ == '__main__':
    y=torch.tensor([2,3,6,10])
    x = torch.tensor([
        [4,5,8,12],
        [5,6,9,13],
        [4,5,8,15],
    ])
    bb_box(y,x)

2. 计算两个矩形的iou

def calculate_iou(box1, box2):
    """
    计算两个边界框的 IoU.

    参数:
    box1 (tuple): 第一个边界框的坐标 (x1, y1, x2, y2)
    box2 (tuple): 第二个边界框的坐标 (x1, y1, x2, y2)

    返回:
    iou (float): 交并比
    """
    x1_min, y1_min, x1_max, y1_max = box1
    x2_min, y2_min, x2_max, y2_max = box2

    # 计算交集部分的坐标
    intersection_x_min = max(x1_min, x2_min)
    intersection_y_min = max(y1_min, y2_min)
    intersection_x_max = min(x1_max, x2_max)
    intersection_y_max = min(y1_max, y2_max)

    # 计算交集的面积
    intersection_area = max(0, intersection_x_max - intersection_x_min) * max(0, intersection_y_max - intersection_y_min)

    # 计算两个边界框的面积
    box1_area = (x1_max - x1_min) * (y1_max - y1_min)
    box2_area = (x2_max - x2_min) * (y2_max - y2_min)

    # 计算并集的面积
    union_area = box1_area + box2_area - intersection_area

    # 计算 IoU
    iou = intersection_area / union_area if union_area > 0 else 0
    return iou

# 示例用法
box1 = (100, 100, 200, 200)
box2 = (120, 120, 220, 220)
iou = calculate_iou(box1, box2)
print("IoU:", iou)

 

3. 交并比(IoU,Intersection over Union)在计算机视觉和图像处理领域中有多种重要用途:

  1. 目标检测:用于评估检测框与真实框的重合程度,从而判断目标检测算法的准确性。较高的 IoU 值表示检测结果更接近真实情况。
    • 例如,在自动驾驶中,准确检测车辆、行人等目标对于安全至关重要,通过计算检测框和真实框的 IoU 来衡量检测效果。
  2. 图像分割:评估分割结果与真实标注的匹配程度。
    • 比如在医学图像分割中,判断肿瘤区域的分割是否准确。
  3. 跟踪算法评估:衡量跟踪框在不同帧之间与目标真实位置的匹配情况。
    • 例如在监控视频中的人物跟踪,IoU 可以反映跟踪的稳定性和准确性。
  4. 模型选择和比较:在训练不同的模型或使用不同的参数时,通过计算 IoU 来比较它们的性能,选择最优的模型或参数设置。
  5. 数据标注质量评估:帮助检查标注数据的一致性和准确性,如果标注者之间的 IoU 值较低,可能表明标注存在较大的差异或错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西柚与蓝莓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值