Skip to main content
 首页 » 编程设计

python之在 2D numpy 数组中找到给定角度的最近项目

2025年01月19日9lhb25

给定一个 numpy 二维数组,在给定角度的情况下,从指定坐标(“X”所在的位置)获取最近项(对于本例“1”)的最佳方法是什么。

例如,假设我们的“X”位于二维数组中的 (1,25),如下所示。假设角度为 225 度,假设 0 度向右笔直,90 度笔直向上。如何获得位于该矢量方向的“1”的最近坐标?

[ 
0000000000000000000000000000 
0000000000000000000000000X00 
0000000000000000000000000000 
1110000000000000000000000000 
1111100000000000000000000000 
1111110000000000000000000000 
1111111000000000000000000000 
1111111110000000000000000000 
1111111111100000000000000000 
] 

请您参考如下方法:

我假设朝着那个方向你的意思是像在那条射线上一样。在这种情况下,255° 无解,所以我冒昧地将其更改为 195°。

然后你可以暴力破解它:

import numpy as np 
 
a = """ 
0000000000000000000000000000 
0000000000000000000000000X00 
0000000000000000000000000000 
1110000000000000000000000000 
1111100000000000000000000000 
1111110000000000000000000000 
1111111000000000000000000000 
1111111110000000000000000000 
1111111111100000000000000000 
""" 
 
a = np.array([[int(i) for i in row] for row in a.strip().replace('X', '2').split()], dtype=np.uint8) 
 
x = np.argwhere(a==2)[0] 
y = np.argwhere(a==1) 
d = y-x 
 
phi = 195 # 255 has no solutions 
 
on_ray = np.abs(d@(np.sin(np.radians(-phi-90)), np.cos(np.radians(-phi-90))))<np.sqrt(0.5) 
 
show_ray = np.zeros_like(a) 
show_ray[tuple(y[on_ray].T)] = 1 
print(show_ray) 
 
ymin=y[on_ray][np.argmin(np.einsum('ij,ij->i', d[on_ray], d[on_ray]))] 
print(ymin) 

输出:

# [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 
#  [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 
#  [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 
#  [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 
#  [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 
#  [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 
#  [0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 
#  [1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 
#  [1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]] 
# [6 6]