python 不使用for计算两组、多个矩形两两间的iou
2019-07-23 17:36
330 查看
解决问题: 不使用for计算两组、多个矩形两两间的iou
使用numpy广播的方法,在python程序中并不建议使用for语句,python中的for语句耗时较多,如果使用numpy广播的思想将会提速不少。
代码:
[code]def calc_iou(bbox1, bbox2): if not isinstance(bbox1, np.ndarray): bbox1 = np.array(bbox1) if not isinstance(bbox2, np.ndarray): bbox2 = np.array(bbox2) xmin1, ymin1, xmax1, ymax1, = np.split(bbox1, 4, axis=-1) xmin2, ymin2, xmax2, ymax2, = np.split(bbox2, 4, axis=-1) area1 = (xmax1 - xmin1) * (ymax1 - ymin1) area2 = (xmax2 - xmin2) * (ymax2 - ymin2) ymin = np.maximum(ymin1, np.squeeze(ymin2, axis=-1)) xmin = np.maximum(xmin1, np.squeeze(xmin2, axis=-1)) ymax = np.minimum(ymax1, np.squeeze(ymax2, axis=-1)) xmax = np.minimum(xmax1, np.squeeze(xmax2, axis=-1)) h = np.maximum(ymax - ymin, 0) w = np.maximum(xmax - xmin, 0) intersect = h * w union = area1 + np.squeeze(area2, axis=-1) - intersect return intersect / union
程序中输入为多个矩形[xmin, ymin, xmax,ymax]格式的数组或者list,输出为numpy格式,例:输入的shape为(3, 4)、(5,4)则输出为(3, 5)各个位置为boxes间相互的iou值。后面会卡一个iou的阈值,然后就可以将满足条件的索引取出。如:
[code]def delete_bbox(bbox1, bbox2, roi_bbox1, roi_bbox2, class1, class2, idx1, idx2, iou_value): idx = np.where(iou_value > 0.4) left_idx = idx[0] right_idx = idx[1] left = roi_bbox1[left_idx] right = roi_bbox2[right_idx] xmin1, ymin1, xmax1, ymax1, = np.split(left, 4, axis=-1) xmin2, ymin2, xmax2, ymax2, = np.split(right, 4, axis=-1) left_area = (xmax1 - xmin1) * (ymax1 - ymin1) right_area = (xmax2 - xmin2) * (ymax2 - ymin2) left_idx = left_idx[np.squeeze(left_area < right_area, axis=-1)]#小的被删 right_idx = right_idx[np.squeeze(left_area > right_area, axis=-1)] bbox1 = np.delete(bbox1, idx1[left_idx], 0) class1 = np.delete(class1, idx1[left_idx]) bbox2 = np.delete(bbox2, idx2[right_idx], 0) class2 = np.delete(class2, idx2[right_idx]) return bbox1, bbox2, class1, class2
IOU计算原理:
ymin = np.maximum(ymin1, np.squeeze(ymin2, axis=-1))
xmin = np.maximum(xmin1, np.squeeze(xmin2, axis=-1))
ymax = np.minimum(ymax1, np.squeeze(ymax2, axis=-1))
xmax = np.minimum(xmax1, np.squeeze(xmax2, axis=-1))
h = np.maximum(ymax - ymin, 0)
w = np.maximum(xmax - xmin, 0)
intersect = h * w
计算矩形间min的最大值,max的最小值,如果ymax-ymin值大于0则如左图所示,如果小于0则如右图所示
相关文章推荐
- MySQLdb for Python使用指南/Python的数据库操作
- [转]使用python调用计算所分词
- Python中怎样使用shape计算矩阵的行和列
- MySQLdb for Python使用指南/Python的数据库操作
- Python学习笔记之疑问 9:如何使用For语句
- 使用Ipython notebook 学习《Python for Data Analysis》 在win7下搭建注意事项
- 使用python的列表解析以及函数式计算来简化代码
- Python学习笔记十二:列表(4)--len 、in、For的使用
- C#--第2周实验--任务四--编写一个控制台应用--分别使用for,while,do-while循环语句计算 n!
- 转:Python 文本挖掘:使用gensim进行文本相似度计算
- Python 文本挖掘:使用gensim进行文本相似度计算
- python使用datetime模块计算各种时间间隔的方法
- Python使用matplotlib实现在坐标系中画一个矩形的方法
- windows下如何快速优雅的使用python的科学计算库?
- 零基础学python-12.6 使用for和zip来并行使用多个序列
- MySQLdb for Python使用指南/Python的数据库操作
- Python:通过计算阶乘来学习lambda和reduce这两个函数的使用
- 第二周 任务四 分别使用for,while,do-while循环语句计算 n!
- python中的for...else的使用方法
- 使用三角形,矩形细分连通域轮廓多边形计算连通域重心