手写计算iou代码

思路

假设有两个框,设第一个框的两个关键点坐标:(x1,y1)(X1,Y1),第二个框的两个关键点坐标:(x2,y2)(X2,Y2)。以大小写来区分左上角坐标和右下角坐标。首先,要知道两个框如果有交集,一定满足下面这个公式:
max(x1,x2)<=min(X1,X2) && max(y1,y2)<=min(Y1,Y2)!!!!

附上代码:

import numpy as np
# boxA和boxB为两个识别框,box[:4]分别代表框的x1、y1、x2、y2值
def ComputeIOU(boxA, boxB):
    ## 计算相交框的坐标
    x1 = np.max([boxA[0], boxB[0]])
    
### 手写 NMS(非极大值抑制)算法的代码实现 以下是基于 Python手写 NMS 实现,适用于目标检测中的边界框过滤场景: ```python def non_max_suppression(boxes, scores, threshold): """ 非极大值抑制 (Non-Maximum Suppression) 算法的手动实现。 参数: boxes: list of lists 或 numpy array, 形状为 [n_boxes, 4], 表示 n 个矩形框, 每个框由左上角坐标(x_min, y_min) 和右下角坐标(x_max, y_max) 定义。 scores: list 或 numpy array, 形状为 [n_boxes, ], 表示每个矩形框对应的置信度得分。 threshold: float, IOU阈值,用于判断两个矩形框是否重叠过多。 返回: keep_indices: list, 经过NMS处理后保留下来的矩形框索引列表。 """ # 如果没有输入任何框,则返回空列表 if len(boxes) == 0 or len(scores) == 0: return [] # 将输入转换为numpy数组以便于计算 import numpy as np boxes = np.array(boxes).astype(float) scores = np.array(scores).astype(float) # 获取矩形框的数量 num_boxes = boxes.shape[0] # 初始化一个布尔掩码来标记哪些框被保留下来 suppressed = np.zeros(num_boxes, dtype=bool) # 对scores按照降序排列并获取其对应索引 order = np.argsort(scores)[::-1] # 存储最终保留下来的框的索引 keep_indices = [] while len(order) > 0: # 当前最高分的框索引 current_index = order[0] keep_indices.append(current_index) # 计算当前框与其他剩余框之间的IOU xx1 = np.maximum(boxes[current_index][0], boxes[order[1:], 0]) yy1 = np.maximum(boxes[current_index][1], boxes[order[1:], 1]) xx2 = np.minimum(boxes[current_index][2], boxes[order[1:], 2]) yy2 = np.minimum(boxes[current_index][3], boxes[order[1:], 3]) width = np.maximum(0.0, xx2 - xx1 + 1) height = np.maximum(0.0, yy2 - yy1 + 1) intersection_area = width * height area_current_box = (boxes[current_index][2] - boxes[current_index][0] + 1) * \ (boxes[current_index][3] - boxes[current_index][1] + 1) areas_other_boxes = (boxes[order[1:], 2] - boxes[order[1:], 0] + 1) * \ (boxes[order[1:], 3] - boxes[order[1:], 1] + 1) union_areas = area_current_box + areas_other_boxes - intersection_area iou = intersection_area / union_areas # 抑制那些与当前框IOU超过threshold的其他框 suppress_mask = iou >= threshold suppressed[order[1:]] |= suppress_mask # 更新未被抑制的框顺序 unsuppressed_indices = np.where(~suppressed[order])[0] order = order[unsuppressed_indices] return keep_indices ``` #### 关键点解释 - **输入参数**: `boxes` 是一组候选框,通常表示为目标检测模型预测出来的多个可能对象的位置;`scores` 则是这些框对应的置信度分数。`threshold` 是用来控制重叠程度的一个超参,只有当两框间的交并比(IOU)低于此阈值时才不会互相抑制[^2]。 - **核心逻辑**: 使用贪心策略依次选取具有最大置信度的框作为参考标准,并移除与其高度重合的所有其它候选项直到遍历结束为止[^1]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值