Python源码示例:trimesh.load()

示例1
def load(self, model_path, idx):
        file_path = os.path.join(model_path, self.file_name)

        pointcloud_dict = np.load(file_path)

        points = pointcloud_dict['points'].astype(np.float32)
        normals = pointcloud_dict['normals'].astype(np.float32)

        data = {
            None: points.T,
            'normals': normals.T,
        }

        if self.with_transforms:
            data['loc'] = pointcloud_dict['loc'].astype(np.float32)
            data['scale'] = pointcloud_dict['scale'].astype(np.float32)

        if self.transform is not None:
            data = self.transform(data)

        return data 
示例2
def load(self, model_path, idx, c_idx=None, start_idx=0, **kwargs):
        ''' Loads the points subsequence field.

        Args:
            model_path (str): path to model
            idx (int): ID of data point
            category (int): index of category
            start_idx (int): id of sequence start
        '''
        files = self.load_files(model_path, start_idx)
        # Load loc and scale from t_0
        points_dict = np.load(files[0])
        loc0 = points_dict['loc'].astype(np.float32)
        scale0 = points_dict['scale'].astype(np.float32)

        if self.all_steps:
            data = self.load_all_steps(files, points_dict, loc0, scale0)
        else:
            data = self.load_single_step(files, points_dict, loc0, scale0)

        if self.transform is not None:
            data = self.transform(data)
        return data 
示例3
def load_and_scale_mesh(mesh_path, loc=None, scale=None):
    ''' Loads and scales a mesh.

    Args:
        mesh_path (str): mesh path
        loc (tuple): location
        scale (float): scaling factor
    '''
    mesh = trimesh.load(mesh_path, process=False)

    # Compute location and scale
    if loc is None or scale is None:
        bbox = mesh.bounding_box.bounds
        loc = (bbox[0] + bbox[1]) / 2
        scale = (bbox[1] - bbox[0]).max()

    mesh.apply_translation(-loc)
    mesh.apply_scale(1/scale)

    return loc, scale, mesh 
示例4
def default_scene(obj_file, width=640, height=480, use_distortion=True):

    mesh_trimesh = trimesh.load(obj_file)

    mesh = ColoredTriMesh.from_trimesh(mesh_trimesh)

    # rot = Rotation.from_euler("xyz", [180, 0, 0], degrees=True).as_matrix()
    rot = Rotation.from_euler("xyz", [180, 0, 0], degrees=True).as_matrix()

    camera = differentiable_renderer.default_camera(
        width, height, 80, mesh.vertices, rot
    )
    if use_distortion:
        camera.distortion = np.array([-0.5, 0.5, 0, 0, 0])

    bg_color = np.array((0.8, 0.8, 0.8))
    scene = differentiable_renderer.Scene3D()
    light_ambient = 0
    light_directional = 0.3 * np.array([1, -1, 0])
    scene.set_light(light_directional=light_directional, light_ambient=light_ambient)
    scene.set_mesh(mesh)
    background_image = np.ones((height, width, 3)) * bg_color
    scene.set_background(background_image)
    return scene, camera 
示例5
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 
示例6
def load(self, model_path, idx, category):
        ''' Loads the data point.

        Args:
            model_path (str): path to model
            idx (int): ID of data point
            category (int): index of category
        '''
        file_path = os.path.join(model_path, self.file_name)

        with open(file_path, 'rb') as f:
            voxels = binvox_rw.read_as_3d_array(f)
        voxels = voxels.data.astype(np.float32)

        if self.transform is not None:
            voxels = self.transform(voxels)

        return voxels 
示例7
def load(self, model_path, idx, category):
        ''' Loads the data point.

        Args:
            model_path (str): path to model
            idx (int): ID of data point
            category (int): index of category
        '''
        file_path = os.path.join(model_path, self.file_name)

        mesh = trimesh.load(file_path, process=False)
        if self.transform is not None:
            mesh = self.transform(mesh)

        data = {
            'verts': mesh.vertices,
            'faces': mesh.faces,
        }

        return data 
示例8
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')
  if not FLAGS.input_mesh:
    raise IOError('--input_mesh must be specified.')
  if not FLAGS.output_ply:
    raise IOError('--output_ply must be specified.')

  mesh = trimesh.load(FLAGS.input_mesh)
  mesh = normalize_mesh(mesh)
  sample_pts, sample_normals = sample_mesh(mesh)
  print('Computed {} samples from mesh.'.format(sample_pts.shape[0]))
  print('Writing sampled points to {}'.format(FLAGS.output_ply))
  pu.write_point_ply(FLAGS.output_ply, sample_pts, sample_normals) 
示例9
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') 
示例10
def get_contact_info(
    hand_vert,
    hand_faces,
    obj_vert,
    obj_faces,
    result_close=None,
    result_distance=None,
    contact_thresh=25,
):
    obj_mesh_dict = {"vertices": obj_vert, "faces": obj_faces}
    obj_mesh = trimesh.load(obj_mesh_dict)
    trimesh.repair.fix_normals(obj_mesh)
    # hand_mesh_dict = {'vertices': hand_vert, 'faces': hand_faces}
    # hand_mesh = trimesh.load(hand_mesh_dict)
    # trimesh.repair.fix_normals(hand_mesh)
    if result_close is None or result_distance is None:
        result_close, result_distance, _ = trimesh.proximity.closest_point(
            obj_mesh, hand_vert
        )
    penetrating, exterior = mesh_vert_int_exts(
        obj_mesh, hand_vert, result_distance
    )

    below_dist = result_distance < contact_thresh
    missed_mask = below_dist & exterior
    return result_close, missed_mask, penetrating 
示例11
def load_objects(
        obj_root='/sequoia/data2/dataset/handatasets/fhb/Object_models',
        object_names=['juice']):
    all_models = OrderedDict()
    for obj_name in object_names:
        import trimesh
        obj_path = os.path.join(obj_root, '{}_model'.format(obj_name),
                                '{}_model.ply'.format(obj_name))
        mesh = trimesh.load(obj_path)
        all_models[obj_name] = {
            'verts': np.array(mesh.vertices),
            'faces': np.array(mesh.faces)
        }
    return all_models 
示例12
def load(self, model_path, idx):
        return idx 
示例13
def load(self, model_path, idx):
        folder_path = os.path.join(model_path, self.folder_name)
        file_path = os.path.join(folder_path, 'model.off')
        mesh = trimesh.load(file_path, process=False)
        if self.transform is not None:
            mesh = self.transform(mesh)

        data = {
            'vertices': np.array(mesh.vertices),
            'faces': np.array(mesh.faces),
        }

        return data 
示例14
def load(self, model_path, idx):
        folder = os.path.join(model_path, self.folder_name)
        files = glob.glob(os.path.join(folder, '*.%s' % self.extension))
        files.sort()
        if self.random_view:
            idx_img = random.randint(0, len(files)-1)
        else:
            idx_img = 0
        filename = files[idx_img]

        image = imageio.imread(filename, **self.imageio_kwargs)
        image = np.asarray(image)

        if len(image.shape) == 2:
            image = image.reshape(image.shape[0], image.shape[1], 1)
            image = np.concatenate([image, image, image], axis=2)  

        if image.shape[2] == 4:
            image = image[:, :, :3]

        if image.dtype == np.uint8:
            image = image.astype(np.float32) / 255
        else:
            image = image.astype(np.float32)

        if self.transform is not None:
            image = self.transform(image)
        image = image.transpose(2, 0, 1)
        data = {
            None: image
        }

        if self.with_camera:
            camera_file = os.path.join(folder, 'cameras.npz')
            camera_dict = np.load(camera_file)
            Rt = camera_dict['world_mat_%d' % idx_img].astype(np.float32)
            K = camera_dict['camera_mat_%d' % idx_img].astype(np.float32)
            data['world_mat'] = Rt
            data['camera_mat'] = K

        return data 
示例15
def load(self, model_path, idx, category, start_idx=0, **kwargs):
        ''' Loads the index field.

        Args:
            model_path (str): path to model
            idx (int): ID of data point
            category (int): index of category
            start_idx (int): id of sequence start
        '''
        return idx 
示例16
def load(self, model_path, idx, category):
        ''' Loads the category field.

        Args:
            model_path (str): path to model
            idx (int): ID of data point
            category (int): index of category
        '''
        return category 
示例17
def load_single_step(self, files, points_dict, loc0, scale0):
        ''' Loads data for a single step.

        Args:
            files (list): list of files
            points_dict (dict): points dictionary for first step of sequence
            loc0 (tuple): location of first time step mesh
            scale0 (float): scale of first time step mesh
        '''
        if self.fixed_time_step is None:
            # Random time step
            time_step = np.random.choice(self.seq_len)
        else:
            time_step = int(self.fixed_time_step)

        if time_step != 0:
            points_dict = np.load(files[time_step])
        # Load points
        points = points_dict['points'].astype(np.float32)
        occupancies = points_dict['occupancies']
        if self.unpackbits:
            occupancies = np.unpackbits(occupancies)[:points.shape[0]]
        occupancies = occupancies.astype(np.float32)
        loc = points_dict['loc'].astype(np.float32)
        scale = points_dict['scale'].astype(np.float32)
        # Transform to loc0, scale0
        points = (loc + scale * points - loc0) / scale0

        if self.seq_len > 1:
            time = np.array(
                time_step / (self.seq_len - 1), dtype=np.float32)
        else:
            time = np.array([1], dtype=np.float32)

        data = {
            None: points,
            'occ': occupancies,
            'time': time,
        }
        return data 
示例18
def load_single_file(self, file_path):
        ''' Loads a single file.

        Args:
            file_path (str): file path
        '''
        pointcloud_dict = np.load(file_path)
        points = pointcloud_dict['points'].astype(np.float32)
        loc = pointcloud_dict['loc'].astype(np.float32)
        scale = pointcloud_dict['scale'].astype(np.float32)

        return points, loc, scale 
示例19
def load(self, model_path, idx, c_idx=None, start_idx=0, **kwargs):
        ''' Loads the point cloud sequence field.

        Args:
            model_path (str): path to model
            idx (int): ID of data point
            c_idx (int): index of category
            start_idx (int): id of sequence start
        '''
        pc_seq = []
        # Get file paths
        files = self.load_files(model_path, start_idx)
        # Load first pcl file
        _, loc0, scale0 = self.load_single_file(files[0])
        for f in files:
            points, loc, scale = self.load_single_file(f)
            # Transform mesh to loc0 / scale0
            if self.scale_pointcloud:
                points = (loc + scale * points - loc0) / scale0

            pc_seq.append(points)

        data = {
            None: np.stack(pc_seq),
            'time': self.get_time_values(),
        }

        if self.transform is not None:
            data = self.transform(data)
        return data 
示例20
def load(self, model_path, idx, c_idx=None, start_idx=0, **kwargs):
        ''' Loads the mesh sequence field.

        Args:
            model_path (str): path to model
            idx (int): ID of data point
            c_idx (int): index of category
            start_idx (int): id of sequence start
        '''
        folder = os.path.join(model_path, self.folder_name)
        mesh_files = glob.glob(os.path.join(folder, '*.%s' % self.file_ext))
        mesh_files.sort()
        mesh_files = mesh_files[start_idx:start_idx+self.seq_len]
        if self.only_end_points:
            mesh_files = [mesh_files[0], mesh_files[-1]]
        elif self.only_start_point:
            mesh_files = mesh_files[[0]]

        if self.scale:
            mesh_0 = trimesh.load(mesh_files[0], process=False)
            loc, scale = self.return_loc_scale(mesh_0)

            vertices = []
            for mesh_p in mesh_files:
                mesh = trimesh.load(mesh_p, process=False)
                mesh = self.apply_normalization(mesh, loc, scale)
                vertices.append(np.array(mesh.vertices, dtype=np.float32))

        faces = np.array(trimesh.load(
            mesh_files[0], process=False).faces, dtype=np.float32)
        data = {
            'vertices': np.stack(vertices),
            'faces': faces
        }

        return data 
示例21
def meshlab_poisson(pointcloud):
    r''' Runs the meshlab ball pivoting algorithm.

    Args:
        pointcloud (numpy tensor): input point cloud
    '''
    with tempfile.TemporaryDirectory() as tmpdir:
        script_path = os.path.join(tmpdir, 'script.mlx')
        input_path = os.path.join(tmpdir, 'input.ply')
        output_path = os.path.join(tmpdir, 'out.off')

        # Write script
        with open(script_path, 'w') as f:
            f.write(FILTER_SCRIPT_RECONSTRUCTION)

        # Write pointcloud
        export_pointcloud(pointcloud, input_path, as_text=False)

        # Export
        env = os.environ
        subprocess.Popen('meshlabserver -i ' + input_path + ' -o '
                         + output_path + ' -s ' + script_path,
                         env=env, cwd=os.getcwd(), shell=True,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         ).wait()
        mesh = trimesh.load(output_path, process=False)

    return mesh 
示例22
def getVolumeFromOFF(path, sideLen=32):
    mesh = trimesh.load(path)
    volume = trimesh.voxel.Voxel(mesh, 0.5).raw
    (x, y, z) = map(float, volume.shape)
    volume = nd.zoom(volume.astype(float), 
                     (sideLen/x, sideLen/y, sideLen/z),
                     order=1, 
                     mode='nearest')
    volume[np.nonzero(volume)] = 1.0
    return volume.astype(np.bool) 
示例23
def load(self):
        path = self.find_scene(self.meta.path)
        if not path:
            raise ValueError("Scene '{}' not found".format(self.meta.path))

        file_obj = str(path)
        if file_obj.endswith('.gz'):
            file_obj = gzip.GzipFile(file_obj)

        stl_mesh = trimesh.load(file_obj, file_type='stl')
        scene = Scene(self.meta.resolved_path)
        scene_mesh = Mesh("mesh")
        scene_mesh.material = Material("default")

        vao = VAO("mesh", mode=moderngl.TRIANGLES)
        vao.buffer(numpy.array(stl_mesh.vertices, dtype='f4'), '3f', ['in_position'])
        vao.buffer(numpy.array(stl_mesh.vertex_normals, dtype='f4'), '3f', ['in_normal'])
        vao.index_buffer(numpy.array(stl_mesh.faces, dtype='u4'))
        scene_mesh.vao = vao
        scene_mesh.add_attribute('POSITION', 'in_position', 3)
        scene_mesh.add_attribute('NORMAL', 'in_normal', 3)

        scene.meshes.append(scene_mesh)
        scene.root_nodes.append(Node(mesh=scene_mesh))
        scene.prepare()

        return scene 
示例24
def load(self) -> Scene:
        """Loads and stl scene/file

        Returns:
            Scene: The Scene instance
        """
        path = self.find_scene(self.meta.path)
        if not path:
            raise ImproperlyConfigured("Scene '{}' not found".format(self.meta.path))

        file_obj = str(path)
        if file_obj.endswith('.gz'):
            file_obj = gzip.GzipFile(file_obj)

        stl_mesh = trimesh.load(file_obj, file_type='stl')
        scene = Scene(self.meta.resolved_path)
        scene_mesh = Mesh("mesh")
        scene_mesh.material = Material("default")

        vao = VAO("mesh", mode=moderngl.TRIANGLES)
        vao.buffer(numpy.array(stl_mesh.vertices, dtype='f4'), '3f', ['in_position'])
        vao.buffer(numpy.array(stl_mesh.vertex_normals, dtype='f4'), '3f', ['in_normal'])
        vao.index_buffer(numpy.array(stl_mesh.faces, dtype='u4'))
        scene_mesh.vao = vao
        scene_mesh.add_attribute('POSITION', 'in_position', 3)
        scene_mesh.add_attribute('NORMAL', 'in_normal', 3)

        scene.meshes.append(scene_mesh)
        scene.root_nodes.append(Node(mesh=scene_mesh))
        scene.prepare()

        return scene 
示例25
def get_camera_intrinsic(folder):
    with open(folder+'intrinsics.json', 'r') as f:
        camera_intrinsics = json.load(f)


    K = np.zeros((3, 3), dtype='float64')
    K[0, 0], K[0, 2] = float(camera_intrinsics['fx']), float(camera_intrinsics['ppx'])
    K[1, 1], K[1, 2] = float(camera_intrinsics['fy']), float(camera_intrinsics['ppy'])

    K[2, 2] = 1.
    return (camera_intrinsics, K) 
示例26
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 
示例27
def load(file_obj):
        """Load a URDF from a file.

        Parameters
        ----------
        file_obj : str or file-like object
            The file to load the URDF from. Should be the path to the
            ``.urdf`` XML file. Any paths in the URDF should be specified
            as relative paths to the ``.urdf`` file instead of as ROS
            resources.

        Returns
        -------
        urdf : :class:`.URDF`
            The parsed URDF.
        """
        if isinstance(file_obj, six.string_types):
            if os.path.isfile(file_obj):
                parser = ET.XMLParser(remove_comments=True,
                                      remove_blank_text=True)
                tree = ET.parse(file_obj, parser=parser)
                path, _ = os.path.split(file_obj)
            else:
                raise ValueError('{} is not a file'.format(file_obj))
        else:
            parser = ET.XMLParser(remove_comments=True, remove_blank_text=True)
            tree = ET.parse(file_obj, parser=parser)
            path, _ = os.path.split(file_obj.name)

        node = tree.getroot()
        return URDF._from_xml(node, path) 
示例28
def load(self, model_path, idx, category):
        ''' Loads the index field.

        Args:
            model_path (str): path to model
            idx (int): ID of data point
            category (int): index of category
        '''
        return idx 
示例29
def load(self, model_path, idx, category):
        ''' Loads the category field.

        Args:
            model_path (str): path to model
            idx (int): ID of data point
            category (int): index of category
        '''
        return category 
示例30
def load(self, model_path, idx, category):
        ''' Loads the data point.

        Args:
            model_path (str): path to model
            idx (int): ID of data point
            category (int): index of category
        '''
        folder = os.path.join(model_path, self.folder_name)
        files = glob.glob(os.path.join(folder, '*.%s' % self.extension))
        if self.random_view:
            idx_img = random.randint(0, len(files)-1)
        else:
            idx_img = 0
        filename = files[idx_img]

        image = Image.open(filename).convert('RGB')
        if self.transform is not None:
            image = self.transform(image)

        data = {
            None: image
        }

        if self.with_camera:
            camera_file = os.path.join(folder, 'cameras.npz')
            camera_dict = np.load(camera_file)
            Rt = camera_dict['world_mat_%d' % idx_img].astype(np.float32)
            K = camera_dict['camera_mat_%d' % idx_img].astype(np.float32)
            data['world_mat'] = Rt
            data['camera_mat'] = K

        return data