def test_texture(): """Test adding texture coordinates""" # create a rectangle vertices vertices = np.array([ [0, 0, 0], [1, 0, 0], [1, 0.5, 0], [0, 0.5, 0], ]) # mesh faces faces = np.hstack([[3, 0, 1, 2], [3, 0, 3, 2]]).astype(np.int8) # Create simple texture coordinates t_coords = np.array([[0, 0], [1, 0], [1, 1], [0, 1]]) # Create the poly data mesh = pyvista.PolyData(vertices, faces) # Attempt setting the texture coordinates mesh.t_coords = t_coords # now grab the texture coordinates foo = mesh.t_coords assert np.allclose(foo, t_coords) texture = pyvista.read_texture(examples.mapfile) mesh.textures['map'] = texture assert mesh.textures['map'] is not None mesh.clear_textures() assert len(mesh.textures) == 0
def _fetch_texture(fname: str, location: Optional[bool] = False) -> TextureLike: """ Get the texture resource from cache. If the resource is not already available in the GeoVista :data:`CACHE`, then it will be downloaded from the :data:`BASE_URL`. Parameters ---------- fname : str The base file name of the resource, excluding any directory prefix. location : bool, default=False Determine whether the absolute path filename to the texture resource location within the cache is returned Returns ------- str or Texture The PyVista texture filename or the texture. Notes ----- .. versionadded:: 0.1.0 """ resource = CACHE.fetch(f"raster/{fname}") if not location: resource = pv.read_texture(resource) return resource
def test_read_obj(): obj = read_obj(config.obj_path) faces = obj['faces'] threes = np.full((faces.shape[0], 1), faces.shape[1]) faces = np.concatenate((threes, faces), axis=1) mesh = pv.PolyData(obj['vertices'], faces) mesh.t_coords = obj['vertex_texture_coords'] texture = pv.read_texture(config.texture_path) mesh.plot(texture=texture)
def __init__(self, *args, **kwargs): if len(args) == 1: if isinstance(args[0], vtk.vtkTexture): self._from_texture(args[0]) elif isinstance(args[0], np.ndarray): self._from_array(args[0]) elif isinstance(args[0], vtk.vtkImageData): self._from_image_data(args[0]) elif isinstance(args[0], str): self._from_texture(pyvista.read_texture(args[0])) else: raise TypeError('Table unable to be made from ({})'.format(type(args[0])))
def animate(self, movement, f=None, index_col=0, index_row=0, texture=None, cmap='jet', plotter=None, title='', font_size=10, font_color='black', gif_path=None, camera=None): """ animate the mash using movement as movement metrix press "q" after adjusting the frame to start the animation Args: movement: tuple of V side vector as elements, (hull_movement,tip_movement) f: map between (x,y,z) of vertex to scalar for the color map index_row: chosen subplot row index_col: chosen subplot column texture: the texture to use cmap: the colormap to use plotter: the pyvista plotter title: the title of the figure font_size: the font size of the title font_color: the color of the font for the title gif_path: gif path to create, None if no gif is needed camera: the [camera position , focal point, view up] each (x,y,z) tuple Returns: None """ if not plotter: plotter = pv.Plotter() plotter.subplot(index_column=index_col, index_row=index_row) plotter.add_text(title, position="upper_edge", font_size=font_size, color=font_color) if camera is not None: # it gives .any() crushes without.. plotter.set_position(camera[0]) plotter.set_focus(camera[1]) plotter.set_viewup(camera[2]) if not texture: plotter.add_mesh(self.pv_mesh, scalars=f, cmap=cmap, texture=texture) else: if isinstance(texture, np.ndarray): tex = pv.numpy_to_texture(texture) else: tex = pv.read_texture(texture) self.pv_mesh.texture_map_to_plane(inplace=True) plotter.add_mesh(self.pv_mesh, texture=tex) plotter.show(auto_close=False) if gif_path: plotter.open_gif(gif_path) for item in movement: plotter.update_coordinates(item, mesh=self.pv_mesh) if gif_path: plotter.write_frame() plotter.close()
def load_globe_texture(): """Load a vtk.vtkTexture that can be applied to the globe source. Returns ------- pyvista.Texture Dataset. Examples -------- >>> from pyvista import examples >>> dataset = examples.load_globe_texture() >>> dataset.plot() """ return pyvista.read_texture(mapfile)
def __init__(self, *args, **kwargs): """Initialize the texture.""" assert_empty_kwargs(**kwargs) if len(args) == 1: if isinstance(args[0], vtk.vtkTexture): self._from_texture(args[0]) elif isinstance(args[0], np.ndarray): self._from_array(args[0]) elif isinstance(args[0], vtk.vtkImageData): self._from_image_data(args[0]) elif isinstance(args[0], str): self._from_texture(pyvista.read_texture(args[0])) else: raise TypeError( f'Table unable to be made from ({type(args[0])})')
def plot_faces(self, f=None, index_row=0, index_col=0, show=True, plotter=None, cmap='jet', title=None, title_location="upper_edge", font_size=10, font_color='black', texture=None, camera=None): """ plots the faces of the Mesh Args: f: map between (x,y,z) of vertex to scalar for the color map index_row: chosen subplot row index_col: chosen subplot column show: should the function call imshow() plotter: the pyvista plotter cmap: the color map to use title: the title of the figure title_location: title location font_size: the font size of the title font_color: the color of the font for the title texture: the filename for the texture of the figure or np array camera: the [camera position , focal point, view up] each (x,y,z) tuple Returns: the pyvista plotter """ if not plotter: plotter = pv.Plotter() plotter.subplot(index_column=index_col, index_row=index_row) if title: plotter.add_text(title, position=title_location, font_size=font_size, color=font_color) if camera is not None: plotter.set_position(camera[0]) plotter.set_focus(camera[1]) plotter.set_viewup(camera[2]) if self.texture: plotter.add_mesh(self.pv_mesh, texture=self.texture) elif texture is None: plotter.add_mesh(self.pv_mesh, scalars=f, cmap=cmap, texture=texture, show_scalar_bar=False) else: if isinstance(texture, np.ndarray): tex = pv.numpy_to_texture(texture) else: tex = pv.read_texture(texture) self.pv_mesh.texture_map_to_plane(inplace=True) plotter.add_mesh(self.pv_mesh, texture=tex) if show: plotter.show() return plotter
def test_texture_airplane(): mesh = examples.load_airplane() mesh.texture_map_to_plane(inplace=True, name="tex_a", use_bounds=False) mesh.texture_map_to_plane(inplace=True, name="tex_b", use_bounds=True) assert not np.allclose(mesh["tex_a"], mesh["tex_b"]) texture = pyvista.read_texture(examples.mapfile) mesh.textures["tex_a"] = texture.copy() mesh.textures["tex_b"] = texture.copy() mesh._activate_texture("tex_a") assert np.allclose(mesh.t_coords, mesh["tex_a"]) mesh._activate_texture("tex_b") assert np.allclose(mesh.t_coords, mesh["tex_b"]) # Now test copying cmesh = mesh.copy() assert len(cmesh.textures) == 2 assert "tex_a" in cmesh.textures assert "tex_b" in cmesh.textures
def plot_projection(self, normal=(1, 1, 1), index_row=0, index_col=0, show=True, texture=None, cmap="jet", f=None, plotter=None, title='', font_size=10, font_color='black'): """ plots the projection of the Mesh Args: normal: the normal of the projected image index_row: chosen subplot row index_col: chosen subplot column show: should the function call imshow() texture: the texture to use cmap: the color map to use f: the color for each vertex or face. plotter: the pyvista plotter title: the title of the figure font_size: the font size of the title font_color: the color of the font for the title Returns: the pyvista plotter """ if not plotter: plotter = pv.Plotter() plotter.subplot(index_column=index_col, index_row=index_row) plotter.add_text(title, position="upper_edge", font_size=font_size, color=font_color) tex = None if texture: if isinstance(texture, np.ndarray): tex = pv.numpy_to_texture(texture) else: tex = pv.read_texture(texture) self.pv_mesh.texture_map_to_plane(inplace=True) # plotter.add_mesh(pv_mesh, texture=tex) og = self.pv_mesh.center projected = self.pv_mesh.project_points_to_plane(origin=og, normal=normal) projected.texture_map_to_plane() plotter.add_mesh(projected, texture=tex) if show: plotter.show() return plotter
def __init__(self, path, texture=None): """ Constructor Args: path: path to .off file """ data = read_off(path) self.vertices = data[0] self.faces = data[1] self.table = data[2] adj_set = set() self.pv_mesh = None for face in self.faces: for a, b in zip(face[:-1], face[1:]): adj_set.add((min(a, b), max(a, b))) adj_set.add((min(face[-1], face[0]), max(face[-1], face[0]))) adj_np_arr = np.array(list(adj_set)) x = adj_np_arr[:, 0] y = adj_np_arr[:, 1] values = np.ones(len(x)) self.adj = csr_matrix((values, (x, y)), shape=(len(self.vertices), len(self.vertices))) self.corners = defaultdict(set) for idx, face in enumerate(self.faces): for v in face: self.corners[v].add(idx) self.corners = {k: np.fromiter(v, int, len(v)) for (k, v) in self.corners.items()} pv_styled_faces = np.insert(self.faces, 0, 3, axis=1) # mesh in pyvista format self.pv_mesh = pv.PolyData(self.vertices, pv_styled_faces) if texture: self.pv_mesh.texture_map_to_plane(inplace=True, use_bounds=1) self.texture = pv.read_texture(texture) else: self.texture = None
def sphere(update: Update, context: CallbackContext) -> None: photos = update.message.photo best_photo = None for photo in photos: if best_photo is None or best_photo['width'] * best_photo['height'] < photo['width'] * photo['height']: best_photo = photo logger.info(f'Photo from {update.message.from_user.full_name} aka @{update.message.from_user.username} ' f'({best_photo["height"]}x{best_photo["width"]})') image_bytes = best_photo.get_file().download_as_bytearray() image = Image.open(io.BytesIO(image_bytes)).transpose(Image.FLIP_LEFT_RIGHT) image.save('orig.png') tex = pv.read_texture('orig.png') sphere_surf = pv.Sphere() sphere_surf.texture_map_to_sphere(inplace=True) sphere_surf.plot(texture=tex, screenshot='sphere.png', interactive=False, off_screen=True, background=(0, 0, 0, 0), cpos=[(0, 2, 0), (0, 1, 0), (0, 0, -1)], show_axes=False, lighting=False, window_size=(640, 640)) update.message.reply_photo(photo=open('sphere.png', 'rb'))
def load_nbt_file_plot(nbt_file): NBT_FILE = nbt_file # Loading Gravel Path (A lot faster) block_data, nbt_struct = extract_nbt_blocks(NBT_FILE) # Use glyphs to generate meshes for each block type # create a basic (1 x 1 x 1) cube cube = pv.Cube() blocks = {} poly_meshes = {} for block_type in block_data: # create a "point cloud" containing the centers of every cube new_points = np.array(block_data[block_type]) mesh = pv.PolyData(new_points) poly_meshes.update({block_type: mesh}) # use a glyph filter to create a cube at each point in polydata glyphs = mesh.glyph(geom=cube) glyphs.textures[block_type] = pv.read_texture(texture_dict[block_type]) blocks.update({block_type: glyphs}) ############################################################################### # Plot # Use 3 lights because it's a bit brighter pl.background_color = 'w' pl.enable_3_lights() # we have to add block types one at a type since it seems we can only # apply one texture per block type. This may complicate things with complicated or mixed block types. picker = Picker(pl, blocks, poly_meshes, ordered_points) pl.track_click_position(picker, side='right') for mesh in blocks.values(): pl.add_mesh(mesh) add_actors, block_add_manager = add_block_extras(pl, block_data) picker.add_actors = add_actors picker.add_manager = block_add_manager picker.texture_dict = texture_dict # Save NBT Functionality nbt_save_callback = SaveNBTCallback(nbt_struct, NBT_FILE, picker) # Add checkbox widget # New checkbox manager master_checkbox = CheckboxManager(picker) # Delete pl.add_checkbox_button_widget(ToggleModeCallback(1, master_checkbox), position=(10.0, 10.0), value=False, color_off='grey', color_on='red') pl.add_text("Del", position=(18.0, 25.0), font_size=9) # Add pl.add_checkbox_button_widget(ToggleModeCallback(2, master_checkbox), position=(10.0, 70.0), value=False, color_off='grey', color_on='green') pl.add_text("Add", position=(15.0, 85.0), font_size=9) # Publish pl.add_checkbox_button_widget(nbt_save_callback, position=(10.0, 130.0), value=False, color_off='grey', color_on='yellow', size=60) pl.add_text("Save", position=(17.0, 148.0), font_size=9)
# use the puppy image tex = examples.download_puppy_texture() curvsurf.plot(texture=tex) ############################################################################### # Textures from Files # +++++++++++++++++++ # # What about loading your own texture from an image? This is often most easily # done using the :func:`pyvista.read_texture` function - simply pass an image # file's path, and this function with handle making a ``vtkTexture`` for you to # use. image_file = examples.mapfile tex = pv.read_texture(image_file) curvsurf.plot(texture=tex) ############################################################################### # NumPy Arrays as Textures # ++++++++++++++++++++++++ # # Want to use a programmatically built image? :class:`pyvista.UniformGrid` # objects can be converted to textures using :func:`pyvista.image_to_texture` # and 3D NumPy (X by Y by RGB) arrays can be converted to textures using # :func:`pyvista.numpy_to_texture`. # create an image using numpy, xx, yy = np.meshgrid(np.linspace(-200, 200, 20), np.linspace(-200, 200, 20)) A, b = 500, 100
# Assumes 'land_surface' is at index 0 surf = project.elements[0] tex = surf.textures[0] print(tex.name) og = tex.origin pu = tex.axis_u pv = tex.axis_v dec.texture_map_to_plane(origin=og, point_u=og + pu, point_v=og + pv, inplace=True, name='geo_aer') dec.textures['geo_aer'] = pyvista.read_texture( gdc19.get_web_path('geology-aerial-compressed.jpg')) dec.plot(texture=True) dec.save(gdc19.get_web_path('topo.vtk')) ############################################################################### # Decimate Granite Surface gran = surfaces['top_granitoid'] print(gran) ############################################################################### dec = gran.extract_geometry().decimate(0.99, inplace=False) dec.plot(notebook=True, show_edges=True)
# Show GCPs in relation to topo surface with texture coordinates displayed p = pv.Plotter() p.add_point_labels( np.array([ origin, point_u, point_v, ]), ["Origin", "Point U", "Point V"], point_size=5, ) p.add_mesh(topo) p.show(cpos="xy") ############################################################################### # Read the GeoTIFF as a ``Texture`` in PyVista: texture = pv.read_texture(filename) # Now plot the topo surface with the texture draped over it # And make window size large for a high-res screenshot p = pv.Plotter(window_size=np.array([1024, 768]) * 3) p.add_mesh(topo, texture=texture) p.camera_position = [ (337461.4124956896, 4257141.430658634, 2738.4956020899253), (339000.40935731295, 4260394.940646875, 1724.0720826501868), (0.10526647627366331, 0.2502863297360612, 0.962432190920575), ] p.show()
def _download_and_read(filename, texture=False, file_format=None): saved_file, _ = _download_file(filename) if texture: return pyvista.read_texture(saved_file) return pyvista.read(saved_file, file_format=file_format)
def load_globe_texture(): """Load a vtk.vtkTexture that can be applied to the globe source.""" return pyvista.read_texture(mapfile)
def animate_few_meshes(mesh, movement, f=None, subplot=(0, 0), texture=None, cmap='jet', plotter=None, title='', font_size=10, font_color='black', gif_path=None, camera=None, depth=False): """ animate few mashes using f as movment metrix. press "q" after adjusting the frame to start the animation Args: mesh: list of the meshes to plot movement: list of iterable with Vn side vector as elements for the num of vercies of the n-th mesh f: list of function that map between id of vertex to scalar for the color map subplot: list of subplots to use, each is a tuple in the form of: (row,col) texture: list of the textures to use cmap: list of the colormap to use plotter: the pyvista plotter title: the title of the figure font_size: the font size of the title font_color: the color of the font for the title gif_path: gif path to create, None if no gif is needed camera: list of the [camera position , focal point, view up] each (x,y,z) tuple Returns: None """ num_of_plots = len(mesh) if num_of_plots == 1: return mesh.animate(movement=movement, f=f, index_col=subplot[1], index_row=subplot[0], texture=texture, cmap=cmap, plotter=plotter, title=title, font_color=font_color, font_size=font_size, gif_path=gif_path, camera=camera) if not plotter: plotter = pv.Plotter() pv_mesh = [] # adding mushes with textures for idx in range(num_of_plots): plotter.subplot(subplot[idx][0], subplot[idx][1]) if depth: plotter.enable_depth_peeling(0) plotter.add_text(title[idx], position="upper_edge", font_size=font_size[idx], color=font_color[idx]) if camera[idx] is not None: plotter.set_position(camera[idx][0]) plotter.set_focus(camera[idx][1]) plotter.set_viewup(camera[idx][2]) pv_mesh.append(mesh[idx].pv_mesh) if not texture[idx]: plotter.add_mesh(pv_mesh[idx], scalars=f[idx], cmap=cmap[idx], texture=texture[idx]) else: if isinstance(texture[idx], np.ndarray): tex = pv.numpy_to_texture(texture[idx]) else: tex = pv.read_texture(texture[idx]) pv_mesh[idx].texture_map_to_plane(inplace=True) plotter.add_mesh(pv_mesh[idx], texture=tex) # starting the animation plotter.show(auto_close=False) if gif_path: plotter.open_gif(gif_path) for frame, item in enumerate(movement[0]): for plt_id in range(num_of_plots): plotter.update_coordinates(movement[plt_id][frame], mesh=pv_mesh[plt_id]) if gif_path: plotter.write_frame() plotter.close()