사소한 Tip . 오류 해결법/python

[python] 좌표값 정렬하기

Js.Y 2022. 4. 14. 11:06
728x90
반응형

Json포맷으로 된 bbox 값이 중구난방으로 나열된 경우, 내가 원하는 순서대로 정렬하기 위한 코드

TL(Top Left) -> TR(Top Right) -> BR(Bottom Right) -> BL(Bottom Left) 순서

def coord_adjust(coord):
    
    """
    coord : np.array
    [[xA,yA],
     [xB,yB],
     [xC,yC],
     [xD,yD]]
    
    """
    
    distance = []

    for idx, c in enumerate(coord):

        x = c[0]
        y = c[1]

        zero_distance = x+y
        distance.append([idx,zero_distance])

    distance = sorted(distance, key=itemgetter(1))

    left_top = coord[distance[0][0]]
    right_bottom = coord[distance[-1][0]]

    box1 = coord[distance[1][0]]
    box2 = coord[distance[2][0]]

    if box1[0] > box2[0]:
        left_bottom = box2
        right_top = box1
    else:
        left_bottom=box1
        right_top=box2
            
    x1,y1 = left_top
    x2,y2 = right_top
    x3,y3 = right_bottom
    x4,y4 = left_bottom
    
    output_coord = [[x1,y1],
                    [x2,y2],
                    [x3,y3],
                    [x4,y4]]
    
    return output_coord

 

728x90
반응형