Python之根据四个坐标确定其位于左上下右上下

1、导入模块

import numpy as np

2、存储所需要确定位置的四个坐标点

# 所需要确定位置的四个坐标
coordinate = [[2570, 1948], [2391, 1919], [2411, 1792], [2591, 1821]]  # 常规矩形坐标
# coordinate = [[0, 1], [1, 0], [1, 2], [2, 1]]  # 非常规(菱形)矩形坐标,用以验证代码
coordinate = np.array(coordinate)

3、求出中心坐标点

center = coordinate[0]
for _ in range(1, 4):
    center = center + coordinate[_]
center = center / 4

4、找出x轴小于中心坐标点的点 left_coordinate

coordinate_temp = coordinate.copy() # 复制一份坐标,避免原坐标被破坏
left_coordinate = [] # 存储x轴小于中心坐标点的点
delete_index = []

# 将 x轴小于中心坐标点的点 存储进left_coordinate
for _ in range(4):
    if(coordinate[_][0] < center[0]):
        left_coordinate.append(coordinate[_])
        delete_index.append(_)
# 将存储进 left_coordinate 的元素从coordinate_temp中删除
coordinate_temp = np.delete(coordinate_temp, delete_index, axis=0)

5、确定四个坐标所处位置 'left_top', 'right_top', 'right_bottom', 'left_bottom'

思路:
若 len(left_coordinate) == 2:
比较left_coordinate中的坐标的y轴大小,小的确定为 左下,另一个确定为左上
比较coordinate_temp中的坐标的y轴大小,小的确定为 左下,另一个确定为左上
若 len(left_coordinate) == 1:
确定该点为左下
比较coordinate_temp中的坐标,找出其x轴大于中心坐标点的,确定为右上,并删除该点,
比较剩下两点的y轴,大的确定为左上,小的确定为右下

left_coordinate_temp = left_coordinate.copy() # 避免程序过程因为left_coordinate的变动而导致最初的条件判断错误

if(len(left_coordinate_temp) == 2):
    # 比较左边两个点的y轴,大的为左上
    if(left_coordinate[0][1] < left_coordinate[1][1]):
        left_bottom = left_coordinate[0]
        left_top = left_coordinate[1]
    elif(left_coordinate[0][1] > left_coordinate[1][1]):
        left_bottom = left_coordinate[1]
        left_top = left_coordinate[0]
            
    # 比较右边两个点的y轴,大的为右上
    if(coordinate_temp[0][1] < coordinate_temp[1][1]):
        right_bottom = coordinate_temp[0]
        right_top = coordinate_temp[1]
    elif(coordinate_temp[0][1] > coordinate_temp[1][1]):
        right_bottom = coordinate_temp[1]
        right_top = coordinate_temp[0]
        
elif(len(left_coordinate_temp) == 1):
    left_bottom = left_coordinate[0]
    delete_index = []
    
    for _ in range(3):
        if(coordinate_temp[_][0] == center[0] and coordinate_temp[_][1] > center[1]):
            left_top = coordinate_temp[_]
            delete_index.append(_)
        if(coordinate_temp[_][0] == center[0] and coordinate_temp[_][1] < center[1]):
            right_bottom = coordinate_temp[_]
            delete_index.append(_)
    
    coordinate_temp = np.delete(coordinate_temp, delete_index, axis=0)
    right_top = coordinate_temp[0]

6、检验定位效果

print(left_top, right_top)
print(left_bottom, right_bottom)

运行结果:

 

 

posted @ 2020-09-06 10:11  Jony-2018  阅读(3808)  评论(0编辑  收藏  举报