[英]what's the difference between np.array[:,0] and np.array[:,[0]]?
[英]Project np.array of points to np.array of segments
我有以下工作代碼將單個點投影到數組中的每個段。 但我希望將點數組中的每個點投影到每個段。
import numpy as np
#find closest segment to single point
#line segment
l1 = np.array([[2,3,0],[7,5,0]])
l2 = np.array([[5,1,0],[8,6,0]])
#point that gets projected
p = np.array([[6,5,0]]) #only single point
#set to origin
line = l2-l1
pv = p-l1
#length of line squared
len_sq = np.sum(line**2, axis = 1) #len_sq = numpy.einsum("ij,ij->i", line, line)
#dot product of 3D vectors with einsum
dot = np.einsum('ij,ij->i',line,pv) #np.sum(line*pv,axis=1)
#percentage of line the pv vector travels in
param = np.array([dot/len_sq])
#param<0 projected point=l1, param>1 pp=l2
clamped_param = np.clip(param,0,1)
#add line fraction to l1 to get projected point
pp = l1+(clamped_param.T*line)
例如,使
p = np.array([[6,5,0],[3,2,0]]) #multiple points
並返回 4 個投影點的 np.array()。
也許您可以嘗試以下方法。 如果項目是 function 可以對單個點進行操作,那么通過沿軸應用,您可以使其對點數組中的所有點進行操作。 output 作為每個點的單獨生成器產生,必須使用堆疊操作將其轉換回單個數組。
l1 = np.array([[2,3,0],[7,5,0]])
l2 = np.array([[5,1,0],[8,6,0]])
line = l2-l1
len_sq = np.sum(line**2, axis = 1)
def project(p):
pv = p-l1
dot = np.einsum('ij,ij->i',line,pv)
param = np.array([dot/len_sq])
clamped_param = np.clip(param,0,1)
yield l1+(clamped_param.T*line)
pts = np.array([[6,5,0],
[3,2,0]])
gen = np.apply_along_axis(project, 1, pts)
out = np.hstack([list(G) for G in gen])[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.