Пример #1
0
    def _run_interface(self, runtime):
        import os.path as op
        import nibabel.gifti as ng
        import numpy as np
        import skimage.measure as sm
        import nilearn.image as nimg

        import slam.io as sio
        import slam.differential_geometry as sdg

        from nipype.utils.filemanip import split_filename

        # Generate output mesh filename from the input image name
        _, fname, _ = split_filename(self.inputs.image_file)
        gii_file = op.abspath(op.join(runtime.cwd, fname + ".gii"))

        # Load the largest connected component of the input image
        img = nimg.largest_connected_component_img(self.inputs.image_file)

        # TODO: check if the input image is correct (binary)

        # Run the marching cube algorithm
        verts, faces, normals, values = sm.marching_cubes_lewiner(
            img.get_data(), self.inputs.level)

        # Convert vertices coordinates to image space
        # TODO: check that is correct by plotting the mesh on the image
        x, y, z = nimg.coord_transform(verts[:, 0], verts[:, 1], verts[:, 2],
                                       img.affine)
        mm_verts = np.array([x, y, z]).T

        # Save the mesh as Gifti
        # FIXME: FreeView can not open the mesh (but anatomist do)
        gii = ng.GiftiImage(darrays=[
            ng.GiftiDataArray(mm_verts, intent='NIFTI_INTENT_POINTSET'),
            ng.GiftiDataArray(faces, intent='NIFTI_INTENT_TRIANGLE')
        ])
        gii.meta = ng.GiftiMetaData().from_dict({
            "volume_file":
            self.inputs.image_file,
            "marching_cube_level":
            str(self.inputs.level),
            "smoothing_iterations":
            str(self.inputs.smoothing_iter),
            "smoothing_dt":
            str(self.inputs.smoothing_dt)
        })
        ng.write(gii, gii_file)

        # Optional: Smooth the marching cube output with SLAM
        if self.inputs.smoothing_iter > 0:
            mesh = sdg.laplacian_mesh_smoothing(
                sio.load_mesh(gii_file),
                nb_iter=self.inputs.smoothing_iter,
                dt=self.inputs.smoothing_dt)
            sio.write_mesh(mesh, gii_file)

        return runtime
Пример #2
0
    def test_basic(self):
        mesh_a = self.sphere_A.copy()
        mesh_a_save = self.sphere_A.copy()

        sio.write_mesh(mesh_a, "tests/data/io/temp.gii")

        # Non modification
        assert (mesh_a.vertices == mesh_a_save.vertices).all()
        assert (mesh_a.faces == mesh_a_save.faces).all()

        mesh_b = sio.load_mesh('tests/data/io/temp.gii')

        precision_A = .00001

        # Correctness
        assert (np.isclose(mesh_a.vertices, mesh_b.vertices,
                           precision_A).all())
        assert (np.isclose(mesh_a.faces, mesh_b.faces, precision_A).all())
def main(arguments):
    if len(arguments)==3:
        meshN = arguments[1]
        texN = arguments[2]

        mesh = sio.load_mesh(meshN)

        maxCurv = maxAbsCurvature(mesh)

        # visb_sc = splt.visbrain_plot(mesh=mesh, tex=maxCurv,
        #                              caption='max absolute curvature',
        #                              cblabel='max absolute curvature')
        # visb_sc.preview()

        sio.write_texture(stex.TextureND(darray=maxCurv), texN)
    else:
        print('Usage:')
        print('python computeMaxCurvature.py mesh curvTex')
Пример #4
0
# Authors: Guillaume Auzias <*****@*****.**>

# License: BSD (3-clause)
# sphinx_gallery_thumbnail_number = 2

###############################################################################
# importation of slam modules
import slam.plot as splt
import slam.io as sio
import numpy as np
import trimesh

###############################################################################
# loading an two unregistered meshes
mesh_1 = sio.load_mesh('../examples/data/example_mesh.gii')
mesh_2 = sio.load_mesh('../examples/data/example_mesh_2.gii')

###############################################################################
# plot them to check the misalignment
joint_mesh = mesh_1 + mesh_2
joint_tex = np.ones((joint_mesh.vertices.shape[0], ))
joint_tex[:mesh_1.vertices.shape[0]] = 10
visb_sc = splt.visbrain_plot(mesh=joint_mesh,
                             tex=joint_tex,
                             caption='before registration')
visb_sc.preview()

###############################################################################
# compute ICP registration
transf_mat, cost = trimesh.registration.mesh_other(mesh_1,
    print(np.min(mesh_coords))
    print(np.max(mesh_coords))"""

    main_folder = "/hpc/meca/users/souani.a/curvature/Compute_curvatures/Quadrics"
    curv_types = ['Peyre', 'Rusinkiewicz', 'PetitJean', 'Taubin',
                  'Dong']  #, 'Peyre', 'fem', 'boix', 'bary']
    curv_types_leg = curv_types.copy()
    curv_types_leg.append('analytic')
    meshes = list()
    curv_mean = list()
    Ks = [[-1, 1], [1, 1], [0, 1]]
    for K in Ks:
        meshes.append('hex_quad_k1_' + str(K[0]) + '_k2_' + str(K[1]) + '_100')
        os.chdir(
            r"/hpc/meca/users/souani.a/curvature/Compute_curvatures/Quadrics")
        tmp_m = sio.load_mesh('hex_quad_k1_' + str(K[0]) + '_k2_' + str(K[1]) +
                              '_100.gii')
        mesh_coords = tmp_m.vertices
        print(np.shape(mesh_coords))
        curv_mean.append(
            gp.quadric_curv_mean(K[0], K[1])(mesh_coords[:, 0],
                                             mesh_coords[:, 1]))
    #meshes.append('FSsphere.ico7')
    #meshes.append('KKI2009_113_MR1.lh.white')
    for mesh_type, curv_ref in zip(meshes, curv_mean):
        print(mesh_type)

        print("Shaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaape", np.shape(curv_ref))
        file_fig = os.path.join(main_folder,
                                mesh_type + '_curv_mean_comparison_hist.png')
        curvatures = list()
        integral = list()
Пример #6
0
class TestTopologyMethods(unittest.TestCase):

    # Sphere cut by two planes, with new vertices added at the intersection
    cutSphere_A = make_cut_sphere_a()

    # Sphere cut by one plane, with new vertices added at the intersection
    cutSphere_B = make_cut_sphere_b()

    # Sphere cut by two planes, with no new vertices added at the intersection
    cutSphere_C = sio.load_mesh("tests/data/topology/mesh_C.gii")

    # A 3D disk with height 0 and radius 2
    disk_radius_2 = sio.load_mesh("tests/data/topology/mesh_D.gii")

    # hexagon 2 rings
    K = 4
    k_rings = create_K_rings(K)

    def test_boundary_angles(self):
        # for a k ring the angle between two consecutive sides is pi - pi/(3k)
        N = len(self.k_rings.vertices)
        coords = np.hstack([self.k_rings.vertices, np.zeros((N, 1))])
        indices = range(N - 6 * (self.K - 1), N)
        ang, norm = stop.boundary_angles(indices, coords)
        assert (ang == 180 - 180 / (3 * (self.K - 1))).all

    def test_boundaries_basic(self):
        mesh_a = self.cutSphere_A

        mesh_a_save = mesh_a.copy()

        boundary = stop.mesh_boundary(mesh_a)

        # Non modification
        assert (mesh_a.vertices == mesh_a_save.vertices).all()
        assert (mesh_a.faces == mesh_a_save.faces).all()

        # Correctness
        assert (len(boundary) == 2)

        # Type
        assert (isinstance(boundary, list))
        assert (isinstance(boundary[0], list))

        iterable = list(itertools.combinations(boundary, 2))

        # Uniqueness
        for b1, b2 in iterable:
            assert set(b1).intersection(set(b2)) == set()

    def test_boundaries_triangles(self):

        mesh_a = distinct_triangles(5)
        mesh_b = random_triangles(5)

        boundary_a = stop.mesh_boundary(mesh_a)
        boundary_b = stop.mesh_boundary(mesh_b)

        iterable_a = list(itertools.combinations(boundary_a, 2))
        iterable_b = list(itertools.combinations(boundary_b, 2))

        # Correctness
        assert (len(boundary_a) == 5)
        assert (len(boundary_b) == 5)

        # Uniqueness
        for b1, b2 in iterable_a:
            assert set(b1).intersection(set(b2)) == set()
        for b1, b2 in iterable_b:
            assert set(b1).intersection(set(b2)) == set()

    def test_angle_norm_boundary(self):

        # GET A DISK IN 3D

        radius = 2
        mesh_a = self.disk_radius_2
        coords3D = mesh_a.vertices

        # COMPUTE BOUNDARY

        boundary = stop.mesh_boundary(mesh_a)

        # Correctness
        assert (len(boundary) == 1)

        # COMPUTE ANGLE AND NORM VARIATIONS

        angles, norms = stop.boundary_angles(boundary[0], coords3D)
        angles = abs(180 - angles)

        sum_angles, sum_norms = sum(angles), sum(norms)

        # Computation on three arbitrary linked vertices
        three_angles, three_norms = stop.boundary_angles([0, 1, 2], coords3D)
        three_angles = abs(180 - three_angles)

        perimeter = radius * np.pi * 2
        precision_A = .001
        precision_B = .001

        # Coherence of the angle sum and norm sum
        assert (np.isclose(sum_angles, 360, precision_A))
        assert (np.isclose(sum_norms, perimeter, precision_B))

        # Coherence of a partial angle and a partial norm variation
        assert (np.isclose(three_angles[1], 360 / len(coords3D), precision_A))
        assert (np.isclose(three_norms[1], perimeter / len(coords3D),
                           precision_B))

    def test_boundaries_intersection_copy(self):
        mesh_a = self.cutSphere_A

        boundary = stop.mesh_boundary(mesh_a)
        b1 = boundary[0]
        b2 = boundary[1]
        b2_save = b2.copy()

        concat = b1 + b2

        inter_1 = stop.boundaries_intersection([concat, b2])
        inter_1 = inter_1[0][2]

        # Non modification
        assert (b2 == b2_save)

        # Type
        assert (isinstance(inter_1, list))

        # Correctness
        assert (set(inter_1) == set(b2))

    def test_close_mesh(self):
        mesh_a = self.cutSphere_C.copy()

        boundary_prev = stop.mesh_boundary(mesh_a)

        # Correctness
        assert (len(boundary_prev) == 2)

        mesh_a_closed, nvertices_added = stop.close_mesh(mesh_a)

        # Coherence
        assert (len(mesh_a_closed.vertices) == len(mesh_a.vertices) +
                nvertices_added)

        boundary_closed = stop.mesh_boundary(mesh_a_closed)

        # Mesh is now closed
        assert (len(boundary_closed) == 0)

        # Non modification of the vertices which are not on the boundaries
        sbase = (set(range(len(mesh_a.vertices))))
        sbound1 = (set(boundary_prev[0]))
        sbound2 = (set(boundary_prev[1]))
        sbound = sbound1.union(sbound2)
        snot_bound = (sbase.difference(sbound))

        for i in snot_bound:
            assert (mesh_a.vertices[i] == mesh_a_closed.vertices[i]).all()

    def test_remove_mesh_boundary_faces(self):
        mesh_a = self.cutSphere_A.copy()
        mesh_a_save = mesh_a.copy()
        boundary = stop.mesh_boundary(mesh_a)
        mesh_processed = stop.remove_mesh_boundary_faces(mesh_a,
                                                         face_vertex_number=1)
        # Non modification
        assert (mesh_a.vertices == mesh_a_save.vertices).all()
        # Correctness
        # check that when removing all faces with any vertex on the boundary,
        # all the boundary vertices are removed from the mesh
        print(len(boundary[0]))
        print(len(mesh_a.vertices))
        print(len(mesh_processed.vertices))
        assert (len(mesh_processed.vertices) == len(mesh_a.vertices) -
                len(boundary[0]))

    def test_k_ring_neighborhood(self):
        mesh_hexagon = self.k_rings.copy()
        # WARNING, 0 is not the center...
        texture_2_rings = stop.k_ring_neighborhood(mesh_hexagon, index=0, k=2)
        zero_ring = np.where(texture_2_rings == 0)[0]
        one_ring = np.where(texture_2_rings == 1)[0]
        two_ring = np.where(texture_2_rings == 2)[0]
        assert (zero_ring == [0]).all()
        assert (one_ring == [i for i in range(1, 7)]).all()
        assert (two_ring == [i for i in range(7, 19)]).all()

    def test_adjacency_matrix(self):
        toy_graph = create_test_graph()
        gd_truth_adja = []
        gd_truth_adja.append([0, 1, 1, 0])
        gd_truth_adja.append([1, 0, 1, 1])
        gd_truth_adja.append([1, 1, 0, 1])
        gd_truth_adja.append([0, 1, 1, 0])
        gd_truth_adja = np.array(gd_truth_adja)
        adja = stop.adjacency_matrix(toy_graph)
        assert (adja == gd_truth_adja).all()
Пример #7
0
# License: BSD (3-clause)
# sphinx_gallery_thumbnail_number = 2


###############################################################################
# Importation of slam modules
import slam.distortion as sdst
import slam.differential_geometry as sdg
import slam.plot as splt
import slam.io as sio
import numpy as np

###############################################################################
# Loading an example mesh and a smoothed copy of it

mesh = sio.load_mesh('../examples/data/example_mesh.gii')
mesh_s = sdg.laplacian_mesh_smoothing(mesh, nb_iter=50, dt=0.1)

##########################################################################
# Visualization of the original mesh
visb_sc = splt.visbrain_plot(mesh=mesh, caption='original mesh')
visb_sc.preview()

###############################################################################
# Visualization of the smoothed mesh
visb_sc = splt.visbrain_plot(mesh=mesh_s, caption='smoothed mesh')
visb_sc.preview()

###############################################################################
# Computation of the angle difference between each faces of mesh and mesh_s
angle_diff = sdst.angle_difference(mesh, mesh_s)
Пример #8
0
import os
import slam.io as sio
from scipy.stats import pearsonr
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

if __name__ == '__main__':
    output_folder = '/hpc/meca/users/auzias/test_curvature/real_mesh_all_curvatures'
    target_spherical_mesh = sio.load_mesh('/hpc/meca/softs/dev/auzias/FSsphere.ico7.gii')

    curv_types = ['mean_Rusinkiewicz', 'mean_Dong', 'mean_PetitJean', 'mean_Peyre', 'mean_Taubin', 'gauss_Dong', 'gauss_PetitJean', 'gauss_Peyre', 'gauss_Rusinkiewicz', 'gauss_Taubin']
    #'mean_Maillot', 'gauss_Maillot'
    sides = ['lh']

    files_list=os.listdir(output_folder)
    correl = list()
    diff = list()
    for curv_type in curv_types:
        print(curv_type+'------------------------------------------------')
        for side in sides:
            tex_files = list()
            subjects = list()
            for fil in files_list:
                if curv_type in fil and 'NN_FSsphere.ico7.gii' in fil and side in fil:
                    tex_files.append(fil)
                    filename_split = fil.split('.')
                    subj = filename_split[0]
                    filename = filename_split[-1]
                    side = filename_split[1]
# script for calculating the 3D elongations
# based on the differences of the averages of the distances
# between the vertex of interest and its 4 neighbors since we are working on
# quadrilateral configurations
# Ref: Makki.K et al. A new geodesic-based feature for characterizationof 3D shapes:
# application to soft tissue organtemporal deformations
# ICPR International Conference on Pattern Recognition -- Milan 01/2021

output_path = '../Data/Features/elongation_all/'
path = '../Data/AF_Dyn3D_5SL_QuadMesh_Gifti/'
basename = 'output_AF_Dyn3D_5SL_3dRecbyReg'
mesh_set = glob.glob(path + basename + '*.gii')
mesh_set.sort()
print(mesh_set)

data_ref = sio.load_mesh('QuadMesh_AF.gii')
pcd_pts_ref = data_ref.vertices

nbrs = NearestNeighbors(n_neighbors=5, algorithm='ball_tree').fit(pcd_pts_ref)

distances, indices = nbrs.kneighbors(pcd_pts_ref)
print(distances.shape)
print(indices.shape)
average_dist_ref = np.mean(distances[:, 1:5], axis=1)
print(average_dist_ref)
distances_trg_i = np.zeros(distances.shape)
distances_trg_j = np.zeros(distances.shape)

for t in range(len(mesh_set) - 1):
    data_dist_i = sio.load_mesh(mesh_set[t])
    pcd_pts_dist_i = data_dist_i.vertices
import trimesh
import slam.io as sio
import slam.plot as splt
import nibabel as nb
import os
import numpy as np

if __name__ == '__main__':
	fd = '/hpc/meca/users/bohi.a/Data/Models/week23_ref_surf/B0.txt'
	coords = np.loadtxt(fd, skiprows=1, max_rows=50943)
	faces = np.loadtxt(fd, skiprows=50945, dtype=np.int)
	mesh = trimesh.Trimesh(faces=faces - 1, vertices=coords, process=False)
	mesh.show()
	os.chdir(r"/hpc/meca/users/souani.a/data/OASIS")
	mesh1 = sio.load_mesh('OAS1_0277_Rwhite.gii')
	mesh1.show()
	# curv_gifti = nb.gifti.read('hex_quad_k1_0_k2_10_curv_mean_Dong.gii')
	# curv_tex = curv_gifti.darrays[0].data.squeeze()
	
	# splt.pyglet_plot(mesh1, curv_tex)
	"""mesh1 = sio.load_mesh('example_1_curv_mean_Dong.gii')
	mesh1.show()
	mesh1 = sio.load_mesh('example_1_curv_gauss_PetitJean.gii')
	mesh1.show()
	mesh1 = sio.load_mesh('example_1_curv_mean_PetitJean.gii')
	mesh1.show()
	mesh1 = sio.load_mesh('example_1_curv_gauss_Peyre.gii')
	mesh1.show()
	mesh1 = sio.load_mesh('example_1_curv_mean_Peyre.gii')
	mesh1.show()
Пример #11
0
				
				# Estimate curvatures :
				cc = 'hex_quad_k1_' + str(Ks[i][0]) + '_k2_' + str(Ks[i][1]) + '_' + str(nstep) + '_noise_' + str(
					int(sigma * 1000))
				# os.chdir(r"/hpc/meca/users/souani.a/curvature/Compute_curvatures/Noise")
				# os.mkdir(cc )
				os.chdir(r"/hpc/meca/users/souani.a/curvature/Compute_curvatures/Noise/"+cc)
				sio.write_mesh(mesh, cc+'.gii')
				list_exampels.append(cc)
				print("done for " + cc)
				data = list()
				for curv_type in curv_types:
					mesh_file = 'hex_quad_k1_' + str(Ks[i][0]) + '_k2_' + str(Ks[i][1]) + '_' + str(nstep) + '.gii'
					texture_file = cc + '_curv_mean_' + curv_type + '.gii'
					os.chdir("/hpc/meca/users/souani.a/curvature/Compute_curvatures/Quadrics")
					mesh = sio.load_mesh(mesh_file)
					# mesh.apply_transform(mesh.principal_inertia_transform)
					
					os.chdir(
						"/hpc/meca/users/souani.a/curvature/Compute_curvatures/Noise/" + cc)
					tex = sio.load_texture(texture_file)
					
					# splt.pyglet_plot(mesh, tex.darray, plot_colormap=True)
					# splt.pyglet_plot(mesh, tex.darray, 'hot', plot_colormap=True)
					# print(tex.darray)
					data.append(tex.darray)
				xx = sps.quadric_curv_mean(Ks[i][0], Ks[i][1])(mesh.vertices[:, 0], mesh.vertices[:, 1])
				xx = np.reshape(xx, (1, nstep ** 2))
				data = np.array(data)
				data_m = np.zeros((6, nstep ** 2))
				data_m[:5, :] = data[:, :, 0]
            for sigma in Sigma:

                # Generate the quadric
                # X, Y, faces, Zs = gqs.generate_quadric([ks], nstep=list_nbr_steps[i], ax=list_ax_ay[i][0ay=list_ax_ay[i][1])
                # Z = Zs[0]
                # coords = np.array([X, Y, Z]).transpose()
                # mesh = trimesh.Trimesh(faces=faces, vertices=coords, process=False)
                # mesh.show()
                # print("mesh surface = ", mesh.area, "\n surface needed = ", list_surfaces[i])

                os.chdir(
                    r"/hpc/meca/users/souani.a/curvature/Compute_curvatures/Curvatures/0Noise"
                )
                cc = 'hex_quad_k1_' + str(ks[0]) + '_k2_' + str(
                    ks[1]) + '_' + str(list_nbr_steps[i])
                mesh = sio.load_mesh(cc + '.gii')
                data = list()
                xx = gqs.quadric_curv_mean(ks[0], ks[1])(mesh.vertices[:, 0],
                                                         mesh.vertices[:, 1])
                print("-------------------------------" + cc + '_noise_' +
                      str(int(sigma * 1000)))
                for curv_type in curv_types:
                    print(curv_type)
                    texture_file = cc + '_noise_' + str(int(
                        sigma * 1000)) + '_curv_mean_' + curv_type + '.gii'

                    # mesh.apply_transform(mesh.principal_inertia_transform)

                    os.chdir(
                        "/hpc/meca/users/souani.a/curvature/Compute_curvatures/Curvatures/Noise/"
                        + cc + '_noise_' + str(int(sigma * 1000)))
import real_mesh_compute_all_curvatures
import compute_all_curvatures
import slam.plot as splt
import numpy as np
import generate_quadric_surfaces as gqs

if __name__ == "__main__":
    ccc = ["sub_mesh0", "sub_mesh1", "sub_mesh2", "sub_mesh3", "sub_mesh4"]
    curv_types = ["Dong", "PetitJean", "Peyre", "Rusinkiewicz", "Taubin"]
    mm = "lhwhite"
    i = 0
    for cc in ccc:

        os.chdir(r"/hpc/meca/users/souani.a/curvature")
        data = list()
        mesh = sio.load_mesh(cc + ".gii")
        for curv_type in curv_types:
            print(curv_type)
            os.chdir(r"/hpc/meca/users/souani.a/data/sub_m/sub_m" + str(i))
            texture_mean = sio.load_texture(cc + "_curv_mean_" + curv_type +
                                            ".gii")
            print(np.shape(texture_mean.darray))
            data.append(texture_mean.darray)
            # splt.pyglet_plot(mesh, texture_mean.darray, color_map='jet')
            texture_gauss = sio.load_texture(cc + "_curv_gauss_" + curv_type +
                                             ".gii")
            # splt.pyglet_plot(mesh, texture_gauss.darray, color_map='jet')
        #data = np.array(data)
        #print(data)
        data = np.array(data)
        print(np.shape(data))
Пример #14
0
class TestTopologyMethods(unittest.TestCase):

    # Sphere cut by two planes, with new vertices added at the intersection
    cutSphere_A = make_cut_sphere_a()

    # Sphere cut by one plane, with new vertices added at the intersection
    cutSphere_B = make_cut_sphere_b()

    # Sphere cut by two planes, with no new vertices added at the intersection
    cutSphere_C = sio.load_mesh("tests/data/topology/mesh_C.gii")

    # A 3D disk with height 0 and radius 2
    disk_radius_2 = sio.load_mesh("tests/data/topology/mesh_D.gii")

    def test_boundaries_basic(self):
        mesh_a = self.cutSphere_A

        mesh_a_save = mesh_a.copy()

        boundary = stop.mesh_boundary(mesh_a)

        # Non modification
        assert (mesh_a.vertices == mesh_a_save.vertices).all()
        assert (mesh_a.faces == mesh_a_save.faces).all()

        # Correctness
        assert (len(boundary) == 2)

        # Type
        assert (isinstance(boundary, list))
        assert (isinstance(boundary[0], list))

        iterable = list(itertools.combinations(boundary, 2))

        # Uniqueness
        for b1, b2 in iterable:
            assert set(b1).intersection(set(b2)) == set()

    def test_boundaries_triangles(self):

        mesh_a = distinct_triangles(5)
        mesh_b = random_triangles(5)

        boundary_a = stop.mesh_boundary(mesh_a)
        boundary_b = stop.mesh_boundary(mesh_b)

        iterable_a = list(itertools.combinations(boundary_a, 2))
        iterable_b = list(itertools.combinations(boundary_b, 2))

        # Correctness
        assert (len(boundary_a) == 5)
        assert (len(boundary_b) == 5)

        # Uniqueness
        for b1, b2 in iterable_a:
            assert set(b1).intersection(set(b2)) == set()
        for b1, b2 in iterable_b:
            assert set(b1).intersection(set(b2)) == set()

    def test_angle_norm_boundary(self):

        # GET A DISK IN 3D

        radius = 2
        mesh_a = self.disk_radius_2
        coords3D = mesh_a.vertices

        # COMPUTE BOUNDARY

        boundary = stop.mesh_boundary(mesh_a)

        # Correctness
        assert (len(boundary) == 1)

        # COMPUTE ANGLE AND NORM VARIATIONS

        angles, norms = stop.boundary_angles(boundary[0], coords3D)
        angles = abs(180 - angles)

        sum_angles, sum_norms = sum(angles), sum(norms)

        # Computation on three arbitrary linked vertices
        three_angles, three_norms = stop.boundary_angles([0, 1, 2], coords3D)
        three_angles = abs(180 - three_angles)

        perimeter = radius * np.pi * 2
        precision_A = .001
        precision_B = .001

        # Coherence of the angle sum and norm sum
        assert (np.isclose(sum_angles, 360, precision_A))
        assert (np.isclose(sum_norms, perimeter, precision_B))

        # Coherence of a partial angle and a partial norm variation
        assert (np.isclose(three_angles[1], 360 / len(coords3D), precision_A))
        assert (np.isclose(three_norms[1], perimeter / len(coords3D),
                           precision_B))

    def test_boundaries_intersection_copy(self):
        mesh_a = self.cutSphere_A

        boundary = stop.mesh_boundary(mesh_a)
        b1 = boundary[0]
        b2 = boundary[1]
        b2_save = b2.copy()

        concat = b1 + b2

        inter_1 = stop.boundaries_intersection([concat, b2])
        inter_1 = inter_1[0][2]

        # Non modification
        assert (b2 == b2_save)

        # Type
        assert (isinstance(inter_1, list))

        # Correctness
        assert (set(inter_1) == set(b2))

    def test_close_mesh(self):
        mesh_a = self.cutSphere_C.copy()

        boundary_prev = stop.mesh_boundary(mesh_a)

        # Correctness
        assert (len(boundary_prev) == 2)

        mesh_a_closed, nvertices_added = stop.close_mesh(mesh_a)

        # Coherence
        assert (len(mesh_a_closed.vertices) == len(mesh_a.vertices) +
                nvertices_added)

        boundary_closed = stop.mesh_boundary(mesh_a_closed)

        # Mesh is now closed
        assert (len(boundary_closed) == 0)

        # Non modification of the vertices which are not on the boundaries
        sbase = (set(range(len(mesh_a.vertices))))
        sbound1 = (set(boundary_prev[0]))
        sbound2 = (set(boundary_prev[1]))
        sbound = sbound1.union(sbound2)
        snot_bound = (sbase.difference(sbound))

        for i in snot_bound:
            assert (mesh_a.vertices[i] == mesh_a_closed.vertices[i]).all()

    def test_remove_mesh_boundary_faces(self):
        mesh_a = self.cutSphere_A.copy()
        mesh_a_save = mesh_a.copy()
        boundary = stop.mesh_boundary(mesh_a)
        mesh_processed = stop.remove_mesh_boundary_faces(mesh_a,
                                                         face_vertex_number=1)
        # Non modification
        assert (mesh_a.vertices == mesh_a_save.vertices).all()
        # Correctness
        # check that when removing all faces with any vertex on the boundary,
        # all the boundary vertices are removed from the mesh
        print(len(boundary[0]))
        print(len(mesh_a.vertices))
        print(len(mesh_processed.vertices))
        assert (len(mesh_processed.vertices) == len(mesh_a.vertices) -
                len(boundary[0]))
Пример #15
0
import numpy as np
import slam.io as sio
import os

if __name__ == '__main__':
    list_str_meshes = [
        'sub_mesh0', 'sub_mesh1', 'sub_mesh2', 'sub_mesh3', 'sub_mesh4'
    ]
    data_path = "/hpc/meca/users/souani.a/curvature/"
    list_surfaces, list_densities, list_nbr_vertex = list(), list(), list()
    os.chdir(data_path)
    for str_mesh in list_str_meshes:
        mesh = sio.load_mesh(str_mesh + '.gii')
        # mesh.show()
        print(str_mesh, ' surface : ', mesh.area_faces.sum())
        list_surfaces.append(mesh.area_faces.sum())
        print(str_mesh, ' vertices nbr : ', np.shape(mesh.vertices)[0])
        list_nbr_vertex.append(np.shape(mesh.vertices)[0])
        print(str_mesh, ' density : ',
              np.shape(mesh.vertices)[0] / mesh.area_faces.sum())
        list_densities.append(
            np.shape(mesh.vertices)[0] / mesh.area_faces.sum())
    # Comparaison d'histogrammes
Пример #16
0
import slam.plot as splt
import slam.io as sio
import slam.remeshing as srem

###############################################################################
# source object files
source_mesh_file = 'data/example_mesh.gii'
source_texture_file = 'data/example_texture.gii'
source_spherical_mesh_file = 'data/example_mesh_spherical.gii'

###############################################################################
# target object files
target_mesh_file = 'data/example_mesh_2.gii'
target_spherical_mesh_file = 'data/example_mesh_2_spherical.gii'

source_mesh = sio.load_mesh(source_mesh_file)
source_tex = sio.load_texture(source_texture_file)
source_spherical_mesh = sio.load_mesh(source_spherical_mesh_file)

target_mesh = sio.load_mesh(target_mesh_file)
target_spherical_mesh = sio.load_mesh(target_spherical_mesh_file)

interpolated_tex_values = \
    srem.spherical_interpolation_nearest_neigbhor(source_spherical_mesh,
                                                    target_spherical_mesh,
                                                    source_tex.darray[0])
###############################################################################
# plot
visb_sc = splt.visbrain_plot(mesh=source_mesh, tex=source_tex.darray[0],
                                caption='source with curvature',
                                cblabel='curvature')
Пример #17
0
			plt.xlabel(' Noise')
			plt.ylabel(' MSE ')
			s = 0
			for curv_type in curv_types:
				err= list()
				for sigma in Sigma:
					cc = 'hex_quad_k1_' + str(Ks[i][0]) + '_k2_' + str(Ks[i][1]) + '_' + str(nstep) + '_noise_' + str(
						int(sigma * 1000))
					# os.chdir(r"/hpc/meca/users/souani.a/curvature/Compute_curvatures/Noise")
					# os.mkdir(cc )
					# os.chdir(r"/hpc/meca/users/souani.a/curvature/Compute_curvatures/Noise/"+cc)
					# sio.write_mesh(mesh, cc+'.gii')
					list_exampels.append(cc)
					mesh_file = 'hex_quad_k1_' + str(Ks[i][0]) + '_k2_' + str(Ks[i][1]) + '_' + str(nstep) + '.gii'
					os.chdir("/hpc/meca/users/souani.a/curvature/Compute_curvatures/Curvatures/0Noise")
					mesh = sio.load_mesh(mesh_file)
					xx = sps.quadric_curv_mean(Ks[i][0], Ks[i][1])(mesh.vertices[:, 0], mesh.vertices[:, 1])
					xx_m = np.zeros((nstep ** 2, 1))
					texture_file = cc + '_curv_mean_' + curv_type + '.gii'
					# mesh.apply_transform(mesh.principal_inertia_transform)
					os.chdir(
						"/hpc/meca/users/souani.a/curvature/Compute_curvatures/Curvatures/Noise/" + cc)
					tex = sio.load_texture(texture_file)
					err.append(mean_squared_error(xx, tex.darray))
				
				plt.plot( Sigma,err, color=couleur[s] , marker= 'o', label=str(curv_types[s]))
				print("Done for "+ cc[:-5]+ ' for '+ curv_type)
				# plt.text(Sigma[0], err[0], curv_types[s], fontsize=9)
				s += 1
			# plt.show()
			os.chdir(r"/hpc/meca/users/souani.a/curvature/Compute_curvatures/Curvatures/Figures/Mean_squarred_error_function_of_noise")
Пример #18
0
            "marching_cube_level": self.input_spec.level,
            "smoothing_iterations": self.input_spec.smoothing_iter,
            "smoothing_dt": self.input_spec.smoothing_dt
=======
            "volume_file": self.inputs.image_file,
            "marching_cube_level": str(self.inputs.level),
            "smoothing_iterations": str(self.inputs.smoothing_iter),
            "smoothing_dt": str(self.inputs.smoothing_dt)
>>>>>>> 02924efd7fd9ff93e10f0e0030a43b878812e288
        })
        ng.write(gii, gii_file)

        # Optional: Smooth the marching cube output with SLAM
<<<<<<< HEAD
        if self.input_spec.smoothing_iter > 0:
            mesh = sdg.laplacian_mesh_smoothing(
                sio.load_mesh(gii_file), 
                nb_iter=self.input_spec.smoothing_iter,
                dt=self.input_spec.smoothing_dt)
            sio.write_mesh(mesh, gii_file)
=======
        if self.inputs.smoothing_iter > 0:
            mesh = sdg.laplacian_mesh_smoothing(
                sio.load_mesh(gii_file),
                nb_iter=self.inputs.smoothing_iter,
                dt=self.inputs.smoothing_dt)
            sio.write_mesh(mesh, gii_file)

        return runtime
>>>>>>> 02924efd7fd9ff93e10f0e0030a43b878812e288
Пример #19
0
# License: BSD (3-clause)
# sphinx_gallery_thumbnail_number = 2

###############################################################################
# Importation of slam modules
import slam.distortion as sdst
import slam.differential_geometry as sdg
import slam.plot as splt
import slam.io as sio
import numpy as np

###############################################################################
# Loading an example mesh and a smoothed copy of it

mesh = sio.load_mesh('data/example_mesh.gii')
mesh_s = sdg.laplacian_mesh_smoothing(mesh, nb_iter=50, dt=0.1)

################################################################################
# Visualization of the original mesh
visb_sc = splt.visbrain_plot(mesh=mesh, caption='original mesh')
visb_sc.preview()

###############################################################################
# Visualization of the smoothed mesh
visb_sc = splt.visbrain_plot(mesh=mesh_s,
                             caption='smoothed mesh',
                             visb_sc=visb_sc)
visb_sc.preview()

###############################################################################
Пример #20
0

#--------------------------------------------------------------------
# quadrilateral to triangular mesh Converter
#


result_path = '../Data/MESH_DATA/trimesh_gifti_all/'
path = '../Data/MESH_DATA/mesh_gifti_all/TV_Dyn3D_5SL/'
basename = 'output_TV_Dyn3D_5SL_3dRecbyReg'
mesh_set = glob.glob(path+basename+'*.gii')
mesh_set.sort()

print(len(mesh_set))

for t in range(0,len(mesh_set)):

    print(t)

    prefix = mesh_set[t].split('/')[-1].split('.')[0]

    print(prefix)

    gifti_file = result_path+prefix+'.gii'

    print(gifti_file)
    mesh = sio.load_mesh(mesh_set[t])
    #mesh = trimesh.load_mesh(mesh_set[t])
    sio.write_mesh(mesh, gifti_file)