IOU计算for循环实现及张量实现

参考博客
IOU计算for循环实现及张量实现_第1张图片

  • for循环
    IOU计算for循环实现及张量实现_第2张图片
import cv2
import numpy as np


def CountIOU(recA, recB):
    # 两个矩形的左上角坐标(取靠右下的)
    xA = max(recA[0], recB[0])
    yA = max(recA[1], recB[1])
    # 两个矩形的右下角坐标(去靠左上的)
    xB = min(recA[2], recA[2])
    yB = min(recA[3], recA[3])
    # 计算交集的面积(如果两个矩形没有交集则为0)
    interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
    # 计算预测框和真实框的面积
    recA_Area = (recA[2] - recA[0] + 1) * (recA[3] - recA[1] + 1)
    recB_Area = (recB[2] - recB[0] + 1) * (recB[3] - recB[1] + 1)

    # 计算IOU
    iou = interArea / float(recA_Area + recB_Area - interArea)
    return iou


img = np.zeros((512, 512, 3))
img.fill(255)

recA = [50, 50, 99, 99]
recB = [74, 74, 124, 124]

# (图片,长方形框左上角坐标, 长方形框右下角坐标, 字体颜色,字体粗细)
cv2.rectangle(img, (recA[0], recA[1]), (recA[2], recA[3]), (0, 255, 0), 1)
cv2.rectangle(img, (recB[0], recB[1]), (recB[2], recB[3]), (0, 0, 255), 1)

IOU = CountIOU(recA, recB)
# (图片,添加的文字,左上角坐标,字体,字体大小,颜色,字体粗细)
cv2.putText(img, "IOU = %.2f" % IOU, (130, 190), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 2)

cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
  • 向量
    IOU计算for循环实现及张量实现_第3张图片
import cv2
import numpy as np

anchors = np.array([[50, 50, 150, 150],
                    [250, 50, 350, 150]])
ground_truth = np.array([[100, 100, 200, 200],
                         [400, 50, 500, 150]])

# 左上角坐标
# np.maximum:逐元素比较并返回最大值
top_left = np.maximum(anchors[:, :2], ground_truth[:, :2])
# 右下角坐标
# np.minimum:逐元素比较并返回最大值
bottom_right = np.minimum(anchors[:, 2:], ground_truth[:, 2:])

print('top_left:\n', top_left)
print('bottom_right:\n', bottom_right)

# 重叠部分的面积
# np.prod()函数用来计算所有元素的乘积
# .all()判断是否有重叠部分,有就返回True(1),否则返回False(0)
area_overlap = np.prod(bottom_right - top_left, axis=1) * (top_left < bottom_right).all(axis=1)
print('area_overlap:\n', area_overlap)

# 候选框的面积
area_anchors = np.prod(anchors[:, 2:] - anchors[:, :2], axis=1)
print('area_anchors:\n', area_anchors)

# 真实框的面积
area_ground_truth = np.prod(ground_truth[:, 2:] - ground_truth[:, :2], axis=1)
print('area_ground_truth:\n', area_ground_truth)

# 计算IOU
ious = (area_overlap / (area_anchors + area_ground_truth - area_overlap))
print('ious:\n', ious)

img = np.zeros((512, 512, 3))
img.fill(255)

for index in anchors:
    cv2.rectangle(img, (index[0], index[1]), (index[2], index[3]), (0, 255, 0), 1)

cv2.rectangle(img, (ground_truth[0][0], ground_truth[0][1]), (ground_truth[0][2], ground_truth[0][3]), (0, 0, 255), 1)

cv2.putText(img, "ious = %.2f" % ious[0], (130, 190), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 2)
cv2.putText(img, "ious = %.2f" % ious[1], (300, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 2)

cv2.imshow('img', img)
cv2.waitKey()
cv2.destroyAllWindows()

你可能感兴趣的:(深度学习,目标检测,python,计算机视觉,opencv)