【问题标题】:How to find right coordinates from numpy array如何从numpy数组中找到正确的坐标
【发布时间】:2021-10-26 05:56:38
【问题描述】:

我有一个 numpy 数组,其中包含 4 个矩形/四边形坐标:

pts = np.array([(690, 110), (345, 130), (690, 300), (445, 298)])

请注意,这些不是按顺序排列的。

现在我想找到一个矩形/四边形的左上角、右上角、左下角、右下角。

点是这样随机排列的:

我设计了一些手动逻辑,但是不正确。需要一些帮助。我的逻辑:

import numpy as np

pts = np.array([(690, 110), (345, 130), (690, 300), (445, 298)])


min_X_Cord = pts[np.where(pts == pts[:, 0].min())[0]]

sec_min = pts[np.where(pts == np.unique(pts[:, 0])[1])[0]]

top2 = np.array([min_X_Cord, sec_min]).reshape(-1, 2)

top_left, bot_left = (
    top2[np.where(top2 == top2[:, 1].max())[0]],
    top2[np.where(top2 == top2[:, 1].min())[0]],
)

print(top_left, bot_left)

max_X_Cord = pts[np.where(pts == pts[:, 0].max())[0]]
sec_min = pts[np.where(pts == np.unique(pts[:, 0])[-2])[0]]

编辑

我的问题之前可能不清楚。如果坐标系上有 4 个点,则可以用它们制作一个矩形或四边形。现在的问题是,要做到这一点并对其执行一些进一步的操作,我确实需要知道哪个点是左上角,哪个是右上角,哪个是左下角,哪个是右下角。

例如,在这个数组中:

[[300,120], [213,306], [538, 171], [550, 374]]

(300, 110) 是左上角,(538, 171) 是右上角,(213, 306) 是左下角,(550, 374) 是右下角。它没有特定的顺序,有时我的坐标可能是这样的

[[213,306],[300,120], [550, 374], [538, 171]]

相同的坐标,不同的位置。

现在我要提取左上、右上、左下、右下。

【问题讨论】:

  • 不清楚你想做什么。图片与什么有什么关系?
  • 图片显示点1、2、3、4不按顺序排列,我想从中分类topl、topr、botl、botr。

标签: python arrays numpy rectangles


【解决方案1】:

试试这个:

pts = np.array([(690, 110), (345, 130), (690, 300), (445, 298)])
pts = sorted(list(pts), key=lambda x: x[1])

b_l , b_r = sorted(list(pts[2:]), key=lambda x: x[0])
t_l , t_r = sorted(list(pts[:2]), key=lambda x: x[0])


print(b_l) # bottom_left
# [445 298]

print(b_r) # bottom_right
# [690 300]

print(t_l) # top_left
# [345 130]

print(t_r) # top_right
# [690 110]

【讨论】:

  • 实际左上角为(345, 130),右上角实际为(690,110),左下角为345, 130,右下角为690, 300
  • 为什么左上角是 (345, 130)?和其他?
  • @AhmadAnis,我编辑答案并添加了一个新代码块,这是你的答案吗?
  • 这并非总是如此。我需要一个通用的解决方案。就像有时第一个点可以在右下角,有时它可以在左下角。
  • @AhmadAnis,请解释一下您查找左上角、右上角...的逻辑?
【解决方案2】:
l_d =  (pts[:,0].min(), pts[:,1].min())
r_u =  (pts[:,0].max(), pts[:,1].max())
l_u =  (pts[:,0].min(), pts[:,1].max())
r_d =  (pts[:,0].max(), pts[:,1].min())

print(f"0:{r_u} 1:{l_u} 2:{r_d},3:{l_d}")

【讨论】:

  • 欢迎来到 SO 并感谢您的贡献。请不要添加代码作为屏幕截图。搜索引擎无法对其进行索引,依赖文本转语音软件浏览网页的人将无法访问它
猜你喜欢
  • 2018-07-04
  • 1970-01-01
  • 2013-10-20
  • 2015-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多