Debian Codegraph @

examples/02-plot/texture.py

raw
1 """
2 .. _texture_example:
3
4 Applying Textures
5 ~~~~~~~~~~~~~~~~~
6
7 Plot a mesh with an image projected onto it as a texture.
8 """
9
10 from matplotlib.pyplot import get_cmap
11 import numpy as np
12 import pyvista as pv
13 from pyvista import examples
14
15 # %%
16 # Texture mapping is easily implemented using PyVista. Many of the geometric
17 # objects come preloaded with texture coordinates, so quickly creating a
18 # surface and displaying an image is simply:
19
20 # load a sample texture
21 tex = examples.download_masonry_texture()
22
23 # create a surface to host this texture
24 surf = pv.Cylinder()
25
26 surf.plot(texture=tex)
27
28
29 # %%
30 # But what if your dataset doesn't have texture coordinates? Then you can
31 # harness the :func:`pyvista.DataSetFilters.texture_map_to_plane` filter to
32 # properly map an image to a dataset's surface.
33 # For example, let's map that same image of bricks to a curvey surface:
34
35 # create a structured surface
36 x = np.arange(-10, 10, 0.25)
37 y = np.arange(-10, 10, 0.25)
38 x, y = np.meshgrid(x, y)
39 r = np.sqrt(x**2 + y**2)
40 z = np.sin(r)
41 curvsurf = pv.StructuredGrid(x, y, z)
42
43 # Map the curved surface to a plane - use best fitting plane
44 curvsurf.texture_map_to_plane(inplace=True)
45
46 curvsurf.plot(texture=tex)
47
48 # %%
49 # Display scalar data along with a texture by ensuring the
50 # ``interpolate_before_map`` setting is ``False`` and specifying both the
51 # ``texture`` and ``scalars`` arguments.
52
53 elevated = curvsurf.elevation()
54
55 elevated.plot(
56 scalars='Elevation', cmap='terrain', texture=tex, interpolate_before_map=False
57 )
58
59
60 # %%
61 # Note that this process can be completed with any image texture.
62
63 # use the puppy image
64 tex = examples.download_puppy_texture()
65 curvsurf.plot(texture=tex)
66
67
68 # %%
69 # Textures from Files
70 # +++++++++++++++++++
71 #
72 # What about loading your own texture from an image? This is often most easily
73 # done using the :func:`pyvista.read_texture` function - simply pass an image
74 # file's path, and this function with handle making a :vtk:`vtkTexture` for you to
75 # use.
76
77 image_file = examples.mapfile
78 tex = pv.read_texture(image_file)
79 curvsurf.plot(texture=tex)
80
81
82 # %%
83 # NumPy Arrays as Textures
84 # ++++++++++++++++++++++++
85 #
86 # Want to use a programmatically built image? :class:`pyvista.ImageData`
87 # objects can be converted to textures using :func:`pyvista.image_to_texture`
88 # and 3D NumPy (X by Y by RGB) arrays can be converted to textures using
89 # :func:`pyvista.numpy_to_texture`.
90
91 # create an image using numpy,
92 xx, yy = np.meshgrid(np.linspace(-200, 200, 20), np.linspace(-200, 200, 20))
93 A, b = 500, 100
94 zz = A * np.exp(-0.5 * ((xx / b) ** 2.0 + (yy / b) ** 2.0))
95
96 # Creating a custom RGB image
97 cmap = get_cmap('nipy_spectral')
98 norm = lambda x: (x - np.nanmin(x)) / (np.nanmax(x) - np.nanmin(x))
99 hue = norm(zz.ravel())
100 colors = (cmap(hue)[:, 0:3] * 255.0).astype(np.uint8)
101 image = colors.reshape((xx.shape[0], xx.shape[1], 3), order='F')
102
103 # Convert 3D numpy array to texture
104 tex = pv.numpy_to_texture(image)
105
106 # Render it
107 curvsurf.plot(texture=tex)
108
109 # %%
110 # Create a GIF Movie with updating textures
111 # +++++++++++++++++++++++++++++++++++++++++
112 # Generate a moving gif from an active plotter with updating textures.
113
114 mesh = curvsurf.extract_surface(algorithm=None)
115
116 # Create a plotter object
117 pl = pv.Plotter(notebook=False, off_screen=True)
118
119 actor = pl.add_mesh(mesh, smooth_shading=True, color='white')
120
121 # Open a gif
122 pl.open_gif('texture.gif')
123
124 # Update Z and write a frame for each updated position
125 nframe = 15
126 for phase in np.linspace(0, 2 * np.pi, nframe + 1)[:nframe]:
127 # create an image using numpy,
128 z = np.sin(r + phase)
129 mesh.points[:, -1] = z.ravel()
130
131 # Creating a custom RGB image
132 zz = A * np.exp(-0.5 * ((xx / b) ** 2.0 + (yy / b) ** 2.0))
133 hue = norm(zz.ravel()) * 0.5 * (1.0 + np.sin(phase))
134 colors = (cmap(hue)[:, 0:3] * 255.0).astype(np.uint8)
135 image = colors.reshape((xx.shape[0], xx.shape[1], 3), order='F')
136
137 # Convert 3D numpy array to texture
138 actor.texture = pv.numpy_to_texture(image)
139
140 # must update normals when smooth shading is enabled
141 mesh.compute_normals(cell_normals=False, inplace=True)
142 pl.write_frame()
143 pl.clear()
144
145 # Closes and finalizes movie
146 pl.close()
147
148 # %%
149 # Textures with Transparency
150 # ++++++++++++++++++++++++++
151 #
152 # Textures can also specify per-pixel opacity values. The image must
153 # contain a 4th channel specifying the opacity value from 0 [transparent] to
154 # 255 [fully visible]. To enable this feature just pass the opacity array as the
155 # 4th channel of the image as a 3 dimensional matrix with shape [nrows, ncols, 4]
156 # :func:`pyvista.numpy_to_texture`.
157 #
158 # Here we can download an image that has an alpha channel:
159 rgba = examples.download_rgba_texture()
160 rgba.n_components
161
162 # %%
163
164 # Render it
165 curvsurf.plot(texture=rgba, show_grid=True)
166
167
168 # %%
169 # Repeating Textures
170 # ++++++++++++++++++
171 #
172 # What if you have a single texture that you'd like to repeat across a mesh?
173 # Simply define the texture coordinates for all nodes explicitly.
174 #
175 # Here we create the texture coordinates to fill up the grid with several
176 # mappings of a single texture. In order to do this we must define texture
177 # coordinates outside of the typical ``(0, 1)`` range:
178
179 axial_num_puppies = 4
180 xc = np.linspace(0, axial_num_puppies, curvsurf.dimensions[0])
181 yc = np.linspace(0, axial_num_puppies, curvsurf.dimensions[1])
182
183 xxc, yyc = np.meshgrid(xc, yc)
184 puppy_coords = np.c_[yyc.ravel(), xxc.ravel()]
185
186 # %%
187 # By defining texture coordinates that range ``(0, 4)`` on each axis, we will
188 # produce 4 repetitions of the same texture on this mesh.
189 #
190 # Then we must associate those texture coordinates with the mesh through the
191 # :attr:`pyvista.DataSet.active_texture_coordinates` property.
192
193 curvsurf.active_texture_coordinates = puppy_coords
194
195 # %%
196 # Now display all the puppies.
197
198 # use the puppy image
199 tex = examples.download_puppy_texture()
200 curvsurf.plot(texture=tex, cpos='xy')
201
202
203 # %%
204 # Spherical Texture Coordinates
205 # +++++++++++++++++++++++++++++
206 # We have a built in convienance method for mapping textures to spherical
207 # coordinate systems much like the planar mapping demoed above.
208 mesh = pv.Sphere()
209 tex = examples.download_masonry_texture()
210
211 mesh.texture_map_to_sphere(inplace=True)
212 mesh.plot(texture=tex)
213
214
215 # %%
216 # The helper method above does not always produce the desired texture
217 # coordinates, so sometimes it must be done manually. Here is a great, user
218 # contributed example from `this support issue <https://github.com/pyvista/pyvista-support/issues/257>`_
219 #
220 # Manually create the texture coordinates for a globe map. First, we create
221 # the mesh that will be used as the globe. Note the `start_theta` for a slight
222 # overlappig
223 sphere = pv.Sphere(
224 radius=1,
225 theta_resolution=120,
226 phi_resolution=120,
227 start_theta=270.001,
228 end_theta=270,
229 )
230
231 # Initialize the texture coordinates array
232 sphere.active_texture_coordinates = np.zeros((sphere.points.shape[0], 2))
233
234 # Populate by manually calculating
235 for i in range(sphere.points.shape[0]):
236 sphere.active_texture_coordinates[i] = [
237 0.5 + np.arctan2(-sphere.points[i, 0], sphere.points[i, 1]) / (2 * np.pi),
238 0.5 + np.arcsin(sphere.points[i, 2]) / np.pi,
239 ]
240
241 # And let's display it with a world map
242 tex = examples.load_globe_texture()
243 sphere.plot(texture=tex)
244 # %%
245 # .. tags:: plot