当前位置:   article > 正文

目标检测基础——IOU计算

iou计算

1. 什么是IOU?

      IoU 的全称为交并比(Intersection over Union),通过这个名称我们大概可以猜到 IoU 的计算方法。IoU 计算的是 “预测的边框” 和 “真实的边框” 的交集和并集的比值。该值越大,说明”预测框“越接近”真实框“。

     iou定义如下:

Caption

2. IOU计算

      直接上代码:

  1. # --*-- coding:utf-8 -*-
  2. import cv2
  3. def draw_box(img, box):
  4. x,y,x1,y1 = box
  5. cv2.rectangle(img, (x,y), (x1, y1), (0,0,255), 2)
  6. return img
  7. def iou(bbox1, bbox2):
  8. """
  9. Calculates the intersection-over-union of two bounding boxes.
  10. """
  11. bbox1 = [float(x) for x in bbox1]
  12. bbox2 = [float(x) for x in bbox2]
  13. (x0_1, y0_1, x1_1, y1_1) = bbox1
  14. (x0_2, y0_2, x1_2, y1_2) = bbox2
  15. # get the overlap rectangle
  16. overlap_x0 = max(x0_1, x0_2)
  17. overlap_y0 = max(y0_1, y0_2)
  18. overlap_x1 = min(x1_1, x1_2)
  19. overlap_y1 = min(y1_1, y1_2)
  20. # check if there is an overlap
  21. if overlap_x1 - overlap_x0 <= 0 or overlap_y1 - overlap_y0 <= 0:
  22. return 0
  23. # if yes, calculate the ratio of the overlap to each ROI size and the unified size
  24. size_1 = (x1_1 - x0_1) * (y1_1 - y0_1)
  25. size_2 = (x1_2 - x0_2) * (y1_2 - y0_2)
  26. size_intersection = (overlap_x1 - overlap_x0) * (overlap_y1 - overlap_y0)
  27. size_union = size_1 + size_2 - size_intersection
  28. return size_intersection / size_union
  29. if __name__ == "__main__":
  30. img_path = "test.jpg"
  31. img = cv2.imread(img_path)
  32. person_box = [210, 33, 328, 191]
  33. horse_box = [65, 73, 403, 310]
  34. img = draw_box(img, person_box)
  35. img = draw_box(img, horse_box)
  36. iou_result = iou(person_box, horse_box)
  37. print("The IOU of person and horse is:%s" % iou_result)
  38. cv2.imwrite("result.jpg", img)
python iou.py

    输出:The IOU of person and horse is:0.16414778487727819

    test.jpg和result.jpg如下图:

Caption
Caption

       人和马的IOU为:0.164

       IOU为目标检测的基础,从这里开始吧!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/114149?site
推荐阅读