Esempio n. 1
0
def ComputeMeanLandmarks(targetNameList, dirlandmarks, dirOutput, sourceName):
    # loading landmarks into vtk polydata object
    group = vtk.vtkMultiBlockDataGroupFilter()
    for name in targetNameList:
        filename = os.path.join(dirlandmarks, name + '.txt')
        if not os.path.isfile(filename):
            print('Can not read landmark file: %s' % filename)
            continue
        npLandmarks = np.loadtxt(filename, skiprows=2)
        numberOfLandmarks = int(np.size(npLandmarks) / 3)
        vtkLandmarks = vtk.vtkPoints()
        for landmark in npLandmarks:
            vtkLandmarks.InsertNextPoint(landmark)
        vtkPolyDataLandmarks = vtk.vtkPolyData()
        vtkPolyDataLandmarks.SetPoints(vtkLandmarks)
        group.AddInputData(vtkPolyDataLandmarks)
        group.Update()

    Procrustes = vtk.vtkProcrustesAlignmentFilter()
    Procrustes.SetInputConnection(group.GetOutputPort())

    Procrustes.GetLandmarkTransform().SetModeToRigidBody()
    #===========================================================================
    # Procrustes.GetLandmarkTransform().SetModeToSimilarity()
    #===========================================================================

    Procrustes.Update()
    MeanPoints = Procrustes.GetMeanPoints()
    return MeanPoints
Esempio n. 2
0
def procrustes(sources, rigid=False, legend=None):
    '''
    Return an Assembly of aligned source actors with
    the vtkProcrustesAlignmentFilter class. Assembly is normalized in space.
    
    Takes N set of points and aligns them in a least-squares sense 
    to their mutual mean. The algorithm is iterated until convergence, 
    as the mean must be recomputed after each alignment.
    '''
    group = vtk.vtkMultiBlockDataGroupFilter()
    for source in sources:
        if sources[0].N() != source.N():
            vc.printc('Procrustes error in align():' , c=1)
            vc.printc(' sources have different nr of points', c=1)
            exit(0)
        group.AddInputData(source.polydata())
    procrustes = vtk.vtkProcrustesAlignmentFilter()
    procrustes.StartFromCentroidOn()
    procrustes.SetInputConnection(group.GetOutputPort())
    if rigid:
        procrustes.GetLandmarkTransform().SetModeToRigidBody()
    procrustes.Update()
    
    acts = []
    for i in range(len(sources)):
        poly = procrustes.GetOutput().GetBlock(i)
        actor = Actor(poly)
        actor.SetProperty(sources[i].GetProperty())
        acts.append(actor)
    assem = Assembly(acts, legend=legend)
    assem.info['transform'] = procrustes.GetLandmarkTransform()
    return assem
Esempio n. 3
0
def ComputeMeanSuface(targetNameList,
                      dirSurface,
                      dirOutput,
                      sourceName,
                      StatsFile=None,
                      thRMS=100):
    print("================ STATSFILE ======================")
    print(StatsFile)
    rmsMetric = np.loadtxt(StatsFile, dtype=str, delimiter=',')
    RMS = rmsMetric[:, -1]
    nameList = rmsMetric[:, 0]
    count = 1
    skibedSurface = 0
    # loading surface into vtk group
    group = vtk.vtkMultiBlockDataGroupFilter()
    for targetName in targetNameList:
        filename = os.path.join(dirSurface, targetName + '.vtk')
        if not os.path.isfile(filename):
            print('Can not read file: %s' % filename)
            continue
        nameIdx = -1
        for name in nameList:
            # if '%d' % int(name) == targetName:
            if name == targetName:
                break
            nameIdx += 1
        if np.float(RMS[nameIdx]) > thRMS:
            print('To high RMS for surface: %s RMS = %0.2f' %
                  (targetName, np.float(RMS[nameIdx])))
            count += 1
            skibedSurface += 1
            continue
        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(filename)
        reader.Update()
        group.AddInputConnection(reader.GetOutputPort())
        count += 1
    Procrustes = vtk.vtkProcrustesAlignmentFilter()
    Procrustes.SetInputConnection(group.GetOutputPort())
    Procrustes.GetLandmarkTransform().SetModeToRigidBody()
    #===========================================================================
    # Procrustes.GetLandmarkTransform().SetModeToSimilarity()
    #===========================================================================
    Procrustes.Update()

    polydata = reader.GetOutput()
    polydata.SetPoints(Procrustes.GetMeanPoints())
    polydata = computeNormals(polydata)
    writer = vtk.vtkPolyDataWriter()
    filename = os.path.join(dirOutput, sourceName + '.vtk')
    writer.SetFileName(filename)
    writer.SetInputData(polydata)
    writer.Write()
 def __init__(self):
   """
   """
    
   self.filterGPA = vtk.vtkProcrustesAlignmentFilter()
   self.filterPCA = vtk.vtkPCAAnalysisFilter()
   
   self.vertexGrids = []
   self.alignedGrids = []
   self.analyzedGrids = []
   self.meanShape = [] 
   self.meanPositions = []
   self.variationPositions = []
Esempio n. 5
0
def procrustesAlignment(sources, rigid=False):
    """
    Return an ``Assembly`` of aligned source meshes with
    the `Procrustes` algorithm. The output ``Assembly`` is normalized in size.

    `Procrustes` algorithm takes N set of points and aligns them in a least-squares sense
    to their mutual mean. The algorithm is iterated until convergence,
    as the mean must be recomputed after each alignment.

    The set of average points generated by the algorithm can be accessed with
    ``algoutput.info['mean']`` as a numpy array.

    :param bool rigid: if `True` scaling is disabled.

    |align3| |align3.py|_
    """
    from vedo.mesh import Mesh
    group = vtk.vtkMultiBlockDataGroupFilter()
    for source in sources:
        if sources[0].N() != source.N():
            colors.printc("Error in procrustesAlignment():", c='r')
            colors.printc(" sources have different nr of points", c='r')
            raise RuntimeError()
        group.AddInputData(source.polydata())
    procrustes = vtk.vtkProcrustesAlignmentFilter()
    procrustes.StartFromCentroidOn()
    procrustes.SetInputConnection(group.GetOutputPort())
    if rigid:
        procrustes.GetLandmarkTransform().SetModeToRigidBody()
    procrustes.Update()

    acts = []
    for i, s in enumerate(sources):
        poly = procrustes.GetOutput().GetBlock(i)
        mesh = Mesh(poly)
        mesh.SetProperty(s.GetProperty())
        if hasattr(s, 'name'):
            mesh.name = s.name
            mesh.flagText = s.flagText
        acts.append(mesh)
    assem = Assembly(acts)
    assem.transform = procrustes.GetLandmarkTransform()
    assem.info['mean'] = vtk_to_numpy(procrustes.GetMeanPoints().GetData())
    return assem
Esempio n. 6
0
def surface_statistics(target_names,
                       dir_surface,
                       dir_output,
                       source_name,
                       stats_file=None,
                       rms_threshold=100):
    print('Reading', stats_file)
    rms_metric = np.loadtxt(stats_file, dtype=str, delimiter=',')
    n_rms = len(rms_metric)
    surface_group = vtk.vtkMultiBlockDataGroupFilter()

    for idx in range(n_rms):
        name = rms_metric[idx, 0]
        rms = float(rms_metric[idx, -1])
        print('Surface:', name, 'RMS:', rms)
        if rms < rms_threshold:
            filename = os.path.join(dir_surface, name + '.vtk')
            reader = vtk.vtkPolyDataReader()
            reader.SetFileName(filename)
            reader.Update()
            if reader.GetOutput().GetNumberOfPoints() < 3:
                print('Could not read', filename)
            else:
                surface_group.AddInputConnection(reader.GetOutputPort())
        else:
            print('Surface', name, 'excluded due to high RMS:', rms)

    procrustes = vtk.vtkProcrustesAlignmentFilter()
    procrustes.SetInputConnection(surface_group.GetOutputPort())
    procrustes.GetLandmarkTransform().SetModeToRigidBody()
    # ===========================================================================
    # Procrustes.GetLandmarkTransform().SetModeToSimilarity()
    # ===========================================================================
    procrustes.Update()

    polydata = reader.GetOutput()
    polydata.SetPoints(procrustes.GetMeanPoints())
    polydata = computeNormals(polydata)
    writer = vtk.vtkPolyDataWriter()
    filename = os.path.join(dir_output, source_name + '_Procrustes_mean.vtk')
    writer.SetFileName(filename)
    writer.SetInputData(polydata)
    writer.Write()
    pts_list_i = []

    for j in range(nPt):
        pts_str = pts_data[j][i]

        pts_str_parsed = ''.join(
            (ch if ch in '0123456789.-e' else ' ') for ch in pts_str)

        pt_j = [float(pt_j_str) for pt_j_str in pts_str_parsed.split()]

        pts_list_i.append(pt_j)

    pts_list.append(pts_list_i)

# Procrustes Filter
procrustes_filter = vtk.vtkProcrustesAlignmentFilter()

group = vtk.vtkMultiBlockDataGroupFilter()

pts_polyData_list = []

scale_obs_list = []

# Check
# nObs = 3

for i in range(nObs):
    pt_polyData = vtk.vtkPolyData()
    pt_Points = vtk.vtkPoints()
    pt_lines = vtk.vtkCellArray()
    vol_r = float(df_ids.iloc[i, :].vol_r)
    vol_l = float(df_ids.iloc[i, :].vol_l)
    idb = int(df_ids.iloc[i, :].id_alomar)

    if vol_r >= 1500 and vol_l >= 1500 and idb not in visual_outliers_list:
        meshes_total.AddInputData(mesh)
        # Compute mean points
        points = ExtractVTKPoints(mesh)
        points_total.append(points)
    i += 1

# Left mesh
import pickle

# Compute alignment of left hippocampus
pcra = vtk.vtkProcrustesAlignmentFilter()
pcra.GetLandmarkTransform().SetModeToRigidBody()
pcra.SetInputConnection(meshes_left.GetOutputPort())
pcra.Update()

out_block = pcra.GetOutput()
n = out_block.GetNumberOfBlocks()
print(len(df_apoe_f))
print(n)

# Extract the output and save it to new folder
for i in range(n):
    mesh = out_block.GetBlock(i)
    # get id of said
    id = str(int(df_apoe_f.iloc[i, :].id_alomar))
    # save to disk
Actor1b.GetProperty().SetDiffuseColor(0.3882, 1.0000, 0.2784)

map1c = vtk.vtkPolyDataMapper()
map1c.SetInputConnection(transformer2.GetOutputPort())

Actor1c = vtk.vtkActor()
Actor1c.SetMapper(map1c)
Actor1c.GetProperty().SetDiffuseColor(0.3882, 0.2784, 1.0000)

group = vtk.vtkMultiBlockDataGroupFilter()
group.AddInputConnection(sphere.GetOutputPort())
group.AddInputConnection(transformer1.GetOutputPort())
group.AddInputConnection(transformer2.GetOutputPort())

# align the shapes using Procrustes (using SetModeToRigidBody)
procrustes1 = vtk.vtkProcrustesAlignmentFilter()
procrustes1.SetInputConnection(group.GetOutputPort())
procrustes1.GetLandmarkTransform().SetModeToRigidBody()
procrustes1.StartFromCentroidOn()
procrustes1.Update()

# map the aligned shapes into the second renderer
map2a = vtk.vtkPolyDataMapper()
map2a.SetInputData(procrustes1.GetOutput().GetBlock(0))

Actor2a = vtk.vtkActor()
Actor2a.SetMapper(map2a)
Actor2a.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)

map2b = vtk.vtkPolyDataMapper()
map2b.SetInputData(procrustes1.GetOutput().GetBlock(1))
Esempio n. 10
0
map1b = vtk.vtkPolyDataMapper()
map1b.SetInputConnection(transformer1.GetOutputPort())
Actor1b = vtk.vtkActor()
Actor1b.SetMapper(map1b)
Actor1b.GetProperty().SetDiffuseColor(0.3882,1.0000,0.2784)
map1c = vtk.vtkPolyDataMapper()
map1c.SetInputConnection(transformer2.GetOutputPort())
Actor1c = vtk.vtkActor()
Actor1c.SetMapper(map1c)
Actor1c.GetProperty().SetDiffuseColor(0.3882,0.2784,1.0000)
# -- align the shapes using Procrustes (using SetModeToRigidBody) --
group = vtk.vtkMultiBlockDataGroupFilter()
group.AddInputConnection(sphere.GetOutputPort())
group.AddInputConnection(transformer1.GetOutputPort())
group.AddInputConnection(transformer2.GetOutputPort())
procrustes1 = vtk.vtkProcrustesAlignmentFilter()
procrustes1.SetInputConnection(group.GetOutputPort())
procrustes1.GetLandmarkTransform().SetModeToRigidBody()
procrustes1.Update()
# map the aligned shapes into the second renderer
map2a = vtk.vtkPolyDataMapper()
map2a.SetInputData(procrustes1.GetOutput().GetBlock(0))
Actor2a = vtk.vtkActor()
Actor2a.SetMapper(map2a)
Actor2a.GetProperty().SetDiffuseColor(1.0000,0.3882,0.2784)
map2b = vtk.vtkPolyDataMapper()
map2b.SetInputData(procrustes1.GetOutput().GetBlock(1))
Actor2b = vtk.vtkActor()
Actor2b.SetMapper(map2b)
Actor2b.GetProperty().SetDiffuseColor(0.3882,1.0000,0.2784)
map2c = vtk.vtkPolyDataMapper()
Esempio n. 11
0
Actor1b.SetMapper(map1b)
Actor1b.GetProperty().SetDiffuseColor(0.3882,1.0000,0.2784)
map1c = vtk.vtkPolyDataMapper()
map1c.SetInputConnection(transformer2.GetOutputPort())
Actor1c = vtk.vtkActor()
Actor1c.SetMapper(map1c)
Actor1c.GetProperty().SetDiffuseColor(0.3882,0.2784,1.0000)
#------------------------------------------------------------------
# align the shapes using Procrustes (using SetModeToRigidBody)
# and map the aligned shapes into the second renderer
#------------------------------------------------------------------
group = vtk.vtkMultiBlockDataGroupFilter()
group.AddInputConnection(sphere.GetOutputPort())
group.AddInputConnection(transformer1.GetOutputPort())
group.AddInputConnection(transformer2.GetOutputPort())
procrustes = vtk.vtkProcrustesAlignmentFilter()
procrustes.SetInputConnection(group.GetOutputPort())
procrustes.GetLandmarkTransform().SetModeToRigidBody()
procrustes.Update()
map2a = vtk.vtkPolyDataMapper()
map2a.SetInputData(procrustes.GetOutput().GetBlock(0))
Actor2a = vtk.vtkActor()
Actor2a.SetMapper(map2a)
Actor2a.GetProperty().SetDiffuseColor(1.0000,0.3882,0.2784)
map2b = vtk.vtkPolyDataMapper()
map2b.SetInputData(procrustes.GetOutput().GetBlock(1))
Actor2b = vtk.vtkActor()
Actor2b.SetMapper(map2b)
Actor2b.GetProperty().SetDiffuseColor(0.3882,1.0000,0.2784)
map2c = vtk.vtkPolyDataMapper()
map2c.SetInputData(procrustes.GetOutput().GetBlock(2))
Esempio n. 12
0
def compute_mean_surface_and_lm(targetNameList,
                                dirSurface,
                                dirLM,
                                dirOutput,
                                sourceName,
                                StatsFile=None,
                                thRMS=100):
    rmsMetric = np.loadtxt(StatsFile, dtype=str, delimiter=',')
    RMS = rmsMetric[:, -1]
    nameList = rmsMetric[:, 0]
    count = 1
    skibedSurface = 0
    # loading surface into vtk group
    group = vtk.vtkMultiBlockDataGroupFilter()
    lm_group = vtk.vtkMultiBlockDataGroupFilter()
    for targetName in targetNameList:
        filename = os.path.join(dirSurface, targetName + '.vtk')
        if not os.path.isfile(filename):
            print('Can not read file: %s' % filename)
            continue
        nameIdx = 0
        for name in nameList:
            # if '%d' % int(name) == targetName:
            if name == targetName:
                break
            nameIdx += 1
        if nameIdx >= len(nameList):
            print('Can not read RMS stat for file: %s' % filename)
            continue
        if np.float(RMS[nameIdx]) > thRMS:
            print('To high RMS for surface: %s RMS = %0.2f' %
                  (targetName, np.float(RMS[nameIdx])))
            count += 1
            skibedSurface += 1
            continue

        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(filename)
        reader.Update()
        group.AddInputConnection(reader.GetOutputPort())
        group.Update()

        lmfilename = os.path.join(dirLM, targetName + '.txt')
        npLandmarks = np.loadtxt(lmfilename, skiprows=2)
        vtkLandmarks = vtk.vtkPoints()
        for landmark in npLandmarks:
            vtkLandmarks.InsertNextPoint(landmark)
        vtkPolyDataLandmarks = vtk.vtkPolyData()
        vtkPolyDataLandmarks.SetPoints(vtkLandmarks)
        lm_group.AddInputData(vtkPolyDataLandmarks)
        lm_group.Update()

        count += 1

    Procrustes = vtk.vtkProcrustesAlignmentFilter()
    Procrustes.SetInputConnection(group.GetOutputPort())
    Procrustes.GetLandmarkTransform().SetModeToRigidBody()
    Procrustes.Update()

    polydata = reader.GetOutput()
    polydata.SetPoints(Procrustes.GetMeanPoints())
    polydata = computeNormals(polydata)
    writer = vtk.vtkPolyDataWriter()
    filename = os.path.join(dirOutput, sourceName + '.vtk')
    writer.SetFileName(filename)
    writer.SetInputData(polydata)
    writer.Write()

    lm_procrustes = vtk.vtkProcrustesAlignmentFilter()
    lm_procrustes.SetInputConnection(lm_group.GetOutputPort())
    lm_procrustes.StartFromCentroidOff()
    lm_procrustes.GetLandmarkTransform().SetModeToRigidBody()
    lm_procrustes.Update()
    mean_points = lm_procrustes.GetMeanPoints()

    filename = os.path.join(dirOutput, sourceName + '.txt')
    WriteLandmarkFile(mean_points, filename)
Esempio n. 13
0
    surface = sReader.GetOutput()
    pd = vtk.vtkPolyData()
    pd.DeepCopy(surface)
    surfaces.append( pd )

# if requested do alignment
nrOfSurfaces = len(surfaces)
if args.transform == True:

    print("Procrustes Alignment...")

    group = vtk.vtkMultiBlockDataGroupFilter()
    for surface in surfaces:  
        group.AddInputData(surface)  
    
    align = vtk.vtkProcrustesAlignmentFilter()
    align.SetInputConnection(group.GetOutputPort())
    align.GetLandmarkTransform().SetModeToRigidBody()
    align.Update()

    surfaces = []
    for i in range(nrOfSurfaces):  
        pd = vtk.vtkPolyData()
        pd.DeepCopy(align.GetOutput().GetBlock(i))
        surfaces.append( pd )

print("Creating landmark matrix...")

# gather all points for all surfaces
allPoints = []
for surface in surfaces: