예제 #1
0
def brainvisa_to_gifti(bv_mesh, gii_mesh):
    """ Conversion of brainvisa mesh to a gifti mesh

    Caveat
    ======
    requires aims
    """
    from gifti import GiftiEncoding, GiftiImage_fromarray, GiftiIntentCode
    from soma import aims
    mesh = aims.Reader().read(bv_mesh)
    vertices = np.array(mesh.vertex())
    poly = np.array([np.array(p) for p in mesh.polygon()])

    def buildMeshImage(vertices,
                       faces,
                       encoding=GiftiEncoding.GIFTI_ENCODING_ASCII):
        """ build a GiftiImage from arrays of vertices and faces

        NOTE : this is doing the same as the gifti.GiftiImage_fromTriangles
        function and is only redefined here for demonstration purpose"""

        k = GiftiImage_fromarray(vertices)
        k.arrays[0].intentString = "NIFTI_INTENT_POINTSET"
        k.addDataArray_fromarray(faces, GiftiIntentCode.NIFTI_INTENT_TRIANGLE)
        for a in k.arrays:
            a.encoding = encoding
        return k

    buildMeshImage(vertices, poly).save(gii_mesh)
예제 #2
0
def execution(self, context):
    from soma import aims
    r = aims.Reader({'Volume': {'S16': 'Graph'}})
    graph = r.read(self.read.fullPath())
    graph['filename_base'] = '*'
    aims.GraphManip.volume2Buckets(graph)
    aims.write(graph, self.write.fullPath())
    registration.getTransformationManager().copyReferential(self.read,
                                                            self.write)
    if self.removeSource:
        for f in self.read.fullPaths():
            shelltools.rm(f)
예제 #3
0
def main(Primate1, Primate2, side):
    """
    Main function that uses the text file returned by the Affine_transformations.py code in order to rescale the
    Primate2's texture so we can map Primate1's textures onto Primate1's brain surface.
    :param Primate1: string - name of Primate1
    :param Primate2: string - name of Primate2
    :param side: string - hemisphere 'L' or 'R'
    :return: the rescaled Primate2's longitudinal and latitudinal textures
    """

    nameLon = Primate2 + '_' + side + 'white_lon.gii'
    nameLat = Primate2 + '_' + side + 'white_lat.gii'

    print('reading coordinates')

    r = aims.Reader()
    texLatF = r.read(nameLat)
    texLonF = r.read(nameLon)
    texLat = np.array(texLatF[0])
    texLon = np.array(texLonF[0])

    print('reading affine transformations')

    affine_model = 'affine_trans_' + Primate1 + '_to_' + Primate2 + '_' + side + '.txt'
    int_lon, int_lat, lon_transform, lat_transform = read_affine(affine_model)

    print('processing longitude')

    newLon = rescale(texLon, lon_transform, int_lon)

    print('processing latitude')

    newLat = rescale(texLat, lat_transform, int_lat)

    print('writing textures')

    nv = texLat.size
    newLatT = aims.TimeTexture_FLOAT(1, nv)
    newLonT = aims.TimeTexture_FLOAT(1, nv)

    for i in range(nv):
        newLatT[0][i] = newLat[i]
        newLonT[0][i] = newLon[i]

    outLat = Primate1 + '_' + side + 'white_lat_to' + Primate2 + '.gii'
    outLon = Primate1 + '_' + side + 'white_lon_to' + Primate2 + '.gii'

    r = aims.Writer()
    r.write(newLatT, outLat)
    r.write(newLonT, outLon)
    print('done')
예제 #4
0
def main(arguments):
    if len(arguments) == 4:
        myelinN = arguments[1]
        surfaceN = arguments[2]
        surfMapN = arguments[3]

        r = aims.Reader()
        myelin = r.read(myelinN)
        surface = r.read(surfaceN)

        surfMap, volOut = projectOnSurface(myelin, surface)

        w = aims.Writer()
        w.write(surfMap, surfMapN)
        #w.write(volOut, 'midVoxels.nii')
    else:
        print 'Usage:'
        print 'python projectT1T2onSurface.py myelinImage surface map'
예제 #5
0
def execution(self, context):
    from soma import aims
    reader = aims.Reader()

    texture2 = reader.read(str(self.input[0]))
    texture = aims.TimeTexture_FLOAT(len(self.input), len(texture2[0]))

    # for i in six.moves.xrange(len(texture2[0])):
    # texture[0][i] = texture2[0][i]

    for i in six.moves.xrange(len(self.input)):
        aux = reader.read(str(self.input[i]))
        for j in six.moves.xrange(len(aux[0])):
            texture[i][j] = aux[0][j]
    context.write(texture.size())
    writer = aims.Writer()
    writer.write(texture, str(self.output))
    context.write("Finished")
def cingular_project(parameters):
    DATABASE, s_id = parameters

    subj_dir = os.path.join(DATABASE, s_id)

    for sd in ['L', 'R']:
        file_white_mesh = os.path.join(subj_dir, "t1mri", "BL",
                                       "default_analysis", "segmentation",
                                       "mesh", s_id + "_" + sd + "white.gii")
        pole_cingular = os.path.join(
            subj_dir, "t1mri", "BL", "default_analysis", "segmentation",
            "mesh", "surface_analysis",
            s_id + "_" + sd + "white_pole_cingular.gii")
        #aparc = os.path.join(subj_dir, "label",
        #                     s_id+ "."+sd+".aparc.native.label.gii")
        fs_cortex_label = os.path.join(subj_dir, "label",
                                       sd.lower() + 'h.cortex.label')
        re = aims.Reader()
        ws = aims.Writer()
        mesh = re.read(file_white_mesh)
        nbv = len(mesh.vertex())
        data = np.ones(nbv)

        f = open(fs_cortex_label, 'r')
        lines = f.readlines()
        for a in lines[2:]:
            a_spl = a.split()
            data[int(a_spl[0])] = a_spl[4]
        f.close()
        #data_in = gio.read(file_aparc).darrays[0].data
        #data = np.zeros_like(data_in)
        #data[data_in==-1]=1
        a, b = textureTls.textureTopologicalCorrection(mesh, data, 1)
        cingular_tex_clean, cingular_tex_boundary = a, b
        tex_out = aims.TimeTexture_S16()
        tex_out[0].assign(cingular_tex_clean)
        ws.write(tex_out, pole_cingular)
예제 #7
0
    ### =======================================================================
    ### Mesh perforator by a cylindre, centered on the lacune gravity center
    ### =======================================================================
    mesh_perfo = aims.SurfaceGenerator.cylinder(perfo_ext1, perfo_ext2, .5, .5,
                                                100, 1, 1)
    aims.write(mesh_perfo, mesh_perfo__native_filename)
    perfo_ext1_centered = perfo_ext1 - mass_center
    perfo_ext2_centered = perfo_ext2 - mass_center
    mesh_perfo_centered = aims.SurfaceGenerator.cylinder(
        perfo_ext1_centered, perfo_ext2_centered, 1, 1, 100, 1, 1)
    aims.write(mesh_perfo_centered, mesh_perfo__centered_filename)

    ### =======================================================================
    ### QC check center_of_mass == the one computed by AimsMoments
    ### =======================================================================
    ima = aims.Reader().read(ima_filename)
    mesh_lacune = aims.Reader().read(mesh_lacunes_filename)
    mesh_xyz = np.array(mesh_lacune.vertex())
    mesh_tri = np.array(mesh_lacune.polygon())
    # t,z,y,x
    arr = ima.arraydata().squeeze()
    voxel_size = ima.header()['voxel_size'].arraydata()

    # recompute mass_center from image to check that zyx*voxel_size == what is csv
    # file
    zyx = np.where(arr != 0)
    xyz_mm = np.vstack([
        zyx[2] * voxel_size[0], zyx[1] * voxel_size[1], zyx[0] * voxel_size[2]
    ]).T
    xyz_mass_center_mm = xyz_mm.mean(axis=0)
    # Check we retrive mass_center
예제 #8
0
def main(Primate1, Primate2, side):
    nameLon = Primate2 + '_' + side + 'white_lon.gii'
    nameLat = Primate2 + '_' + side + 'white_lat.gii'

    print('reading models\' informations')

    modelP1F = 'model_' + Primate1 + '_' + side + '.txt'
    modelP2F = 'model_' + Primate2 + '_' + side + '.txt'
    modelP1 = read_model(modelP1F)
    modelP2 = read_model(modelP2F)
    dimRect_P1, poles_lat_P1, longID_P1, latID_P1, sulci_lon_P1, sulci_lat_P1, lon_coor_P1, lat_coor_P1 = modelP1
    dimRect_P2, poles_lat_P2, longID_P2, latID_P2, sulci_lon_P2, sulci_lat_P2, lon_coor_P2, lat_coor_P2 = modelP2

    print('reading correspondences\' table')

    name_corr = Primate1 + '_' + Primate2 + '_' + 'corr.txt'
    if os.path.exists(name_corr):
        corrTable = read_corr(name_corr)
    else:
        name_corr = Primate2 + '_' + Primate1 + '_' + 'corr.txt'
        corrTable = read_corr(name_corr)

    print('reading coordinates')

    r = aims.Reader()
    texLatF = r.read(nameLat)
    texLonF = r.read(nameLon)
    texLat = np.array(texLatF[0])
    texLon = np.array(texLonF[0])

    print('rescaling square coordinates to sphere coordinates')

    sulciP1, sulciP2 = SquareToSphere(dimRect_P1, dimRect_P2,
                                      [lon_coor_P1, lat_coor_P1],
                                      [lon_coor_P2, lat_coor_P2], poles_lat_P1,
                                      poles_lat_P2)

    print('extracting correspondences')

    assert (len(corrTable['lon_' + Primate1]) == len(corrTable['lon_' + Primate2]) and
            len(corrTable['lat_' + Primate1]) == len(corrTable['lat_' + Primate2])), \
        "Number of corresponding sulci do not match in corr text file."

    Ncorr_lon = len(corrTable['lon_' + Primate1])
    Ncorr_lat = len(corrTable['lat_' + Primate1])
    long_corr = np.zeros((Ncorr_lon, 2)).astype('int')
    lat_corr = np.zeros((Ncorr_lat, 2)).astype('int')
    for i in range(Ncorr_lon):
        long_corr[i][0] = longID_P1[sulci_lon_P1[corrTable['lon_' +
                                                           Primate1][i]]]
        long_corr[i][1] = longID_P2[sulci_lon_P2[corrTable['lon_' +
                                                           Primate2][i]]]
    for i in range(Ncorr_lat):
        lat_corr[i][0] = latID_P1[sulci_lat_P1[corrTable['lat_' +
                                                         Primate1][i]]]
        lat_corr[i][1] = latID_P2[sulci_lat_P2[corrTable['lat_' +
                                                         Primate2][i]]]

    print('computing affine transformations')

    long_transform, lat_transform = Affine_Transform(sulciP1, sulciP2,
                                                     long_corr, lat_corr,
                                                     poles_lat_P1,
                                                     poles_lat_P2)

    print('processing longitude')

    intervals_lon = np.concatenate(([0], sulciP2[0][long_corr[:, 1]], [360]))
    intervals_lon = np.sort(intervals_lon)
    newLon = rescale(texLon, long_transform, intervals_lon)

    print('processing latitude')

    intervals_lat = np.concatenate(([30], sulciP2[1][lat_corr[:, 1]], [150]))
    intervals_lat = np.sort(intervals_lat)
    newLat = rescale(texLat, lat_transform, intervals_lat)

    print('writing textures')

    nv = texLat.size
    newLatT = aims.TimeTexture_FLOAT(1, nv)
    newLonT = aims.TimeTexture_FLOAT(1, nv)

    for i in range(nv):
        newLatT[0][i] = newLat[i]
        newLonT[0][i] = newLon[i]

    outLat = Primate1 + '_' + side + 'white_lat_to' + Primate2 + '.gii'
    outLon = Primate1 + '_' + side + 'white_lon_to' + Primate2 + '.gii'

    r = aims.Writer()
    r.write(newLatT, outLat)
    r.write(newLonT, outLon)
    print('done')

    return None
예제 #9
0
def iterate(Primate1, Primate2, side, Primate_inter=None):
    """
    Meant to be used on a database to iterate the reparametrization on a list of individuals of one species to the
    coordinate system of Primate1.
    :param Primate1: string - name of Primate1
    :param Primate2: string - name of Primate2
    :param side: string - hemisphere 'L' or 'R'
    :return: the rescaled longitudinal and latitudinal textures for each individual of Primate2
    """

    individuals = [i for i in os.listdir(Primate2) if '.' not in i]

    print('reading affine transformations')

    dir = Primate1 + '_to_' + Primate2
    if Primate_inter is not None:
        dir = Primate1 + '_to_' + Primate2 + '_via' + Primate_inter

    affine_model = os.path.join(dir,
                                'affine_trans_' + dir + '_' + side + '.txt')
    int_lon, int_lat, lon_transform, lat_transform = read_affine(affine_model)

    for ind in individuals:

        nameLon = os.path.join(Primate2, ind,
                               ind + '_' + side + 'white_lon.gii')
        nameLat = os.path.join(Primate2, ind,
                               ind + '_' + side + 'white_lat.gii')

        # print('reading coordinates')

        r = aims.Reader()
        texLatF = r.read(nameLat)
        texLonF = r.read(nameLon)
        texLat = np.array(texLatF[0])
        texLon = np.array(texLonF[0])

        # print('processing longitude')

        newLon = rescale(texLon, lon_transform, int_lon)

        # print('processing latitude')

        newLat = rescale(texLat, lat_transform, int_lat)

        # print('writing textures')

        nv = texLat.size
        newLatT = aims.TimeTexture_FLOAT(1, nv)
        newLonT = aims.TimeTexture_FLOAT(1, nv)

        for i in range(nv):
            newLatT[0][i] = newLat[i]
            newLonT[0][i] = newLon[i]

        outLat = os.path.join(
            dir, Primate1 + '_' + side + 'white_lat_to' + ind + '.gii')
        outLon = os.path.join(
            dir, Primate1 + '_' + side + 'white_lon_to' + ind + '.gii')

        r = aims.Writer()
        r.write(newLatT, outLat)
        r.write(newLonT, outLon)

    print('done')
예제 #10
0
in_file = os.path.join('/neurospin/brainomics/2016_AUSZ',"preproc_VBM","list_subjects","list_T1.txt")
out_file = os.path.join('/neurospin/brainomics/2016_AUSZ',"preproc_VBM","tissues-volumes-globals_spm-segmentation.csv")



suffix_im = "mprage_noface.nii"
inf=open(in_file, "r")
outf=open(out_file, "w")
outf.write("subject"+" "+"dimX"+" "+"dimY"+" "+"dimZ"+" "+
        "voxsizeX"+" "+"voxsizeY"+" "+"voxsizeZ"+" "+
        "nvoxGM_nomask"+" "+"nvoxWM_nomask"+" "+"nvoxCSF_nomask"+" "+
        "nvoxGM"+" "+"nvoxWM"+" "+"nvoxCSF\n")
outf.flush()


r = aims.Reader()
for cur_anat_path in inf.readlines():
    cur_anat_path = cur_anat_path.replace("\n","")
    cur_dir = os.path.dirname(cur_anat_path)
    image = os.path.basename(cur_anat_path)
    image= image[:-3]
    

    # read segmeted images
    gm_im = r.read(os.path.join(cur_dir, "c1"+image+'nii'))
    wm_im = r.read(os.path.join(cur_dir, "c2"+image+'nii'))
    csf_im = r.read(os.path.join(cur_dir, "c3"+image+'nii'))
    skull_im = r.read(os.path.join(cur_dir, "c4"+image+'nii'))
    outside_im = r.read(os.path.join(cur_dir, "c5"+image+'nii'))

    gm_arr = gm_im.arraydata().squeeze()
예제 #11
0
def csvMapGraph(options,
                agraphs=None,
                window=None,
                displayProp=None,
                palette=None,
                propPrefix=None,
                csvfilename=None,
                filterCol=None,
                filterExpr=None,
                min=None,
                max=None):
    '''csvMapGraph( options, agraphs=None, window=None, displayProp=None,
  palette=None, propPrefix=None, csvfilename=None )

  read a CSV-like file, extract numeric figures on sulci from it and map it
  on a sulci graph displayed in anatomist.

  Paramters:

  options: command-line parsing options of siCsvMapGraph (see the help of this
    command)
  agraphs: existing anatomist graph(s) on which to map data. If not specified, a
    graph is read from the options.graphname parameter.
  window: existing anatomist window in which the sulci graph will be displayed.
    If not specified, a new window will be opened.
  displayProp: when several data are read at the same time, specifies which
    one will be currently displayed. If not specified, the first data column
    will be used.
  palette: color palette to apply to the graph display. May be either an
    anatomist palette object, or a parameters dictionary, corresponding to the
    parameters of the SetObjectPalette command (see
    http://brainvisa.info/doc/anatomist-4.0/html/fr/programmation/commands.html#SetObjectPalette)
  propPrefix: data read from the CSV file are stored in the graph nodes as
    properties. The prefix is used in the properties names. If not specified,
    'csv' is used
  csvfilename: if specified, overrides options.csvfilename for convenience

  Return values: aobjects, awindows
  '''
    if csvfilename is None:
        csvfilename = options.csvfilename
    if csvfilename is None:
        parseOpts([sys.argv[0], '-h'])
        sys.exit(1)
    # read
    ft = sigraph.FoldLabelsTranslator(options.transfile)
    sigraph.si().setLabelsTranslPath(options.transfile)
    labels, sulci_data, mode = read_csv(csvfilename,
                                        options.columns,
                                        operator=options.operator,
                                        filterCol=filterCol,
                                        filterExpr=filterExpr)
    if options.summarycsvfilename:
        write_summary_csv(options.summarycsvfilename, labels, sulci_data, mode)

    # graph
    if not options.graphname: return
    from soma import aims
    graphs = []
    if agraphs:
        if isinstance(agraphs, anatomist.Anatomist.AGraph):
            agraphs = [agraphs]
        graphs = [x.graph() for x in agraphs]
    else:
        r = aims.Reader(options={'subobjectsfilter': 1})
        graphs = [r.read(f) for f in options.graphname]
        for g in graphs:
            ft.translate(g, options.label_attribute, options.label_attribute)

    # mesh
    for mfile in options.meshname:
        m = aims.read(mfile)
    else:
        m = None
    if propPrefix is None:
        propPrefix = 'csv'

    for g in graphs:
        for v in g.vertices():
            if v.getSyntax() != 'fold': continue
            if mode in ('sulci', 'label', 'name'):
                try:
                    l = v[options.label_attribute]
                    data = getdata(sulci_data, v[options.label_attribute])
                except exceptions.KeyError:
                    continue
            elif mode == 'nodes':
                try:
                    data = getdata(sulci_data, str(int(v['index'])))
                except exceptions.KeyError:
                    continue
            for i, h in enumerate(labels):
                v[propPrefix + '_mean_' + h] = data[0][i]
                if options.log and data[0][i] != 0:
                    v[propPrefix + '_log_mean_' + h] = numpy.log(data[0][i])
                elif options.log10 and data[0][i] != 0:
                    v[propPrefix + '_log_mean_' + h] = numpy.log10(data[0][i])
                # add only no-null std
                if data[1][i]: v[propPrefix + '_std_' + h] = data[1][i]
                v[propPrefix + '_sum_' + h] = data[2][i]

    a = anatomist.Anatomist()
    aobjects = []
    if not agraphs:
        agraphs = [a.toAObject(g) for g in graphs]
        aobjects = agraphs
    if displayProp is None:
        displayProp = propPrefix + '_mean_' + labels[0]
    for ag in agraphs:
        ag.setColorMode(ag.PropertyMap)
        ag.setColorProperty(displayProp)
        #modified to get the palette as imput argument
        palette = a.getPalette(palette)
        if palette is not None:
            if isinstance(palette, a.APalette):
                #modified to get min and max values as imputs
                ag.setPalette(palette,
                              minVal=min,
                              maxVal=max,
                              absoluteMode=True)
                #ag.setPalette( palette )
            else:  # dict
                a.execute('SetObjectPalette', objects=[ag], **palette)
        ag.notifyObservers()
        if m:
            am = a.toAObject(m)
            aobjects.append(am)
    if window is not None:
        win = window
        wins = []
    else:
        win = a.createWindow(wintype='3D')
        wins = [win]
    win.setHasCursor(0)
    win.addObjects(aobjects, add_graph_nodes=True)
    return aobjects, wins
예제 #12
0
def do_mesh_cluster_rendering(
        title,
        clust_mesh_file,
        clust_texture_file,
        brain_mesh_file,
        anat_file,
        palette_file="palette_signed_values_blackcenter",
        #a = None,
        check=False,
        verbose=True):
    """ Vizualization of signed stattistic map or weigths.

    Parameters
    ----------
    clust_mesh_file : str (mandatory)
        a mesh file of interest.
    clust_texture_file : str (mandatory)
        an IMAGE from which to extract texture (for the mesh file).
    brain_mesh_file : str (mandatory)
        a mesh file of the underlying neuroanatomy.
    anat_file : str (mandatory)
        an IMAGE of the underlying neuroanatomy.
    check : bool (default False)
        manual check of the input parameters.
    verbose : bool (default True)
        print to stdout the function prototype.

    Returns
    -------
    None
    """
    #FunctionSummary(check, verbose)
    global ANATOMIST
    global VIEWS
    global IMAGE
    # instance of anatomist
    if ANATOMIST is None:
        ANATOMIST = anatomist.Anatomist()
        # Add new SnapshotControl button
        pix = QtGui.QPixmap('control.xpm')
        anatomist.cpp.IconDictionary.instance().addIcon('Snap', pix)
        ad = anatomist.cpp.ActionDictionary.instance()
        ad.addAction('SnapshotAction', lambda: SnapshotAction())
        cd = anatomist.cpp.ControlDictionary.instance()
        cd.addControl('Snap', lambda: SnapshotControl(), 25)
        cm = anatomist.cpp.ControlManager.instance()
        cm.addControl('QAGLWidget3D', '', 'Snap')
    a = ANATOMIST
    # ------------
    # load objects
    # ------------
    clust_mesh = a.loadObject(clust_mesh_file)
    brain_mesh = a.loadObject(brain_mesh_file)
    clust_texture = a.loadObject(clust_texture_file)
    IMAGE = aims.Reader().read(clust_texture_file)
    image_dim = IMAGE.header()['volume_dimension'].arraydata()[:3]
    """
    cd /home/ed203246/mega/data/mescog/wmh_patterns/summary/cluster_mesh/tvl1l20001
    from soma import aims
    clust_texture_file = "clust_values.nii.gz"
    IMAGE = aims.Reader().read(clust_texture_file)
    image_dim = IMAGE.header()['volume_dimension'].arraydata()[:3]


    trm_ima_mm2ref_mm = aims.Motion(ima.header()['transformations'][0])

    trm_xyz_to_mm = ima_get_trm_xyz_to_mm(ima)
    min_mm = trm_ima_mm2ref_mm.transform([0, 0, 0])
    #a=ima.header()['volume_dimension']
    ima_dim_xyz = ima.header()['volume_dimension'].arraydata()[:3]
    max_mm = trm_ima_mm2ref_mm.transform(ima_dim_xyz)

    trm_ima_mm2ref_mm = aims.Motion(ima.header()['transformations'][0])
    ima_voxel_size = ima.header()['voxel_size'][:3]
    xyz_to_mm(trm_ima_mm2ref_mm, ima_voxel_size)
    """
    #print clust_texture.header()#['volume_dimension']
    a_anat = a.loadObject(anat_file)

    # mesh option
    material = a.Material(diffuse=[0.8, 0.8, 0.8, 0.6])
    brain_mesh.setMaterial(material)

    # change palette
    #palette_file = get_sample_data("brainvisa_palette").edouard
    #    bv_rgb_dir = os.path.join(os.environ["HOME"], ".anatomist", "rgb")
    #    if not os.path.isdir(bv_rgb_dir):
    #        os.makedirs(bv_rgb_dir)
    #    bv_rgb_file = os.path.join(bv_rgb_dir,
    #                               os.path.basename(palette_file))
    #    if not os.path.isfile(bv_rgb_file):
    #        shutil.copyfile(palette_file, bv_rgb_file)
    palette = a.getPalette(palette_file)
    clust_texture.setPalette(palette, minVal=-10, maxVal=10, absoluteMode=True)

    # view object
    block = a.createWindowsBlock(2)
    windows = list()
    objects = list()
    # --------------------------------
    # 3D view = fusion 3D + brain_mesh
    # --------------------------------
    win3d = a.createWindow("3D", block=block)
    # orientation front left
    Q_rot = [np.cos(np.pi / 8.), np.sin(np.pi / 8.), 0, 0]
    fusion3d = a.fusionObjects([clust_mesh, clust_texture], "Fusion3DMethod")
    win3d.addObjects([fusion3d, brain_mesh])
    a.execute("Fusion3DParams",
              object=fusion3d,
              step=0.1,
              depth=5.,
              sumbethod="max",
              method="line_internal")
    #define point of view
    Q1 = win3d.getInfos()["view_quaternion"]  # current point of view
    Q = product_quaternion(Q1, Q_rot)
    a.execute("Camera", windows=[win3d], view_quaternion=Q)
    windows.append(win3d)
    objects.append(fusion3d)
    VIEWS[(title, "3d")] = [win3d, fusion3d]
    # -------------------------------------
    # Slices view = three VIEWS offusion 2D
    # -------------------------------------
    # fusion 2D
    fusion2d = a.fusionObjects([a_anat, clust_texture], "Fusion2DMethod")
    a.execute("Fusion2DMethod", object=fusion2d)
    # change 2D fusion settings
    a.execute("TexturingParams",
              texture_index=1,
              objects=[
                  fusion2d,
              ],
              mode="Geometric")  #, rate=0.1)

    ##############
    # Coronal view
    win_coronal = a.createWindow("3D", block=block)
    print "win_coronal", win_coronal
    # Fusion cut mesh
    fusionmesh_coronal = a.fusionObjects([brain_mesh, fusion2d],
                                         "FusionCutMeshMethod")
    a.execute("FusionCutMeshMethod", object=fusionmesh_coronal)
    fusionmesh_coronal.addInWindows(win_coronal)
    # Coronal view
    # Slice
    #sclice_coronal(fusionmesh_coronal, -90)
    sclice_coronal(fusionmesh_coronal, int(-(image_dim / 2)[1]))
    # Store
    windows.append(win_coronal)
    #a.execute
    objects.append([fusion2d, fusionmesh_coronal])
    VIEWS[(title, "coronal")] = [win_coronal, fusionmesh_coronal]

    ##############
    # Axial view
    win_axial = a.createWindow("3D", block=block)
    print "win_axial", win_axial, win_axial.getInfos()
    # Fusion cut mesh
    fusionmesh_axial = a.fusionObjects([brain_mesh, fusion2d],
                                       "FusionCutMeshMethod")
    a.execute("FusionCutMeshMethod", object=fusionmesh_axial)
    fusionmesh_axial.addInWindows(win_axial)
    # Axial view, orientation front top left
    Q_rot = [np.cos(np.pi / 8.), np.sin(np.pi / 8.), 0, np.sin(np.pi / 8.)]
    Q1 = win_axial.getInfos()["view_quaternion"]  # current point of view
    Q = product_quaternion(Q1, Q_rot)
    a.execute("Camera", windows=[win_axial], view_quaternion=Q, zoom=0.8)
    # Slice
    sclice_axial(fusionmesh_axial, int(-(image_dim / 2)[2]))
    # Store
    windows.append(win_axial)
    #a.execute
    objects.append([fusion2d, fusionmesh_axial])
    VIEWS[(title, "axial")] = [win_axial, fusionmesh_axial]

    ##############
    #Sagital view
    win_sagital = a.createWindow("3D", block=block)
    print "win_sagital", win_sagital
    # Fusion cut mesh
    fusionmesh_sagital = a.fusionObjects([brain_mesh, fusion2d],
                                         "FusionCutMeshMethod")
    a.execute("FusionCutMeshMethod", object=fusionmesh_sagital)
    fusionmesh_sagital.addInWindows(win_sagital)
    # Sagital view: rotation -Pi/4 --> orientation right
    Q_rot = [np.sqrt(2) / 2., -np.sqrt(2) / 2., 0, 0]
    Q1 = win_sagital.getInfos()["view_quaternion"]  # current point of view
    Q = product_quaternion(Q1, Q_rot)
    a.execute("Camera", windows=[win_sagital], view_quaternion=Q, zoom=0.9)
    # Slice
    sclice_sagital(fusionmesh_sagital, int(-(image_dim / 2)[0]))
    # Store
    windows.append(win_sagital)
    #a.execute
    objects.append([fusion2d, fusionmesh_sagital])
    VIEWS[(title, "sagital")] = [win_sagital, fusionmesh_sagital]

    # Global windows info
    try:
        block.widgetProxy().widget.setWindowTitle(str(title))
    except:
        print "could not set name"

    return [
        clust_mesh, brain_mesh, clust_texture, a_anat, material, palette,
        block, windows, objects
    ]
예제 #13
0
                [['moment_invariant_%i' % i, values[i]] for i in xrange(len(values))]
            moment_invariant = False
    cols, values = zip(*lacune_keys_values)
    #if columns is None:
    #    columns = cols
    #assert cols == columns
    columns += list(cols)
    moments += list(values)
    # 3) Mesh file
    out = os.popen('AimsMesh -i %s -o %s' % (ima_filename, prefix_mesh_filename))
    # 4) Compute surface & volume from mesh
    out = os.popen('AimsMeshArea -i %s' % mesh_filename)
    columns += ["area_mesh", "vol_mesh"]
    moments += [float(l.strip().split(" ")[1]) for l in out.readlines()]
   # 5) Get perforator orientation
    vol_aims = aims.Reader().read(perforator_filename)
    # t,z,y,x
    arr = vol_aims.arraydata().squeeze()
    voxel_size = vol_aims.header()['voxel_size'].arraydata()
    perfo_xyz1 = np.asarray(np.where(arr == 2)).squeeze()[::-1] * voxel_size
    perfo_xyz2 = np.asarray(np.where(arr == 1)).squeeze()[::-1] * voxel_size
    perfo_xyz_vec = (perfo_xyz1 - perfo_xyz2)
#    perfo_zyx =  perfo_ext1 - perfo_ext2
#    perfo_ext1 = np.asarray(np.where(arr == 2)).squeeze()
#    perfo_ext2 = np.asarray(np.where(arr == 1)).squeeze()
#    perfo_zyx =  perfo_ext1 - perfo_ext2
#    perfo_xyz = (perfo_zyx * voxel_size[::-1])[::-1]
    columns += ['perfo_orientation_%s' % xyz[i] for i in xrange(len(perfo_xyz_vec))]
    moments += perfo_xyz_vec.tolist()
    columns += ['perfo_ext1_%s' % xyz[i] for i in xrange(len(perfo_xyz1))]
    moments += perfo_xyz1.tolist()