当前位置:首页 » python教程 » 正文

如何通过python实现IOU计算代码实例

看: 757次  时间:2020-12-02  分类 : python教程

Intersection over Union(IOU)是一种测量在特定数据集中检测相应物体准确度的一个标准。IoU是一个简单的测量标准,只要是在输出中得出一个预测范围(bounding boxes)的任务都可以用IoU来进行测量。

IoU分数是对象类别分割问题的标准性能度量 [1] 。 给定一组图像,IoU测量给出了在该组图像中存在的对象的预测区域和地面实况区域之间的相似性

计算两个矩形的交并比,通常在检测任务里面可以作为一个检测指标。你的预测bbox和groundtruth之间的差异,就可以通过IOU来体现。

代码如下

#!/usr/bin/env python
# encoding: utf-8

import numpy as np

'''
函数说明:计算两个框的重叠面积
输入:
rec1 第一个框xmin ymin xmax ymax
rec2 第二个框xmin ymin xmax ymax
输出:
iouv 重叠比例 0 没有
'''
def compute_iou(rec1, rec2):

  # computing area of each rectangles
  S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) # H1*W1
  S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1]) # H2*W2

  # computing the sum_area
  sum_area = S_rec1 + S_rec2 #总面积

  # find the each edge of intersect rectangle
  left_line = max(rec1[0], rec2[0])
  right_line = min(rec1[2], rec2[2])
  top_line = max(rec1[1], rec2[1])
  bottom_line = min(rec1[3], rec2[3])

  # judge if there is an intersect
  if left_line >= right_line or top_line >= bottom_line:
    #print("没有重合区域")
    return 0
  else:
  #print("有重合区域")
    intersect = (right_line - left_line) * (bottom_line - top_line)
    iouv=(float(intersect) / float(sum_area - intersect))*1.0

    return iouv

'''
函数说明:获取两组匹配结果
输入:
rectA 车位
rectB 车辆
threod 重叠面积最小数值界限 默认0.6
输出:
CarUse 一维数组保存是否占用 1 占用 0 没有

'''
def TestCarUse(rectA,rectB,threod=0.6,debug=0):
  #threod=0.8#设定最小值
  ALength=len(rectA)
  BLength=len(rectB)

  #创建保存匹配结果的矩阵
  recIOU=np.zeros((ALength,BLength),dtype=float,order='C')
  #用于记录车位能够使否占用  
  CarUse=np.zeros((1,ALength),dtype=int,order='C')

  for i in range(0,ALength):
    for j in range(0,BLength):
      iou = compute_iou(rectA[i], rectB[j])
      recIOU[i][j]=format(iou,'.3f')
      if iou>=threod:    
        CarUse[0,i]=1 #有一个超过匹配认为车位i被占用
  if debug==1:
    print('----匹配矩阵----')
    print(recIOU)
    '''
    print('----车位占用情况----')
    for i in range(0,ALength):
    msg='车位'+str(i)+"-"+str(CarUse[0][i])
    print(msg)
    '''
  return CarUse



if __name__=='__main__':
  #A代表车位
  rectA1 = (30, 10, 70, 20)
  rectA2 = (70, 10, 80, 20)
  rectA =[rectA1,rectA2]
  #B代表检测车辆
  rectB1 = (20, 10, 35, 20)
  rectB2 = (30, 15, 70, 25)
  rectB3 = (70, 10, 80, 20)
  rectB =[rectB1,rectB2,rectB3]

  #获取车位占用情况 rectA车位 rectB车辆 0.6占面积最小比
  CarUse=TestCarUse(rectA,rectB,0.6,1)

  print('----车位占用情况----')
  for i in range(0,len(CarUse)+1):
  msg='车位'+str(i)+"-"+str(CarUse[0][i])
    print(msg)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。

标签:numpy  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!