コード例 #1
0
ファイル: caret_to_mesh.py プロジェクト: rbakker/sba-dev
    def main(self, surf_coord, surf_topo, faces_csv, vertices_csv,
             vertexlimits_csv):
        F = LoadFaces.fromParent(self).setInput(surf_topo).run().getOutput(
            'faces')
        F = numpy.array(F, int)
        with open(faces_csv, 'w') as fp:
            for line in F:
                fp.write(','.join([str(v) for v in line]) + '\n')

        V = LoadVertices.fromParent(self).setInput(surf_coord).run().getOutput(
            'vertices')
        V = numpy.array(V, float)
        with open(vertices_csv, 'w') as fp:
            for line in V:
                fp.write(','.join([str(v) for v in line]) + '\n')

        minmax = [
            ','.join([str(v) for v in V.min(axis=0)]),
            ','.join([str(v) for v in V.max(axis=0)])
        ]
        with open(vertexlimits_csv, 'w') as fp:
            fp.write('\n'.join(minmax))

        return FancyDict(faces_csv=faces_csv,
                         vertices_csv=vertices_csv,
                         vertexlimits_csv=vertexlimits_csv)
コード例 #2
0
  def main(self,surf_coord,surf_topo,faces_csv,vertices_csv,vertexlimits_csv):
    F = LoadFaces.fromParent(self).setInput(surf_topo).run().getOutput('faces')
    F = numpy.array(F,int)
    with open(faces_csv,'w') as fp:
      for line in F:
        fp.write(','.join([str(v) for v in line])+'\n')
    
    V = LoadVertices.fromParent(self).setInput(surf_coord).run().getOutput('vertices')
    V = numpy.array(V,float)
    with open(vertices_csv,'w') as fp:
      for line in V:
        fp.write(','.join([str(v) for v in line])+'\n')

    minmax = [
      ','.join([str(v) for v in V.min(axis=0)]),
      ','.join([str(v) for v in V.max(axis=0)])
    ]
    with open(vertexlimits_csv,'w') as fp:
      fp.write('\n'.join(minmax))

    return FancyDict(
      faces_csv = faces_csv,
      vertices_csv = vertices_csv,
      vertexlimits_csv = vertexlimits_csv
    )
コード例 #3
0
ファイル: x3d_to_mesh.py プロジェクト: rbakker/sba-dev
    def main(self, surface_x3d, faces_csv, vertices_csv, vertexlimits_csv):
        # custom parser needed to parse files larger than approx. 10 MB.
        tree = etree.parse(surface_x3d,
                           parser=etree.ETCompatXMLParser(huge_tree=True))
        rootNode = tree.getroot()
        faceNode = rootNode.find('.//IndexedFaceSet')
        faces = re.sub('[\s,]+', ',', faceNode.attrib['coordIndex'].strip())
        faces = re.sub(',-1,', '\n', faces)
        faces = re.sub(',-1$', '', faces)
        with open(faces_csv, 'w') as fp:
            fp.write(faces)
        # experimental: save binary data (works well, but gz is more useful)
        """
    faces = json.loads('[['+re.sub('\n','],[',faces)+']]')
    faces = numpy.array(faces,numpy.dtype('<u4'))
    faces_dat = re.sub('\.csv$','',faces_csv)+'.dat';
    with open(faces_dat,'w') as fp:
      fp.write(faces.tostring())
    """

        vertexNode = faceNode.find('Coordinate')
        with open(vertices_csv, 'w') as fp:
            vertices = re.sub('[\s,]+', ' ',
                              vertexNode.attrib['point'].strip())
            vertices = vertices.split(' ')
            vertices = [
                ','.join(vertices[i:i + 3])
                for i in range(0, len(vertices), 3)
            ]
            fp.write('\n'.join(vertices))

        V = LoadVertices().setInput(vertices_csv).getOutput('vertices')
        V = numpy.array(V, float)
        minmax = [
            ','.join([str(v) for v in V.min(axis=0)]),
            ','.join([str(v) for v in V.max(axis=0)])
        ]
        with open(vertexlimits_csv, 'w') as fp:
            fp.write('\n'.join(minmax))

        return FancyDict(faces_csv=faces_csv,
                         vertices_csv=vertices_csv,
                         vertexlimits_csv=vertexlimits_csv)
コード例 #4
0
  def main(self,surface_x3d,faces_csv,vertices_csv,vertexlimits_csv):
    # custom parser needed to parse files larger than approx. 10 MB.
    tree = etree.parse(surface_x3d,parser=etree.ETCompatXMLParser(huge_tree=True))
    rootNode = tree.getroot()
    faceNode = rootNode.find('.//IndexedFaceSet')
    faces = re.sub('[\s,]+',',',faceNode.attrib['coordIndex'].strip())
    faces = re.sub(',-1,','\n',faces)
    faces = re.sub(',-1$','',faces)
    with open(faces_csv,'w') as fp:
      fp.write(faces)
    # experimental: save binary data (works well, but gz is more useful)
    """
    faces = json.loads('[['+re.sub('\n','],[',faces)+']]')
    faces = numpy.array(faces,numpy.dtype('<u4'))
    faces_dat = re.sub('\.csv$','',faces_csv)+'.dat';
    with open(faces_dat,'w') as fp:
      fp.write(faces.tostring())
    """
    
    vertexNode = faceNode.find('Coordinate')
    with open(vertices_csv,'w') as fp:
      vertices = re.sub('[\s,]+',' ',vertexNode.attrib['point'].strip())
      vertices = vertices.split(' ')
      vertices = [','.join(vertices[i:i+3]) for i in range(0,len(vertices),3)]
      fp.write('\n'.join(vertices))
      
    V = LoadVertices().setInput(vertices_csv).getOutput('vertices')
    V = numpy.array(V,float)
    minmax = [
      ','.join([str(v) for v in V.min(axis=0)]),
      ','.join([str(v) for v in V.max(axis=0)])
    ]
    with open(vertexlimits_csv,'w') as fp:
      fp.write('\n'.join(minmax))

    return FancyDict(
      faces_csv = faces_csv,
      vertices_csv = vertices_csv,
      vertexlimits_csv = vertexlimits_csv
    )
コード例 #5
0
  def main(self,gm_vertices_csv,wm_vertices_csv,mid_vertices_csv,mid_vertexlimits_csv,wm_pct):
    V_gm = LoadVertices.fromParent(self).setInput(gm_vertices_csv).run().getOutput('vertices')
    V_gm = numpy.array(V_gm,float)

    V_wm = LoadVertices.fromParent(self).setInput(wm_vertices_csv).run().getOutput('vertices')
    V_wm = numpy.array(V_wm,float)
    
    V = V_gm*(1-0.01*wm_pct)+V_wm*0.01*wm_pct
    with open(mid_vertices_csv,'w') as fp:
      for line in V:
        fp.write(','.join([str(v) for v in line])+'\n')

    minmax = [
      ','.join([str(v) for v in V.min(axis=0)]),
      ','.join([str(v) for v in V.max(axis=0)])
    ]
    with open(mid_vertexlimits_csv,'w') as fp:
      fp.write('\n'.join(minmax))

    return FancyDict(
      mid_vertices_csv = mid_vertices_csv,
      mid_vertexlimits_csv = mid_vertexlimits_csv
    )
コード例 #6
0
  def main(self,vertices_csv,faces_csv,datavolume_nii,paintmode):
    V = LoadVertices.fromParent(self).setInput(vertices_csv).run().getOutput('vertices')
    if paintmode=='F':
      F = LoadFaces.fromParent(self).setInput(faces_csv).requestOutput('faces')
      X = FaceCenters.fromParent(self).setInput(F,V).requestOutput('centers')
    elif paintmode=='V':
      X = V
    elif paintmode=='FV':
      F = LoadFaces.fromParent(self).setInput(faces_csv).run().getOutput('faces')
      X = FaceVertexCenters.fromParent(self).setInput(F,V).requestOutput('centers')
    else:
      raise RuntimeError('Invalid paintmode "{}".'.format(paintmode))
    nii = nibabel.load(datavolume_nii)
    affine = nii.get_header().get_sform()
    dataVolume = nii.get_data()
    indexedPoints = IndexedPoints.fromParent(self).setInput(
      X,affine
    )
    labelsFromVolume = LabelsFromVolume.fromParent(self).setInput(
      labelVolume = dataVolume,
      points = indexedPoints.requestOutput('points'),
      bgIndex = 0
    )
    meshdata = labelsFromVolume.run().getOutput('labels').tolist()
    meshdata = [str(v) for v in meshdata]
    if paintmode == 'FV':
      offset = numpy.cumsum([0]+[len(line) for line in F])
      meshdata = [','.join(labels[offset[i]:offset[i+1]]) for i in range(0,len(F))]

    meshdata_csv = self.tempfile('meshdata.csv')
    with open(meshdata_csv,'w') as fp:
      fp.write('\n'.join(meshdata))
    
    minmax = numpy.array(V,float)
    minmax = [
      ','.join([str(v) for v in minmax.min(axis=0)]),
      ','.join([str(v) for v in minmax.max(axis=0)])
    ]
    vertexlimits_csv = self.tempfile('vertexlimits.csv')
    with open(vertexlimits_csv,'w') as fp:
      fp.write('\n'.join(minmax))

    return FancyDict(
      vertexlimits_csv = vertexlimits_csv,
      meshdata_csv = meshdata_csv
    )
コード例 #7
0
ファイル: mesh_to_volume.py プロジェクト: rbakker/sba-dev
 def main(self,faces_csv,vertices_csv,labels_nii,volume_nii):
   V = LoadVertices().setInput(vertices_csv).getOutput('vertices')
   F = LoadFaces().setInput(faces_csv).getOutput('faces')
   X = FaceCenters().setInput(F,V).getOutput('centers')
   nii = nibabel.load(labels_nii)
   affine = nii.get_header().get_best_affine()
   points = IndexedPoints().setInput(X,affine).getOutput('points')
   if volume_nii is None: volume_nii = self.tempfile('volume.nii.gz')
   output_nii = VolumeFromLabels().setInput(
     points = points,
     labels = numpy.zeros((len(points),),numpy.uint8)+255,
     reference = labels_nii,
     output = volume_nii
   ).getOutput('output')
   return FancyDict(
     volume_nii = output_nii
   )
コード例 #8
0
ファイル: mesh_to_x3d.py プロジェクト: rbakker/sba-dev
    def main(self,
             faces_csv,
             vertices_csv,
             vertexlimits_csv,
             output_x3d,
             x3d_width=800,
             x3d_height=800):
        if isinstance(vertices_csv, list): V = vertices_csv
        else: V = LoadVertices().setInput(vertices_csv).getOutput('vertices')
        if isinstance(faces_csv, list): F = faces_csv
        else: F = LoadFaces().setInput(faces_csv).getOutput('faces')
        with open(vertexlimits_csv, 'r') as fp:
            limits = fp.readlines()
        mn = [float(v) for v in limits[0].split(',')]
        mx = [float(v) for v in limits[1].split(',')]
        centerX = 0.5 * (mx[0] + mn[0])
        centerY = 0.5 * (mx[1] + mn[1])
        centerZ = 0.5 * (mx[2] + mn[2])
        distanceW = 32 * max(mx[0] - mn[0],
                             mx[1] - mn[1]) * x3d_height / x3d_width
        distanceH = 32 * max(mx[0] - mn[0],
                             mx[2] - mn[2]) * x3d_width / x3d_height
        distance = max(distanceW, distanceH)
        position = '{},{},{}'.format(centerX - distance, centerY, centerZ)
        centerOfRotation = '{},{},{}'.format(centerX, centerY, centerZ)
        faces = ' -1 '.join([' '.join([str(v) for v in line]) for line in F])
        vertices = ' '.join([','.join([str(v) for v in line]) for line in V])

        with open(output_x3d, 'w') as fp:
            fp.write(
                '<X3D id="X3D_ROOT" width="{}px" height="{}px" profile="Interchange" version="3.2" xmlns:xsd="http://www.w3.org/2001/XMLSchema-instance" xsd:noNamespaceSchemaLocation="http://www.web3d.org/specifications/x3d-3.2.xsd">\n'
                .format(x3d_width, x3d_height))
            fp.write('<Scene id="X3D_SCENE">\n')
            fp.write('<Background id="X3D_BACKGROUND" skyColor="0 0 0"/>\n')
            fp.write(
                '<Viewpoint id="X3D_VIEW" fieldOfView="0.032725" position="{}" description="Left" orientation="-0.57735 0.57735 0.57735 -2.0944" centerOfRotation="{}"/>\n'
                .format(position, centerOfRotation))
            fp.write(
                '<NavigationInfo type="&quot;EXAMINE&quot; &quot;FLY&quot; &quot;ANY&quot;" speed="4" headlight="true"/>\n'
            )
            fp.write(
                '<DirectionalLight ambientIntensity="1" intensity="0" color="1 1 1"/>\n'
            )
            fp.write('<Transform DEF="ROOT" translation="0 0 0">\n')
            fp.write('<Shape>\n')
            fp.write('<Appearance>\n')
            fp.write(
                '<Material ambientIntensity="0" emissiveColor="0 0 0" diffuseColor="1 1 1" specularColor="0 0 0" shininess="0.0078125" transparency="0"/>\n'
            )
            fp.write('</Appearance>\n')
            fp.write(
                '<IndexedFaceSet id="X3D_SURF" creaseAngle="0.785" solid="false" colorPerVertex="false" normalPerVertex="false" coordIndex="{}">\n'
                .format(faces))
            fp.write('<Coordinate point="{}"/>\n'.format(vertices))
            fp.write('</IndexedFaceSet>\n')
            fp.write('</Shape>\n')
            fp.write('</Transform>\n')
            fp.write('</Scene>\n')
            fp.write('</X3D>\n')

        return FancyDict(output_x3d=output_x3d)
コード例 #9
0
ファイル: labels_to_meshdata.py プロジェクト: rbakker/sba-dev
    def main(self, faces_csv, vertices_csv, labels_nii, multilabelfilter,
             colormap_json, labels_csv, labelmode, label2rgb_csv,
             mesh2labels_nii):
        last = lastUpdate(faces_csv, vertices_csv, labels_nii)
        first = firstUpdate(labels_csv, label2rgb_csv)
        fancyLog(dict(last=last, first=first), 'debug')
        if last < first:
            return FancyDict(labels_csv=labels_csv,
                             label2rgb_csv=label2rgb_csv)

        V = LoadVertices().setInput(vertices_csv).getOutput('vertices')
        if labelmode == 'F':
            F = LoadFaces().setInput(faces_csv).requestOutput('faces')
            X = FaceCenters().setInput(F, V).requestOutput('centers')
        elif labelmode == 'V':
            X = V
        elif labelmode == 'FV':
            F = LoadFaces().setInput(faces_csv).getOutput('faces')
            X = FaceVertexCenters().setInput(F, V).requestOutput('centers')
        else:
            raise RuntimeError('Invalid labelmode "{}".'.format(labelmode))
        if multilabelfilter:
            labels_nii = MultiLabelSmooth().setInput(
                raw_nii=labels_nii, filter=multilabelfilter,
                ignore=[0]).getOutput('smoothed_nii')
        nii = nibabel.load(labels_nii)
        affine = nii.get_header().get_best_affine()
        labelVolume = nii.get_data()
        indexedPoints = IndexedPoints().setInput(X, affine)
        labelsFromVolume = LabelsFromVolume().setInput(
            labelVolume=labelVolume,
            points=indexedPoints.requestOutput('points'),
            bgIndex=0)
        labels = labelsFromVolume.getOutput('labels').tolist()
        labels = [str(v) for v in labels]
        if labelmode == 'FV':
            offset = numpy.cumsum([0] + [len(line) for line in F])
            labels = [
                ','.join(labels[offset[i]:offset[i + 1]])
                for i in range(0, len(F))
            ]
        with open(labels_csv, 'w') as fp:
            fp.write('\n'.join(labels))

        if mesh2labels_nii:
            VolumeFromLabels().setInput(
                points=indexedPoints.requestOutput('points'),
                labels=labelsFromVolume.requestOutput('labels'),
                reference=labels_nii,
                output=mesh2labels_nii).getOutput()

        with open(colormap_json, 'r') as fp:
            colormap = json.load(fp)
        if isinstance(colormap, dict):
            mx = 0
            for k in colormap.keys():
                if int(k) > mx:
                    mx = int(k)
            baseColor = 'AAAAAA'
            colormap = [
                colormap[str(i)] if str(i) in colormap else baseColor
                for i in range(0, mx + 1)
            ]
        colormap = [
            ','.join([
                '{0:.3f}'.format(int(v[i:i + 2], 16) / 255.0)
                for i in range(0, 6, 2)
            ]) for v in colormap
        ]
        with open(label2rgb_csv, 'w') as fp:
            fp.write('\n'.join(colormap))

        return FancyDict(labels_csv=labels_csv, label2rgb_csv=label2rgb_csv)
コード例 #10
0
  def main(self,space,mesh,deformation,labelvolume,labelnames,name2value,colormap,colorlimits,spacesroot,jsonrpc2):
    spacesFolder = '{}/{}'.format(spacesroot,space)
    with open( '{}/config.json'.format(spacesFolder) ) as fp:
      spaceConfig = json.load(fp)
    meshConfig = spaceConfig['meshes'][mesh]['deformations']['fiducial']

    facesFile = None
    verticesFile = None
    faceLabels = None
    label2value = None
    label2rgb = None
    if labelvolume:
      nii = nibabel.load(labelvolume)
      hdr = nii.get_header()
      img = nii.get_data()
      sform = hdr.get_sform()
      bgIndex = 0

      facesFile = '{}/meshes/{}'.format(spacesFolder,meshConfig['faces'])
      verticesFile = '{}/meshes/{}'.format(spacesFolder,meshConfig['vertices'])
      F = LoadFaces.fromParent(self).setInput(facesFile).requestOutput('faces')
      V = LoadVertices.fromParent(self).setInput(verticesFile).requestOutput('vertices')
      X = FaceCenters.fromParent(self).setInput(F,V).requestOutput('centers')
      faceCenters = IndexedPoints.fromParent(self).setInput(X,sform).requestOutput('points')
      faceLabels = LabelsFromVolume.fromParent(self).setInput(
        labelVolume = img,
        points = faceCenters,
        bgIndex = bgIndex
      ).run().requestOutput('labels')
      with open(self.tempfile('facelabels.csv'),'w') as fp:
        fp.write('\n'.join([str(v) for v in faceLabels]))      
      
      getLabelValues = GetLabelValues.fromParent(self).setInput(faceLabels,labelnames,name2value,colormap,colorlimits)
      label2value = getLabelValues.requestOutput('label2value')
      label2rgb = getLabelValues.requestOutput('label2rgb')
      colormap = getLabelValues.requestOutput('colormap')
    
    meshConfig = spaceConfig['meshes'][mesh]['deformations'][deformation]
    deformedVerticesFile = '{}/meshes/{}'.format(spacesFolder,meshConfig['vertices'])
    deformedFacesFile = '{}/meshes/{}'.format(spacesFolder,meshConfig['faces'])
    if deformedVerticesFile != verticesFile: 
      V = LoadVertices.fromParent(self).setInput(deformedVerticesFile).requestOutput('vertices')
    if deformedFacesFile != facesFile: 
      F = LoadFaces.fromParent(self).setInput(deformedFacesFile).requestOutput('faces')
    if labelnames:
      with open(labelnames) as fp:
        labelnames = json.load(fp)
    
    generateX3D = GenerateX3D.fromParent(self).setInput(
      vertices = V,
      faces = F,
      facelabels = faceLabels,
      label2rgb = label2rgb,
      label2name = labelnames,
      label2value = label2value,
      colormap = colormap
    )
    return FancyDict(
      x3dfile = generateX3D.requestOutput('x3dfile'),
      x3dviewer = generateX3D.requestOutput('x3dviewer'),
      x3d_files = generateX3D.requestOutput('x3dviewer_files')
    )
コード例 #11
0
    def main(self, space, mesh, deformation, labelvolume, labelnames,
             name2value, colormap, colorlimits, spacesroot, jsonrpc2):
        spacesFolder = '{}/{}'.format(spacesroot, space)
        with open('{}/config.json'.format(spacesFolder)) as fp:
            spaceConfig = json.load(fp)
        meshConfig = spaceConfig['meshes'][mesh]['deformations']['fiducial']

        facesFile = None
        verticesFile = None
        faceLabels = None
        label2value = None
        label2rgb = None
        if labelvolume:
            nii = nibabel.load(labelvolume)
            hdr = nii.get_header()
            img = nii.get_data()
            sform = hdr.get_sform()
            bgIndex = 0

            facesFile = '{}/meshes/{}'.format(spacesFolder,
                                              meshConfig['faces'])
            verticesFile = '{}/meshes/{}'.format(spacesFolder,
                                                 meshConfig['vertices'])
            F = LoadFaces.fromParent(self).setInput(facesFile).requestOutput(
                'faces')
            V = LoadVertices.fromParent(self).setInput(
                verticesFile).requestOutput('vertices')
            X = FaceCenters.fromParent(self).setInput(
                F, V).requestOutput('centers')
            faceCenters = IndexedPoints.fromParent(self).setInput(
                X, sform).requestOutput('points')
            faceLabels = LabelsFromVolume.fromParent(self).setInput(
                labelVolume=img, points=faceCenters,
                bgIndex=bgIndex).run().requestOutput('labels')
            with open(self.tempfile('facelabels.csv'), 'w') as fp:
                fp.write('\n'.join([str(v) for v in faceLabels]))

            getLabelValues = GetLabelValues.fromParent(self).setInput(
                faceLabels, labelnames, name2value, colormap, colorlimits)
            label2value = getLabelValues.requestOutput('label2value')
            label2rgb = getLabelValues.requestOutput('label2rgb')
            colormap = getLabelValues.requestOutput('colormap')

        meshConfig = spaceConfig['meshes'][mesh]['deformations'][deformation]
        deformedVerticesFile = '{}/meshes/{}'.format(spacesFolder,
                                                     meshConfig['vertices'])
        deformedFacesFile = '{}/meshes/{}'.format(spacesFolder,
                                                  meshConfig['faces'])
        if deformedVerticesFile != verticesFile:
            V = LoadVertices.fromParent(self).setInput(
                deformedVerticesFile).requestOutput('vertices')
        if deformedFacesFile != facesFile:
            F = LoadFaces.fromParent(self).setInput(
                deformedFacesFile).requestOutput('faces')
        if labelnames:
            with open(labelnames) as fp:
                labelnames = json.load(fp)

        generateX3D = GenerateX3D.fromParent(self).setInput(
            vertices=V,
            faces=F,
            facelabels=faceLabels,
            label2rgb=label2rgb,
            label2name=labelnames,
            label2value=label2value,
            colormap=colormap)
        return FancyDict(
            x3dfile=generateX3D.requestOutput('x3dfile'),
            x3dviewer=generateX3D.requestOutput('x3dviewer'),
            x3d_files=generateX3D.requestOutput('x3dviewer_files'))