Debian Codegraph @

examples/98-common/project_points_tessellate.py

raw
1 """
2 .. _project_points_tessellate_example:
3
4 Project points to a plane and Tessellate
5 ----------------------------------------
6
7 Using pyvista and numpy, generate a 3D point cloud, project it to a plane, and
8 tessellate it.
9
10 This demonstrates how to use
11 :class:`pyvista.UnstructuredGridFilters.delaunay_2d` and a simple numpy
12 function that projects points to a plane.
13
14 """
15
16 import numpy as np
17 import pyvista as pv
18
19 # %%
20 # Project Points
21 # ~~~~~~~~~~~~~~
22 # Create a point cloud and project it to a plane.
23
24 num_points = 100
25 rng = np.random.default_rng(seed=0) # Seed rng for reproducibility
26 point_cloud = rng.random((num_points, 3))
27
28 # Define a plane
29 origin = [0, 0, 0]
30 normal = [0, 0, 1]
31 plane = pv.Plane(center=origin, direction=normal)
32
33
34 def project_points_to_plane(points, plane_origin, plane_normal):
35 """Project points to a plane."""
36 vec = points - plane_origin
37 dist = np.dot(vec, plane_normal)
38 return points - np.outer(dist, plane_normal)
39
40
41 projected_points = project_points_to_plane(point_cloud, origin, normal)
42
43 # Create a polydata object with projected points
44 polydata = pv.PolyData(projected_points)
45
46 # Mesh using delaunay_2d and pyvista
47 mesh = polydata.delaunay_2d()
48
49
50 # %%
51 # Visualize the Result
52 # ~~~~~~~~~~~~~~~~~~~~
53
54 # Create a plane for visualization
55 plane_vis = pv.Plane(
56 center=origin,
57 direction=normal,
58 i_size=2,
59 j_size=2,
60 i_resolution=10,
61 j_resolution=10,
62 )
63
64 # plot it
65 pl = pv.Plotter()
66 pl.add_mesh(mesh, show_edges=True, color='white', opacity=0.5, label='Tessellated mesh')
67 pl.add_mesh(
68 pv.PolyData(point_cloud),
69 color='red',
70 render_points_as_spheres=True,
71 point_size=10,
72 label='Points to project',
73 )
74 pl.add_mesh(plane_vis, color='blue', opacity=0.1, label='Projection Plane')
75 pl.add_legend()
76 pl.show()