python不使用for计算两组、多个矩形两两间的iou方式

yipeiwu_com6年前Python基础

解决问题: 不使用for计算两组、多个矩形两两间的iou

使用numpy广播的方法,在python程序中并不建议使用for语句,python中的for语句耗时较多,如果使用numpy广播的思想将会提速不少。

代码:

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的阈值,然后就可以将满足条件的索引取出。如:

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则如右图所示

以上这篇python不使用for计算两组、多个矩形两两间的iou方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3.x 生成3维随机数组实例

python3.x 生成3维随机数组实例

如下所示: import numpy as np a=np.random.randint(0,10,size=[3,3,3]) print(a) 以上这篇python...

Python实现定时备份mysql数据库并把备份数据库邮件发送

一、先来看备份mysql数据库的命令 mysqldump -u root --password=root --database abcDataBase > c:/abc_bac...

django之对FileField字段的upload_to的设定方法

用django开发,经常要处理用户上传的文件, 比如user模型里面如果又个人头像的字段 ImageField等等,而django在FielField字段(包括ImageField)的支...

Python3.4解释器用法简单示例

本文实例讲述了Python3.4解释器用法。分享给大家供大家参考,具体如下: Linux/Unix的系统上,Python解释器通常被安装在 /usr/local/bin/python3....

Python 包含汉字的文件读写之每行末尾加上特定字符

      最近,接手的项目里,提供的数据文件格式简直让人看不下去,使用pandas打不开,一直是io error.仔细查看,发现文件中...