点云三维凸包

2024-09-28 19:06:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要绘制一个三维点云(点数:N),然后从这些点绘制一个凸壳(实际上是一个有N个顶点的多面体)。我用python编写了一个脚本,其中scipy.space converxhull用于绘制8个点和一个立方体,点云的绘制是可以的,但是立方体是不可以的,因为代码除了边缘线之外,还放置了两条穿过立方体对角线的线。我不明白为什么要在脸上画线。

剧本:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull  

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

points= np.array([[0,0,0],
            [4,0,0],
            [4,4,0],
            [0,4,0],
            [0,0,4],
            [4,0,4],
            [4,4,4],
            [0,4,4]])

hull=ConvexHull(points)

edges= zip(*points)

for i in hull.simplices:
    plt.plot(points[i,0], points[i,1], points[i,2], 'r-')

ax.plot(edges[0],edges[1],edges[2],'bo') 

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

ax.set_xlim3d(-5,5)
ax.set_ylim3d(-5,5)
ax.set_zlim3d(-5,5)

plt.show()

脚本结果:

enter image description here


Tags: fromimport脚本asnpfig绘制plt
1条回答
网友
1楼 · 发布于 2024-09-28 19:06:52

我知道这是旧的,但我从谷歌来到这里,所以我认为其他人也可能。

问题只出在你使用的绘图方法上。 单纯形是由3个点定义的nD三角形。 但是绘图函数必须循环回到最后一点,否则只绘制3个单纯形边中的2个。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.spatial import ConvexHull


# 8 points defining the cube corners
pts = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0],
                [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1], ])

hull = ConvexHull(pts)

fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")

# Plot defining corner points
ax.plot(pts.T[0], pts.T[1], pts.T[2], "ko")

# 12 = 2 * 6 faces are the simplices (2 simplices per square face)
for s in hull.simplices:
    s = np.append(s, s[0])  # Here we cycle back to the first coordinate
    ax.plot(pts[s, 0], pts[s, 1], pts[s, 2], "r-")

# Make axis label
for i in ["x", "y", "z"]:
    eval("ax.set_{:s}label('{:s}')".format(i, i))

plt.show()

image

相关问题 更多 >