目标检测基础之IOU计算
- 概念理解——什么是IOU
- demo
- 后记
概念理解——什么是IOU
IOU 交并比(Intersection over Union),从字面上很容易理解:计算交集在并集的比重。从网上截张图看看
I
O
U
=
A
∩
B
A
∪
B
IOU = \frac{A \cap B}{A \cup B}
IOU=A∪BA∩B
demo
import cv2
import matplotlib.pyplot as plt
def draw_box(img, box,color):
x,y,x1,y1 = box
cv2.rectangle(img, (x,y), (x1, y1), color, 2)# (x,y)左上顶点,(x1,y1)右下顶点
return img
def iou(bbox1, bbox2):
"""
计算两个矩形的交并比
"""
bbox1 = [float(x) for x in bbox1]
bbox2 = [float(x) for x in bbox2]
(x0_1, y0_1, x1_1, y1_1) = bbox1
(x0_2, y0_2, x1_2, y1_2) = bbox2
# get the overlap rectangle
overlap_x0 = max(x0_1, x0_2)
overlap_y0 = max(y0_1, y0_2)
overlap_x1 = min(x1_1, x1_2)
overlap_y1 = min(y1_1, y1_2)
# check if there is an overlap
if overlap_x1 - overlap_x0 <= 0 or overlap_y1 - overlap_y0 <= 0:
return 0
# if yes, calculate the ratio of the overlap to each ROI size and the unified size
size_1 = (x1_1 - x0_1) * (y1_1 - y0_1)
size_2 = (x1_2 - x0_2) * (y1_2 - y0_2)
size_intersection = (overlap_x1 - overlap_x0) * (overlap_y1 - overlap_y0)
size_union = size_1 + size_2 - size_intersection
return size_intersection / (size_union+1e-6)
if __name__ == "__main__":
img_path = "test.png"
img = cv2.imread(img_path)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.show()
person_box_1 = [375, 169, 785, 586]
person_box_2 = [320, 269, 833, 460]
img = draw_box(img, person_box_1,(0,0,255))
img = draw_box(img, person_box_2,(0,255,0))
iou_result = iou(person_box_1, person_box_2)
print(f"The result of IOU is :{iou_result}")
cv2.imwrite("result.jpg", img)
plt.imshow(img)
plt.title(f"IOU:{iou_result}")
plt.show()
后记
最近在研究segment anything,后面会不定期更新与目标检测和图像分割的相关东西!