如何在圆柱面上生成规则点
我刚开始学习Python,现在需要用Numpy做一个项目。
我需要在一个圆柱体的表面上生成一些点(比如一百万个)。这些点应该在一个特定的角度定义的区域内均匀分布。请问我该怎么做呢?
我的输入参数有:
圆柱体中心的
position
(例如[0,0,0]
)圆柱体的
orientation
(方向)圆柱体的
length
(长度)圆柱体的
radius
(半径)一个
angle
(这个角度定义了点应该分布的圆柱体部分。如果alpha = 360
,那么就是整个表面)delta_l
是长度方向上每两个点之间的距离delta_alpha
是旋转方向上每两个点之间的距离
我的输出参数是:
- 一个数组,里面包含所有点的坐标
有没有人能帮我,或者给我一点提示该怎么做呢?
非常感谢!
1 个回答
4
这是我之前一个项目中的内容:
def make_cylinder(radius, length, nlength, alpha, nalpha, center, orientation):
#Create the length array
I = np.linspace(0, length, nlength)
#Create alpha array avoid duplication of endpoints
#Conditional should be changed to meet your requirements
if int(alpha) == 360:
A = np.linspace(0, alpha, num=nalpha, endpoint=False)/180*np.pi
else:
A = np.linspace(0, alpha, num=nalpha)/180*np.pi
#Calculate X and Y
X = radius * np.cos(A)
Y = radius * np.sin(A)
#Tile/repeat indices so all unique pairs are present
pz = np.tile(I, nalpha)
px = np.repeat(X, nlength)
py = np.repeat(Y, nlength)
points = np.vstack(( pz, px, py )).T
#Shift to center
shift = np.array(center) - np.mean(points, axis=0)
points += shift
#Orient tube to new vector
#Grabbed from an old unutbu answer
def rotation_matrix(axis,theta):
a = np.cos(theta/2)
b,c,d = -axis*np.sin(theta/2)
return np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)],
[2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)],
[2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]])
ovec = orientation / np.linalg.norm(orientation)
cylvec = np.array([1,0,0])
if np.allclose(cylvec, ovec):
return points
#Get orthogonal axis and rotation
oaxis = np.cross(ovec, cylvec)
rot = np.arccos(np.dot(ovec, cylvec))
R = rotation_matrix(oaxis, rot)
return points.dot(R)
绘制的点如下:
points = make_cylinder(3, 5, 5, 360, 10, [0,2,0], [1,0,0])
关于旋转的部分写得比较简单粗暴,你可能需要仔细检查一下。这个旋转用的是欧拉-罗德里格斯公式,感谢unutbu的帮助。