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设计】。

相关文章

Python单元测试unittest的具体使用示例

Python单元测试unittest的具体使用示例

Python中有一个自带的单元测试框架是unittest模块,用它来做单元测试,它里面封装好了一些校验返回的结果方法和一些用例执行前的初始化操作。 unittest是python的标准...

python中for循环输出列表索引与对应的值方法

python中for循环输出列表索引与对应的值方法

如下所示: list = [‘a','b','c'] 想用for循环输出list的元素以及对应的索引。 代码及结果如下: 以上这篇python中for循环输出列表索引与对应的值...

Python入门篇之正则表达式

 正则表达式有两种基本的操作,分别是匹配和替换。 匹配就是在一个文本字符串中搜索匹配一特殊表达式; 替换就是在一个字符串中查找并替换匹配一特殊表达式的字符串。   1...

python操作ie登陆土豆网的方法

本文实例讲述了python操作ie登陆土豆网的方法。分享给大家供大家参考。具体如下: 这里利用ie操作登陆土豆网,很简单,仅做一下记录,以备后用。 # -*- coding: utf...

Python文件读写常见用法总结

1. 读取文件 # !/usr/bin/env python # -*- coding:utf-8 -*- """ 文件读取三步骤: 1.打开文件 f=open(file...