| 1 |
"""Wrapper for :vtk:`vtkTexture`.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from collections.abc import Sequence |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
import numpy as np |
| 9 |
|
| 10 |
import pyvista as pv |
| 11 |
from pyvista import _vtk |
| 12 |
from pyvista._warn_external import warn_external |
| 13 |
from pyvista.core import _validation |
| 14 |
from pyvista.core.dataobject import DataObject |
| 15 |
from pyvista.core.utilities.fileio import _try_imageio_imread |
| 16 |
from pyvista.core.utilities.misc import AnnotatedIntEnum |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
from typing import Literal |
| 20 |
|
| 21 |
from pyvista.core._typing_core import NumpyArray |
| 22 |
|
| 23 |
|
| 24 |
class Texture(DataObject, _vtk.vtkTexture): |
| 25 |
"""Wrap :vtk:`vtkTexture`. |
| 26 |
|
| 27 |
Textures can be used to apply images to surfaces, as in the case of |
| 28 |
:ref:`texture_example`. |
| 29 |
|
| 30 |
They can also be used for environment textures to affect the lighting of |
| 31 |
the scene, or even as a environment cubemap as in the case of |
| 32 |
:ref:`pbr_example` and :ref:`planets_example`. |
| 33 |
|
| 34 |
.. versionchanged:: 0.47 |
| 35 |
|
| 36 |
All textures now use ``'direct'`` :attr:`color_mode` by default. |
| 37 |
|
| 38 |
Parameters |
| 39 |
---------- |
| 40 |
uinput : str, :vtk:`vtkImageData`, :vtk:`vtkTexture`, sequence[ImageData], optional |
| 41 |
Filename, :vtk:`vtkImageData`, :vtk:`vtkTexture`, :class:`numpy.ndarray` or a |
| 42 |
sequence of images to create a cubemap. If a sequence of images, must |
| 43 |
be of the same size and in the following order: |
| 44 |
|
| 45 |
* +X |
| 46 |
* -X |
| 47 |
* +Y |
| 48 |
* -Y |
| 49 |
* +Z |
| 50 |
* -Z |
| 51 |
|
| 52 |
**kwargs : dict, optional |
| 53 |
Optional arguments when reading from a file. Generally unused. |
| 54 |
|
| 55 |
Examples |
| 56 |
-------- |
| 57 |
Load a texture from file. File should be a "image" or "image-like" file. |
| 58 |
|
| 59 |
>>> from pathlib import Path |
| 60 |
>>> import pyvista as pv |
| 61 |
>>> from pyvista import examples |
| 62 |
>>> path = examples.download_masonry_texture(load=False) |
| 63 |
>>> Path(path).name |
| 64 |
'masonry.bmp' |
| 65 |
>>> texture = pv.Texture(path) |
| 66 |
>>> texture |
| 67 |
Texture (...) |
| 68 |
Components: 3 |
| 69 |
Cube Map: False |
| 70 |
Dimensions: 256, 256 |
| 71 |
|
| 72 |
Create a texture from an RGB array. Note how this is colored per "point" |
| 73 |
rather than per "pixel". |
| 74 |
|
| 75 |
>>> import numpy as np |
| 76 |
>>> arr = np.array( |
| 77 |
... [ |
| 78 |
... [255, 255, 255], |
| 79 |
... [255, 0, 0], |
| 80 |
... [0, 255, 0], |
| 81 |
... [0, 0, 255], |
| 82 |
... ], |
| 83 |
... dtype=np.uint8, |
| 84 |
... ) |
| 85 |
>>> arr = arr.reshape((2, 2, 3)) |
| 86 |
>>> texture = pv.Texture(arr) |
| 87 |
>>> texture.plot() |
| 88 |
|
| 89 |
Create a cubemap from 6 images. |
| 90 |
|
| 91 |
>>> px = examples.download_sky(direction='posx') # doctest:+SKIP |
| 92 |
>>> nx = examples.download_sky(direction='negx') # doctest:+SKIP |
| 93 |
>>> py = examples.download_sky(direction='posy') # doctest:+SKIP |
| 94 |
>>> ny = examples.download_sky(direction='negy') # doctest:+SKIP |
| 95 |
>>> pz = examples.download_sky(direction='posz') # doctest:+SKIP |
| 96 |
>>> nz = examples.download_sky(direction='negz') # doctest:+SKIP |
| 97 |
>>> texture = pv.Texture([px, nx, py, ny, pz, nz]) # doctest:+SKIP |
| 98 |
>>> texture.cube_map # doctest:+SKIP |
| 99 |
True |
| 100 |
|
| 101 |
""" |
| 102 |
|
| 103 |
class WrapType(AnnotatedIntEnum): |
| 104 |
"""Types of wrapping a texture can support. |
| 105 |
|
| 106 |
Wrap mode for the texture coordinates valid values are: |
| 107 |
|
| 108 |
* CLAMP_TO_EDGE |
| 109 |
* REPEAT (Default in :class:`pyvista.Texture`) |
| 110 |
* MIRRORED_REPEAT |
| 111 |
* CLAMP_TO_BORDER |
| 112 |
|
| 113 |
See :attr:`Texture.wrap` for usage. |
| 114 |
|
| 115 |
""" |
| 116 |
|
| 117 |
CLAMP_TO_EDGE = (0, 'Clamp to edge') |
| 118 |
REPEAT = (1, 'Repeat') |
| 119 |
MIRRORED_REPEAT = (2, 'Mirrored repeat') |
| 120 |
CLAMP_TO_BORDER = (3, 'Clamp to border') |
| 121 |
|
| 122 |
_default_color_mode: Literal['direct'] = 'direct' |
| 123 |
|
| 124 |
def __init__(self, uinput=None, **kwargs): |
| 125 |
"""Initialize the texture.""" |
| 126 |
super().__init__(uinput) |
| 127 |
|
| 128 |
if isinstance(uinput, _vtk.vtkTexture): |
| 129 |
self._from_texture(uinput) |
| 130 |
elif isinstance(uinput, np.ndarray): |
| 131 |
self._from_array(uinput) |
| 132 |
elif isinstance(uinput, _vtk.vtkImageData): |
| 133 |
self._from_image_data(uinput) |
| 134 |
elif isinstance(uinput, str): |
| 135 |
self._from_file(filename=uinput, **kwargs) |
| 136 |
elif isinstance(uinput, Sequence) and len(uinput) == 6: |
| 137 |
# Create a cubemap |
| 138 |
self.mipmap = True |
| 139 |
self.interpolate = True |
| 140 |
self.cube_map = True # Must be set prior to setting images |
| 141 |
|
| 142 |
# add each image to the cubemap |
| 143 |
for i, image in enumerate(uinput): |
| 144 |
if not isinstance(image, pv.ImageData): |
| 145 |
msg = ( |
| 146 |
'If a sequence, the each item in the first argument must be a ' |
| 147 |
'pyvista.ImageData' |
| 148 |
) |
| 149 |
raise TypeError(msg) |
| 150 |
# must flip y for cubemap to display properly |
| 151 |
self.SetInputDataObject(i, image._flip_uniform(1)) |
| 152 |
elif uinput is None: |
| 153 |
pass |
| 154 |
else: |
| 155 |
msg = f'Cannot create a pyvista.Texture from ({type(uinput)})' |
| 156 |
raise TypeError(msg) |
| 157 |
|
| 158 |
self.color_mode = self._default_color_mode |
| 159 |
|
| 160 |
def _from_file(self, filename, **kwargs): |
| 161 |
try: |
| 162 |
image = pv.read(filename, cls=pv.ImageData, **kwargs) |
| 163 |
if image.n_points < 2: # pragma: no cover |
| 164 |
msg = 'Problem reading the image with VTK.' |
| 165 |
raise RuntimeError(msg) |
| 166 |
self._from_image_data(image) |
| 167 |
except (KeyError, ValueError, OSError): |
| 168 |
self._from_array(_try_imageio_imread(filename)) # pragma: no cover |
| 169 |
|
| 170 |
def _from_texture(self, texture): |
| 171 |
image = texture.GetInput() |
| 172 |
self._from_image_data(image) |
| 173 |
|
| 174 |
@property |
| 175 |
def color_mode(self) -> Literal['map', 'direct']: # numpydoc ignore=RT01 |
| 176 |
"""Return or set the color mode. |
| 177 |
|
| 178 |
Either ``'direct'``, or ``'map'``. |
| 179 |
|
| 180 |
* ``'direct'`` - All integer types are treated as colors with values in |
| 181 |
the range 0-255 and floating types are treated as colors with values |
| 182 |
in the range 0.0-1.0 |
| 183 |
* ``'map'`` - All scalar data will be mapped through the lookup table. |
| 184 |
|
| 185 |
.. versionadded:: 0.47 |
| 186 |
|
| 187 |
""" |
| 188 |
mode = self.GetColorMode() |
| 189 |
if mode == 0: |
| 190 |
# VTK's default mode uses 'direct' if scalars have uint8 dtype, and 'map' otherwise |
| 191 |
# But PyVista's default is to always use 'direct', even for floats |
| 192 |
self.color_mode = self._default_color_mode |
| 193 |
return self.color_mode |
| 194 |
return 'map' if mode == 1 else 'direct' |
| 195 |
|
| 196 |
@color_mode.setter |
| 197 |
def color_mode(self, value: Literal['map', 'direct']): |
| 198 |
_validation.check_contains(['map', 'direct'], must_contain=value, name='color_mode') |
| 199 |
if value == 'direct': |
| 200 |
self.SetColorModeToDirectScalars() |
| 201 |
else: |
| 202 |
self.SetColorModeToMapScalars() |
| 203 |
|
| 204 |
@property |
| 205 |
def interpolate(self) -> bool: # numpydoc ignore=RT01 |
| 206 |
"""Return if interpolate is enabled or disabled. |
| 207 |
|
| 208 |
Examples |
| 209 |
-------- |
| 210 |
Show the masonry texture without interpolation. Here, we zoom to show |
| 211 |
the individual pixels. |
| 212 |
|
| 213 |
>>> from pyvista import examples |
| 214 |
>>> texture = examples.download_masonry_texture() |
| 215 |
>>> texture.interpolate = False |
| 216 |
>>> texture.plot(cpos='xy', zoom=3) |
| 217 |
|
| 218 |
Plot the same texture with interpolation. |
| 219 |
|
| 220 |
>>> texture.interpolate = True |
| 221 |
>>> texture.plot(cpos='xy', zoom=3) |
| 222 |
|
| 223 |
""" |
| 224 |
return bool(self.GetInterpolate()) |
| 225 |
|
| 226 |
@interpolate.setter |
| 227 |
def interpolate(self, value: bool): |
| 228 |
self.SetInterpolate(value) |
| 229 |
|
| 230 |
@property |
| 231 |
def mipmap(self) -> bool: # numpydoc ignore=RT01 |
| 232 |
"""Return if mipmap is enabled or disabled.""" |
| 233 |
return bool(self.GetMipmap()) |
| 234 |
|
| 235 |
@mipmap.setter |
| 236 |
def mipmap(self, value: bool): |
| 237 |
self.SetMipmap(value) |
| 238 |
|
| 239 |
def _from_image_data(self, image): |
| 240 |
if not isinstance(image, pv.ImageData): |
| 241 |
image = pv.ImageData(image) |
| 242 |
self.SetInputDataObject(image) |
| 243 |
self.Update() |
| 244 |
|
| 245 |
def _from_array(self, image): |
| 246 |
"""Create a texture from a np.ndarray.""" |
| 247 |
if image.ndim not in [2, 3]: |
| 248 |
# we support 2 [single component image] or 3 [e.g. rgb or rgba] dims |
| 249 |
msg = 'Input image must be nn by nm by RGB[A]' |
| 250 |
raise ValueError(msg) |
| 251 |
|
| 252 |
if image.ndim == 3: |
| 253 |
if image.shape[2] not in [1, 3, 4]: |
| 254 |
msg = 'Third dimension of the array must be of size 3 (RGB) or 4 (RGBA)' |
| 255 |
raise ValueError(msg) |
| 256 |
n_components = image.shape[2] |
| 257 |
elif image.ndim == 2: |
| 258 |
n_components = 1 |
| 259 |
|
| 260 |
grid = pv.ImageData(dimensions=(image.shape[1], image.shape[0], 1)) |
| 261 |
grid.point_data['Image'] = np.flip(image.swapaxes(0, 1), axis=1).reshape( |
| 262 |
(-1, n_components), |
| 263 |
order='F', |
| 264 |
) |
| 265 |
grid.set_active_scalars('Image') |
| 266 |
self._from_image_data(grid) |
| 267 |
|
| 268 |
@property |
| 269 |
def repeat(self) -> bool: # numpydoc ignore=RT01 |
| 270 |
"""Repeat the texture. |
| 271 |
|
| 272 |
This is provided for convenience and backwards compatibility. |
| 273 |
|
| 274 |
For new code, use :func:`Texture.wrap`. |
| 275 |
|
| 276 |
Examples |
| 277 |
-------- |
| 278 |
Load the masonry texture and create a simple :class:`pyvista.PolyData` |
| 279 |
with texture coordinates using :func:`pyvista.Plane`. By default the |
| 280 |
texture coordinates are between 0 and 1. Let's raise these values over |
| 281 |
1 by multiplying them in place. This will allow us to wrap the texture. |
| 282 |
|
| 283 |
>>> import pyvista as pv |
| 284 |
>>> from pyvista import examples |
| 285 |
>>> texture = examples.download_masonry_texture() |
| 286 |
>>> plane = pv.Plane() |
| 287 |
>>> plane.active_texture_coordinates *= 2 |
| 288 |
|
| 289 |
This is the texture plotted with repeat set to ``False``. |
| 290 |
|
| 291 |
>>> texture.repeat = False |
| 292 |
>>> pl = pv.Plotter() |
| 293 |
>>> actor = pl.add_mesh(plane, texture=texture) |
| 294 |
>>> pl.camera.zoom('tight') |
| 295 |
>>> pl.show() |
| 296 |
|
| 297 |
This is the texture plotted with repeat set to ``True``. |
| 298 |
|
| 299 |
>>> texture.repeat = True |
| 300 |
>>> pl = pv.Plotter() |
| 301 |
>>> actor = pl.add_mesh(plane, texture=texture) |
| 302 |
>>> pl.camera.zoom('tight') |
| 303 |
>>> pl.show() |
| 304 |
|
| 305 |
""" |
| 306 |
return bool(self.GetRepeat()) |
| 307 |
|
| 308 |
@repeat.setter |
| 309 |
def repeat(self, flag: bool): |
| 310 |
self.SetRepeat(flag) |
| 311 |
|
| 312 |
def flip_x(self) -> Texture: |
| 313 |
"""Flip the texture in the x direction. |
| 314 |
|
| 315 |
Returns |
| 316 |
------- |
| 317 |
pyvista.Texture |
| 318 |
Flipped texture. |
| 319 |
|
| 320 |
Examples |
| 321 |
-------- |
| 322 |
>>> from pyvista import examples |
| 323 |
>>> texture = examples.download_puppy_texture() |
| 324 |
>>> flipped = texture.flip_x() |
| 325 |
>>> flipped.plot() |
| 326 |
|
| 327 |
""" |
| 328 |
return Texture(self.to_image()._flip_uniform(0)) # type: ignore[abstract] |
| 329 |
|
| 330 |
def flip_y(self) -> Texture: |
| 331 |
"""Flip the texture in the y direction. |
| 332 |
|
| 333 |
Returns |
| 334 |
------- |
| 335 |
pyvista.Texture |
| 336 |
Flipped texture. |
| 337 |
|
| 338 |
Examples |
| 339 |
-------- |
| 340 |
>>> from pyvista import examples |
| 341 |
>>> texture = examples.download_puppy_texture() |
| 342 |
>>> flipped = texture.flip_y() |
| 343 |
>>> flipped.plot() |
| 344 |
|
| 345 |
""" |
| 346 |
return Texture(self.to_image()._flip_uniform(1)) # type: ignore[abstract] |
| 347 |
|
| 348 |
def to_image(self): |
| 349 |
"""Return the texture as an image. |
| 350 |
|
| 351 |
Returns |
| 352 |
------- |
| 353 |
pyvista.ImageData |
| 354 |
Texture represented as a uniform grid. |
| 355 |
|
| 356 |
""" |
| 357 |
return self.GetInput() |
| 358 |
|
| 359 |
def to_array(self) -> NumpyArray[float]: |
| 360 |
"""Return the texture as an array. |
| 361 |
|
| 362 |
Notes |
| 363 |
----- |
| 364 |
The shape of the array's first two dimensions will be swapped. For |
| 365 |
example, a ``(300, 200)`` image will return an array of ``(200, 300)``. |
| 366 |
|
| 367 |
Returns |
| 368 |
------- |
| 369 |
numpy.ndarray |
| 370 |
Texture as a numpy array. |
| 371 |
|
| 372 |
Examples |
| 373 |
-------- |
| 374 |
>>> from pyvista import examples |
| 375 |
>>> texture = examples.download_puppy_texture() |
| 376 |
>>> texture |
| 377 |
Texture (...) |
| 378 |
Components: 3 |
| 379 |
Cube Map: False |
| 380 |
Dimensions: 1600, 1200 |
| 381 |
>>> texture.to_array().shape |
| 382 |
(1200, 1600, 3) |
| 383 |
>>> texture.to_array().dtype |
| 384 |
dtype('uint8') |
| 385 |
|
| 386 |
""" |
| 387 |
return self.to_image().active_scalars.reshape( |
| 388 |
[*list(self.dimensions)[::-1], self.n_components] |
| 389 |
)[::-1] |
| 390 |
|
| 391 |
def rotate_cw(self) -> Texture: |
| 392 |
"""Rotate this texture 90 degrees clockwise. |
| 393 |
|
| 394 |
Returns |
| 395 |
------- |
| 396 |
pyvista.Texture |
| 397 |
Rotated texture. |
| 398 |
|
| 399 |
Examples |
| 400 |
-------- |
| 401 |
>>> from pyvista import examples |
| 402 |
>>> texture = examples.download_puppy_texture() |
| 403 |
>>> rotated = texture.rotate_cw() |
| 404 |
>>> rotated.plot() |
| 405 |
|
| 406 |
""" |
| 407 |
return Texture(np.rot90(self.to_array())) # type: ignore[abstract] |
| 408 |
|
| 409 |
def rotate_ccw(self) -> Texture: |
| 410 |
"""Rotate this texture 90 degrees counter-clockwise. |
| 411 |
|
| 412 |
Returns |
| 413 |
------- |
| 414 |
pyvista.Texture |
| 415 |
Rotated texture. |
| 416 |
|
| 417 |
Examples |
| 418 |
-------- |
| 419 |
>>> from pyvista import examples |
| 420 |
>>> texture = examples.download_puppy_texture() |
| 421 |
>>> rotated = texture.rotate_ccw() |
| 422 |
>>> rotated.plot() |
| 423 |
|
| 424 |
""" |
| 425 |
return Texture(np.rot90(self.to_array(), k=3)) # type: ignore[abstract] |
| 426 |
|
| 427 |
@property |
| 428 |
def cube_map(self) -> bool: # numpydoc ignore=RT01 |
| 429 |
"""Return ``True`` if cube mapping is enabled and ``False`` otherwise.""" |
| 430 |
return self.GetCubeMap() |
| 431 |
|
| 432 |
@cube_map.setter |
| 433 |
def cube_map(self, flag: bool): |
| 434 |
self.SetCubeMap(flag) |
| 435 |
|
| 436 |
def copy(self): # type: ignore[override] |
| 437 |
"""Make a copy of this texture. |
| 438 |
|
| 439 |
Returns |
| 440 |
------- |
| 441 |
pyvista.Texture |
| 442 |
Copied texture. |
| 443 |
|
| 444 |
""" |
| 445 |
return Texture(self.to_image().copy()) # type: ignore[abstract] |
| 446 |
|
| 447 |
def to_skybox( |
| 448 |
self, |
| 449 |
*, |
| 450 |
projection: Literal['auto', 'cube', 'sphere'] = 'auto', |
| 451 |
floor_plane: Sequence[float] | None = None, |
| 452 |
floor_right: Sequence[float] | None = None, |
| 453 |
): |
| 454 |
"""Return the texture as a :vtk:`vtkSkybox`. |
| 455 |
|
| 456 |
Cubemap textures default to cube-map projection. Non-cubemap textures |
| 457 |
default to spherical projection so equirectangular environment textures |
| 458 |
can also be shown as skyboxes. |
| 459 |
|
| 460 |
.. versionchanged:: 0.48 |
| 461 |
|
| 462 |
Non-cubemap textures now return a skybox using spherical |
| 463 |
projection by default. Optional floor orientation parameters were |
| 464 |
also added. |
| 465 |
|
| 466 |
Parameters |
| 467 |
---------- |
| 468 |
projection : {'auto', 'cube', 'sphere'}, default: 'auto' |
| 469 |
Skybox projection mode. ``'auto'`` selects ``'cube'`` for cubemap |
| 470 |
textures and ``'sphere'`` otherwise. |
| 471 |
|
| 472 |
floor_plane : sequence[float], optional |
| 473 |
Floor plane for the skybox as ``(nx, ny, nz, d)``. This can be |
| 474 |
used to orient equirectangular environments in scenes with a |
| 475 |
custom up direction. |
| 476 |
|
| 477 |
floor_right : sequence[float], optional |
| 478 |
Right direction for the floor plane as ``(x, y, z)``. |
| 479 |
|
| 480 |
Returns |
| 481 |
------- |
| 482 |
:vtk:`vtkSkybox` |
| 483 |
Skybox actor. |
| 484 |
|
| 485 |
""" |
| 486 |
_validation.check_contains( |
| 487 |
['auto', 'cube', 'sphere'], |
| 488 |
must_contain=projection, |
| 489 |
name='projection', |
| 490 |
) |
| 491 |
|
| 492 |
if projection == 'auto': |
| 493 |
projection = 'cube' if self.cube_map else 'sphere' |
| 494 |
elif projection == 'cube' and not self.cube_map: |
| 495 |
msg = 'Cube projection requires a cubemap texture.' |
| 496 |
raise ValueError(msg) |
| 497 |
|
| 498 |
skybox = _vtk.vtkSkybox() |
| 499 |
skybox.SetTexture(self) |
| 500 |
if projection == 'cube': |
| 501 |
skybox.SetProjectionToCube() |
| 502 |
else: |
| 503 |
skybox.SetProjectionToSphere() |
| 504 |
|
| 505 |
if floor_plane is not None: |
| 506 |
valid_floor_plane = _validation.validate_array( |
| 507 |
floor_plane, |
| 508 |
must_have_shape=4, |
| 509 |
dtype_out=float, |
| 510 |
to_tuple=True, |
| 511 |
name='floor_plane', |
| 512 |
) |
| 513 |
skybox.SetFloorPlane(*valid_floor_plane) |
| 514 |
|
| 515 |
if floor_right is not None: |
| 516 |
valid_floor_right = _validation.validate_array3( |
| 517 |
floor_right, |
| 518 |
dtype_out=float, |
| 519 |
to_tuple=True, |
| 520 |
name='floor_right', |
| 521 |
) |
| 522 |
skybox.SetFloorRight(*valid_floor_right) |
| 523 |
|
| 524 |
return skybox |
| 525 |
|
| 526 |
def __repr__(self): |
| 527 |
"""Return the object representation.""" |
| 528 |
return pv.DataSet.__repr__(self) # type: ignore[type-var] |
| 529 |
|
| 530 |
def _get_attrs(self): |
| 531 |
"""Return the representation methods (internal helper).""" |
| 532 |
attrs = [] |
| 533 |
attrs.append(('Components', self.n_components, '{:d}')) |
| 534 |
attrs.append(('Cube Map', self.cube_map, '{:}')) |
| 535 |
attrs.append(('Dimensions', self.dimensions, '{:d}, {:d}')) # type: ignore[arg-type] |
| 536 |
return attrs |
| 537 |
|
| 538 |
@property |
| 539 |
def n_components(self) -> int: # numpydoc ignore=RT01 |
| 540 |
"""Return the number of components in the image. |
| 541 |
|
| 542 |
In textures, 3 or 4 components are used for representing RGB and RGBA |
| 543 |
images. |
| 544 |
|
| 545 |
Examples |
| 546 |
-------- |
| 547 |
Show the number of components in the example masonry texture. |
| 548 |
|
| 549 |
>>> from pyvista import examples |
| 550 |
>>> texture = examples.download_masonry_texture() |
| 551 |
>>> texture.n_components |
| 552 |
3 |
| 553 |
|
| 554 |
""" |
| 555 |
input_data = self.GetInput() |
| 556 |
if input_data is None: |
| 557 |
return 0 |
| 558 |
return input_data.GetPointData().GetScalars().GetNumberOfComponents() |
| 559 |
|
| 560 |
@property |
| 561 |
def dimensions(self) -> tuple[int, int]: # numpydoc ignore=RT01 |
| 562 |
"""Dimensions of the texture. |
| 563 |
|
| 564 |
Examples |
| 565 |
-------- |
| 566 |
>>> from pyvista import examples |
| 567 |
>>> texture = examples.download_masonry_texture() |
| 568 |
>>> texture.dimensions |
| 569 |
(256, 256) |
| 570 |
|
| 571 |
""" |
| 572 |
input_data = self.GetInput() |
| 573 |
if input_data is None: |
| 574 |
return (0, 0) |
| 575 |
return input_data.GetDimensions()[:2] |
| 576 |
|
| 577 |
def plot(self, **kwargs): |
| 578 |
"""Plot the texture as an image. |
| 579 |
|
| 580 |
If the texture is a cubemap, it will be displayed as a skybox with a |
| 581 |
sphere in the center reflecting the environment. |
| 582 |
|
| 583 |
Parameters |
| 584 |
---------- |
| 585 |
**kwargs : dict, optional |
| 586 |
Optional keyworld arguments. See :func:`pyvista.plot`. |
| 587 |
|
| 588 |
Returns |
| 589 |
------- |
| 590 |
output : pyvista.Actor | None |
| 591 |
See the returns section of :func:`pyvista.plot`. |
| 592 |
|
| 593 |
Examples |
| 594 |
-------- |
| 595 |
Plot a simple texture. |
| 596 |
|
| 597 |
>>> from pyvista import examples |
| 598 |
>>> texture = examples.download_masonry_texture() |
| 599 |
>>> texture.plot() |
| 600 |
|
| 601 |
Plot a cubemap as a skybox. |
| 602 |
|
| 603 |
>>> cube_map = examples.download_sky_box_cube_map() |
| 604 |
>>> cube_map.plot() |
| 605 |
|
| 606 |
""" |
| 607 |
if self.cube_map: |
| 608 |
return self._plot_skybox(**kwargs) |
| 609 |
kwargs.setdefault('zoom', 'tight') |
| 610 |
kwargs.setdefault('lighting', False) |
| 611 |
kwargs.setdefault('show_axes', False) |
| 612 |
kwargs.setdefault('show_scalar_bar', False) |
| 613 |
mesh = pv.Plane(i_size=self.dimensions[0], j_size=self.dimensions[1]) |
| 614 |
return mesh.plot(texture=self, **kwargs) |
| 615 |
|
| 616 |
def _plot_skybox(self, **kwargs): |
| 617 |
"""Plot this texture as a skybox.""" |
| 618 |
cpos = kwargs.pop('cpos', 'xy') |
| 619 |
zoom = kwargs.pop('zoom', 0.5) |
| 620 |
show_axes = kwargs.pop('show_axes', True) |
| 621 |
lighting = kwargs.pop('lighting', None) |
| 622 |
pl = pv.Plotter(lighting=lighting) |
| 623 |
pl.add_actor(self.to_skybox()) |
| 624 |
pl.set_environment_texture(self, is_srgb=True) |
| 625 |
pl.add_mesh(pv.Sphere(), pbr=True, roughness=0.5, metallic=1.0) |
| 626 |
pl.camera_position = cpos |
| 627 |
pl.camera.zoom(zoom) |
| 628 |
if show_axes: |
| 629 |
pl.show_axes() |
| 630 |
pl.show(**kwargs) |
| 631 |
|
| 632 |
@property |
| 633 |
def wrap(self) -> Texture.WrapType: # numpydoc ignore=RT01 |
| 634 |
"""Return or set the Wrap mode for the texture coordinates. |
| 635 |
|
| 636 |
Wrap mode for the texture coordinates valid values are: |
| 637 |
|
| 638 |
* ``0`` - CLAMP_TO_EDGE |
| 639 |
* ``1`` - REPEAT |
| 640 |
* ``2`` - MIRRORED_REPEAT |
| 641 |
* ``3`` - CLAMP_TO_BORDER |
| 642 |
|
| 643 |
Notes |
| 644 |
----- |
| 645 |
CLAMP_TO_BORDER is not supported with OpenGL ES <= 3.2. Wrap will |
| 646 |
default to CLAMP_TO_EDGE if it is set to CLAMP_TO_BORDER in this case. |
| 647 |
|
| 648 |
Requires ``vtk`` v9.1.0 or newer. |
| 649 |
|
| 650 |
Examples |
| 651 |
-------- |
| 652 |
Load the masonry texture and create a simple :class:`pyvista.PolyData` |
| 653 |
with texture coordinates using :func:`pyvista.Plane`. By default the |
| 654 |
texture coordinates are between 0 and 1. Let's raise these values over |
| 655 |
1 by multiplying them in place. This will allow us to wrap the texture. |
| 656 |
|
| 657 |
>>> import pyvista as pv |
| 658 |
>>> from pyvista import examples |
| 659 |
>>> texture = examples.download_masonry_texture() |
| 660 |
>>> plane = pv.Plane() |
| 661 |
>>> plane.active_texture_coordinates *= 2 |
| 662 |
|
| 663 |
Let's now set the texture wrap to clamp to edge and visualize it. |
| 664 |
|
| 665 |
>>> texture.wrap = pv.Texture.WrapType.CLAMP_TO_EDGE |
| 666 |
>>> pl = pv.Plotter() |
| 667 |
>>> actor = pl.add_mesh(plane, texture=texture) |
| 668 |
>>> pl.camera.zoom('tight') |
| 669 |
>>> pl.show() |
| 670 |
|
| 671 |
Here is the default repeat: |
| 672 |
|
| 673 |
>>> texture.wrap = pv.Texture.WrapType.REPEAT |
| 674 |
>>> pl = pv.Plotter() |
| 675 |
>>> actor = pl.add_mesh(plane, texture=texture) |
| 676 |
>>> pl.camera.zoom('tight') |
| 677 |
>>> pl.show() |
| 678 |
|
| 679 |
And here is mirrored repeat: |
| 680 |
|
| 681 |
>>> texture.wrap = pv.Texture.WrapType.MIRRORED_REPEAT |
| 682 |
>>> pl = pv.Plotter() |
| 683 |
>>> actor = pl.add_mesh(plane, texture=texture) |
| 684 |
>>> pl.camera.zoom('tight') |
| 685 |
>>> pl.show() |
| 686 |
|
| 687 |
Finally, this is clamp to border: |
| 688 |
|
| 689 |
>>> texture.wrap = pv.Texture.WrapType.CLAMP_TO_BORDER |
| 690 |
>>> pl = pv.Plotter() |
| 691 |
>>> actor = pl.add_mesh(plane, texture=texture) |
| 692 |
>>> pl.camera.zoom('tight') |
| 693 |
>>> pl.show() |
| 694 |
|
| 695 |
""" |
| 696 |
if not hasattr(self, 'GetWrap'): # pragma: no cover |
| 697 |
from pyvista.core.errors import VTKVersionError # noqa: PLC0415 |
| 698 |
|
| 699 |
msg = '`wrap` requires VTK v9.1.0 or newer.' |
| 700 |
raise VTKVersionError(msg) |
| 701 |
|
| 702 |
return Texture.WrapType(self.GetWrap()) # type: ignore[call-arg] |
| 703 |
|
| 704 |
@wrap.setter |
| 705 |
def wrap(self, value: Texture.WrapType | int): |
| 706 |
if not hasattr(self, 'SetWrap'): # pragma: no cover |
| 707 |
from pyvista.core.errors import VTKVersionError # noqa: PLC0415 |
| 708 |
|
| 709 |
msg = '`wrap` requires VTK v9.1.0 or newer.' |
| 710 |
raise VTKVersionError(msg) |
| 711 |
|
| 712 |
self.SetWrap(value) |
| 713 |
|
| 714 |
def to_grayscale(self) -> Texture: |
| 715 |
"""Convert this texture as a single component (grayscale) texture. |
| 716 |
|
| 717 |
Returns |
| 718 |
------- |
| 719 |
pyvista.Texture |
| 720 |
Texture converted to grayscale. If already grayscale, the original |
| 721 |
texture itself is returned. |
| 722 |
|
| 723 |
Notes |
| 724 |
----- |
| 725 |
The transparency channel (if available) will be dropped. |
| 726 |
|
| 727 |
Follows the `CCIR 601 <https://en.wikipedia.org/wiki/Rec._601>`_ luma |
| 728 |
calculation equation of ``Y = 0.299*R + 0.587*G + 0.114*B``. |
| 729 |
|
| 730 |
Examples |
| 731 |
-------- |
| 732 |
>>> from pyvista import examples |
| 733 |
>>> texture = examples.download_masonry_texture() |
| 734 |
>>> bw_texture = texture.to_grayscale() |
| 735 |
>>> bw_texture |
| 736 |
Texture (...) |
| 737 |
Components: 1 |
| 738 |
Cube Map: False |
| 739 |
Dimensions: 256, 256 |
| 740 |
>>> bw_texture.plot() |
| 741 |
|
| 742 |
""" |
| 743 |
if self.n_components == 1: |
| 744 |
return self.copy() |
| 745 |
|
| 746 |
data = self.to_array() |
| 747 |
r, g, b = data[..., 0], data[..., 1], data[..., 2] |
| 748 |
data = (0.299 * r + 0.587 * g + 0.114 * b).round().astype(np.uint8) |
| 749 |
return Texture(data) # type: ignore[abstract] |
| 750 |
|
| 751 |
|
| 752 |
def image_to_texture(image): |
| 753 |
"""Convert :class:`pyvista.ImageData` to a :class:`pyvista.Texture`. |
| 754 |
|
| 755 |
Parameters |
| 756 |
---------- |
| 757 |
image : pyvista.ImageData | :vtk:`vtkImageData` |
| 758 |
Image to convert. |
| 759 |
|
| 760 |
Returns |
| 761 |
------- |
| 762 |
pyvista.Texture |
| 763 |
The texture. |
| 764 |
|
| 765 |
""" |
| 766 |
return Texture(image) # type: ignore[abstract] |
| 767 |
|
| 768 |
|
| 769 |
def numpy_to_texture(image): |
| 770 |
"""Convert a NumPy image array to a :class:`pyvista.Texture`. |
| 771 |
|
| 772 |
Parameters |
| 773 |
---------- |
| 774 |
image : numpy.ndarray |
| 775 |
Numpy image array. Texture datatype expected to be ``np.uint8``. |
| 776 |
|
| 777 |
Returns |
| 778 |
------- |
| 779 |
pyvista.Texture |
| 780 |
PyVista texture. |
| 781 |
|
| 782 |
Examples |
| 783 |
-------- |
| 784 |
Create an all white texture. |
| 785 |
|
| 786 |
>>> import pyvista as pv |
| 787 |
>>> import numpy as np |
| 788 |
>>> tex_arr = np.ones((1024, 1024, 3), dtype=np.uint8) * 255 |
| 789 |
>>> tex = pv.numpy_to_texture(tex_arr) |
| 790 |
|
| 791 |
""" |
| 792 |
if image.dtype != np.uint8: |
| 793 |
image = image.astype(np.uint8) |
| 794 |
warn_external( |
| 795 |
'Expected `image` dtype to be ``np.uint8``. `image` has been copied ' |
| 796 |
'and converted to np.uint8.', |
| 797 |
UserWarning, |
| 798 |
) |
| 799 |
|
| 800 |
return Texture(image) # type: ignore[abstract] |