【code】四座標點位排序

sortCoordinate

排序座標,使得座標符合(x_min,y_min),(x_max,y_min),(x_max,y_max),(x_min,y_max)

def sortCoordinate(box):

    '''
    :param box: x,y座標共4點8值;[x1, y1, x2, y2, x3, y3, x4, y4]
    x1y1->x2y2->x3y3-x4y4
    top_left->top_right->bottom_right->bottom_letft
    (x_min,y_min),(x_max,y_min),(x_max,y_max),(x_min,y_max)
    ------------------
    | *********      |
    |  *********     |
    |   *********    |
    |    *********   |
    |     *********  |
    ------------------
    :return: [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
    '''

    x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]
    newBox = [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
    
    # 按第一維度正序排序[x_min,x_min,x_max,x_max]
    newBox = sorted(newBox, key=lambda x: x[0],reverse=False) 
    # 排序後,前兩個是左邊的上下兩個座標點x_min,按第二維排序,使得y_min最小的在前面
    x1, y1 = sorted(newBox[:2], key=lambda x: x[1])[0] 
    index = newBox.index([x1, y1]) # 取出(x_min,y_min)
    newBox.pop(index)
    
    newBox = sorted(newBox, key=lambda x: x[1],reverse=True)
    x4, y4 = sorted(newBox[:2], key=lambda x: x[0])[0]
    index = newBox.index([x4, y4])
    newBox.pop(index)
    
    newBox = sorted(newBox, key=lambda x: x[0],reverse=True)
    x2, y2 = sorted(newBox[:2], key=lambda x: x[1])[0]
    index = newBox.index([x2, y2])
    newBox.pop(index)

    newBox = sorted(newBox, key=lambda x: x[1],reverse=True)
    x3, y3 = sorted(newBox[:2], key=lambda x: x[0])[0]

    res = [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
    
    return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章