How to use the trimesh.Trimesh function in trimesh

To help you get started, we’ve selected a few trimesh examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ThibaultGROUEIX / 3D-CODED / auxiliary / model.py View on Github external
ax.set_zlim3d(-0.8, 0.8)
                # ax.set_xlabel('X Label')
                # ax.set_ylabel('Y Label')
                # ax.set_zlabel('Z Label')
                ax.scatter(p3, p1, p2, alpha=1, s=10, c='salmon', edgecolor='orangered')
                plt.grid(b=None)
                plt.axis('off')
                fig.savefig(os.path.join(path, "points_" + str(0) + "_" + str(self.count)), bbox_inches='tight',
                            pad_inches=0)
            else:
                print("can't save png if dim template is not 3!")
        if self.patch_deformation:
            templates = self.get_patch_deformation_template()
            if self.dim_template == 3:
                template_points = templates[0].cpu().clone().detach().numpy()
                mesh_patch_deformation = trimesh.Trimesh(vertices=template_points,
                faces=self.template[0].mesh.faces, process=False)
                mesh_patch_deformation.export(os.path.join(path, "mesh_patch_deformation.ply"))
                p1 = template_points[:, 0]
                p2 = template_points[:, 1]
                p3 = template_points[:, 2]
                fig = plt.figure(figsize=(20, 20), dpi=80)
                fig.set_size_inches(20, 20)
                ax = fig.add_subplot(111, projection='3d', facecolor='white')
                # ax = fig.add_subplot(111, projection='3d',  facecolor='#202124')
                ax.view_init(0, 30)
                ax.set_xlim3d(-0.8, 0.8)
                ax.set_ylim3d(-0.8, 0.8)
                ax.set_zlim3d(-0.8, 0.8)
                # ax.set_xlabel('X Label')
                # ax.set_ylabel('Y Label')
                # ax.set_zlabel('Z Label')
github ThibaultGROUEIX / 3D-CODED / auxiliary / my_utils.py View on Github external
def clean(input_mesh, prop=None):
    """
    This function remove faces, and vertex that doesn't belong to any face. Intended to be used before a feed forward pass in pointNet
    Input : mesh
    output : cleaned mesh
    """
    print("cleaning ...")
    print("number of point before : " , np.shape(input_mesh.vertices)[0])
    pts = input_mesh.vertices
    faces = input_mesh.faces
    faces = faces.reshape(-1)
    unique_points_index = np.unique(faces)
    unique_points = pts[unique_points_index]

    print("number of point after : " , np.shape(unique_points)[0])
    mesh = trimesh.Trimesh(vertices=unique_points, faces=np.array([[0,0,0]]), process=False)
    if prop is not None:
        new_prop = prop[unique_points_index]
        return mesh, new_prop
    else:
        return mesh
github VarianAPIs / PyESAPI / pyesapi / tools / plans / shape_based_dose.py View on Github external
open_field_dose = None
    if use_beam_dose:
        if ref_image is None:
            # use dose grid resolution
            open_field_dose = pysapi_beam.Dose.np_array_like()  # dose grid res
        else:
            # use image grid resolution
            open_field_dose = pysapi_beam.Dose.np_array_like(ref_image)
        assert open_field_dose.shape == dose_shape, "dose shape does not match beam dose or image shape"
        # get dose from beam

    csr = compute_Dij_bodymesh(  # v_dig_valid, x_bins, y_bins
        dose_shape,
        idxs_oi,
        pts_3d,
        bodymesh=tm.Trimesh(vertices=body_verts, faces=body_faces),
        beam_energy=pysapi_beam.EnergyModeDisplayName,
        SAD=pysapi_beam.TreatmentUnit.get_SourceAxisDistance(),
        gantry_angle=gantry_angle_deg,
        field_size=field_size_mm,
        field_buffer=field_buffer_mm,  # added to all sides
        beamlet_size_x=beamlet_size_x_mm,
        beamlet_size_z=beamlet_size_z_mm,
        show_plots=False,
        anti_alias=anti_alias,
        pdd_dose=open_field_dose
    )

    return csr
github xuelin-chen / pcl2pcl-gan-pub / pc2pc / tools / render_results / convert_point_cloud_to_balls.py View on Github external
points = []
    faces = []

    for pts in tqdm(pc):
        sphere_m = trimesh.creation.uv_sphere(radius=sphere_r, count=[16,16])
        sphere_m.apply_translation(pts)

        faces_offset = np.array(sphere_m.faces) + len(points)
        faces.extend(faces_offset)
        points.extend(np.array(sphere_m.vertices))
    
    points = np.array(points)
    faces = np.array(faces)
    print(points.shape, faces.shape)
    finale_mesh = trimesh.Trimesh(vertices=points, faces=faces)
    finale_mesh.export(output_filename)
    #write_obj(points, faces, output_filename)
github ThibaultGROUEIX / 3D-CODED / inference / reconstruct.py View on Github external
faces_tosave = global_variables.network.mesh_HR.faces
    else:
        faces_tosave = global_variables.network.mesh.faces

    # create initial guess
    mesh = trimesh.Trimesh(vertices=(bestPoints[0].data.cpu().numpy() + translation)/scalefactor, faces=global_variables.network.mesh.faces, process = False)


    #START REGRESSION
    print("start regression...")

    # rotate with optimal angle
    rot_matrix = np.array([[np.cos(best_theta), 0, np.sin(best_theta)], [0, 1, 0], [- np.sin(best_theta), 0,  np.cos(best_theta)]])
    rot_matrix = torch.from_numpy(rot_matrix).float().cuda()
    points2 = torch.matmul(rot_matrix, points)
    mesh_tmp = trimesh.Trimesh(vertices=points2[0].transpose(1,0).data.cpu().numpy(), faces=global_variables.network.mesh.faces, process=False)
    bbox = np.array([[np.max(mesh_tmp.vertices[:,0]), np.max(mesh_tmp.vertices[:,1]), np.max(mesh_tmp.vertices[:,2])], [np.min(mesh_tmp.vertices[:,0]), np.min(mesh_tmp.vertices[:,1]), np.min(mesh_tmp.vertices[:,2])]])
    norma = torch.from_numpy((bbox[0] + bbox[1]) / 2).float().cuda()
    norma2 = norma.unsqueeze(1).expand(3,points2.size(2)).contiguous()
    points2[0] = points2[0] - norma2
    pointsReconstructed1 = regress(points2)
    # unrotate with optimal angle
    norma3 = norma.unsqueeze(0).expand(pointsReconstructed1.size(1), 3).contiguous()
    rot_matrix = np.array([[np.cos(-best_theta), 0, np.sin(-best_theta)], [0, 1, 0], [- np.sin(-best_theta), 0,  np.cos(-best_theta)]])
    rot_matrix = torch.from_numpy(rot_matrix).float().cuda()
    pointsReconstructed1[0] = pointsReconstructed1[0] + norma3
    pointsReconstructed1 = torch.matmul(pointsReconstructed1, rot_matrix.transpose(1,0))

    # create optimal reconstruction
    meshReg = trimesh.Trimesh(vertices=(pointsReconstructed1[0].data.cpu().numpy()  + translation)/scalefactor, faces=faces_tosave, process=False)

    print("... Done!")
github schlegelp / navis / navis / core / neurons.py View on Github external
def __getattr__(self, key):
        """We will use this magic method to calculate some attributes on-demand."""
        # Note that we're mixing @property and __getattr__ which causes problems:
        # if a @property raises an Exception, Python falls back to __getattr__
        # and traceback is lost!

        if key == 'trimesh':
            self.trimesh = tm.Trimesh(vertices=self.vertices, faces=self.faces)
            return self.trimesh

        # See if trimesh can help us
        if hasattr(self.trimesh, key):
            return getattr(self.trimesh, key)

        # Last ditch effort - maybe the base class knows the key?
        return super().__getattr__(key)
github tangjiapeng / SkeletonBridgeRecon / Volume_refinement / Local_Synthesis / save_obj.py View on Github external
for i in range(2):
            for j in range(2):
                for k in range(2):
                    prediction[:, i * 64:(i + 1) * 64, j * 64:(j + 1) * 64, k * 64:(k + 1) * 64] = output.data[i * 4 + j * 2 + k, :, :, :]
                    groudtruth[:, i * 64:(i + 1) * 64, j * 64:(j + 1) * 64, k * 64:(k + 1) * 64] = gt.data[i * 4 + j * 2 + k, :, :, :]

        objfile = os.path.join(outdir, mod + '_' + seq + '.obj')
        voxels = torch.squeeze(prediction).cpu().numpy()
        voxels = np.pad(voxels, (1, 1), 'constant', constant_values=(0, 0))  ## padding for generating a closed shape
        gt_file = os.path.join(gt_dir, mod + '_' + seq + '.binvox')
        with open(gt_file, 'rb') as fp:
            dims, translate, scale = binvox_rw.read_header(fp)
        vertices, faces, = libmcubes.marching_cubes(voxels, 0.5)
        vertices = (vertices - 63.5)/128.0 * scale + np.array([0, 0, -0.8], dtype='f4') 
        #vertices = (vertices - 63.5)/128.0 * scale + translate # don't use this
        mesh = trimesh.Trimesh(vertices, faces, vertex_normals=None, process=False)
        mesh = libsimplify.simplify_mesh(mesh, opt.nfaces)
        mesh.export(objfile)
        print('[%d/%d] time: %f' % (idx, len(dataset) / 8, time.time() - t0), objfile)

network.eval()
if True:
    for idx in range(len_dataset_test/8):
        t0 = time.time()
        refine, input, gt, f, mod, seq = dataset_test.get_batch()
        objfile = os.path.join(outdir, mod + '_' + seq + '.obj')
        if os.path.exists(objfile):
            continue
        refine = refine.cuda()
        input = input.cuda()
        gt = gt.cuda()
github BerkeleyAutomation / perception / perception / image.py View on Github external
if vertex_indices[i+1,j] == -1:
                        vertices.append(v2)
                        vertex_indices[i+1,j] = len(vertices)-1
                    if vertex_indices[i+1,j+1] == -1:
                        vertices.append(v3)
                        vertex_indices[i+1,j+1] = len(vertices)-1
                
                    # add tri
                    i0 = vertex_indices[i,j]
                    i2 = vertex_indices[i+1,j]
                    i3 = vertex_indices[i+1,j+1]
                    triangles.append([i0, i3, i2])

        # return trimesh
        import trimesh
        mesh = trimesh.Trimesh(vertices, triangles)
        return mesh
github schlegelp / skeletonizer / skeletor / skeletonizers.py View on Github external
coords :    trimesh.Trimesh | np.ndarray of vertices
                Used to get coordinates for nodes in ``x``.
    reindex :   bool
                If True, will re-number node IDs, if False will keep original
                vertex IDs.
    validate :  bool
                If True, will check check if SWC table is valid and raise an
                exception if issues are found.

    Returns
    -------
    SWC table : pandas.DataFrame

    """
    assert isinstance(coords, (tm.Trimesh, np.ndarray))

    if isinstance(x, np.ndarray):
        edges = x
    elif isinstance(x, (nx.Graph, nx.DiGraph)):
        edges = np.array(x.edges)
    else:
        raise TypeError(f'Expected array or Graph, got "{type(x)}"')

    # Make sure edges are unique
    edges = np.unique(edges, axis=0)

    # Generate node table
    swc = pd.DataFrame(edges, columns=['node_id', 'parent_id'])

    # See if we need to add manually add rows for root node(s)
    miss = swc.parent_id.unique()
github schlegelp / skeletonizer / skeletonizer / skeleton.py View on Github external
mesh :      trimesh.Trimesh
                Original mesh. We will extract coordinates.
    reindex :   bool
                If True, will re-number node IDs, if False will keep original
                vertex IDs.
    validate :  bool
                If True, will check check if SWC table is valid and raise an
                exception if issues are found.

    Returns
    -------
    SWC table : pandas.DataFrame

    """
    assert isinstance(mesh, tm.Trimesh)

    if isinstance(x, np.ndarray):
        edges = x
    elif isinstance(x, (nx.Graph, nx.DiGraph)):
        edges = np.array(x.edges)
    else:
        raise TypeError(f'Expected array or Graph, got "{type(x)}"')

    # Make sure edges are unique
    edges = np.unique(edges, axis=0)

    # Generate node table
    swc = pd.DataFrame(edges, columns=['node_id', 'parent_id'])

    # See if we need to add manually add rows for root node(s)
    miss = swc.parent_id.unique()