def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkDijkstraGraphGeodesicPath(), 'Processing.',
         ('vtkPolyData',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkDijkstraGraphGeodesicPath(),
                                       'Processing.', ('vtkPolyData', ),
                                       ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Exemple #3
0
    def run(self) -> None:
        global APART_POINT_INDEX, UPDATE

        center_point = POINTS[PICKED_POINT_INDEX[-1]]
        dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
        dijkstra.SetInputData(INPUT_MODEL.GetOutput())

        # propagation
        for sp in APART_POINT_INDEX[-1]:
            nn_index = []

            cellidlist = vtk.vtkIdList()
            INPUT_MODEL.GetOutput().GetPointCells(sp, cellidlist)
            for i in range(cellidlist.GetNumberOfIds()):
                cell = INPUT_MODEL.GetOutput().GetCell(cellidlist.GetId(i))
                for e in range(cell.GetNumberOfEdges()):
                    edge = cell.GetEdge(e)
                    pointidlist = edge.GetPointIds()
                    if pointidlist.GetId(0) != sp and pointidlist.GetId(
                            1) != sp:
                        nn_index.append(pointidlist.GetId(0))
                        nn_index.append(pointidlist.GetId(1))
                        break

            nn_index = {}.fromkeys(nn_index).keys()

            for p in nn_index:
                dijkstra.SetStartVertex(PICKED_POINT_INDEX[-1])
                dijkstra.SetEndVertex(p)
                dijkstra.Update()

                path_distance = 0.0

                id_list = dijkstra.GetIdList()
                for i in range(id_list.GetNumberOfIds() - 1):
                    p0 = POINTS[id_list.GetId(i)]
                    p1 = POINTS[id_list.GetId(i + 1)]
                    path_distance += math.sqrt(((p0[0] - p1[0])**2) +
                                               ((p0[1] - p1[1])**2) +
                                               ((p0[2] - p1[2])**2))

                if path_distance > DISTANCE_LIMITATION:
                    continue

                if_pushback = True

                for ep in APART_POINT_INDEX[-1]:
                    if p == ep:
                        if_pushback = False
                        break

                if if_pushback is True:
                    APART_POINT_INDEX[-1].append(p)
                    print('append', len(APART_POINT_INDEX[-1]))

        UPDATE = True
        print('segmentation finished!')
Exemple #4
0
def find_create_path(mesh, p1, p2):
    """Get shortest path (using Dijkstra algorithm) between p1 and p2 on the mesh. Returns a polydata"""
    dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
    if vtk.vtkVersion().GetVTKMajorVersion() > 5:
        dijkstra.SetInputData(mesh)
    else:
        dijkstra.SetInput(mesh)
    dijkstra.SetStartVertex(p1)
    dijkstra.SetEndVertex(p2)
    dijkstra.Update()
    return dijkstra.GetOutput()
Exemple #5
0
    def combineCurves(self, inputCurve1, inputCurve2, inputModel):
        outputPoints = vtk.vtkPoints()
        locator = vtk.vtkPointLocator()
        locator.SetDataSet(inputModel)
        locator.BuildLocator()

        outputPoints = vtk.vtkPoints()
        for i in range(inputCurve1.GetNumberOfPoints()):
            outputPoints.InsertNextPoint(inputCurve1.GetPoint(i))

        point1Id = locator.FindClosestPoint(
            inputCurve1.GetPoint(inputCurve1.GetNumberOfPoints() - 1))
        point2Id = locator.FindClosestPoint(
            inputCurve2.GetPoint(inputCurve2.GetNumberOfPoints() - 1))

        dijkstra1 = vtk.vtkDijkstraGraphGeodesicPath()
        dijkstra1.SetInputData(inputModel)
        dijkstra1.SetStartVertex(point2Id)
        dijkstra1.SetEndVertex(point1Id)
        dijkstra1.Update()
        dijkstraPath1 = dijkstra1.GetOutput()
        for i in range(dijkstraPath1.GetNumberOfPoints()):
            outputPoints.InsertNextPoint(dijkstraPath1.GetPoint(i))

        for i in reversed(range(inputCurve2.GetNumberOfPoints())):
            outputPoints.InsertNextPoint(inputCurve2.GetPoint(i))

        point1Id = locator.FindClosestPoint(inputCurve2.GetPoint(0))
        point2Id = locator.FindClosestPoint(inputCurve1.GetPoint(0))

        dijkstra2 = vtk.vtkDijkstraGraphGeodesicPath()
        dijkstra2.SetInputData(inputModel)
        dijkstra2.SetStartVertex(point2Id)
        dijkstra2.SetEndVertex(point1Id)
        dijkstra2.Update()
        dijkstraPath2 = dijkstra2.GetOutput()
        for i in range(dijkstraPath2.GetNumberOfPoints()):
            outputPoints.InsertNextPoint(dijkstraPath2.GetPoint(i))

        return outputPoints
Exemple #6
0
def calcDistanceAlongSurface(mesh, startPt, endPt):
    dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
    dijkstra.SetInput(mesh)
    dijkstra.SetStartVertex(startPt)
    dijkstra.SetEndVertex(endPt)
    dijkstra.Update()
    pts = dijkstra.GetOutput().GetPoints()
    dist = 0.0
    for ptId in range(pts.GetNumberOfPoints() - 1):
        pts.GetPoint(ptId, p0)
        pts.GetPoint(ptId + 1, p1)
        dist += math.sqrt(vtk.vtkMath.Distance2BetweenPoints(p0, p1))
    return dist
Exemple #7
0
def main():
    # Create a sphere
    sphereSource = vtk.vtkSphereSource()
    sphereSource.Update()

    dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
    dijkstra.SetInputConnection(sphereSource.GetOutputPort())
    dijkstra.SetStartVertex(0)
    dijkstra.SetEndVertex(10)
    dijkstra.Update()

    # Create a mapper and actor
    pathMapper = vtk.vtkPolyDataMapper()
    pathMapper.SetInputConnection(dijkstra.GetOutputPort())

    pathActor = vtk.vtkActor()
    pathActor.SetMapper(pathMapper)
    pathActor.GetProperty().SetColor(1, 0, 0)  # Red
    pathActor.GetProperty().SetLineWidth(4)

    # Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(sphereSource.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # Create a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actor to the scene
    renderer.AddActor(actor)
    renderer.AddActor(pathActor)
    renderer.SetBackground(.3, .6, .3)  # Background color green

    # Render and interact
    renderWindow.Render()
    renderWindowInteractor.Start()

    return 1
Exemple #8
0
def create_patch_optimised(model, modelGraph, idArray, invIdArray, ID, size):
    neighbourhood = []

    candidates = vtk.vtkDoubleArray()
    candidates.SetNumberOfValues(model.GetNumberOfPoints())
    dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
    dijkstra.SetInputData(model)
    dijkstra.SetStartVertex(ID)
    dijkstra.SetEndVertex(
        0)  # just a random vertex so that it will compute all the paths
    dijkstra.Update()
    dijkstra.GetCumulativeWeights(candidates)

    for i in range(model.GetNumberOfPoints()):
        weight = candidates.GetValue(i)
        if weight <= size:
            neighbourhood.append(i)

    return neighbourhood
Exemple #9
0
def geodesic_distance(poly, start, end):
    '''
    The mesh must be a manifold
    '''
    d_graph = vtk.vtkDijkstraGraphGeodesicPath()
    d_graph.SetInputData(poly)
    d_graph.SetStartVertex(start)
    d_graph.SetEndVertex(end)
    d_graph.Update()

    id_list = d_graph.GetIdList()
    if id_list.GetNumberOfIds() == 0:
        return float("inf")
    distance = 0.
    points = poly.GetPoints()
    for i in range(id_list.GetNumberOfIds() - 1):
        i_curr = id_list.GetId(i)
        i_next = id_list.GetId(i + 1)
        dist = vtk.vtkMath()
        distance += dist.Distance2BetweenPoints(points.GetPoint(i_curr),
                                                points.GetPoint(i_next))
    return distance
Exemple #10
0
  def run(self,inputVolume,outputVolume):
    """
    Run the actual algorithm
    """

    self.delayDisplay('Running the aglorithm')

	##get the distance of the geodesic path 
	appendFilter = vtk.vtkAppendFilter()
	appendFilter.MergePointsOn()
	points = vtk.vtkPoints()
	vIds = [closestPointId,closestPointId1]
	p0 = [0,0,0]
	p1 = [0,0,0]
	dist = 0.0
	for n in range(len(vIds)-1):
		v0 = vIds[n]
		v1 = vIds[n+1]
		
		#create geodesic path: vtkDijkstraGraphGeodesicPath
		dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
		dijkstra.SetInputConnection(pd.GetOutputPolyDataConnection())
		dijkstra.SetStartVertex(v0)
		dijkstra.SetEndVertex(v1)
		dijkstra.Update()
					
		pts = dijkstra.GetOutput().GetPoints()
		end = n<len(vIds)-2 and 0 or -1
		for ptId in range(pts.GetNumberOfPoints()-1, end, -1):
			pts.GetPoint(ptId, p0)
			points.InsertNextPoint(p0)		
		
		for ptId in range(pts.GetNumberOfPoints()-1):
			pts.GetPoint(ptId, p0)
			pts.GetPoint(ptId+1, p1)
			dist += math.sqrt(vtk.vtkMath.Distance2BetweenPoints(p0, p1))
			
		appendFilter.AddInputConnection(dijkstra.GetOutputPort())
Exemple #11
0
def get_geodesic_path(start_index, end_index):
    global INPUT_MODEL

    dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
    dijkstra.SetInputData(INPUT_MODEL.GetOutput())
    dijkstra.SetStartVertex(start_index)
    dijkstra.SetEndVertex(end_index)
    dijkstra.Update()

    path_mapper = vtk.vtkPolyDataMapper()
    path_mapper.SetInputConnection(dijkstra.GetOutputPort())

    path_actor = vtk.vtkActor()
    path_actor.SetMapper(path_mapper)
    path_actor.GetProperty().SetColor(BLUE)
    path_actor.GetProperty().SetLineWidth(10)

    ids = []
    id_list = dijkstra.GetIdList()
    for i in range(id_list.GetNumberOfIds()):
        ids.append(id_list.GetId(i))

    return ids, path_actor
Exemple #12
0
def generate_one(index, input_file, output_path):
    print('Start!')

    input_points = POINTS
    input_model = INPUT_MODEL

    calculation = CDLL('./calculation.so')
    calculation.path_distance.argtypes = (POINTER(c_float), c_int)
    calculation.path_distance.restype = c_float

    dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
    dijkstra.SetInputData(INPUT_MODEL.GetOutput())

    for i, pp in enumerate(index):

        # use propagation
        knn_points = [pp]
        for sp in knn_points:
            nn_index = []

            cellidlist = vtk.vtkIdList()
            INPUT_MODEL.GetOutput().GetPointCells(sp, cellidlist)
            for k in range(cellidlist.GetNumberOfIds()):
                cell = INPUT_MODEL.GetOutput().GetCell(cellidlist.GetId(k))
                for e in range(cell.GetNumberOfEdges()):
                    edge = cell.GetEdge(e)
                    pointidlist = edge.GetPointIds()
                    if pointidlist.GetId(0) != sp and pointidlist.GetId(
                            1) != sp:
                        nn_index.append(pointidlist.GetId(0))
                        nn_index.append(pointidlist.GetId(1))
                        break

            nn_index = {}.fromkeys(nn_index).keys()

            for p in nn_index:
                if_pushback = True

                for ep in knn_points:
                    if p == ep:
                        if_pushback = False
                        break

                start_point = input_points[pp]
                end_point = input_points[p]

                if distance(start_point, end_point) > distance_limitation:
                    if_pushback = False

                if if_pushback is True:
                    knn_points.append(p)
        # end propagation

        apart_points = []

        for nnp in knn_points:
            # print('pp', pp)
            # print('nnp', nnp)
            dijkstra.SetStartVertex(pp)
            dijkstra.SetEndVertex(nnp)
            dijkstra.Update()
            # print('over')

            id_list = dijkstra.GetIdList()

            path_data_list = c_float * (id_list.GetNumberOfIds() * 3)
            path_data = path_data_list()

            for k in range(id_list.GetNumberOfIds()):
                path_data[k * 3] = input_points[id_list.GetId(k)][0]
                path_data[k * 3 + 1] = input_points[id_list.GetId(k)][1]
                path_data[k * 3 + 2] = input_points[id_list.GetId(k)][2]

            path_dis = calculation.path_distance(path_data,
                                                 id_list.GetNumberOfIds() * 3)

            if path_dis < distance_limitation:
                apart_points.append(nnp)

        cells = []

        # get cells
        for ap in apart_points:
            cell_id_list = vtk.vtkIdList()
            input_model.GetOutput().GetPointCells(ap, cell_id_list)

            for j in range(cell_id_list.GetNumberOfIds()):
                cells.append(cell_id_list.GetId(j))

        cells = list(dict.fromkeys(cells))

        faces = []

        # get faces
        for c in cells:
            f = (input_model.GetOutput().GetCell(c).GetPointIds().GetId(0),
                 input_model.GetOutput().GetCell(c).GetPointIds().GetId(1),
                 input_model.GetOutput().GetCell(c).GetPointIds().GetId(2))

            if f[0] in apart_points and f[1] in apart_points and f[
                    2] in apart_points:
                faces.append((apart_points.index(f[0]) + 1,
                              apart_points.index(f[1]) + 1,
                              apart_points.index(f[2]) + 1))

        # save file
        print(i)
        file = open(
            os.path.join(output_path, input_file[:-4] + '-' + str(i) + '.obj'),
            'w')

        for p in apart_points:
            file.writelines('v {} {} {}\n'.format(input_points[p][0],
                                                  input_points[p][1],
                                                  input_points[p][2]))

        file.writelines('\n')

        for f in faces:
            file.writelines('f {} {} {}\n'.format(f[0], f[1], f[2]))

        file.writelines('\n')

        file.close()
        print('Save finished!')

    print('All finished!')
Exemple #13
0
            break

    guessPoint = -1
    for i in range(guessModel.GetNumberOfPoints()):
        if guessScalars.GetValue(i) == 2:
            guessPoint = i
            break

    mapCoords = mapModel.GetPoint(mapPoint)
    guessCoords = mapModel.GetPoint(guessPoint)

    euclideanDistance = math.sqrt((mapCoords[0] - guessCoords[0])**2 +
                                  (mapCoords[1] - guessCoords[1])**2 +
                                  (mapCoords[2] - guessCoords[2])**2)

    dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
    dijkstra.SetInputData(mapModel)
    dijkstra.SetStartVertex(mapPoint)
    dijkstra.SetEndVertex(guessPoint)
    dijkstra.Update()
    weights = vtk.vtkDoubleArray()
    dijkstra.GetCumulativeWeights(weights)

    geodesicDistance = weights.GetValue(guessPoint)

    pairwisePoints.append(
        (actualLandmarkNo, euclideanDistance, geodesicDistance))

csvFilename = guessFilename.split(".")[0] + "_comparedAllPoints.csv"

with open(csvFilename, 'wb') as csvfile:
Exemple #14
0
def generate_one(input_path, input_file, output_path):
    random_number = 20
    distance_limitation = 15

    # load data
    input_model = vtk.vtkOBJReader()
    input_model.SetFileName(os.path.join(input_path, input_file))
    input_model.Update()
    print('load over')

    input_points = []

    p = [0.0, 0.0, 0.0]
    for i in range(input_model.GetOutput().GetNumberOfPoints()):
        input_model.GetOutput().GetPoint(i, p)
        input_points.append(tuple(p))

    picked_points = [
        random.randint(0, len(input_points)) for i in range(random_number)
    ]

    calculation = CDLL('./calculation.so')
    calculation.path_distance.argtypes = (POINTER(c_float), c_int)
    calculation.path_distance.restype = c_float

    dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
    dijkstra.SetInputData(input_model.GetOutput())

    for i, pp in enumerate(picked_points):
        # bug, if two points are not connected
        # knn_points = kd_tree.query_ball_point(input_points[pp], distance_limitation)
        # print(len(knn_points))

        # use propagation
        knn_points = [pp]
        for sp in knn_points:
            nn_index = []

            cellidlist = vtk.vtkIdList()
            input_model.GetOutput().GetPointCells(sp, cellidlist)
            for k in range(cellidlist.GetNumberOfIds()):
                cell = input_model.GetOutput().GetCell(cellidlist.GetId(k))
                for e in range(cell.GetNumberOfEdges()):
                    edge = cell.GetEdge(e)
                    pointidlist = edge.GetPointIds()
                    if pointidlist.GetId(0) != sp and pointidlist.GetId(
                            1) != sp:
                        nn_index.append(pointidlist.GetId(0))
                        nn_index.append(pointidlist.GetId(1))
                        break

            nn_index = {}.fromkeys(nn_index).keys()

            for p in nn_index:
                if_pushback = True

                for ep in knn_points:
                    if p == ep:
                        if_pushback = False
                        break

                start_point = input_points[pp]
                end_point = input_points[p]

                if distance(start_point, end_point) > distance_limitation:
                    if_pushback = False

                if if_pushback is True:
                    knn_points.append(p)
        # end propagation

        apart_points = []

        for nnp in knn_points:
            dijkstra.SetStartVertex(pp)
            dijkstra.SetEndVertex(nnp)
            dijkstra.Update()

            id_list = dijkstra.GetIdList()

            path_data_list = c_float * (id_list.GetNumberOfIds() * 3)
            path_data = path_data_list()

            for k in range(id_list.GetNumberOfIds()):
                path_data[k * 3] = input_points[id_list.GetId(k)][0]
                path_data[k * 3 + 1] = input_points[id_list.GetId(k)][1]
                path_data[k * 3 + 2] = input_points[id_list.GetId(k)][2]

            path_dis = calculation.path_distance(path_data,
                                                 id_list.GetNumberOfIds() * 3)

            if path_dis < distance_limitation:
                apart_points.append(nnp)

        cells = []

        # get cells
        for ap in apart_points:
            cell_id_list = vtk.vtkIdList()
            input_model.GetOutput().GetPointCells(ap, cell_id_list)

            for j in range(cell_id_list.GetNumberOfIds()):
                cells.append(cell_id_list.GetId(j))

        cells = list(dict.fromkeys(cells))

        faces = []

        # get faces
        for c in cells:
            f = (input_model.GetOutput().GetCell(c).GetPointIds().GetId(0),
                 input_model.GetOutput().GetCell(c).GetPointIds().GetId(1),
                 input_model.GetOutput().GetCell(c).GetPointIds().GetId(2))

            if f[0] in apart_points and f[1] in apart_points and f[
                    2] in apart_points:
                faces.append((apart_points.index(f[0]) + 1,
                              apart_points.index(f[1]) + 1,
                              apart_points.index(f[2]) + 1))

        # save file
        print(i)
        file = open(
            os.path.join(output_path, input_file[:-4] + '-' + str(i) + '.obj'),
            'w')

        for p in apart_points:
            file.writelines('v {} {} {}\n'.format(input_points[p][0],
                                                  input_points[p][1],
                                                  input_points[p][2]))

        file.writelines('\n')

        for f in faces:
            file.writelines('f {} {} {}\n'.format(f[0], f[1], f[2]))

        file.writelines('\n')

        print('Save finished!')
        file.close()