def test_texture(): texture = pyvista.Texture(examples.mapfile) assert texture is not None image = texture.to_image() assert isinstance(image, pyvista.UniformGrid) arr = texture.to_array() assert isinstance(arr, np.ndarray) assert arr.shape[0] * arr.shape[1] == image.n_points texture.flip(0) texture.flip(1) texture = pyvista.Texture(examples.load_globe_texture()) assert texture is not None
def read_texture(filename, attrs=None): """Load a ``vtkTexture`` from an image file.""" filename = os.path.abspath(os.path.expanduser(filename)) try: # initialize the reader using the extension to find it reader = get_reader(filename) image = standard_reader_routine(reader, filename, attrs=attrs) if image.n_points < 2: raise ValueError("Problem reading the image with VTK.") return pyvista.Texture(image) except (KeyError, ValueError): # Otherwise, use the imageio reader pass import imageio return pyvista.Texture(imageio.imread(filename))
def read_texture(filename, attrs=None): """Load a texture from an image file. Parameters ---------- filename : str The path of the texture file to read. attrs : dict, optional A dictionary of attributes to call on the reader. Keys of dictionary are the attribute/method names and values are the arguments passed to those calls. If you do not have any attributes to call, pass ``None`` as the value. Returns ------- pyvista.Texture PyVista texture object. Examples -------- Read in an example jpg map file as a texture. >>> import os >>> import pyvista >>> from pyvista import examples >>> os.path.basename(examples.mapfile) '2k_earth_daymap.jpg' >>> texture = pyvista.read_texture(examples.mapfile) >>> type(texture) <class 'pyvista.core.objects.Texture'> """ filename = os.path.abspath(os.path.expanduser(filename)) try: # initialize the reader using the extension to find it reader = get_vtk_reader(filename) image = standard_reader_routine(reader, filename, attrs=attrs) if image.n_points < 2: raise ValueError("Problem reading the image with VTK.") return pyvista.Texture(image) except (KeyError, ValueError): # Otherwise, use the imageio reader pass import imageio return pyvista.Texture(imageio.imread(filename))
def wrap_texture(texture: pv.Texture, central_meridian: Optional[float] = None) -> pv.Texture: """ Re-center the texture about the specified central meridian, wrapping the image appropriately. Assumes that the source of the texture has global coverage, is on the Geographic projection and uses the WGS84 datum, with square pixels and no rotation. Parameters ---------- texture : Texture The global texture to be re-centered. central_meridian : float, default=0.0 The meridian (degrees) that specifies the new center of the texture image. Returns ------- Texture The re-centered PyVista texture. Notes ----- .. versionadded:: 0.1.0 """ if central_meridian is None: central_meridian = 0.0 meridian = wrap(central_meridian)[0] if not np.isclose(meridian, 0): # get the texture as a pyvista.UniformGrid grid = texture.to_image() shape = (grid.dimensions[1], grid.dimensions[0], texture.n_components) # convert grid to an rgb image (un-do pyvista.Texture._from_array mangling) image = np.flip(grid.active_scalars.reshape(shape), axis=0) width, height = image.shape[1], image.shape[0] logger.debug("texture image width=%dpx, height=%dpx)", width, height) # calculate the rendering window over the tiled image centered around the meridian offset = int(np.round( ((meridian + 180) / 360) * width, decimals=0)) + width start = offset - (width // 2) end = start + width logger.debug("start=%dpx, meridian=%dpx, end=%dpx", start, offset, end) # horizontally tile the image (along the x-axis) tiled = np.concatenate([image, image, image], axis=1) # now extract the image based on the central meridian image = tiled[:, start:end] texture = pv.Texture(image) return texture
def numpy_to_texture(image): """Convert a NumPy image array to a vtk.vtkTexture. Parameters ---------- image : numpy.ndarray Numpy image array. Returns ------- vtkTexture VTK texture. """ return pyvista.Texture(image)
def image_to_texture(image): """Convert ``vtkImageData`` (:class:`pyvista.UniformGrid`) to a ``vtkTexture``. Parameters ---------- image : pyvista.UniformGrid or vtkImageData Image to convert. Returns ------- vtkTexture VTK texture. """ return pyvista.Texture(image)
def numpy_to_texture(image): """Convert a NumPy image array to a vtk.vtkTexture.""" return pyvista.Texture(image)
def image_to_texture(image): """Convert ``vtkImageData`` (:class:`pyvista.UniformGrid`) to a ``vtkTexture``.""" return pyvista.Texture(image)
def cubemap(path='', prefix='', ext='.jpg'): """Construct a cubemap from 6 images. Each of the 6 images must be in the following format: - <prefix>negx<ext> - <prefix>negy<ext> - <prefix>negz<ext> - <prefix>posx<ext> - <prefix>posy<ext> - <prefix>posz<ext> Prefix may be empty, and extension will default to ``'.jpg'`` For example, if you have 6 images with the skybox2 prefix: - ``'skybox2-negx.jpg'`` - ``'skybox2-negy.jpg'`` - ``'skybox2-negz.jpg'`` - ``'skybox2-posx.jpg'`` - ``'skybox2-posy.jpg'`` - ``'skybox2-posz.jpg'`` Parameters ---------- prefix : str, optional Prefix to the filename. ext : str, optional The filename extension. For example ``'.jpg'``. path : str, optional Directory containing the cubemap images. Returns ------- pyvista.Texture Texture with cubemap. Examples -------- >>> import pyvista >>> skybox = pyvista.cubemap('my_directory', 'skybox', '.jpeg') # doctest:+SKIP """ sets = ['posx', 'negx', 'posy', 'negy', 'posz', 'negz'] image_paths = [ os.path.join(path, f'{prefix}{suffix}{ext}') for suffix in sets ] for image_path in image_paths: if not os.path.isfile(image_path): file_str = '\n'.join(image_paths) raise FileNotFoundError(f'Unable to locate {image_path}\n' 'Expected to find the following files:\n' f'{file_str}') texture = pyvista.Texture() texture.cube_map = True # Must be set prior to setting images # add each image to the cubemap for i, fn in enumerate(image_paths): image = pyvista.read(fn) flip = _vtk.vtkImageFlip() flip.SetInputDataObject(image) flip.SetFilteredAxis(1) # flip y axis flip.Update() texture.SetInputDataObject(i, flip.GetOutput()) return texture
def numpy_to_texture(image): """Convert a NumPy image array to a vtk.vtkTexture.""" if not isinstance(image, np.ndarray): raise TypeError('Unknown input type ({})'.format(type(image))) return pyvista.Texture(image)
def read(filename, attrs=None, file_format=None): """Read any VTK file. It will figure out what reader to use then wrap the VTK object for use in PyVista. Parameters ---------- filename : str The string path to the file to read. If a list of files is given, a :class:`pyvista.MultiBlock` dataset is returned with each file being a separate block in the dataset. attrs : dict, optional A dictionary of attributes to call on the reader. Keys of dictionary are the attribute/method names and values are the arguments passed to those calls. If you do not have any attributes to call, pass ``None`` as the value. file_format : str, optional Format of file to read with meshio. Examples -------- Load an example mesh >>> import pyvista >>> from pyvista import examples >>> mesh = pyvista.read(examples.antfile) Load a vtk file >>> mesh = pyvista.read('my_mesh.vtk') # doctest:+SKIP Load a meshio file >>> mesh = pyvista.read("mesh.obj") # doctest:+SKIP """ if isinstance(filename, (list, tuple)): multi = pyvista.MultiBlock() for each in filename: if isinstance(each, (str, pathlib.Path)): name = os.path.basename(str(each)) else: name = None multi[-1, name] = read(each, attrs=attrs, file_format=file_format) return multi filename = os.path.abspath(os.path.expanduser(str(filename))) if not os.path.isfile(filename): raise FileNotFoundError(f'File ({filename}) not found') ext = get_ext(filename) # Read file using meshio.read if file_format is present if file_format: return read_meshio(filename, file_format) # From the extension, decide which reader to use if attrs is not None: reader = get_reader(filename) return standard_reader_routine(reader, filename, attrs=attrs) elif ext in '.vti': # ImageData return pyvista.UniformGrid(filename) elif ext in '.vtr': # RectilinearGrid return pyvista.RectilinearGrid(filename) elif ext in '.vtu': # UnstructuredGrid return pyvista.UnstructuredGrid(filename) elif ext in ['.ply', '.obj', '.stl']: # PolyData return pyvista.PolyData(filename) elif ext in '.vts': # StructuredGrid return pyvista.StructuredGrid(filename) elif ext in ['.vtm', '.vtmb', '.case']: return pyvista.MultiBlock(filename) elif ext in ['.e', '.exo']: return read_exodus(filename) elif ext in ['.vtk']: # Attempt to use the legacy reader... return read_legacy(filename) elif ext in ['.jpeg', '.jpg']: return pyvista.Texture(filename).to_image() else: # Attempt find a reader in the readers mapping try: reader = get_reader(filename) return standard_reader_routine(reader, filename) except KeyError: # Attempt read with meshio try: from meshio._exceptions import ReadError try: return read_meshio(filename) except ReadError: pass except SyntaxError: # https://github.com/pyvista/pyvista/pull/495 pass raise IOError("This file was not able to be automatically read by pyvista.")
from smalllib import generate_uv # %% from shapely.geometry import LineString, Point asls = LineString(upperv) uv = generate_uv(asls, upperv) # compute uv coordinates # %% # set the uv array in the polydata and get the image as a numpy array pol.t_coords = uv asarr = np.array(tx) # as an array # %% tx = Image.fromarray(asarr) tx.save("texture.png") text = pyvista.Texture(asarr) text.InterpolateOn() bp.add_mesh(pol, texture=text, ambient=0.8) # add to 3d pol.save("radargram.vtp") # %% from smalllib import save_mesh_and_texture_as_obj pol.points /= 1000 save_mesh_and_texture_as_obj("radargram.obj", pol, asarr) # %% # %%