Python trimesh.Trimesh() Examples
The following are 30
code examples of trimesh.Trimesh().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
trimesh
, or try the search function
.
Example #1
Source File: generation.py From occupancy_networks with MIT License | 6 votes |
def generate_mesh(self, data): self.model.eval() device = self.device inputs = data.get('inputs', torch.empty(1, 0)).to(device) inputs = self.num_voxels * (inputs / 1.2 + 0.5) with torch.no_grad(): offset, topology, occupancy = self.model(inputs) offset = offset.squeeze() topology = topology.squeeze() topology = topology[:, self.vis_topology] vertices, faces = pred_to_mesh_max(offset, topology) faces = faces.astype(np.int64) vertices = 1.2 * (vertices / self.num_voxels - 0.5) mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False) return mesh
Example #2
Source File: render_urdf.py From pytransform3d with BSD 3-Clause "New" or "Revised" License | 6 votes |
def sphere_show(self, scene): """Render sphere.""" A2B = tm.get_transform(self.frame, frame) center = A2B[:3, 3] phi, theta = np.mgrid[0.0:np.pi:100j, 0.0:2.0 * np.pi:100j] X = center[0] + self.radius * np.sin(phi) * np.cos(theta) Y = center[1] + self.radius * np.sin(phi) * np.sin(theta) Z = center[2] + self.radius * np.cos(phi) vertices = [] faces = [] for i in range(X.shape[0] - 1): for j in range(X.shape[1] - 1): v1 = [X[i, j], Y[i, j], Z[i, j]] v2 = [X[i, j + 1], Y[i, j + 1], Z[i, j + 1]] v3 = [X[i + 1, j], Y[i + 1, j], Z[i + 1, j]] vertices.extend([v1, v2, v3]) faces.append(list(range(len(vertices) - 3, len(vertices)))) mesh = trimesh.Trimesh(vertices=vertices, faces=faces).convex_hull mesh = pr.Mesh.from_trimesh(mesh) scene.add(mesh)
Example #3
Source File: render_urdf.py From pytransform3d with BSD 3-Clause "New" or "Revised" License | 6 votes |
def box_show(self, scene): """Render box.""" A2B = tm.get_transform(self.frame, frame) corners = np.array([ [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1] ]) corners = (corners - 0.5) * self.size corners = transform( A2B, np.hstack((corners, np.ones((len(corners), 1)))))[:, :3] mesh = trimesh.Trimesh( vertices=corners, faces=[[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 0]]).bounding_box mesh = pr.Mesh.from_trimesh(mesh) scene.add(mesh)
Example #4
Source File: urdf.py From scikit-robot with MIT License | 6 votes |
def meshes(self, value): if isinstance(value, six.string_types): value = load_meshes(value) elif isinstance(value, (list, tuple, set)): value = list(value) if len(value) == 0: raise ValueError('Mesh must have at least one trimesh.Trimesh') for m in value: if not isinstance(m, trimesh.Trimesh): raise TypeError('Mesh requires a trimesh.Trimesh or a ' 'list of them') elif isinstance(value, trimesh.Trimesh): value = [value] else: raise TypeError('Mesh requires a trimesh.Trimesh') self._meshes = value
Example #5
Source File: dynamic_contour_embedding.py From RingNet with MIT License | 6 votes |
def load_dynamic_contour(template_flame_path='None', contour_embeddings_path='None', static_embedding_path='None', angle=0): template_mesh = Mesh(filename=template_flame_path) contour_embeddings_path = contour_embeddings_path dynamic_lmks_embeddings = np.load(contour_embeddings_path, allow_pickle=True).item() lmk_face_idx_static, lmk_b_coords_static = load_static_embedding(static_embedding_path) lmk_face_idx_dynamic = dynamic_lmks_embeddings['lmk_face_idx'][angle] lmk_b_coords_dynamic = dynamic_lmks_embeddings['lmk_b_coords'][angle] dynamic_lmks = mesh_points_by_barycentric_coordinates(template_mesh.v, template_mesh.f, lmk_face_idx_dynamic, lmk_b_coords_dynamic) static_lmks = mesh_points_by_barycentric_coordinates(template_mesh.v, template_mesh.f, lmk_face_idx_static, lmk_b_coords_static) total_lmks = np.vstack([dynamic_lmks, static_lmks]) # Visualization of the pose dependent contour on the template mesh vertex_colors = np.ones([template_mesh.v.shape[0], 4]) * [0.3, 0.3, 0.3, 0.8] tri_mesh = trimesh.Trimesh(template_mesh.v, template_mesh.f, vertex_colors=vertex_colors) mesh = pyrender.Mesh.from_trimesh(tri_mesh) scene = pyrender.Scene() scene.add(mesh) sm = trimesh.creation.uv_sphere(radius=0.005) sm.visual.vertex_colors = [0.9, 0.1, 0.1, 1.0] tfs = np.tile(np.eye(4), (len(total_lmks), 1, 1)) tfs[:, :3, 3] = total_lmks joints_pcl = pyrender.Mesh.from_trimesh(sm, poses=tfs) scene.add(joints_pcl) pyrender.Viewer(scene, use_raymond_lighting=True)
Example #6
Source File: utils.py From graphics with Apache License 2.0 | 6 votes |
def transform_mesh(mesh, name, trans_dir): """Transform mesh back to the same coordinate of ground truth. Args: mesh: trimesh.Trimesh, predicted mesh before transformation. name: Tensor, hash name of the mesh as recorded in the dataset. trans_dir: string, path to the directory for loading transformations. Returns: mesh: trimesh.Trimesh, the transformed mesh. """ if trans_dir is None: raise ValueError("Need to specify args.trans_dir for loading pred-to-target" "transformations.") cls_name, obj_name = mesh_name_helper(name) with tf.io.gfile.GFile( path.join(trans_dir, "test", cls_name, obj_name, "occnet_to_gaps.txt"), "r") as fin: tx = np.loadtxt(fin).reshape([4, 4]) mesh.apply_transform(np.linalg.inv(tx)) return mesh
Example #7
Source File: urdf.py From urdfpy with MIT License | 6 votes |
def collision_mesh(self): """:class:`~trimesh.base.Trimesh` : A single collision mesh for the link, specified in the link frame, or None if there isn't one. """ if len(self.collisions) == 0: return None if self._collision_mesh is None: meshes = [] for c in self.collisions: for m in c.geometry.meshes: m = m.copy() pose = c.origin if c.geometry.mesh is not None: if c.geometry.mesh.scale is not None: S = np.eye(4) S[:3,:3] = np.diag(c.geometry.mesh.scale) pose = pose.dot(S) m.apply_transform(pose) meshes.append(m) if len(meshes) == 0: return None self._collision_mesh = (meshes[0] + meshes[1:]) return self._collision_mesh
Example #8
Source File: generation.py From occupancy_flow with MIT License | 6 votes |
def generate_mesh_t0(self, z=None, c_s=None, c_t=None, data=None, stats_dict={}): ''' Generates the mesh at time step t=0. Args: z (tensor): latent code z c_s (tensor): conditioned spatial code c_s c_t (tensor): conditioned temporal code c_t data (dict): data dictionary stats_dict (dict): (time) statistics dictionary ''' if self.onet_generator.model.decoder is not None: mesh = self.onet_generator.generate_from_latent( z, c_s, stats_dict=stats_dict) else: vertices = data['mesh.vertices'][:, 0].squeeze(0).cpu().numpy() faces = data['mesh.faces'].squeeze(0).cpu().numpy() mesh = trimesh.Trimesh( vertices=vertices, faces=faces, process=False) return mesh
Example #9
Source File: io.py From occupancy_flow with MIT License | 6 votes |
def load_mesh(mesh_file): with open(mesh_file, 'r') as f: str_file = f.read().split('\n') n_vertices, n_faces, _ = list( map(lambda x: int(x), str_file[1].split(' '))) str_file = str_file[2:] # Remove first 2 lines v = [l.split(' ') for l in str_file[:n_vertices]] f = [l.split(' ') for l in str_file[n_vertices:]] v = np.array(v).astype(np.float32) f = np.array(f).astype(np.uint64)[:, 1:4] mesh = trimesh.Trimesh(vertices=v, faces=f, process=False) return mesh
Example #10
Source File: model.py From scikit-robot with MIT License | 6 votes |
def visual_mesh(self, mesh): """Setter of visual mesh Parameters ---------- mesh : None, trimesh.Trimesh, sequence of trimesh.Trimesh, or str A set of visual meshes for the link in the link frame. """ if not (mesh is None or isinstance(mesh, trimesh.Trimesh) or (isinstance(mesh, collections.Sequence) and all(isinstance(m, trimesh.Trimesh) for m in mesh)) or isinstance(mesh, str)): raise TypeError( 'mesh must be None, trimesh.Trimesh, sequence of ' 'trimesh.Trimesh, or path of mesh file, but got: {}'.format( type(mesh))) if isinstance(mesh, str): mesh = trimesh.load(mesh) self._visual_mesh = mesh
Example #11
Source File: surface.py From pyprocar with GNU General Public License v3.0 | 6 votes |
def _create_trimesh(self): """ creates a trimesh object """ if np.any(np.array([len(x) for x in self.faces])>3): faces = [] for i in range(0,len(self.pyvista_obj.triangulate().faces),4): point_1 = self.pyvista_obj.triangulate().faces[i+1] point_2 = self.pyvista_obj.triangulate().faces[i+2] point_3 = self.pyvista_obj.triangulate().faces[i+3] faces.append([point_1, point_2, point_3]) self.trimesh_obj = trimesh.Trimesh(vertices=self.verts,faces=faces) else: self.trimesh_obj = trimesh.Trimesh(vertices=self.verts,faces=self.faces)
Example #12
Source File: urdf.py From scikit-robot with MIT License | 5 votes |
def collision_trimesh_fk(self, cfg=None, links=None): """Computes the poses of the URDF's collision trimeshes using fk. Parameters ---------- cfg : dict A map from joints or joint names to configuration values for each joint. If not specified, all joints are assumed to be in their default configurations. links : list of str or list of :class:`.Link` The links or names of links to perform forward kinematics on. Only trimeshes from these links will be in the returned map. If not specified, all links are returned. Returns ------- fk : dict A map from :class:`~trimesh.base.Trimesh` objects that are part of the collision geometry of the specified links to the 4x4 homogenous transform matrices that position them relative to the base link's frame. """ lfk = self.link_fk(cfg=cfg, links=links) fk = {} for link in lfk: if link.collision_mesh is not None: fk[link.collision_mesh] = lfk[link] return fk
Example #13
Source File: generation.py From occupancy_networks with MIT License | 5 votes |
def generate_mesh(self, data, fix_normals=False): ''' Generates a mesh. Arguments: data (tensor): input data fix_normals (boolean): if normals should be fixed ''' img = data.get('inputs').to(self.device) camera_args = common.get_camera_args( data, 'pointcloud.loc', 'pointcloud.scale', device=self.device) world_mat, camera_mat = camera_args['Rt'], camera_args['K'] with torch.no_grad(): outputs1, outputs2 = self.model(img, camera_mat) out_1, out_2, out_3 = outputs1 transformed_pred = common.transform_points_back(out_3, world_mat) vertices = transformed_pred.squeeze().cpu().numpy() faces = self.base_mesh[:, 1:] # remove the f's in the first column faces = faces.astype(int) - 1 # To adjust indices to trimesh notation mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False) if fix_normals: # Fix normals due to wrong base ellipsoid trimesh.repair.fix_normals(mesh) return mesh
Example #14
Source File: model.py From scikit-robot with MIT License | 5 votes |
def visual_mesh(self): """Return visual mesh Returns ------- self._visual_mesh : None, trimesh.base.Trimesh, or sequence of trimesh.Trimesh A set of visual meshes for the link in the link frame. """ return self._visual_mesh
Example #15
Source File: model.py From scikit-robot with MIT License | 5 votes |
def collision_mesh(self, mesh): """Setter of collision mesh Parameters ---------- mesh : trimesh.base.Trimesh A single collision mesh for the link. specified in the link frame, or None if there is not one. """ if mesh is not None and \ not isinstance(mesh, trimesh.base.Trimesh): raise TypeError('input mesh is should be trimesh.base.Trimesh, ' 'get type {}'.format(type(mesh))) self._collision_mesh = mesh
Example #16
Source File: utils.py From urdfpy with MIT License | 5 votes |
def load_meshes(filename): """Loads triangular meshes from a file. Parameters ---------- filename : str Path to the mesh file. Returns ------- meshes : list of :class:`~trimesh.base.Trimesh` The meshes loaded from the file. """ meshes = trimesh.load(filename) # If we got a scene, dump the meshes if isinstance(meshes, trimesh.Scene): meshes = list(meshes.dump()) meshes = [g for g in meshes if isinstance(g, trimesh.Trimesh)] if isinstance(meshes, (list, tuple, set)): meshes = list(meshes) if len(meshes) == 0: raise ValueError('At least one mesh must be pmeshesent in file') for r in meshes: if not isinstance(r, trimesh.Trimesh): raise TypeError('Could not load meshes from file') elif isinstance(meshes, trimesh.Trimesh): meshes = [meshes] else: raise ValueError('Unable to load mesh from file') return meshes
Example #17
Source File: urdf.py From scikit-robot with MIT License | 5 votes |
def visual_trimesh_fk(self, cfg=None, links=None): """Computes the poses of the URDF's visual trimeshes using fk. Parameters ---------- cfg : dict A map from joints or joint names to configuration values for each joint. If not specified, all joints are assumed to be in their default configurations. links : list of str or list of :class:`.Link` The links or names of links to perform forward kinematics on. Only trimeshes from these links will be in the returned map. If not specified, all links are returned. Returns ------- fk : dict A map from :class:`~trimesh.base.Trimesh` objects that are part of the visual geometry of the specified links to the 4x4 homogenous transform matrices that position them relative to the base link's frame. """ lfk = self.link_fk(cfg=cfg, links=links) fk = {} for link in lfk: for visual in link.visuals: for mesh in visual.geometry.meshes: pose = lfk[link].dot(visual.origin) if visual.geometry.mesh is not None: if visual.geometry.mesh.scale is not None: S = np.eye(4) S[:3, :3] = np.diag(visual.geometry.mesh.scale) pose = pose.dot(S) fk[mesh] = pose return fk
Example #18
Source File: urdf.py From scikit-robot with MIT License | 5 votes |
def collision_mesh(self): """Return collision mesh :class:`~trimesh.base.Trimesh` : A single collision mesh for the link, specified in the link frame, or None if there isn't one. """ if len(self.collisions) == 0: return None if self._collision_mesh is None: meshes = [] for c in self.collisions: for m in c.geometry.meshes: m = m.copy() pose = c.origin if c.geometry.mesh is not None: if c.geometry.mesh.scale is not None: S = np.eye(4) S[:3, :3] = np.diag(c.geometry.mesh.scale) pose = pose.dot(S) m.apply_transform(pose) meshes.append(m) if len(meshes) == 0: return None self._collision_mesh = (meshes[0] + meshes[1:]) return self._collision_mesh
Example #19
Source File: __init__.py From occupancy_networks with MIT License | 5 votes |
def simplify_mesh(mesh, f_target=10000, agressiveness=7.): vertices = mesh.vertices faces = mesh.faces vertices, faces = mesh_simplify(vertices, faces, f_target, agressiveness) mesh_simplified = trimesh.Trimesh(vertices, faces, process=False) return mesh_simplified
Example #20
Source File: urdf.py From scikit-robot with MIT License | 5 votes |
def meshes(self): """Return list of Trimesh list of :class:`~trimesh.base.Trimesh` : The triangular meshes that represent this object. """ if len(self._meshes) == 0: self._meshes = [trimesh.creation.cylinder( radius=self.radius, height=self.length )] return self._meshes
Example #21
Source File: urdf.py From urdfpy with MIT License | 5 votes |
def meshes(self): """list of :class:`~trimesh.base.Trimesh` : The triangular meshes that represent this object. """ if len(self._meshes) == 0: self._meshes = [trimesh.creation.box(extents=self.size)] return self._meshes
Example #22
Source File: urdf.py From urdfpy with MIT License | 5 votes |
def meshes(self): """list of :class:`~trimesh.base.Trimesh` : The triangular meshes that represent this object. """ if len(self._meshes) == 0: self._meshes = [trimesh.creation.cylinder( radius=self.radius, height=self.length )] return self._mesh
Example #23
Source File: urdf.py From urdfpy with MIT License | 5 votes |
def meshes(self): """list of :class:`~trimesh.base.Trimesh` : The triangular meshes that represent this object. """ if len(self._meshes) == 0: self._meshes = [trimesh.creation.icosphere(radius=self.radius)] return self._meshes
Example #24
Source File: urdf.py From urdfpy with MIT License | 5 votes |
def meshes(self): """list of :class:`~trimesh.base.Trimesh` : The triangular meshes that represent this object. """ return self._meshes
Example #25
Source File: urdf.py From urdfpy with MIT License | 5 votes |
def meshes(self): """list of :class:`~trimesh.base.Trimesh` : The geometry's triangular mesh representation(s). """ return self.geometry.meshes
Example #26
Source File: urdf.py From urdfpy with MIT License | 5 votes |
def visual_trimesh_fk(self, cfg=None, links=None): """Computes the poses of the URDF's visual trimeshes using fk. Parameters ---------- cfg : dict or (n), float A map from joints or joint names to configuration values for each joint, or a list containing a value for each actuated joint in sorted order from the base link. If not specified, all joints are assumed to be in their default configurations. links : list of str or list of :class:`.Link` The links or names of links to perform forward kinematics on. Only trimeshes from these links will be in the returned map. If not specified, all links are returned. Returns ------- fk : dict A map from :class:`~trimesh.base.Trimesh` objects that are part of the visual geometry of the specified links to the 4x4 homogenous transform matrices that position them relative to the base link's frame. """ lfk = self.link_fk(cfg=cfg, links=links) fk = OrderedDict() for link in lfk: for visual in link.visuals: for mesh in visual.geometry.meshes: pose = lfk[link].dot(visual.origin) if visual.geometry.mesh is not None: if visual.geometry.mesh.scale is not None: S = np.eye(4, dtype=np.float64) S[:3,:3] = np.diag(visual.geometry.mesh.scale) pose = pose.dot(S) fk[mesh] = pose return fk
Example #27
Source File: urdf.py From urdfpy with MIT License | 5 votes |
def visual_trimesh_fk_batch(self, cfgs=None, links=None): """Computes the poses of the URDF's visual trimeshes using fk. Parameters ---------- cfgs : dict, list of dict, or (n,m), float One of the following: (A) a map from joints or joint names to vectors of joint configuration values, (B) a list of maps from joints or joint names to single configuration values, or (C) a list of ``n`` configuration vectors, each of which has a vector with an entry for each actuated joint. links : list of str or list of :class:`.Link` The links or names of links to perform forward kinematics on. Only trimeshes from these links will be in the returned map. If not specified, all links are returned. Returns ------- fk : dict A map from :class:`~trimesh.base.Trimesh` objects that are part of the visual geometry of the specified links to the 4x4 homogenous transform matrices that position them relative to the base link's frame. """ lfk = self.link_fk_batch(cfgs=cfgs, links=links) fk = OrderedDict() for link in lfk: for visual in link.visuals: for mesh in visual.geometry.meshes: poses = np.matmul(lfk[link], visual.origin) if visual.geometry.mesh is not None: if visual.geometry.mesh.scale is not None: S = np.eye(4, dtype=np.float64) S[:3,:3] = np.diag(visual.geometry.mesh.scale) poses = np.matmul(poses, S) fk[mesh] = poses return fk
Example #28
Source File: urdf.py From urdfpy with MIT License | 5 votes |
def collision_trimesh_fk(self, cfg=None, links=None): """Computes the poses of the URDF's collision trimeshes using fk. Parameters ---------- cfg : dict or (n), float A map from joints or joint names to configuration values for each joint, or a list containing a value for each actuated joint in sorted order from the base link. If not specified, all joints are assumed to be in their default configurations. links : list of str or list of :class:`.Link` The links or names of links to perform forward kinematics on. Only trimeshes from these links will be in the returned map. If not specified, all links are returned. Returns ------- fk : dict A map from :class:`~trimesh.base.Trimesh` objects that are part of the collision geometry of the specified links to the 4x4 homogenous transform matrices that position them relative to the base link's frame. """ lfk = self.link_fk(cfg=cfg, links=links) fk = OrderedDict() for link in lfk: pose = lfk[link] cm = link.collision_mesh if cm is not None: fk[cm] = pose return fk
Example #29
Source File: render_urdf.py From pytransform3d with BSD 3-Clause "New" or "Revised" License | 5 votes |
def cylinder_show(self, scene): """Render cylinder.""" A2B = tm.get_transform(self.frame, frame) axis_start = A2B.dot(np.array([0, 0, -0.5 * self.length, 1]))[:3] axis_end = A2B.dot(np.array([0, 0, 0.5 * self.length, 1]))[:3] axis = axis_end - axis_start axis /= self.length not_axis = np.array([1, 0, 0]) if (axis == not_axis).all(): not_axis = np.array([0, 1, 0]) n1 = np.cross(axis, not_axis) n1 /= np.linalg.norm(n1) n2 = np.cross(axis, n1) t = np.linspace(0, self.length, 3) theta = np.linspace(0, 2 * np.pi, 50) t, theta = np.meshgrid(t, theta) X, Y, Z = [axis_start[i] + axis[i] * t + self.radius * np.sin(theta) * n1[i] + self.radius * np.cos(theta) * n2[i] for i in [0, 1, 2]] vertices = [] faces = [] for i in range(X.shape[0] - 1): for j in range(X.shape[1] - 1): v1 = [X[i, j], Y[i, j], Z[i, j]] v2 = [X[i, j + 1], Y[i, j + 1], Z[i, j + 1]] v3 = [X[i + 1, j], Y[i + 1, j], Z[i + 1, j]] vertices.extend([v1, v2, v3]) faces.append(list(range(len(vertices) - 3, len(vertices)))) mesh = trimesh.Trimesh(vertices=vertices, faces=faces).convex_hull mesh = pr.Mesh.from_trimesh(mesh) scene.add(mesh)
Example #30
Source File: intersect.py From obman_train with GNU General Public License v3.0 | 5 votes |
def get_sample_intersect_volume(sample_info, mode="voxels"): hand_mesh = trimesh.Trimesh( vertices=sample_info["hand_verts"], faces=sample_info["hand_faces"] ) obj_mesh = trimesh.Trimesh( vertices=sample_info["obj_verts"], faces=sample_info["obj_faces"] ) if mode == "engines": try: intersection = intersect(obj_mesh, hand_mesh, engine="scad") if intersection.is_watertight: volume = intersection.volume else: intersection = intersect(obj_mesh, hand_mesh, engine="blender") # traceback.print_exc() if intersection.vertices.shape[0] == 0: volume = 0 elif intersection.is_watertight: volume = intersection.volume else: volume = None except Exception: intersection = intersect(obj_mesh, hand_mesh, engine="blender") # traceback.print_exc() if intersection.vertices.shape[0] == 0: volume = 0 elif intersection.is_watertight: volume = intersection.volume else: volume = None elif mode == "voxels": volume = intersect_vox(obj_mesh, hand_mesh, pitch=0.005) return volume