Debian Codegraph @

examples/01-filter/slice.py

raw
1 """
2 .. _slice_example:
3
4 Slicing
5 ~~~~~~~
6
7 Extract thin planar slices from a volume.
8 """
9
10 import matplotlib.pyplot as plt
11 import numpy as np
12
13 # sphinx_gallery_thumbnail_number = 2
14 import pyvista as pv
15 from pyvista import examples
16
17 # %%
18 # PyVista meshes have several slicing filters bound directly to all datasets.
19 # These filters allow you to slice through a volumetric dataset to extract and
20 # view sections through the volume of data.
21 #
22 # One of the most common slicing filters used in PyVista is the
23 # :func:`pyvista.DataObjectFilters.slice_orthogonal` filter which creates three
24 # orthogonal slices through the dataset parallel to the three Cartesian planes.
25 # For example, let's slice through the sample geostatistical training image
26 # volume. First, load up the volume and preview it:
27
28 mesh = examples.load_channels()
29 # define a categorical colormap
30 cmap = plt.get_cmap('viridis', 4)
31
32 mesh.plot(cmap=cmap)
33
34 # %%
35 # Note that this dataset is a 3D volume and there might be regions within this
36 # volume that we would like to inspect. We can create slices through the mesh
37 # to gain further insight about the internals of the volume.
38
39 slices = mesh.slice_orthogonal()
40
41 slices.plot(cmap=cmap)
42
43
44 # %%
45 # The orthogonal slices can be easily translated throughout the volume:
46
47 slices = mesh.slice_orthogonal(x=20, y=20, z=30)
48 slices.plot(cmap=cmap)
49 # %%
50 # We can also add just a single slice of the volume by specifying the origin
51 # and normal of the slicing plane with the :func:`pyvista.DataObjectFilters.slice`
52 # filter:
53
54 # Single slice - origin defaults to the center of the mesh
55 single_slice = mesh.slice(normal=[1, 1, 0])
56
57 pl = pv.Plotter()
58 pl.add_mesh(mesh.outline(), color='k')
59 pl.add_mesh(single_slice, cmap=cmap)
60 pl.show()
61 # %%
62 # Adding slicing planes uniformly across an axial direction can also be
63 # automated with the :func:`pyvista.DataObjectFilters.slice_along_axis` filter:
64
65 slices = mesh.slice_along_axis(n=7, axis='y')
66
67 slices.plot(cmap=cmap)
68
69
70 # %%
71 # Slice Along Line
72 # ++++++++++++++++
73 #
74 # We can also slice a dataset along a :func:`pyvista.Spline` or :func:`pyvista.Line`
75 # using the :func:`pyvista.DataObjectFilters.slice_along_line` filter.
76 #
77 # First, define a line source through the dataset of interest. Please note
78 # that this type of slicing is computationally expensive and might take a while
79 # if there are a lot of points in the line - try to keep the resolution of
80 # the line low.
81
82 model = examples.load_channels()
83
84
85 def path(y):
86 """Equation: x = a(y-h)^2 + k"""
87 a = 110.0 / 160.0**2
88 x = a * y**2 + 0.0
89 return x, y
90
91
92 x, y = path(np.arange(model.bounds.y_min, model.bounds.y_max, 15.0))
93 zo = np.linspace(9.0, 11.0, num=len(y))
94 points = np.c_[x, y, zo]
95 spline = pv.Spline(points, n_points=15)
96 spline
97
98
99 # %%
100 # Then run the filter
101 slc = model.slice_along_line(spline)
102 slc
103
104 # %%
105
106 pl = pv.Plotter()
107 pl.add_mesh(slc, cmap=cmap)
108 pl.add_mesh(model.outline())
109 pl.show(cpos=[1, -1, 1])
110
111
112 # %%
113 # Multiple Slices in Vector Direction
114 # +++++++++++++++++++++++++++++++++++
115 #
116 # Slice a mesh along a vector direction perpendicularly.
117
118 mesh = examples.download_brain()
119
120 # Create vector
121 vec = np.array([1.0, 2.0, 1.0])
122 # Normalize the vector
123 normal = vec / np.linalg.norm(vec)
124
125 # Make points along that vector for the extent of your slices
126 a = mesh.center + normal * mesh.length / 3.0
127 b = mesh.center - normal * mesh.length / 3.0
128
129 # Define the line/points for the slices
130 n_slices = 5
131 line = pv.Line(a, b, resolution=n_slices)
132
133 # Generate all of the slices
134 slices = pv.MultiBlock()
135 for point in line.points:
136 slices.append(mesh.slice(normal=normal, origin=point))
137
138 # %%
139
140 pl = pv.Plotter()
141 pl.add_mesh(mesh.outline(), color='k')
142 pl.add_mesh(slices, opacity=0.75)
143 pl.add_mesh(line, color='red', line_width=5)
144 pl.show()
145
146
147 # %%
148 # Slice At Different Bearings
149 # +++++++++++++++++++++++++++
150 #
151 # From `pyvista-support#23 <https://github.com/pyvista/pyvista-support/issues/23>`_
152 #
153 # An example of how to get many slices at different bearings all centered
154 # around a user-chosen location.
155 #
156 # Create a point to orient slices around
157 ranges = np.ptp(np.array(model.bounds).reshape(-1, 2), axis=1)
158 point = np.array(model.center) - ranges * 0.25
159
160 # %%
161 # Now generate a few normal vectors to rotate a slice around the z-axis.
162 # Use equation for circle since its about the Z-axis.
163 increment = np.pi / 6.0
164 # use a container to hold all the slices
165 slices = pv.MultiBlock() # treat like a dictionary/list
166 for theta in np.arange(0, np.pi, increment):
167 normal = np.array([np.cos(theta), np.sin(theta), 0.0]).dot(np.pi / 2.0)
168 name = f'Bearing: {np.rad2deg(theta):.2f}'
169 slices[name] = model.slice(origin=point, normal=normal)
170 slices
171
172 # %%
173 # And now display it.
174 pl = pv.Plotter()
175 pl.add_mesh(slices, cmap=cmap)
176 pl.add_mesh(model.outline())
177 pl.show()
178
179 # %%
180 # Slice ImageData With Indexing
181 # +++++++++++++++++++++++++++++
182 # Most slicing filters return :class:`~pyvista.PolyData` or
183 # :class:`~pyvista.UnstructuredGrid`. For :class:`~pyvista.ImageData` inputs, however,
184 # it's often desirable to return :class:`~pyvista.ImageData`. The
185 # :meth:`~pyvista.ImageDataFilters.slice_index` filter supports this use case.
186 #
187 # Extract a single 2D slice from a 3D segmentation mask and plot it. Here we use
188 # :func:`~pyvista.examples.examples.load_frog_tissues`.
189
190 mask = examples.load_frog_tissues()
191 sliced = mask.slice_index(k=50)
192 colored = sliced.color_labels()
193 colored.plot(cpos='xy', zoom='tight', lighting=False)
194
195 # %%
196 # Extract a 3D volume of interest instead and visualize it as a surface mesh. Here we
197 # define indices to extract the frog's head.
198
199 sliced = mask.slice_index(i=[300, 500], j=[110, 350], k=[0, 100])
200 surface = sliced.contour_labels()
201 colored = surface.color_labels()
202
203 cpos = pv.CameraPosition(
204 position=(520.0, 461.0, -402.0),
205 focal_point=(372.0, 243.0, 52.0),
206 viewup=(-0.73, -0.50, -0.47),
207 )
208 colored.plot(cpos=cpos)
209
210 # %%
211 # .. tags:: filter