Python之根据四个坐标确定其位于左上下右上下
- 2020 年 9 月 6 日
- 筆記
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): delete_index = [] for _ in range(2): if(left_coordinate[_][1] < center[1]): left_bottom = left_coordinate[_] delete_index.append(_) break left_coordinate = np.delete(left_coordinate, delete_index, axis=0) left_top = left_coordinate[0] for _ in range(2): if(coordinate_temp[_][1] < center[1]): right_bottom = coordinate_temp[_] coordinate_temp = np.delete(coordinate_temp, [_], axis=0) break 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)
运行结果: