Python源码示例:trimesh.Trimesh()

示例1
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) 
示例2
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 
示例3
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 
示例4
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 
示例5
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) 
示例6
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 
示例7
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 
示例8
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 
示例9
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 
示例10
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) 
示例11
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) 
示例12
def to_trimesh(data):
    r"""Converts a :class:`torch_geometric.data.Data` instance to a
    :obj:`trimesh.Trimesh`.

    Args:
        data (torch_geometric.data.Data): The data object.
    """

    if trimesh is None:
        raise ImportError('Package `trimesh` could not be found.')

    return trimesh.Trimesh(vertices=data.pos.detach().cpu().numpy(),
                           faces=data.face.detach().t().cpu().numpy(),
                           process=False) 
示例13
def from_trimesh(mesh):
    r"""Converts a :obj:`trimesh.Trimesh` to a
    :class:`torch_geometric.data.Data` instance.

    Args:
        mesh (trimesh.Trimesh): A :obj:`trimesh` mesh.
    """

    if trimesh is None:
        raise ImportError('Package `trimesh` could not be found.')

    pos = torch.from_numpy(mesh.vertices).to(torch.float)
    face = torch.from_numpy(mesh.faces).t().contiguous()

    return torch_geometric.data.Data(pos=pos, face=face) 
示例14
def __init__(self, mesh,
                 T_obj_world=None,
                 material=None,
                 enabled=True):
        """Initialize a scene object with the given mesh, pose, and material.

        Parameters
        ----------
        mesh : trimesh.Trimesh
            A mesh representing the object's geometry.
        T_obj_world : autolab_core.RigidTransform
            A rigid transformation from the object's frame to the world frame.
        material : MaterialProperties
            A set of material properties for the object.
        enabled : bool
            If False, the object will not be rendered.
        """
        if not isinstance(mesh, Trimesh):
            raise ValueError('mesh must be an object of type Trimesh')
        if T_obj_world is None:
            T_obj_world = RigidTransform(from_frame='obj', to_frame='world')
        if material is None:
            material = MaterialProperties()
        if material.smooth:
            mesh = mesh.smoothed()

        self._mesh = mesh
        self._material = material
        self.T_obj_world = T_obj_world
        self._enabled = True 
示例15
def mesh(self):
        """trimesh.Trimesh: A mesh representing the object's geometry.
        """
        return self._mesh 
示例16
def save_mesh(mesh, name, eval_dir):
  """Save a mesh to disk.

  Args:
    mesh: trimesh.Trimesh, the mesh to save.
    name: Tensor, hash name of the mesh as recorded in the dataset.
    eval_dir: string, path to the directory to save the mesh.
  """
  cls_name, obj_name = mesh_name_helper(name)
  cls_dir = path.join(eval_dir, "meshes", cls_name)
  if not tf.io.gfile.isdir(cls_dir):
    tf.io.gfile.makedirs(cls_dir)
  with tf.io.gfile.GFile(path.join(cls_dir, obj_name + ".obj"), "w") as fout:
    mesh.export(fout, file_type="obj") 
示例17
def load(file_obj, file_type=None, **kwargs):
  """Loads a triangle mesh from the given GFile/file path.

  Args:
    file_obj: A tf.io.gfile.GFile object or a string specifying the mesh file
      path.
    file_type: A string specifying the type of the file (e.g. 'obj', 'stl'). If
      not specified the file_type will be inferred from the file name.
    **kwargs: Additional arguments that should be passed to trimesh.load().

  Returns:
    A trimesh.Trimesh or trimesh.Scene.
  """

  if isinstance(file_obj, str):
    with tf.io.gfile.GFile(file_obj, 'r') as f:
      if file_type is None:
        file_type = trimesh.util.split_extension(file_obj)
      return trimesh.load(
          file_obj=f,
          file_type=file_type,
          resolver=GFileResolver(file_obj),
          **kwargs)

  if trimesh.util.is_file(file_obj):
    if not hasattr(file_obj, 'name') or not file_obj.name:
      raise ValueError(
          'file_obj must have attribute "name". Try passing the file name instead.'
      )
    if file_type is None:
      file_type = trimesh.util.split_extension(file_obj.name)
    return trimesh.load(
        file_obj=file_obj,
        file_type=file_type,
        resolver=GFileResolver(file_obj.name),
        **kwargs)

  raise ValueError('file_obj should be either a file object or a string') 
示例18
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 
示例19
def _meshpy_to_trimesh(mesh_m3d):
        vertices = mesh_m3d.vertices
        faces = mesh_m3d.triangles
        mesh_tm = trimesh.Trimesh(vertices, faces)
        return mesh_tm

    # TODO
    # Once trimesh integration is here via meshpy remove this 
示例20
def trimesh(self):
        """ Convert to trimesh. """
        if self.trimesh_ is None:
            self.trimesh_ = tm.Trimesh(vertices=self.vertices,
                                       faces=self.triangles,
                                       vertex_normals=self.normals)
        return self.trimesh_ 
示例21
def generate_meshes_t(self, vertices_0, faces, z=None, c_t=None,
                          vertex_data=None, stats_dict={}):
        ''' Generates meshes for time steps t>0.

        Args:
            vertices_0 (numpy array): vertices of mesh at t=0
            faces (numpy array): faces of mesh at t=0
            z (tensor): latent code z
            c_t (tensor): temporal conditioned code c_t
            vertex_data (tensor): vertex tensor (start and end mesh if
                interpolation is required)
            stats_dict (dict): (time) statistics dictionary
        '''
        device = self.onet_generator.device
        t = self.get_time_steps()
        vertices_0 = torch.from_numpy(
            vertices_0).to(device).unsqueeze(0).float()
        t0 = time.time()
        v_t_batch = self.onet_generator.model.transform_to_t(
            t, vertices_0, c_t=c_t, z=z)
        stats_dict['time (forward propagation)'] = time.time() - t0
        v_t_batch = v_t_batch.squeeze(0).cpu().numpy()
        if self.interpolate:
            vertices_t = vertex_data[:, -1].to(device)
            t0 = time.time()
            v_t_bw = self.onet_generator.model.transform_to_t_backward(
                t, vertices_t, c_t=c_t, z=z)
            stats_dict['time (backward propagation)'] = time.time() - t0

            v_t_bw = v_t_bw.squeeze(0).flip(0).cpu().numpy()[:-1]
            p_interpolate = self.return_interpolate(v_t_batch[:-1], v_t_bw)
            v_t_batch = np.concatenate(
                [p_interpolate, vertices_t.cpu().numpy()])

        meshes = []
        for v_t in v_t_batch:
            meshes.append(trimesh.Trimesh(
                vertices=v_t, faces=faces, process=False))
        return meshes 
示例22
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 
示例23
def trimesh(self):
        """ Convert to trimesh. """
        if self.trimesh_ is None:
            self.trimesh_ = tm.Trimesh(vertices=self.vertices,
                                       faces=self.triangles,
                                       vertex_normals=self.normals)
        return self.trimesh_ 
示例24
def test_visual_mesh(self):
        fetch = self.fetch
        for link in fetch.link_list:
            assert isinstance(link.visual_mesh, list)
            assert all(isinstance(m, trimesh.Trimesh)
                       for m in link.visual_mesh) 
示例25
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 
示例26
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.box(extents=self.size)]
        return self._meshes 
示例27
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 
示例28
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.icosphere(radius=self.radius)]
        return self._meshes 
示例29
def meshes(self):
        """Return list of geometry mesh

        list of :class:`~trimesh.base.Trimesh` : The geometry's triangular
        mesh representation(s).
        """
        return self.geometry.meshes 
示例30
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