python实现iou计算
两个boxes之间的iou计算:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import numpy as np def iou(box1, box2): x1, y1, x2, y2 = box1 w1, h1, w2, h2 = box2 left_max = max (x1, w1) right_min = min (x2, w2) top_max = max (y1, h1) bot_min = min (y2, h2) if left_max > = right_min or top_max > = bot_min: return 0 else : intersection = (right_min - left_max) * (bot_min - top_max) union = (x2 - x1) * (y2 - y1) + (w2 - w1) * (h2 - h1) - intersection return intersection / union b1 = np.array([ 0 , 0 , 200 , 200 ]) b2 = np.array([ 100 , 100 , 500 , 500 ]) out = iou(b1, b2) # out = 0.0526 |
两组boxes的两两box之间的iou计算,下面用的pytorch的张量实现(源码来自torchvision):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import torch def box_iou(boxes1, boxes2): ''' boxes1和boxes2的shape都是: (n_box, 4). 4是指(x1, y1, x2, y2) coordinates. ''' area1 = box_area(boxes1) area2 = box_area(boxes2) lt = torch. max (boxes1[:, None , : 2 ], boxes2[:, : 2 ]) # [N,M,2] 这里使用了广播机制 rb = torch. min (boxes1[:, None , 2 :], boxes2[:, 2 :]) # [N,M,2] wh = (rb - lt).clamp( min = 0 ) # [N,M,2] inter = wh[:, :, 0 ] * wh[:, :, 1 ] # [N,M] union = area1[:, None ] + area2 - inter iou = inter / union return iou, union def box_area(boxes): """ Computes the area of a set of bounding boxes, which are specified by their (x1, y1, x2, y2) coordinates. """ return (boxes[:, 2 ] - boxes[:, 0 ]) * (boxes[:, 3 ] - boxes[:, 1 ]) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
2022-07-15 xmind快捷键
2022-07-15 转:python中 os._exit() 和 sys.exit(), exit(0)和exit(1) 的用法和区别
2021-07-15 long-tail datasets