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()
文章出处登录后可见!
已经登录?立即刷新