目标检测基础之IOU计算

目标检测基础之IOU计算

概念理解——什么是IOU

IOU 交并比(Intersection over Union),从字面上很容易理解:计算交集在并集的比重。从网上截张图看看
在这里插入图片描述
I O U = A ∩ B A ∪ B IOU = \frac{A \cap B}{A \cup B} IOU=ABAB

demo

在这里插入图片描述

import cv2
import matplotlib.pyplot as plt
 
def draw_box(img, box,color):
    x,y,x1,y1 = box
    cv2.rectangle(img, (x,y), (x1, y1), color, 2)# (x,y)左上顶点,(x1,y1)右下顶点
    return img
 
def iou(bbox1, bbox2):
    """
    计算两个矩形的交并比
    """
    bbox1 = [float(x) for x in bbox1]
    bbox2 = [float(x) for x in bbox2]
    (x0_1, y0_1, x1_1, y1_1) = bbox1
    (x0_2, y0_2, x1_2, y1_2) = bbox2
    # get the overlap rectangle
    overlap_x0 = max(x0_1, x0_2)
    overlap_y0 = max(y0_1, y0_2)
    overlap_x1 = min(x1_1, x1_2)
    overlap_y1 = min(y1_1, y1_2)
    # check if there is an overlap
    if overlap_x1 - overlap_x0 <= 0 or overlap_y1 - overlap_y0 <= 0:
        return 0
    # if yes, calculate the ratio of the overlap to each ROI size and the unified size
    size_1 = (x1_1 - x0_1) * (y1_1 - y0_1)
    size_2 = (x1_2 - x0_2) * (y1_2 - y0_2)
    size_intersection = (overlap_x1 - overlap_x0) * (overlap_y1 - overlap_y0)
    size_union = size_1 + size_2 - size_intersection
    return size_intersection / (size_union+1e-6)
 
if __name__ == "__main__":
    img_path = "test.png"
    img = cv2.imread(img_path)
    img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    plt.imshow(img)
    plt.show()
 
    person_box_1 = [375, 169, 785, 586]
    person_box_2 = [320, 269, 833, 460]
 
    img = draw_box(img, person_box_1,(0,0,255))
    img = draw_box(img, person_box_2,(0,255,0))
 
    iou_result = iou(person_box_1, person_box_2)
    print(f"The result of IOU is :{iou_result}")
    cv2.imwrite("result.jpg", img)
    plt.imshow(img)
    plt.title(f"IOU:{iou_result}")
    plt.show()

后记

最近在研究segment anything,后面会不定期更新与目标检测和图像分割的相关东西!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值