티스토리 뷰

Python

[Python] Numpy Batched IoU 코드

developer0hye 2022. 1. 19. 21:16
def compute_iou(bboxes1, bboxes2, bbox_format='cxcywh', normalized=True):
    if bbox_format == 'cxcywh':
        # if bboxes are composed of center point xy and wh/2.
        cx1, cy1, w1, h1 = np.split(bboxes1, 4, axis=1)
        cx2, cy2, w2, h2 = np.split(bboxes2, 4, axis=1)

        x11 = cx1 - w1 / 2
        y11 = cy1 - h1 / 2
        x12 = cx1 + w1 / 2 
        y12 = cy1 + h1 / 2

        x21 = cx2 - w2 /2
        y21 = cy2 - h2 /2
        x22 = cx2 + w2 /2
        y22 = cy2 + h2 /2
    elif bbox_format == 'tlxtlywh':
        # if bboxes are composed of top left point xy and wh.
        tlx1, tly1, w1, h1 = np.split(bboxes1, 4, axis=1)
        tlx2, tly2, w2, h2 = np.split(bboxes2, 4, axis=1)
        
        x11 = tlx1
        y11 = tly1
        x12 = tlx1 + w1 
        y12 = tly1 + h1

        x21 = tlx2
        y21 = tly2
        x22 = tlx2 + w2
        y22 = tly2 + h2
    elif bbox_format == 'tlxtlybrxbry':
        # if bboxes are composed of top left point xy and bottom right xy.
        x11, y11, x12, y12 = np.split(bboxes1, 4, axis=1)
        x21, y21, x22, y22 = np.split(bboxes2, 4, axis=1)

    # determine the (x, y)-coordinates of the intersection rectangle
    inter_x1 = np.maximum(x11, x21.T)
    inter_y1 = np.maximum(y11, y21.T)
    inter_x2 = np.minimum(x12, x22.T)
    inter_y2 = np.minimum(y12, y22.T)

    # # compute the area of intersection rectangle
    offset = 0. if normalized else 1.
    
    inter_area = np.maximum(inter_x2 - inter_x1 + offset , 1e-6) * np.maximum(inter_y2 - inter_y1 + offset , 1e-6)

    # # compute the area of both the prediction and ground-truth rectangles
    bboxes1_area = (x12 - x11 + offset ) * (y12 - y11 + offset)
    bboxes2_area = (x22 - x21 + offset ) * (y22 - y21 + offset)

    iou = inter_area / ((bboxes1_area + bboxes2_area.T - inter_area) + 1e-5)
    return iou

'Python' 카테고리의 다른 글

Anaconda 지원되는 python 버전 확인 명령어  (0) 2022.11.08
[Python] print 비활성화  (0) 2022.10.09
PyPi 배포 스크립트  (0) 2022.01.09
[Python] 파일 수정 시간 받아오기  (0) 2022.01.07
Static member variable in Python  (0) 2021.12.29
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함