关于python:使用numpy计算两个框的iou

5次阅读

共计 994 个字符,预计需要花费 3 分钟才能阅读完成。

需要简略,记录一下。

程序

import numpy as np
import cv2

def iou(bbox1, bbox2):
    xmin1, ymin1, xmax1, ymax1 = bbox1
    xmin2, ymin2, xmax2, ymax2 = bbox2
  
    # 获取矩形框交加对应的顶点坐标 (intersection)
    xx1 = np.max([xmin1, xmin2])
    yy1 = np.max([ymin1, ymin2])
    xx2 = np.min([xmax1, xmax2])
    yy2 = np.min([ymax1, ymax2])
    # 计算交加面积 
    inter_area = (np.max([0, xx2 - xx1])) * (np.max([0, yy2 - yy1]))


    # 计算两个矩形框面积
    area1 = (xmax1 - xmin1) * (ymax1 - ymin1) 
    area2 = (xmax2 - xmin2) * (ymax2 - ymin2)


    # 计算交并比(交加 / 并集)iou = inter_area / (area1 + area2 - inter_area)  # 留神:这里 inter_area 不能乘以 2,乘以 2 就相当于把交加局部挖空了
    return iou

def main():
    img = np.zeros((600,600), dtype=np.uint8)+255   # 创立一个全白画板 (灰度图)
    img = np.stack((img,)*3, axis=-1)               # 将灰度图转化为三通道图。目标是能在画板上画出黑白的图案。# 初始化两个框
    bbox1 = [200, 200, 400, 400]    # xmin, ymin, xmax, ymax
    bbox2 = [275, 300, 325, 550]    # xmin, ymin, xmax, ymax

    
    # 在画板上画出这两个黑白框
    cv2.rectangle(img, (bbox1[0:2]), (bbox1[2:4]), (255,69,0), -1)
    cv2.rectangle(img, (bbox2[0:2]), (bbox2[2:4]), (218,112,214), -1)

    # 计算这两个框的 iou
    rst = iou(bbox1, bbox2)

    cv2.putText(img, 'iou: %.6f' % rst, (10,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
    cv2.imwrite('res.png',img)
  

if __name__ == "__main__":
    main()

后果


正文完
 0