# 建立 Convex hull

``````from random import random
from scipy.spatial import ConvexHull

# 平面上的隨機點
points = [(random(), random()) for i in range(20)]

# 顯示隨機點
for p in points:
show_object(Vertex.makeVertex(p[0], p[1], 0))

# 建立凸包物件
hull = ConvexHull(points)

# vertices 取得凸包的頂點索引，逆時針順序
convex_pts = [points[i] for i in hull.vertices]

# 用 Wire 建立凸包
convex = (Workplane()
.polyline(convex_pts)
.close()
)
show_object(convex)
``````

``````from random import random
from scipy.spatial import ConvexHull

# 用 Wire 來建立凸包
def hull2D(points):
hull = ConvexHull(points)
return (cq.Workplane()
.polyline([points[i] for i in hull.vertices])
.close()
.val()
)

# 將 Workplane 中的 Wire 頂點轉為 (x, y)
def toPoints(workplane):
return [(v.X, v.Y) for v in workplane.vertices().vals()]

# 建立兩個四邊形的凸包
rect1 = Workplane().rect(5, 5)
rect2 = Workplane().center(20, 20).rect(5, 5)
convex = hull2D(toPoints(rect1) + toPoints(rect2))
show_object(convex)
``````

``````...

points = [(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(points)

box = polyhedron(points, hull.simplices)
show_object(box)
``````

``````from random import random
from scipy.spatial import ConvexHull
from cadquery import Vector, Edge, Wire, Solid, Shell, Face

def polyhedron(points, faces):
def _edges(vectors, face_indices):
leng_vertices = len(face_indices)
return (
Edge.makeLine(
vectors[face_indices[i]],
vectors[face_indices[(i + 1) % leng_vertices]]
)
for i in range(leng_vertices)
)

vectors = [Vector(*p) for p in points]

return Solid.makeSolid(
Shell.makeShell(
Face.makeFromWires(
Wire.assembleEdges(
_edges(vectors, face_indices)
)
)
for face_indices in faces
)
)

# 建立 3D 版本的凸包
def hull3D(points):
hull = ConvexHull(points)
# 凸包上的頂點
vertices = [points[i] for i in hull.vertices]

# 用來查詢頂點的索引值
v_i_lookup = {v: i for i, v in enumerate(vertices)}

# 建立面索引
faces = [
[v_i_lookup[points[i]] for i in face]
for face in hull.simplices
]

return polyhedron(vertices, faces)

# 隨機點
points = [(random(), random(), random()) for i in range(10)]
convex = hull3D(points)
show_object(convex)
``````