Debian Codegraph @

examples/01-filter/voxelize.py

raw
1 """
2 .. _voxelize_example:
3
4 Voxelize a Surface Mesh
5 ~~~~~~~~~~~~~~~~~~~~~~~
6
7 Create a voxel model (like legos) of a closed surface or volumetric mesh.
8
9 This example also demonstrates how to compute an implicit distance from a
10 bounding :class:`pyvista.PolyData` surface.
11
12 """
13
14 import numpy as np
15 import pyvista as pv
16
17 # sphinx_gallery_thumbnail_number = 2
18 from pyvista import examples
19
20 # Load a surface to voxelize
21 surface = examples.download_foot_bones()
22 surface
23
24 # %%
25 cpos = pv.CameraPosition(
26 position=(7.656346967151718, -9.802071079151158, -11.021236183314311),
27 focal_point=(0.2224512272564101, -0.4594554282112895, 0.5549738359311297),
28 viewup=(-0.6279216753504941, -0.7513057097368635, 0.20311105371647392),
29 )
30
31 surface.plot(cpos=cpos, opacity=0.75)
32
33
34 # %%
35 # Create a voxel model of the bounding surface
36 voxels = surface.voxelize()
37
38 pl = pv.Plotter()
39 pl.add_mesh(voxels, color=True, show_edges=True, opacity=0.5)
40 pl.add_mesh(surface, color='lightblue', opacity=0.5)
41 pl.show(cpos=cpos)
42
43
44 # %%
45 # We could even add a scalar field to that new voxel model in case we
46 # wanted to create grids for modelling. In this case, let's add a scalar field
47 # for bone density noting:
48 voxels['density'] = np.full(voxels.n_cells, 3.65) # g/cc
49 voxels
50
51 # %%
52 voxels.plot(scalars='density', cpos=cpos)
53
54
55 # %%
56 # A constant scalar field is kind of boring, so let's get a little fancier by
57 # added a scalar field that varies by the distance from the bounding surface.
58 voxels.compute_implicit_distance(surface, inplace=True)
59 voxels
60
61 # %%
62 contours = voxels.contour(6, scalars='implicit_distance')
63
64 pl = pv.Plotter()
65 pl.add_mesh(voxels, opacity=0.25, scalars='implicit_distance')
66 pl.add_mesh(contours, opacity=0.5, scalars='implicit_distance')
67 pl.show(cpos=cpos)
68 # %%
69 # .. tags:: filter