[개인공부] Intersection over Union (IoU)

Jajuna_99·2022년 10월 3일
0

Intersection over Union (IoU)

설명

IoUIntersection over Union의 약자로 보통 두 가지 물체의 위치(Bounding Box)가 얼마나 일치하는지를 수학적으로 나타내는 지표이다.

객체 인식같은 모델을 사용했을 때 실제 물체의 위치와 예측된 물체의 위치를 평가 방법으로 사용할 수 있다.
-> 얼마나 겹치는지 정량적으로 표현하는 방식

즉, 객체 인식(object detection)문제의 손실 함수 지표로 사용될 수 있다.

  • 수식 -> IoUScore=IoU Score = ABAB\displaystyle {A ∩ B \over A ∪ B} == IU\displaystyle{I\over U}
  • 혹은 -> 'area of overlap' / 'area of union'
  • 여기서 UUA+BABA + B - A ∩ B 이다.

직사각형 2개, 모델 예측 경계 상자와 실제 참값(ground truth) 박스, (x, y의 최솟값(좌측 하단), 최댓값(우측 상단)끼리)의 좌표를 구해서 (x축 최대 값- x축 최소 값) * (y축 최대 값 - y축 최소 값)을 구하면 되는 것이다.

이 외의 다각형의 IoU를 구하는 방법도 있다고 하는데, 나중에 공부해서 업데이트 해보겠다...

구현

def IoU(box1, box2):
    # box = (x1, y1, x2, y2)
    box1_area = (box1[2] - box1[0] + 1) * (box1[3] - box1[1] + 1)
    box2_area = (box2[2] - box2[0] + 1) * (box2[3] - box2[1] + 1)

    # obtain x1, y1, x2, y2 of the intersection
    x1 = max(box1[0], box2[0])
    y1 = max(box1[1], box2[1])
    x2 = min(box1[2], box2[2])
    y2 = min(box1[3], box2[3])

    # compute the width and height of the intersection
    w = max(0, x2 - x1 + 1)
    h = max(0, y2 - y1 + 1)

    inter = w * h
    iou = inter / (box1_area + box2_area - inter)
    return iou

tf 구현

#MeanIoU class
tf.keras.metrics.MeanIoU(
    num_classes: int,
    name: Union[str, NoneType] = None,
    dtype: Union[str, tensorflow.python.framework.dtypes.DType, NoneType] = None,
    ignore_class: Union[int, NoneType] = None,
    sparse_y_true: bool = True,
    sparse_y_pred: bool = True,
    axis: int = -1,
)

## complie API
model.compile(
  optimizer='sgd',
  loss='mse',
  metrics=[tf.keras.metrics.MeanIoU(num_classes=2)])

ref

profile
Learning bunch, mostly computer and language

0개의 댓글