【tensorflow】MTCNN网络基本函数IOU

求取IOU:

import tensorflow as tf
import numpy as np
import cv2

def IoU(box, boxes):
    """Compute IoU between detect box and gt boxes
    Parameters:
    ----------
    box: numpy array , shape (5, ): x1, y1, x2, y2, score
        predicted boxes 
    boxes: numpy array, shape (n, 4): x1, y1, x2, y2
        input ground truth boxes
    Returns:
    -------
    ovr: numpy.array, shape (n, )
        IoU
    """
    # 函数的传入参数为box(随机裁剪后的框)和boxes(实际人脸框)
    box_area = (box[2] - box[0] + 1) * (box[3] - box[1] + 1)
    area = (boxes[:, 2] - boxes[:, 0] + 1) * (boxes[:, 3] - boxes[:, 1] + 1)
    # 同上,得出的是实际的人脸框的面积,但是这里要注意一点,因为一张图片的人脸是一个或者多个,所以说实际的boxes是个n行4列的数组,
    # 这样就把n个人脸对应的各自的面积存进了area

    #左上角点去较大的点,右下角去较小的点
    xx1 = np.maximum(box[0], boxes[:, 0])  # 将随机裁剪框的x1和各个人脸的x1比较,得到较大的xx1
    yy1 = np.maximum(box[1], boxes[:, 1])  # 将随机裁剪框的y1和各个人脸的y1比较,得到较大的yy1
    xx2 = np.minimum(box[2], boxes[:, 2])  # 将随机裁剪框的x2和各个人脸的x2比较,得到较小的xx2
    yy2 = np.minimum(box[3], boxes[:, 3])  # 将随机裁剪框的y2和各个人脸的y2比较,得到较小的yy2
    # 这样做的目的是得出两个图片交叉重叠区域的矩形的左上角和右下角坐标

    # compute the width and height of the bounding box
    w = np.maximum(0, xx2 - xx1 + 1)
    h = np.maximum(0, yy2 - yy1 + 1)
    # 获得0和(xx2-xx1)的最大值,因为当两个裁剪框没有丝毫重叠或者是只是一条高部分重合时,xx2-xx1<=0,有重叠时xx2-xx1>0,这个值就是重叠矩形的高,下面求宽也是一样的原理
    inter = w * h  # 求得重叠区域的面积
    ovr = inter / (box_area + area - inter)  # 重叠区域的面积除以真实人脸框的面积与随机裁剪区域面积的和减去重叠区域的面积就是重合率
    return ovr  # 返回重合率

box = np.array([30,45,100,110])   # x1(横坐标),y1(纵坐标),x2,y2
boxes = np.array([[56,78,210,178]])  # x1,y1,x2,y2
IoU(box, boxes)

img = cv2.imread("IOU.jpg",1)
img = cv2.resize(img,(300,250))
cv2.rectangle(img,(box[0],box[1]),(box[2],box[3]),(0,0,255), 2)
cv2.rectangle(img,(boxes[:,0],boxes[:,1]),(boxes[:,2],boxes[:,3]),(0,255,0), 2)
cv2.putText(img,"box",(box[0],box[1]),cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0,0,255), 2)     # 图像,文字内容, 坐标 ,字体,大小,颜色,字体厚度
cv2.putText(img,"box",(boxes[:,2],boxes[:,3]),cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0,255,0), 2)
cv2.imshow("img",img)
print("IoU:%s"%IoU(box, boxes))
cv2.waitKey()

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zhouzongzong/article/details/94644614