Example #1
0
    surface_file_out = surface_file_in[:dot_index] + "_fsT" + surface_file_in[dot_index:]

img = nib.load(args.nii)
R = img.affine[:3,:3]
T = img.affine[:3,3]
z = img.header.get_zooms()
mid_point = np.array(img.shape, dtype=np.float)/2.0

# Input assert
assert not(args.ir and args.r), "--ir or --r option"
assert not(args.it and args.t), "--it or --t option"
assert not(args.im and args.m and args.imz and args.mz ), "--m,im,mz or imz option"
assert not(args.tr and args.itr and args.tir and args.itir), "--tr,itr,tir or itir option"


mesh = TriMesh_Vtk(surface_file_in, None)
    
if args.test :
    tranfo = [-2,33,12]
    mesh.set_vertices(mesh.vertices_translation(tranfo))
    print "test : " + str(tranfo)
    
#todo nii rotation before or after translation?!?!?!
if args.r :
    tranfo = R
    mesh.set_vertices(mesh.vertices_rotation(tranfo))
    print "r : " + str(tranfo)
elif args.ir :
    tranfo = R.T
    mesh.set_vertices(mesh.vertices_rotation(R))
    print "ir : " + str(tranfo)
parser.add_argument('surf_idx_inter', type=str, default=None, help='output surface index for intersection')

parser.add_argument('-rh_mask', type=str, default=None, help='input right surface mask array')
parser.add_argument('-lh_mask', type=str, default=None, help='input left surface mask array')

# option
parser.add_argument('-report', type=str, default=None, help='output intersection report')

args = parser.parse_args()

rh_lines = get_streamlines(load_streamlines_poyldata(args.rh_tracking))
lh_lines = get_streamlines(load_streamlines_poyldata(args.lh_tracking))
lines = [rh_lines, lh_lines]

print "Read .vtk surface file"
rh_mesh = TriMesh_Vtk(args.rh_surface, None)
lh_mesh = TriMesh_Vtk(args.lh_surface, None)
tris = [rh_mesh.get_triangles(), lh_mesh.get_triangles()]
vts = [rh_mesh.get_vertices(), lh_mesh.get_vertices()]

print "Generate OBB-Tree"
#tree = vtk.vtkModifiedBSPTree()
rh_tree = vtk.vtkOBBTree()
rh_tree.SetDataSet(rh_mesh.get_polydata())
rh_tree.BuildLocator()

lh_tree = vtk.vtkOBBTree()
lh_tree.SetDataSet(lh_mesh.get_polydata())
lh_tree.BuildLocator()
tree = [rh_tree, lh_tree]
Example #3
0
# by Etienne St-Onge 

import numpy as np
import time

import trimeshpy
from trimeshpy.trimesh_vtk import TriMesh_Vtk
from trimeshpy.trimeshflow_vtk import TriMeshFlow_Vtk
from trimeshpy.vtk_util import lines_to_vtk_polydata, save_polydata

# Test files
file_name = trimeshpy.data.brain_lh

mesh = TriMesh_Vtk(file_name, None)
triangles = mesh.get_triangles()
vertices = mesh.get_vertices()
mesh.display(display_name="Trimeshpy: Initial Mesh")

# pre-smooth
vertices = mesh.laplacian_smooth(2, 10.0, l2_dist_weighted=False, area_weighted=False, backward_step=True, flow_file=None)
mesh.set_vertices(vertices)
mesh.display(display_name="Trimeshpy: Smoothed Mesh")

tri_mesh_flow = TriMeshFlow_Vtk(triangles, vertices)

# Test parameters
nb_step = 10
diffusion_step = 10
saved_flow = trimeshpy.data.output_test_flow
saved_fib = trimeshpy.data.output_test_fib
Example #4
0
parser.add_argument('annot', type=str, default=None, help='input annot')

parser.add_argument('-index', type=int, nargs='+', default=None, help='color only the selected label')

parser.add_argument('-out_surface', type=str, default=None, help='output surface (.vtk)')
parser.add_argument('-out_vts_mask', type=str, default=None, help='output mask (npy array) from vts index')
parser.add_argument('--inverse_mask', action='store_true', default=False, help='inverse output mask')

parser.add_argument('--v', action='store_true', default=False, help='view surface')
parser.add_argument('--white', action='store_true', default=False, help='color white all label')
parser.add_argument('--info', action='store_true', default=False, help='view surface')

args = parser.parse_args()
print args.annot

mesh = TriMesh_Vtk(args.surface, None)
[vts_label, label_color, label_name] = read_annot(args.annot)

colors = label_color[:,:3]
vts_color =  colors[vts_label]

if args.info:
    for index in range(len(label_name)):
        print index, ": ", label_color[index], label_name[index]
    
#filter
if args.index is not None:
    print args.index
    mask = np.zeros([len(vts_label)], dtype=np.bool )
    for index in args.index:
        if index == -1:
Example #5
0
#file_name = "test_mesh/torus.obj"
#file_name = "test_mesh/spot.obj"
#file_name = "test_mesh/bunny.obj"
#ile_name = "brain_mesh/lh_sim_tri.obj"
#file_name = "brain_mesh/lh_sim_tri_tau20_l3l10.ply"
#file_name = "Raihaan/civet_obj_stl/stosurf_S1-A1_T1_white_surface_rsl_right_calibrated_81920.stl"
#file_name = "brain_mesh/white_rsl_smooth_test.ply"
#file_name = "surf_vtk/lhwhite_fsT.vtk"
#file_name = "brain_mesh/rhwhiteRAS_LPS_smooth.vtk"
#file_name = "brain_mesh/lh_white.vtk"
#file_name = "s1a1/lh_white.vtk"
#file_name = "brain_mesh/prefix_100307_white_surface.obj"
#file_name = "brain_mesh/prefix_100307_mid_surface.obj"
#file_name = "hcp/t1000_01/hcp_test_smooth_rh.vtk"

mesh = TriMesh_Vtk(file_name, None)
triangles = mesh.get_triangles()
vertices = mesh.get_vertices()
mesh.display()

"""
from scipy.spatial import Delaunay

# Triangulate parameter space to determine the triangles
#tri = mtri.Triangulation(u, v)
tri = Delaunay(vertices)
 

delaunay_triangles = np.vstack((tri.simplices[:,0:3], np.roll(tri.simplices,2,axis=1)[:,0:3]))
mesh.set_triangles(tri.simplices[:,0:3]) 
mesh.display()
Example #6
0
# by [email protected]

import numpy as np
from trimeshpy.trimesh_class import TriMesh
from trimeshpy.trimesh_vtk import TriMesh_Vtk

file_name = "../data/test_mesh/cube_simple.obj"
#file_name = "../data/test_mesh/sphere.obj"
#file_name = "../data/test_mesh/torus.obj"

mesh = TriMesh_Vtk(file_name, None)
triangles = mesh.get_triangles()
vertices = mesh.get_vertices()

tri_mesh = TriMesh(triangles, vertices)
print tri_mesh.get_nb_triangles(), tri_mesh.get_nb_vertices()

bool_tests = True
current_test = True

"""CONNECTIVITY MATRIX"""
# test vertex connectivity
vv_matrix = tri_mesh.edge_map(False)
current_test = np.alltrue(vv_matrix.todense() == vv_matrix.T.todense())
print current_test, ": connectivity is symmetric"
bool_tests = bool_tests and current_test

# test triangles vertex connectivity
tv_matrix = tri_mesh.triangle_vertex_map()
nb_triangles_per_points = tri_mesh.nb_triangles_per_vertex()
current_test = np.alltrue(tv_matrix.sum(1) == 3)
Example #7
0
    

# Label fill
if args.max_label:
    label_objects, nb_labels = ndi.label(mask)
    sizes = np.bincount(label_objects.ravel())
    sizes[0] = 0 # ingnore zero voxel
    max_label = np.argmax(sizes)
    max_mask = (label_objects == max_label)
    mask = max_mask

# Extract marching cube surface from mask
vertices, triangles = mcubes.marching_cubes(mask, args.value)

# Generate mesh
mesh = TriMesh_Vtk(triangles.astype(np.int), vertices)

# transformation
if args.world_lps:
    rotation = volume_nib.get_affine()[:3,:3]
    translation = volume_nib.get_affine()[:3,3]
    voxel_space = nib.aff2axcodes(volume_nib.get_affine())
    
    new_vertice = vertices.dot(rotation)
    new_vertice = new_vertice + translation
    # voxel_space -> LPS
    print str(voxel_space), "-to-> LPS"
    if voxel_space[0] != 'L':
        new_vertice[:,0] = -new_vertice[:,0]
    if voxel_space[1] != 'P':
        new_vertice[:,1] = -new_vertice[:,1]
Example #8
0
param_str = "parameters: "
if args.dist_weighted: param_str += "dist_weighted, "
if args.area_weighted: param_str += "area_weighted, "
if args.forward_step: param_str += "forward_step, "

print args.nb_step, "step of size ", args.step_size
print param_str

# mask step size
if args.mask is not None:
    mask = np.load(args.mask)
    step_size = args.step_size * mask
else:
    step_size = args.step_size

mesh = TriMesh_Vtk(surface_file_in, None)
smooth_vertices = mesh.laplacian_smooth(
                    nb_iter=args.nb_step, 
                    diffusion_step=step_size, 
                    l2_dist_weighted=args.dist_weighted, 
                    area_weighted=args.area_weighted, 
                    backward_step=not(args.forward_step), 
                    flow_file=None)


smoothed_mesh = TriMesh_Vtk(mesh.get_triangles(), smooth_vertices)


# Save
smoothed_mesh.save(surface_file_out)
Example #9
0
parser.add_argument('-max_nb_step', type=int, default=100, help='nb step for surface tracking interpolation')
parser.add_argument('-compression', type=float, default=None, help='compression toll (no-compression by default, but 0.01 is dipy default)')

args = parser.parse_args()

### weight correctly the ending triangle !

print " loading files!"
intersect = np.load(args.intersection)
surf_id = np.load(args.surf_idx)

tracto_polydata = load_streamlines_poyldata(args.tracto_cut)
tracto = get_streamlines(tracto_polydata)

rh_mesh = TriMesh_Vtk(args.rh_surface, None)
rh_vts = rh_mesh.get_vertices()
rh_tris = rh_mesh.get_triangles()

lh_mesh = TriMesh_Vtk(args.lh_surface, None)
lh_vts = lh_mesh.get_vertices()
lh_tris = lh_mesh.get_triangles()

rh_info = np.load(args.rh_flow_info)
lh_info = np.load(args.lh_flow_info)

rh_flow = np.memmap(args.rh_flow_file, dtype=np.float64, mode='r', 
                 shape=(rh_info[0], rh_vts.shape[0], rh_vts.shape[1]))

lh_flow = np.memmap(args.lh_flow_file, dtype=np.float64, mode='r', 
                 shape=(rh_info[0], lh_vts.shape[0], lh_vts.shape[1]))
Example #10
0
"""

# Parse input arguments
args = parser.parse_args()
surface_file_in = args.input
nii_name = args.nii

# if we got the output file name, else generate a "_lps" at the end
if args.output:
    surface_file_out = args.output
else:
    dot_index = surface_file_in.rfind(".")
    surface_file_out = surface_file_in[:dot_index] + "_lps" + surface_file_in[dot_index:]

# Apply transformation
mesh = TriMesh_Vtk(surface_file_in, None)
if not args.no_xras_translation:
    temp_file_name = "se_lps_temp_cras.txt"
    temp_dir = tempfile.mkdtemp()
    temp_file_dir = temp_dir + "/" +  temp_file_name
    
    # Find freesurfer transformation
    transform_command_line = "mri_info --cras " + nii_name + " --o " +  temp_file_dir
    print "run :", transform_command_line
    os.system(transform_command_line)
    
    print "read :", temp_file_dir
    open_file = open(temp_file_dir, 'r')
    center_ras = open_file.read()
    open_file.close()
    os.remove(temp_file_dir)
Example #11
0
import numpy as np
import trimeshpy_data
import trimeshpy.math as tmath
import laplacian_pybind as ls
import timeit
from trimeshpy.trimesh_vtk import TriMesh_Vtk
from trimeshpy.trimeshflow_vtk import TriMeshFlow_Vtk

#triangles = np.load(trimeshpy_data.cube_triangles)
#vertices = np.load(trimeshpy_data.cube_vertices)
#vertices_csc = csc_matrix(vertices)
#adjacency_matrix = edge_adjacency(triangles, vertices_csc)
#weights = np.squeeze(np.array(adjacency_matrix.sum(1)))
#print(weights)'''

file_name = trimeshpy_data.spot
mesh = TriMesh_Vtk(file_name, None)
triangles = mesh.get_triangles()
vertices = mesh.get_vertices()

np.save("tri_spot.npy", triangles)
np.save("vts_spot.npy", vertices)
Example #12
0
parser.add_argument('--vf', action='store_true', default=False, help='view surface flow')

# Parse input arguments
args = parser.parse_args()

# option output
print args.nb_step, "step of size ", args.step_size

# mask step size
if args.mask is not None:
    mask = np.load(args.mask)
    step_size = args.step_size * mask
else:
    step_size = args.step_size

mesh = TriMesh_Vtk(args.surface, None)
end_vertices = mesh.positive_mass_stiffness_smooth(
                    nb_iter=args.nb_step,
                    diffusion_step=step_size,
                    flow_file=args.flow_file)


end_mesh = TriMesh_Vtk(mesh.get_triangles(), end_vertices)

print "saving surface tracking ..."
flow = np.memmap(args.flow_file, dtype=np.float64, mode='r', shape=(args.nb_step, end_vertices.shape[0], end_vertices.shape[1]))


if args.tracking is not None:
    lines = compress_streamlines(np.swapaxes(flow, 0, 1))
    lines_polydata = lines_to_vtk_polydata(lines, None, np.float32)
Example #13
0
# by Etienne St-Onge

import trimeshpy
from trimeshpy.trimesh_vtk import TriMesh_Vtk
from trimeshpy.trimeshflow_vtk import TriMeshFlow_Vtk

# Init Sphere
s_mesh = TriMesh_Vtk(trimeshpy.data.sphere, None)
s_vshape0 = s_mesh.get_nb_vertices()

# Display sphere
sphere_tmf = TriMeshFlow_Vtk(s_mesh.get_triangles(), s_mesh.get_vertices())
sphere_tmf.display()
NB_STEP_SPHERE = 100

# Umbrella sphere
sphere_tmf.laplacian_smooth(NB_STEP_SPHERE,
                            1,
                            l2_dist_weighted=False,
                            area_weighted=False,
                            backward_step=False,
                            flow_file=trimeshpy.data.output_test_flow)
sphere_tmf.set_vertices_flow_from_memmap(trimeshpy.data.output_test_flow,
                                         NB_STEP_SPHERE, s_vshape0)
sphere_tmf.display()
sphere_tmf.display_vertices_flow()

# L2 weighted
sphere_tmf.set_vertices_flow(s_mesh.get_vertices())
sphere_tmf.laplacian_smooth(NB_STEP_SPHERE,
                            1,
Example #14
0
#!/usr/bin/env python

import argparse
import numpy as np

from trimeshpy.trimesh_vtk import TriMesh_Vtk

parser = argparse.ArgumentParser(description='Surface transformation from RAS to LPS')
parser.add_argument('input', type=str, default=None, help='input RAS surface file name')
parser.add_argument('output', type=str, default=None, help='output LPS surface file name')


#args = parser.parse_args("brain_mesh/rhwhiteRAS.vtk brain_mesh/t1_PA000002.nii.gz".split())
args = parser.parse_args()
surface_file_in = args.input
surface_file_out = args.output

mesh = TriMesh_Vtk(surface_file_in, None)
    
mesh.update_polydata()
mesh.save(surface_file_out)

Example #15
0
parser.add_argument('fodf', type=str, default=None, help='tractography fodf')
parser.add_argument('tracking', type=str, default=None, help='tracking output (.fib)')

parser.add_argument('-json', type=str, default=None, help='tracking output (.fib)')

args = parser.parse_args()

if args.json is not None:
    json_file = args.json
else:
    json_file = "se_script_config.json"
    
with open(json_file) as data_file:    
    config = json.load(data_file)

rh_mesh = TriMesh_Vtk(args.rh_surface, None)
lh_mesh = TriMesh_Vtk(args.lh_surface, None)

run = config["run"]
if run["translate"]:
    t = fsf.get_xras_translation(args.mask)
    rh_mesh.set_vertices(rh_mesh.vertices_translation(t))
    lh_mesh.set_vertices(lh_mesh.vertices_translation(t))
    print "xras translation", t

if run["space"]:
    if config["space"]["auto"]:
        vox = fsf.get_nifti_voxel_space(args.mask)
        world = fsf.get_nifti_voxel_space(args.mask)
    else: 
        vox = config["space"]["vox"]
 def update_polydata(self, vertices_flow_index=-1):
     TriMesh_Vtk.set_polydata_triangles(
         self, TriMeshFlow.get_triangles(self))
     TriMesh_Vtk.set_polydata_vertices(
         self, TriMeshFlow.get_vertices(self, vertices_flow_index=vertices_flow_index))
Example #17
0
from trimeshpy.trimesh_vtk import TriMesh_Vtk

file_name = "../data/brain_mesh/100307.obj"
save_file = "../data/brain_mesh/100307.vtk"

mesh1 = TriMesh_Vtk(file_name, None)

mesh1.save(save_file)
from trimeshpy.trimesh_vtk import TriMesh_Vtk
from trimeshpy.trimeshflow_vtk import TriMeshFlow_Vtk

# Init
saved_flow = "testflow.dat"

#files names
sphere_file_name = "../data/test_mesh/sphere.obj"
cube_file_name = "../data/test_mesh/cube_simple.obj"
torus_file_name = "../data/test_mesh/torus.obj"
spot_file_name = "../data/test_mesh/spot.obj"
brain_file_name = "../data/brain_mesh/100307_smooth_lh.vtk"


# Init Sphere
s_mesh = TriMesh_Vtk(sphere_file_name, None)
s_vshape0 = s_mesh.get_nb_vertices()

# Display sphere
sphere_tmf = TriMeshFlow_Vtk(s_mesh.get_triangles(), s_mesh.get_vertices())
sphere_tmf.display()

# Umbrella sphere
sphere_tmf.laplacian_smooth(100, 1, l2_dist_weighted=False, area_weighted=False, backward_step=False, flow_file=saved_flow)
sphere_tmf.set_vertices_flow_from_memmap(saved_flow, 100, s_vshape0)
sphere_tmf.display()
sphere_tmf.display_vertices_flow()

# L2 weighted
sphere_tmf.set_vertices_flow(s_mesh.get_vertices())
sphere_tmf.laplacian_smooth(100, 1, l2_dist_weighted=True, area_weighted=False, backward_step=False, flow_file=saved_flow)
parser.add_argument('rh_mask', type=str, default=None, help='input right surface mask array')
parser.add_argument('lh_mask', type=str, default=None, help='input left surface mask array')
parser.add_argument('output', type=str, default=None, help='output right tracking result .fib (VTK FORMAT)')

parser.add_argument('intersection', type=str, default=None, help='output points direction where flow stopped')
parser.add_argument('surf_idx_inter', type=str, default=None, help='output surface index for intersection')

# option
parser.add_argument('-nuclei', nargs='+' , default=None, help='input nuclei surface (hard stop)')
parser.add_argument('-nuclei_soft', nargs='+' , default=None, help='input nuclei surface (soft stop)')
parser.add_argument('-report', type=str, default=None, help='output intersection report')

args = parser.parse_args()

print "Read .vtk surface file"
rh_mesh = TriMesh_Vtk(args.rh_surface, None)
lh_mesh = TriMesh_Vtk(args.lh_surface, None)

print "Generate OBB-Tree"
#tree = vtk.vtkModifiedBSPTree()
rh_tree = vtk.vtkOBBTree()
rh_tree.SetDataSet(rh_mesh.get_polydata())
rh_tree.BuildLocator()

lh_tree = vtk.vtkOBBTree()
lh_tree.SetDataSet(lh_mesh.get_polydata())
lh_tree.BuildLocator()
wm_trees = [rh_tree, lh_tree]

print "Read out_surface .vtk surface file and OBB-Tree"
rh_out_mesh = TriMesh_Vtk(args.rh_out_surface, None)