Example #1
1
def obb(opts,argv):
	poly = nv.readVTK(argv[0])
	obb = vtk.vtkOBBTree()
	obb.SetMaxLevel(10)
	obb.SetNumberOfCellsPerNode(5)
	obb.AutomaticOn()
	sfilt = vtk.vtkSpatialRepresentationFilter()
	sfilt.SetSpatialRepresentation(obb)
	sfilt.SetInput(poly)
	sfilt.Update()
	nv.writeVTK(argv[1],sfilt.GetOutput())
Example #2
0
    def __init__(self, mesh):
        assert mesh != None
        
        self._mesh = mesh
        self._batch = None
        self._color = (0.0, 1.0, 0.0, 1.0)
        
        #smooth_loop = vtk.vtkLoopSubdivisionFilter()
        #smooth_loop.SetNumberOfSubdivisions(3)
        #smooth_loop.SetInput(cleanPolyData.GetOutput())
        #self.mesh = smooth_loop.GetOutput()

        normals = vtk.vtkPolyDataNormals()
        normals.SetInput(self._mesh)
        normals.ComputeCellNormalsOn()
        output = normals.GetOutput()
        output.Update();
        cellData = output.GetCellData();
        self._normals = cellData.GetNormals();

        self._caster = vtk.vtkOBBTree()
        #set the 'mesh' as the caster's dataset
        self._caster.SetDataSet(self._mesh)
        #build a caster locator
        self._caster.BuildLocator()
Example #3
0
  def __init__(self, vtk_mesh, axis):
    """Initialize this object with the mesh in which the points are supposed to be generated. 'axis' should
    be 0, 1 or 2 depending on whether you want to mirror the generated point along the x, y or z axis."""
    if not isinstance(vtk_mesh, vtk.vtkPolyData):
      try:
        vtk_mesh = vtk_mesh.visual_representation.vtk_poly_data
      except AttributeError:
        raise

    if not vtk_mesh.GetPoints() or not vtk_mesh.GetPolys():
      raise ValueError("input argument 'vtk_mesh' has no points and/or triangles")

    self.__vtk_mesh = vtk_mesh

    # Compute the bounding box of the mesh
    vtk_mesh.ComputeBounds()
    self.__bounding_box = b = vtk_mesh.GetBounds()
    self.__bounding_box_diag = math.sqrt((b[1]-b[0])**2 + (b[3]-b[2])**2 + (b[5]-b[4])**2)

    # Populate the lists which contain the point ids
    self.__build_point_id_lists(axis)

    self.__left_point_cloud = UniformPointCloud(self.__left_target)
    self.__right_point_cloud = UniformPointCloud(self.__right_target)
    self.__central_point_cloud = UniformPointCloud(self.__central_target)

    # This is the guy who does an efficient line-surface intersection
    self.__obb_tree = vtk.vtkOBBTree()
    self.__obb_tree.SetDataSet(vtk_mesh)
    self.__obb_tree.BuildLocator()
	def calculateIsInside(self, polydata, imgdata, objects):
		"""
		Calculate whether the objects are on the inside of the surface
		"""
		if not polydata:
			return []
		
		locator = vtk.vtkOBBTree()
		locator.SetDataSet(polydata)
		locator.BuildLocator()
		distances = []
		xs, ys, zs = imgdata.GetSpacing()

		for object in objects:
			x, y, z  = object.getCenterOfMass()
			x *= xs
			y *= ys
			z *= zs

			inside = locator.InsideOrOutside([x,y,z])
			if inside == -1:
				distances.append(True)
			elif inside == 1:
				distances.append(False)
			else:
				distances.append(None)
	
		return distances
Example #5
0
def vtkIntersectWithSegment(surf,lines,tol=0.0):
    """
    Computes the intersection of surf with lines.
    Returns a list of the intersection points lists and of the element number of surf where the point lies.
    The position in the list is equal to the line number. If there is no intersection with the correspondent
    lists are empty
    
    Parameters:
        surf :  can be Formex, Mesh or TriSurface
        lines : a mesh of segments

    """
    from vtk import vtkOBBTree
    
    surf = convert2VPD(surf,clean=False)
    loc = vtkOBBTree()
    loc.SetDataSet(vm)
    loc.SetTolerance(tol)
    loc.BuildLocator()
    loc.Update()
    cellids = [[],]*lines.nelems()
    pts = [[],]*lines.nelems()
    for i in range(lines.nelems()):
        ptstmp = vtkPoints()
        cellidstmp = vtkIdList()
        loc.IntersectWithLine(lines.coords[lines.elems][i][1],lines.coords[lines.elems][i][0],ptstmp, cellidstmp)
        if cellidstmp.GetNumberOfIds():
            cellids[i] = [cellidstmp.GetId(j) for j in range(cellidstmp.GetNumberOfIds())]
            pts[i] = Coords(v2n(ptstmp.GetData()).squeeze())
    loc.FreeSearchStructure()
    del loc
    return pts,cellids
Example #6
0
    def __initCaster(self):
        """Initialize a raycaster

        Internal method that just creates a vtkOBBTree object and setup
        """
        if self.flag == 'bsp':
            self.caster = vtk.vtkModifiedBSPTree()
        elif self.flag == 'obb':
            self.caster = vtk.vtkOBBTree()
        # set the object polydata as the dataset
        self.caster.SetDataSet(self.polydata)
        self.caster.BuildLocator()
    def projectPointsOut(self, sourcePolydata, targetPolydata, originalPoints,
                         projectedPoints, rayLength):
        #sourcePolydata = sourceMesh.GetPolyData()
        #targetPolydata = targetMesh.GetPolyData()

        #set up locater for intersection with normal vector rays
        obbTree = vtk.vtkOBBTree()
        obbTree.SetDataSet(targetPolydata)
        obbTree.BuildLocator()

        #set up point locator for finding surface normals and closest point
        pointLocator = vtk.vtkPointLocator()
        pointLocator.SetDataSet(sourcePolydata)
        pointLocator.BuildLocator()

        targetPointLocator = vtk.vtkPointLocator()
        targetPointLocator.SetDataSet(targetPolydata)
        targetPointLocator.BuildLocator()

        #get surface normal from each landmark point
        rayDirection = [0, 0, 0]
        normalArray = sourcePolydata.GetPointData().GetArray("Normals")
        if (not normalArray):
            normalFilter = vtk.vtkPolyDataNormals()
            normalFilter.ComputePointNormalsOn()
            normalFilter.SetInputData(sourcePolydata)
            normalFilter.Update()
            normalArray = normalFilter.GetOutput().GetPointData().GetArray(
                "Normals")
            if (not normalArray):
                print("Error: no normal array")

        for index in range(originalPoints.GetNumberOfMarkups()):
            originalPoint = [0, 0, 0]
            originalPoints.GetMarkupPoint(0, index, originalPoint)
            # get ray direction from closest normal
            closestPointId = pointLocator.FindClosestPoint(originalPoint)
            rayDirection = normalArray.GetTuple(closestPointId)
            rayEndPoint = [0, 0, 0]
            for dim in range(len(rayEndPoint)):
                rayEndPoint[
                    dim] = originalPoint[dim] + rayDirection[dim] * rayLength
            intersectionIds = vtk.vtkIdList()
            intersectionPoints = vtk.vtkPoints()
            obbTree.IntersectWithLine(originalPoint, rayEndPoint,
                                      intersectionPoints, intersectionIds)
            #if there are intersections, update the point to most external one.
            if intersectionPoints.GetNumberOfPoints() > 0:
                exteriorPoint = intersectionPoints.GetPoint(
                    intersectionPoints.GetNumberOfPoints() - 1)
                projectedPoints.AddFiducialFromArray(exteriorPoint)
        return True
Example #8
0
    def obbTree(self,obstacle):

        mesh = vtk.vtkMarchingCubes()
        mesh.SetInputData(obstacle.GetImageData())
        mesh.SetValue(0, 0.5)
        mesh.Update()


        obbTree = vtk.vtkOBBTree()
        obbTree.SetDataSet(mesh.GetOutput())
        obbTree.BuildLocator()

        return obbTree
Example #9
0
    def obbTree(self):
        """obbTree is an object to generate oriented bounding box (OBB)
        trees. An oriented bounding box is a bounding box that does not
        necessarily line up along coordinate axes. The OBB tree is a
        hierarchical tree structure of such boxes, where deeper levels of OBB
        confine smaller regions of space.
        """
        if not hasattr(self, '_obbTree'):
            self._obbTree = vtk.vtkOBBTree()
            self._obbTree.SetDataSet(self)
            self._obbTree.BuildLocator()

        return self._obbTree
Example #10
0
  def test_algorithm_OBB_IsNot_None(self):
    self.delayDisplay("Starting test: MakeMeshTree IsNot None.")
    inputImage = slicer.util.getNode('r_hippo Vol')
    # Create Mesh of obstacle 1
    mesh = vtk.vtkMarchingCubes(); mesh.SetInputData(inputImage.GetImageData())
    mesh.SetValue(0, 0.5); mesh.Update()

    # Create Tree of obstacle 1
    OBB_obstacle1_tree = vtk.vtkOBBTree()
    OBB_obstacle1_tree.SetDataSet(mesh.GetOutput())
    OBB_obstacle1_tree.BuildLocator()
    self.assertIsNotNone(OBB_obstacle1_tree)
    self.delayDisplay('Test passed! obb tree created is not empty')
Example #11
0
    def _initCaster(self):
        r"""Create a 'caster'

        This is an internal method. DO NOT USE DIRECTLY. This method creates a
        'caster', i.e., a 'vtkOBBTree' object which is used later on to cast
        rays.
        """

        #create a 'vtkOBBTree' object
        self.caster = vtk.vtkOBBTree()
        #set the 'mesh' as the caster's dataset
        self.caster.SetDataSet(self.mesh)
        #build a caster locator
        self.caster.BuildLocator()
Example #12
0
def getTree(area, value=None):
    if value is not None:
        mesh = vtk.vtkMarchingCubes()
        mesh.SetInputData(area.GetImageData())
        mesh.SetValue(value[0], value[1])
    else:
        mesh = vtk.vtkDiscreteMarchingCubes()
        mesh.SetInputData(area.GetImageData())
    mesh.Update()
    polyData = mesh.GetOutput()
    tree = vtk.vtkOBBTree()
    tree.SetDataSet(polyData)
    tree.BuildLocator()
    return tree, polyData
def getIntersections(surfaceOBJ,pSource,pTarget):
    mesh = loadOBJforVTK(surfaceOBJ) 
    obbTree = vtk.vtkOBBTree()
    obbTree.SetDataSet(mesh)
    obbTree.BuildLocator()
    pointsVTKintersection = vtk.vtkPoints()
    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None) #!?   eerst code = 
    pointsVTKIntersectionData = pointsVTKintersection.GetData()
    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
    pointsIntersection = []
    for idx in range(noPointsVTKIntersection):
        _tup = pointsVTKIntersectionData.GetTuple3(idx)
        pointsIntersection.append(_tup)
    return pointsIntersection
Example #14
0
def vtk_intersections(mesh, point_array, point_normals, raycast_length=""):
    point_normals = point_normals
    reverse_normals = -1 * point_normals

    # Load the points into a vtk object
    vtkPts = vtk.vtkPoints()
    vtkPts.SetData(npsup.numpy_to_vtk(point_array, deep=1))
    poly = vtk.vtkPolyData()
    poly.SetPoints(vtkPts)
    noPoints = poly.GetNumberOfPoints()

    #Set up the length of all the lines
    if raycast_length == "":
        image_size = abs(
            np.array(mesh.GetBounds()).min() -
            np.array(mesh.GetBounds()).max())
        RayCastLength = get_ray_length(image_size)
    else:
        RayCastLength = 128 * 128

    #initiate the mesh with the vtk OBB tree
    mesh_voi = vtk.vtkOBBTree()
    mesh_voi.SetDataSet(mesh)
    mesh_voi.BuildLocator()

    # Set up a list to store the results
    total_points_list = set()
    total_cells_list = set()

    pointRayStart = [
        poly.GetPoint(idx) + RayCastLength * np.array(reverse_normals)
        for idx in range(noPoints)
    ]
    pointRayTarget = [
        poly.GetPoint(idx) + RayCastLength * np.array(point_normals)
        for idx in range(noPoints)
    ]

    points_list = [
        GetIntersect(mesh_voi, pointRayStart[idx], pointRayTarget[idx])
        for idx in range(noPoints)
    ]
    #It's much faster just to drop the empty sets
    points_list = [x for x in points_list if x]

    for idx in range(len(points_list)):
        total_cells_list.update(points_list[idx][1])
        total_points_list.update(points_list[idx][0])
    return total_points_list, total_cells_list
Example #15
0
def intersectwithline(surface,p1,p2):

   # Create the locator
    tree = vtk.vtkOBBTree()
    tree.SetDataSet(surface)
    tree.BuildLocator()

    intersectPoints = vtk.vtkPoints()
    intersectCells = vtk.vtkIdList()

    tolerance=1.e-3
    tree.SetTolerance(tolerance)
    tree.IntersectWithLine(p1,p2,intersectPoints,intersectCells)

    return intersectPoints
Example #16
0
def intersectWithLine(act, p0, p1):
    '''Return a list of points between p0 and p1 intersecting the actor'''
    if not hasattr(act, 'linelocator'):
        linelocator = vtk.vtkOBBTree()
        linelocator.SetDataSet(vu.polydata(act, True))
        linelocator.BuildLocator()
        setattr(act, 'linelocator', linelocator)

    intersectPoints = vtk.vtkPoints()
    intersection = [0, 0, 0]
    act.linelocator.IntersectWithLine(p0, p1, intersectPoints, None)
    pts = []
    for i in range(intersectPoints.GetNumberOfPoints()):
        intersectPoints.GetPoint(i, intersection)
        pts.append(list(intersection))
    return pts
Example #17
0
	def calculateAverageDistancesToSurface(self, polydata, imgdata, objects, centerOfMass):
		"""
		Calculate the distance to surface for the given set of objects
		"""
		if not polydata:
			return [], []
		locator = vtk.vtkOBBTree()
		locator.SetDataSet(polydata)
		locator.BuildLocator()
		voxelSizes = self.segmentedSource.getVoxelSize()
		voxelSizes = [x*1000000 for x in voxelSizes]
		print "Setting voxel sizes",voxelSizes
		distanceCalc = vtkbxd.vtkImageLabelDistanceToSurface()
		distanceCalc.SetVoxelSize(voxelSizes)
		distanceCalc.SetMeasurePoint(centerOfMass)
		distanceCalc.SetInputConnection(0, imgdata.GetProducerPort())
		distanceCalc.SetInputConnection(1, polydata.GetProducerPort())
		distanceCalc.SetSurfaceLocator(locator)
		print "Calculating average distances"

		distanceCalc.Update()
		distArray = distanceCalc.GetAverageDistanceToSurfaceArray()
		distStdErrArray = distanceCalc.GetAverageDistanceToSurfaceStdErrArray()
		distances = []
		distancesStdErr = []
		comDistances = []
		comDistancesStdErr = []
		inOut = []
		for i in range(1, distArray.GetSize()):
			value = distArray.GetValue(i)
			distances.append(value)
			value = distStdErrArray.GetValue(i)
			distancesStdErr.append(value)

		distArray = distanceCalc.GetAverageDistanceToPointArray()
		distStdErrArray = distanceCalc.GetAverageDistanceToPointStdErrArray()
		insideArray = distanceCalc.GetInsideCountArray()
		outsideArray = distanceCalc.GetOutsideCountArray()

		for i in range(1, distArray.GetSize()):
			value = distArray.GetValue(i)
			comDistances.append(value)
			value = distStdErrArray.GetValue(i)
			comDistancesStdErr.append(value)
			inOut.append((insideArray.GetValue(i), outsideArray.GetValue(i)))
			
		return comDistances, distances, inOut, comDistancesStdErr, distancesStdErr
def per_vertex_occlusion_accurate(mesh):
    from menpo3d.vtkutils import trimesh_to_vtk
    import vtk
    tol = mesh.mean_edge_length() / 1000
    min_, max_ = mesh.bounds()
    z_min = min_[-1] - 10
    z_max = max_[-1] + 10

    ray_start = mesh.points.copy()
    ray_end = mesh.points.copy()
    points = mesh.points
    ray_start[:, 2] = z_min
    ray_end[:, 2] = z_max


    vtk_mesh = trimesh_to_vtk(mesh)

    obbTree = vtk.vtkOBBTree()
    obbTree.SetDataSet(vtk_mesh)
    obbTree.BuildLocator()


    vtk_points = vtk.vtkPoints()
    vtk_cellIds = vtk.vtkIdList()
    bad_val = tuple(ray_start[0])
    first_intersects = []
    for start, end, point in zip(ray_start, ray_end, points):
        start = tuple(start)
        end = tuple(end)
        obbTree.IntersectWithLine(start, end, vtk_points, vtk_cellIds)
        data = vtk_points.GetData()
        break
    for start, end, point in zip(ray_start, ray_end, points):
        start = tuple(start)
        end = tuple(end)
        #obbTree.IntersectWithLine(start, end, vtk_points, vtk_cellIds)
        data = vtk_points.GetData()
        if data.GetNumberOfTuples() > 0:
            first_intersects.append(data.GetTuple3(0))
        else:
            first_intersects.append(bad_val)

    visible = np.linalg.norm(points - np.array(first_intersects), axis=1) < tol
    return visible
Example #19
0
def per_vertex_occlusion_accurate(mesh):
    from menpo3d.vtkutils import trimesh_to_vtk
    import vtk
    tol = mesh.mean_edge_length() / 1000
    min_, max_ = mesh.bounds()
    z_min = min_[-1] - 10
    z_max = max_[-1] + 10

    ray_start = mesh.points.copy()
    ray_end = mesh.points.copy()
    points = mesh.points
    ray_start[:, 2] = z_min
    ray_end[:, 2] = z_max


    vtk_mesh = trimesh_to_vtk(mesh)

    obbTree = vtk.vtkOBBTree()
    obbTree.SetDataSet(vtk_mesh)
    obbTree.BuildLocator()


    vtk_points = vtk.vtkPoints()
    vtk_cellIds = vtk.vtkIdList()
    bad_val = tuple(ray_start[0])
    first_intersects = []
    for start, end, point in zip(ray_start, ray_end, points):
        start = tuple(start)
        end = tuple(end)
        obbTree.IntersectWithLine(start, end, vtk_points, vtk_cellIds)
        data = vtk_points.GetData()
        break
    for start, end, point in zip(ray_start, ray_end, points):
        start = tuple(start)
        end = tuple(end)
        #obbTree.IntersectWithLine(start, end, vtk_points, vtk_cellIds)
        data = vtk_points.GetData()
        if data.GetNumberOfTuples() > 0:
            first_intersects.append(data.GetTuple3(0))
        else:
            first_intersects.append(bad_val)

    visible = np.linalg.norm(points - np.array(first_intersects), axis=1) < tol
    return visible
    def mesh_descriptors(self, FMIs_dir, type_of_normalize, random_num=0):
        self.cell_normal_generator(cell_flag=True, point_flag=False)
        normals = self.source.GetCellData().GetNormals()
        centers = self.centers_of_cells()

        obb = vtk.vtkOBBTree()
        # locator = vtk.vtkCellLocator()
        obb.SetDataSet(self.source)
        obb.BuildLocator()

        size = self.source.GetNumberOfCells()
        scope = []
        if random_num is not 0:
            scope = np.random.randint(0, size, random_num)
        else:
            scope = range(size)

        print(scope)
        for i in scope:
            normal = np.array([normals.GetTuple(i)[x] for x in range(3)])
            center = np.array([centers.GetPoint(i)[x] for x in range(3)])
            center_disc = self.center_of_disc(normal, center)
            radii = []
            distances = []
            for j in range(self.num_of_circle):
                radius = self.init_radius + j * self.radius_delta
                radii.append(radius)
                points_mesh, points_disc, d = self.compute_descriptor(
                    obb, normal, center_disc, radius)
                # print('distance: ', [np.linalg.norm(x - y) for x, y in zip(points_mesh, points_disc)])
                distances.append(d)
                self.all_points_mesh.append(points_mesh)
                self.all_points_disc.append(points_disc)
            distances = np.array(distances)
            name = FMIs_dir + str(i) + '.bmp'
            if type_of_normalize is 0:
                self.save_FMIs(self.max_min_normalization, distances, name)
            else:
                self.save_FMIs(self.standard_scaler, distances, name)
            # self.hist_distances(distances.reshape((distances.shape[0] * distances.shape[1], 1)))
            self.all_distances.append(distances)
            self.all_normals.append(normal)
            self.all_centers_disc.append(center_disc)
            self.all_radii.append(np.array(radii))
Example #21
0
def vtkIntersectWithSegment(surf, lines, tol=0.0):
    """
    Computes the intersection of surf with lines.
    Returns a list of the intersection points lists and of the element number of surf where the point lies.
    The position in the list is equal to the line number. If there is no intersection with the correspondent
    lists are empty
    
    Parameters:
        surf :  can be Formex, Mesh or TriSurface
        lines : a mesh of segments

    """
    from vtk import vtkOBBTree

    surf = convert2VPD(surf, clean=False)
    loc = vtkOBBTree()
    loc.SetDataSet(vm)
    loc.SetTolerance(tol)
    loc.BuildLocator()
    loc.Update()
    cellids = [
        [],
    ] * lines.nelems()
    pts = [
        [],
    ] * lines.nelems()
    for i in range(lines.nelems()):
        ptstmp = vtkPoints()
        cellidstmp = vtkIdList()
        loc.IntersectWithLine(lines.coords[lines.elems][i][1],
                              lines.coords[lines.elems][i][0], ptstmp,
                              cellidstmp)
        if cellidstmp.GetNumberOfIds():
            cellids[i] = [
                cellidstmp.GetId(j) for j in range(cellidstmp.GetNumberOfIds())
            ]
            pts[i] = Coords(v2n(ptstmp.GetData()).squeeze())
    loc.FreeSearchStructure()
    del loc
    return pts, cellids
Example #22
0
def make_obb(stl_file,
             position=(0, 0, 0),
             orientation=(0, 0, 0, 1),
             scale=(1, 1, 1)):
    reader = vtk.vtkSTLReader()
    reader.SetFileName(stl_file)
    # 'update' the reader i.e. read the .stl file
    reader.Update()

    angle, axis = PyKDL.Rotation.Quaternion(orientation[0], orientation[1],
                                            orientation[2],
                                            orientation[3]).GetRotAngle()
    print("angle", angle)
    print("angle / 180", angle / np.pi * 180)
    print("axis", axis)

    transform = vtk.vtkTransform()
    transform.Scale(scale)
    transform.RotateWXYZ(angle / np.pi * 180, axis.x(), axis.y(), axis.z())
    transform.Translate(position)

    transformFilter = vtk.vtkTransformPolyDataFilter()
    transformFilter.SetInputConnection(reader.GetOutputPort())
    transformFilter.SetTransform(transform)
    transformFilter.Update()

    mesh = transformFilter.GetOutput()
    # print("number of points", mesh.GetNumberOfPoints())
    # If there are no points in 'vtkPolyData' something went wrong
    if mesh.GetNumberOfPoints() == 0:
        raise ValueError("No point data could be loaded from '" + stl_file)
        return None

    obbTree = vtk.vtkOBBTree()
    obbTree.SetDataSet(mesh)
    obbTree.SetTolerance(0.0001)
    obbTree.BuildLocator()

    return obbTree
def computeABPointsFromOrientedBoundingBox(
        mesh,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeABPointsFromOrientedBoundingBox ***")

    center = numpy.array(mesh.GetCenter())

    res_corner = numpy.empty(3)
    res_max = numpy.empty(3)
    res_mid = numpy.empty(3)
    res_min = numpy.empty(3)
    res_size = numpy.empty(3)
    obb_tree = vtk.vtkOBBTree()
    obb_tree.ComputeOBB(
        mesh,
        res_corner,
        res_max,
        res_mid,
        res_min,
        res_size)
    if (verbose >= 2): print "res_corner =", res_corner
    if (verbose >= 2): print "res_max =", res_max
    if (verbose >= 2): print "res_mid =", res_mid
    if (verbose >= 2): print "res_min =", res_min
    if (verbose >= 2): print "res_size =", res_size

    point_A = res_corner + numpy.dot(center-res_corner, res_min/numpy.linalg.norm(res_min)) * res_min/numpy.linalg.norm(res_min) + numpy.dot(center-res_corner, res_mid/numpy.linalg.norm(res_mid)) * res_mid/numpy.linalg.norm(res_mid)
    point_B = point_A + res_max
    if (verbose >= 2): print "point_A =", point_A
    if (verbose >= 2): print "point_B =", point_B
    if (verbose >= 2): print "AB =", point_B-point_A

    points_AB = vtk.vtkPoints()
    points_AB.InsertNextPoint(point_A)
    points_AB.InsertNextPoint(point_B)
    #if (verbose >= 2): print points_AB

    return points_AB
def computeABPointsFromOrientedBoundingBox(
        mesh,
        verbose=1):

    myVTK.myPrint(verbose, "*** computeABPointsFromOrientedBoundingBox ***")

    center = numpy.array(mesh.GetCenter())

    res_corner = numpy.array([0.]*3)
    res_max = numpy.array([0.]*3)
    res_mid = numpy.array([0.]*3)
    res_min = numpy.array([0.]*3)
    res_size = numpy.array([0.]*3)
    obb_tree = vtk.vtkOBBTree()
    obb_tree.ComputeOBB(
        mesh,
        res_corner,
        res_max,
        res_mid,
        res_min,
        res_size)
    if (verbose >= 2): print "res_corner =", res_corner
    if (verbose >= 2): print "res_max =", res_max
    if (verbose >= 2): print "res_mid =", res_mid
    if (verbose >= 2): print "res_min =", res_min
    if (verbose >= 2): print "res_size =", res_size

    point_A = res_corner + numpy.dot(center-res_corner, res_min/numpy.linalg.norm(res_min)) * res_min/numpy.linalg.norm(res_min) + numpy.dot(center-res_corner, res_mid/numpy.linalg.norm(res_mid)) * res_mid/numpy.linalg.norm(res_mid)
    point_B = point_A + res_max
    if (verbose >= 2): print "point_A =", point_A
    if (verbose >= 2): print "point_B =", point_B
    if (verbose >= 2): print "AB =", point_B-point_A

    points_AB = vtk.vtkPoints()
    points_AB.InsertNextPoint(point_A)
    points_AB.InsertNextPoint(point_B)
    #if (verbose >= 2): print points_AB

    return points_AB
	def find_apex(self,Coords,Cent,Norm1,surface_data):
		#Get the min and max and scale the norm
		xmin=min(Coords[:,0]);xmax=max(Coords[:,0])
		ymin=min(Coords[:,1]);ymax=max(Coords[:,1])
		zmin=min(Coords[:,2]);zmax=max(Coords[:,2])
		Length=max(xmax-xmin,ymax-ymin,zmax-zmin)
		Norm1s=Norm1*Length	
		
		#Get the source point
		pSource=[Cent[0]-Norm1s[0],Cent[1]-Norm1s[1],Cent[2]-Norm1s[2]]
		pTarget=[Cent[0]+Norm1s[0],Cent[1]+Norm1s[1],Cent[2]+Norm1s[2]]

		#Create a bounding box of the surface mesh
		obbTree = vtk.vtkOBBTree()
		obbTree.SetDataSet(surface_data)
		obbTree.BuildLocator()
		
		#Create a point array to store intersection points
		pointsVTKintersection = vtk.vtkPoints()
		code=obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
		
		pointsVTKIntersectionData = pointsVTKintersection.GetData()
		noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
		pointsIntersection = []
		distanceCentroid=[]
		for idx in range(noPointsVTKIntersection):
			tup = pointsVTKIntersectionData.GetTuple3(idx)
			dx=(Cent[0]-tup[0])**2
			dy=(Cent[1]-tup[1])**2
			dz=(Cent[2]-tup[2])**2
			distanceCentroid.append((dx+dy+dz)**0.5)
			pointsIntersection.append(tup)	
			
		#Now find the furthest point from Centroid as Apex
		max_idx=np.argmax(distanceCentroid)
		apex_coord=pointsIntersection[max_idx]
		del obbTree,pointsVTKintersection,code,pointsVTKIntersectionData,noPointsVTKIntersection	
		return apex_coord
Example #26
0
def cast_rays_3d(config, debug, settings):
    # Where to find the 2D clusters
    cluster_folder = os.path.join(config['iteration_directory'],
                                  settings['general']['iterations_structure']['detect'])

    # Get camera calibration information
    camera_params = helpers.read_camera_params(
        settings['inputs']['camera_xyz_offset'],
        settings['inputs']['camera_params'])

    # Load 3D mesh
    print 'Loading 3D mesh...'
    mesh = loadSTL(settings['inputs']['3dmesh'])

    # Load mesh offset
    with open(settings['inputs']['3dmesh_offset'], 'r') as offsetfile:
        mesh_offset = np.array(map(float, offsetfile.readlines()[0].split()))

    # build OBB tree for fast intersection search
    print 'Building OBB tree...'
    obbTree = vtk.vtkOBBTree()
    obbTree.SetDataSet(mesh)
    obbTree.BuildLocator()

    for fold_i in range(settings['general']['do_folds']):
        print('-- FOLD {} --'.format(fold_i))

        # initialize result lists
        r = {
            'x': [],
            'y': [],
            'z': [],
            'score': [],
            'id': [],
            'image': [],
            'img_x': [],
            'img_y': []
        }
                    # compute 3d points
        for cluster_list_file in glob(cluster_folder + '/fold_{}/*.csv'.format(fold_i)):

            # read clusters
            cluster_list = np.loadtxt(cluster_list_file, skiprows=1, delimiter=';',
                                      ndmin=2)

            # fetch parameters for image
            this_cam_params = filter(lambda c: c['camera_name'].split('.')[0] == os.path.basename(cluster_list_file).split('.')[0], camera_params)[0]

            # compute camera transforms
            KRt = np.dot(np.dot(this_cam_params['K'], this_cam_params['R']), this_cam_params['t'])
            KRinv = np.linalg.inv(np.dot(this_cam_params['K'], this_cam_params['R']))
            # the zval is like an estimated elevation difference between camera and point
            zval = 200

            # intersection source (camera)
            intersection_source = np.transpose(this_cam_params['t'])[0] - mesh_offset

            # for each cluster
            for cluster in cluster_list:

                # Step 1: project to 3D space
                X2d = np.array([
                    [cluster[0] * zval / float(settings['inputs']['image_pixel_x'])],
                    [cluster[1] * zval / float(settings['inputs']['image_pixel_y'])],
                    [zval]])
                X3d = np.dot(KRinv, (X2d + KRt))

                #  target (3D point) and intersections
                intersection_target = np.transpose(X3d)[0] - mesh_offset
                pointsVTKintersection = vtk.vtkPoints()

                # Step 2: intersect line with surface and retain first
                code = obbTree.IntersectWithLine(intersection_source, intersection_target, pointsVTKintersection, None)
                # code is non-zero if there was an intersection
                if code != 0:
                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                    # retain the first intersect
                    (x, y, z) = pointsVTKIntersectionData.GetTuple3(0)
                    # append results to list
                    r['x'].append(x + mesh_offset[0])
                    r['y'].append(y + mesh_offset[1])
                    r['z'].append(z + mesh_offset[2])
                    r['score'].append(cluster[2])  # the score of the cluster
                    r['id'].append(int(cluster[3]))  # the id of the cluster
                    r['image'].append(os.path.basename(cluster_list_file).split('.')[0])  # the image in which the cluster was detected
                    r['img_x'].append(int(X2d[0][0] / zval))  # image coordinates
                    r['img_y'].append(int(X2d[1][0] / zval))

        # write results to dataframe
        # Where to save 3D points
        output_file = os.path.join(config['iteration_directory'],
                                   settings['general']['iterations_structure']['cast'],
                                   '3dpoints_{}.csv'.format(fold_i))
        pd.DataFrame({
            'x': r['x'],
            'y': r['y'],
            'z': r['z'],
            'score': r['score'],
            'id': r['id'],
            'image': r['image'],
            'img_x': r['img_x'],
            'img_y': r['img_y']
        }).to_csv(output_file)

    return 0
Example #27
0
def getTree(area, value=None):
    polyData = getMesh(area, value).GetOutput()
    tree = vtk.vtkOBBTree()
    tree.SetDataSet(polyData)
    tree.BuildLocator()
    return tree, polyData
Example #28
0
    def run(self, landmarkDirectory, meshDirectory, gridLandmarks,
            outputDirectory):
        #read all landmarks
        #landmarks = self.getLandmarks(landmarkDirectory)
        #print("landmark file shape: ", landmarks.shape)
        #[landmarkNumber,dim,subjectNumber] = landmarks.shape
        #get grid points
        #newGridPoints = self.getGridPoints(landmarks, gridLandmarks)
        #reflect gridPoints onto each surface
        #meshList = self.getAllSubjectMeshes(meshDirectory)
        #for i in range(subjectNumber):
        #mesh = self.readMesh(meshList(i))
        #stickToSurface(newGridPoints(:,:,i), mesh)
        # save semi-landmarks
        #self.saveSemiLandmarks(newGridPoints, outputDirectory)

        #Read data
        S = slicer.util.getNode("gor_skull")
        L = slicer.util.getNode("Gorilla_template_LM1")
        surfacePolydata = S.GetPolyData()

        # Set up point locator for later
        pointLocator = vtk.vtkPointLocator()
        pointLocator.SetDataSet(surfacePolydata)
        pointLocator.BuildLocator()
        #set up locater for intersection with normal vector rays
        obbTree = vtk.vtkOBBTree()
        obbTree.SetDataSet(surfacePolydata)
        obbTree.BuildLocator()

        #Set up fiducial grid
        print("Set up grid")
        fiducialPoints = vtk.vtkPoints()
        point = [0, 0, 0]
        for pt in range(L.GetNumberOfControlPoints()):
            L.GetMarkupPoint(pt, 0, point)
            fiducialPoints.InsertNextPoint(point)

        fiducialPolydata = vtk.vtkPolyData()
        fiducialPolydata.SetPoints(fiducialPoints)
        delaunayFilter = vtk.vtkDelaunay2D()
        delaunayFilter.SetInputData(fiducialPolydata)
        delaunayFilter.Update()
        fiducialMesh = delaunayFilter.GetOutput()
        fiducialMeshModel = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLModelNode", "fiducialMesh")
        fiducialMeshModel.SetAndObservePolyData(fiducialMesh)

        #Set up triangle grid for projection
        gridPoints = vtk.vtkPoints()
        sampleRate = 3

        for row in range(sampleRate):
            for col in range(sampleRate):
                if (row + col) < sampleRate:
                    gridPoints.InsertNextPoint(row, col, 0)

        gridPolydata = vtk.vtkPolyData()
        gridPolydata.SetPoints(gridPoints)

        #Set up source and target for triangle transform
        sourcePoints = vtk.vtkPoints()
        targetPoints = vtk.vtkPoints()

        sourcePoints.InsertNextPoint(gridPoints.GetPoint(0))
        sourcePoints.InsertNextPoint(gridPoints.GetPoint(sampleRate - 1))
        sourcePoints.InsertNextPoint(
            gridPoints.GetPoint(gridPoints.GetNumberOfPoints() - 1))

        #set up transform
        transform = vtk.vtkThinPlateSplineTransform()
        transform.SetSourceLandmarks(sourcePoints)
        transform.SetBasisToR()
        transformNode = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLTransformNode", "TPS")
        transformNode.SetAndObserveTransformToParent(transform)

        #Iterate through each triangle in fiducial mesh and project sampled triangle
        idList = vtk.vtkIdList()
        triangleArray = fiducialMesh.GetPolys()
        triangleArray.InitTraversal()

        #define new landmark sets
        semilandmarkPoints = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLMarkupsFiducialNode", "semiLM")
        gridPoints = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLMarkupsFiducialNode", "grid")

        print("Iterate through cells")
        #iterate through each triangle cell in the landmark mesh
        for triangle in range(4):  #(triangleArray.GetNumberOfCells()):
            print("Semilandmark n: ",
                  semilandmarkPoints.GetNumberOfFiducials())
            print("Triangle: ", triangle)
            triangleArray.GetNextCell(idList)
            print(idList)
            targetPoints.Reset()
            for verticeIndex in range(3):
                verticeID = idList.GetId(verticeIndex)
                verticeLocation = fiducialMesh.GetPoint(verticeID)
                targetPoints.InsertNextPoint(verticeLocation)
                print("Adding target point: ", verticeLocation)

            transform.SetTargetLandmarks(targetPoints)
            model = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLModelNode",
                                                       "mesh_resampled")
            model.SetAndObservePolyData(gridPolydata)
            model.SetAndObserveTransformNodeID(transformNode.GetID())
            slicer.vtkSlicerTransformLogic().hardenTransform(model)
            transformedPolydata = model.GetPolyData()

            # #get surface normal from each landmark point
            rayDirection = [0, 0, 0]
            normalArray = surfacePolydata.GetPointData().GetArray("Normals")

            # #calculate average normal from cell landmarks
            for verticeIndex in range(3):
                verticeLocation = targetPoints.GetPoint(verticeIndex)
                closestPointId = pointLocator.FindClosestPoint(verticeLocation)
                tempNormal = normalArray.GetTuple(closestPointId)
                print("Normal: ", tempNormal)
                rayDirection[0] += tempNormal[0]
                rayDirection[1] += tempNormal[1]
                rayDirection[2] += tempNormal[2]

            for dim in range(len(rayDirection)):
                rayDirection[dim] = rayDirection[dim] / 3

            #get a sample distance for quality control
            m1 = model.GetPolyData().GetPoint(0)
            m2 = model.GetPolyData().GetPoint(1)
            #sampleDistance = 3*abs( (m1[0] - m2[0])+(m1[1] - m2[1])+ (m1[2] - m2[2]))
            sampleDistance = fiducialMesh.GetLength() / 10
            print("Sample distance: ", sampleDistance)

            # iterate through each point in the resampled triangle
            for index in range(model.GetPolyData().GetNumberOfPoints()):
                print("Point: ", index)
                modelPoint = model.GetPolyData().GetPoint(index)
                gridPoints.AddFiducialFromArray(modelPoint)
                rayEndPoint = [0, 0, 0]
                for dim in range(len(rayEndPoint)):
                    rayEndPoint[
                        dim] = modelPoint[dim] + rayDirection[dim] * 1000
                intersectionIds = vtk.vtkIdList()
                intersectionPoints = vtk.vtkPoints()
                obbTree.IntersectWithLine(modelPoint, rayEndPoint,
                                          intersectionPoints, intersectionIds)
                #print("Intersections: ", intersectionIds.GetNumberOfIds())
                #if there are intersections, update the point to most external one.
                if intersectionPoints.GetNumberOfPoints() > 0:
                    exteriorPoint = intersectionPoints.GetPoint(
                        intersectionPoints.GetNumberOfPoints() - 1)
                    projectionDistance = abs(
                        (exteriorPoint[0] - modelPoint[0]) +
                        (exteriorPoint[1] - modelPoint[1]) +
                        (exteriorPoint[2] - modelPoint[2]))
                    semilandmarkPoints.AddFiducialFromArray(exteriorPoint)
                #if there are no intersections, reverse the normal vector
                else:
                    for dim in range(len(rayEndPoint)):
                        rayEndPoint[
                            dim] = modelPoint[dim] + rayDirection[dim] * -1000
                    obbTree.IntersectWithLine(modelPoint, rayEndPoint,
                                              intersectionPoints,
                                              intersectionIds)
                    if intersectionPoints.GetNumberOfPoints() > 0:
                        exteriorPoint = intersectionPoints.GetPoint(0)
                        projectionDistance = abs(
                            (exteriorPoint[0] - modelPoint[0]) +
                            (exteriorPoint[1] - modelPoint[1]) +
                            (exteriorPoint[2] - modelPoint[2]))
                        if projectionDistance < sampleDistance:
                            semilandmarkPoints.AddFiducialFromArray(
                                exteriorPoint)
                        else:
                            print("projectionDistance distance: ",
                                  projectionDistance)
                            closestPointId = pointLocator.FindClosestPoint(
                                modelPoint)
                            rayOrigin = surfacePolydata.GetPoint(
                                closestPointId)
                            semilandmarkPoints.AddFiducialFromArray(rayOrigin)

                    #if none in reverse direction, use closest mesh point
                    else:
                        closestPointId = pointLocator.FindClosestPoint(
                            modelPoint)
                        rayOrigin = surfacePolydata.GetPoint(closestPointId)
                        semilandmarkPoints.AddFiducialFromArray(rayOrigin)
            #remove temporary model node
            #slicer.mrmlScene.RemoveNode(model)

        slicer.mrmlScene.RemoveNode(transformNode)
        return True
	def createData(self, currentTimepoint):
		"""
		Create a test dataset within the parameters defined
		"""
		x,y,z = self.parameters["X"], self.parameters["Y"], self.parameters["Z"]
		if self.modified:
			print "Creating the time series data"
			self.createTimeSeries()
			if self.parameters["CreateAll"]:
				n = min(self.parameters["CacheAmount"], self.parameters["Time"])
				for i in range(0, n):
					if i == currentTimepoint: 
						print "Won't create timepoint %d, it'll be last"%i
						continue
					self.createData(i)

		print "\n\nGenerating timepoint %d"%currentTimepoint
		
		if currentTimepoint in self.imageCache:
			print "Returning cached image"
			return self.imageCache[currentTimepoint]

		print "Allocating image"

		if self.parameters["CreateNoise"]:
			print "Creating background noise"
			noiseSource = vtk.vtkImageNoiseSource()
			noiseSource.SetWholeExtent(0,x-1,0,y-1,0,z-1)
			noiseSource.SetMinimum(self.parameters["BackgroundNoiseMin"])
			noiseSource.SetMaximum(self.parameters["BackgroundNoiseMax"])
			castFilter = vtk.vtkImageCast()
			castFilter.SetOutputScalarTypeToUnsignedChar()
			castFilter.SetInputConnection(noiseSource.GetOutputPort())
			information = vtk.vtkImageChangeInformation()
			information.SetInputConnection(castFilter.GetOutputPort())
			information.SetOutputSpacing(self.spacing)
			image = information.GetOutput()
			image.Update()
		else:
			image = vtk.vtkImageData()
			image.SetScalarTypeToUnsignedChar()
			x,y,z = self.parameters["X"], self.parameters["Y"], self.parameters["Z"]
			image.SetDimensions((x,y,z))
			image.AllocateScalars()
			image.SetSpacing(self.spacing)
			
			print "Initializing image"
			for iz in range(0,z):
				for iy in range(0,y):
					for ix in range(0,x):
						image.SetScalarComponentFromDouble(ix,iy,iz,0,0)

		if self.parameters["CreateNoise"]:
			noisePercentage = self.parameters["ShotNoiseAmount"]
			noiseAmount = (noisePercentage/100.0) * (x*y*z)
			print "Creating shot noise"
		else:
			noiseAmount = 0

		shotNoiseMin = self.parameters["ShotNoiseMin"]
		shotNoiseMax = self.parameters["ShotNoiseMax"]
		shotNoiseDistr = self.parameters["ShotNoiseDistribution"]

		while noiseAmount > 0:
			rx,ry,rz = random.randint(0,x-1), random.randint(0,y-1), random.randint(0,z-1)
			shotInt = self.generateDistributionValue(shotNoiseDistr, shotNoiseMin, shotNoiseMax)				
			image.SetScalarComponentFromDouble(rx,ry,rz,0,shotInt)
			noiseAmount -= 1

		#shiftx, shifty, shiftz = self.shifts[currentTimepoint]
		
		print "Creating objects",currentTimepoint
		for oIter, (objN, (rx,ry,rz), size, objInt) in enumerate(self.objects[currentTimepoint]):
			#rx += shiftx
			#ry += shifty
			#rz += shiftz

			(rx,ry,rz), realSize, intList, voxelList = self.createObjectAt(image, rx,ry,rz, size, objInt)
			objMean, objStd, objStdErr = lib.Math.meanstdeverr(intList)
			# Change possible new size and com to object
			self.objects[currentTimepoint][oIter] = (objN, (rx,ry,rz), realSize, (objMean, objStdErr), voxelList)

		if self.parameters["ObjectsCreateSource"]:
			locator = vtk.vtkOBBTree()
			locator.SetDataSet(self.polydata)
			locator.BuildLocator()
			pointLocator = vtk.vtkPointLocator()
			pointLocator.SetDataSet(self.polydata)
			pointLocator.BuildLocator()
			objPolyTP = []
			for objN, (cx, cy, cz), size, meanInt, voxelList in self.objects[currentTimepoint]:
				cxs = cx * self.spacing[0]
				cys = cy * self.spacing[1]
				czs = cz * self.spacing[2]
				locatorInside = locator.InsideOrOutside((cxs,cys,czs))
				if locatorInside == -1:
					inside = 1
				else:
					inside = 0
				
				percVoxelsInside = 0.0
				numIn = 0
				for (vx,vy,vz) in voxelList:
					vxs = vx * self.spacing[0]
					vys = vy * self.spacing[1]
					vzs = vz * self.spacing[2]
					locatorInside = locator.InsideOrOutside((vxs,vys,vzs))
					if locatorInside == -1:
						numIn += 1
				percVoxelsInside = float(numIn) / len(voxelList)

				objid = pointLocator.FindClosestPoint((cxs, cys, czs))
				x2,y2,z2 = self.polydata.GetPoint(objid)
				x2 /= self.spacing[0]
				y2 /= self.spacing[1]
				z2 /= self.spacing[2]

				distToSurf = self.distance((cx,cy,cz), (x2,y2,z2), self.voxelSize)
				distToCom = self.distance((cx,cy,cz), self.cellCOM, self.voxelSize)
				objPolyTP.append((objN, (cx,cy,cz), distToSurf, distToCom, inside, percVoxelsInside))
			self.objPolydata[currentTimepoint] = objPolyTP
		
		n = len(self.imageCache.items())
		if n > self.parameters["CacheAmount"]:
			items = self.imageCache.keys()
			items.sort()
			print "Removing ", items[0], "from cache"
			self.imageCache[items[0]].ReleaseData()
			del self.imageCache[items[0]]
		self.imageCache[currentTimepoint] = image

		self.progressObj.setProgress(currentTimepoint/self.parameters["Time"])
		self.updateProgress(None, "ProgressEvent")

		return image
Example #30
0
def prepare_slices(imgdata, visualize, padding=1):
    dims = imgdata.GetDimensions()
    print("Original dimensions: %s" % str(dims))

    max_z = 2000
    omega = 1

    if dims[2] > max_z:
        omega = general.trunc(max_z / dims[2], 1)
        imgdata = vtk_functions.resize_imgdata(imgdata, omega)
        imgdata.SetSpacing(1, 1, 1)
        print("Resampled imagedata dimensions (%s): %s" %
              (omega, str(imgdata.GetDimensions())))

    # Create contour (as input for OBBtree)
    sran = imgdata.GetScalarRange()
    polydata = vtk.vtkContourFilter()
    polydata.SetInputData(imgdata)
    polydata.SetValue(0, sran[0] + (sran[1] - sran[0]) / 2.0)
    polydata.Update()
    print("Created contour of imagedata...")

    # Generate OBB
    obb = vtk.vtkOBBTree()
    obb.SetDataSet(polydata.GetOutput())
    obb.SetMaxLevel(1)
    obb.BuildLocator()

    obb_corner = [0.0, 0.0, 0.0]
    obb_max = [0.0, 0.0, 0.0]
    obb_mid = [0.0, 0.0, 0.0]
    obb_min = [0.0, 0.0, 0.0]
    obb_size = [0.0, 0.0, 0.0]

    obb.ComputeOBB(polydata.GetOutput(), obb_corner, obb_max, obb_mid,
                   obb_min, obb_size)

    print("Derived OBB from imagedata's contour...")

    # Create transformation matrix t through axes of OBB
    obb_corner = np.array(obb_corner).reshape((3, 1))
    obb_max = (np.array(obb_max)).reshape((3, 1))
    obb_mid = (np.array(obb_mid)).reshape((3, 1))
    obb_min = (np.array(obb_min)).reshape((3, 1))

    uvw_i = get_transformation_matrix(obb_mid, obb_min, obb_max)

    t = vtk.vtkMatrix4x4()
    t.DeepCopy((uvw_i[0][0], uvw_i[0][1], uvw_i[0][2], 0,
                uvw_i[1][0], uvw_i[1][1], uvw_i[1][2], 0,
                uvw_i[2][0], uvw_i[2][1], uvw_i[2][2], 0,
                0,          0,          0,          1))

    transform = vtk.vtkTransform()
    transform.SetMatrix(t)
    transform.Inverse()  # inverse t --> inverse resampling
    transform.Update()

    imgdata = vtk_functions.reslice_imgdata(imgdata, transform)
    imgdata.SetSpacing(1, 1, 1)

    print("Transformed imagedata by t...")

    # Get bounds of rotated OBB to crop image stack
    corner = uvw_i.dot(obb_corner)
    ax1 = uvw_i.dot(obb_max + obb_corner)
    ax2 = uvw_i.dot(obb_mid + obb_corner)
    ax3 = uvw_i.dot(obb_min + obb_corner)

    x_range = corner[0][0], np.max(np.array([ax1[0], ax2[0], ax3[0]]))
    y_range = corner[1][0], np.max(np.array([ax1[1], ax2[1], ax3[1]]))
    z_range = corner[2][0], np.max(np.array([ax1[2], ax2[2], ax3[2]]))

    new_bounds = x_range + y_range + z_range

    bte = bounds_to_extent(new_bounds, imgdata.GetOrigin(),
                           imgdata.GetSpacing())
    imgdata = vtk_functions.extract_voi(imgdata, bte[0], bte[1], bte[2],
                                        bte[3], bte[4], bte[5], padding)
    print("Cropped imagedata...")

    # Visualization component
    if visualize:
        r_sran = imgdata.GetScalarRange()
        rotated_polydata = vtk.vtkContourFilter()
        rotated_polydata.SetInputData(imgdata)
        rotated_polydata.SetValue(0, (r_sran[1] - r_sran[0])/2.0)
        rotated_polydata.Update()

        transform = vtk.vtkTransform()
        transform.RotateZ(180)
        transform.Update()

        tf = vtk.vtkTransformFilter()
        tf.SetTransform(transform)
        tf.SetInputConnection(rotated_polydata.GetOutputPort())
        tf.Update()

        rotated_polydata = tf

        print("\t(Visualize) Created rotated contour...")

        r_obb = vtk.vtkOBBTree()
        r_obb.SetDataSet(rotated_polydata.GetOutput())
        r_obb.SetMaxLevel(5)
        r_obb.BuildLocator()

        r_obb_corner = [0.0, 0.0, 0.0]
        r_obb_max = [0.0, 0.0, 0.0]
        r_obb_mid = [0.0, 0.0, 0.0]
        r_obb_min = [0.0, 0.0, 0.0]
        r_obb_size = [0.0, 0.0, 0.0]

        r_obb.ComputeOBB(rotated_polydata.GetOutput(), r_obb_corner, r_obb_max,
                         r_obb_mid, r_obb_min, r_obb_size)

        print("\t(Visualize) Derived OBB for rotated imagedata...")

        # MAPPERS + ACTORS
        polydata_mapper = vtk.vtkPolyDataMapper()
        polydata_mapper.SetInputConnection(polydata.GetOutputPort())
        polydata_mapper.SetScalarVisibility(False)
        polydata_actor = vtk.vtkActor()
        polydata_actor.GetProperty().SetColor(1, 1, 1,)
        polydata_actor.SetMapper(polydata_mapper)

        r_polydata_mapper = vtk.vtkPolyDataMapper()
        r_polydata_mapper.SetInputConnection(rotated_polydata.GetOutputPort())
        r_polydata_mapper.SetScalarVisibility(False)
        r_polydata_actor = vtk.vtkActor()
        r_polydata_actor.GetProperty().SetColor(1, 1, 1)
        r_polydata_actor.SetMapper(r_polydata_mapper)

        obb_poly = vtk.vtkPolyData()
        obb.GenerateRepresentation(0, obb_poly)
        obb_mapper = vtk.vtkPolyDataMapper()
        obb_mapper.SetInputData(obb_poly)
        obb_actor = vtk.vtkActor()
        obb_actor.SetMapper(obb_mapper)
        obb_actor.GetProperty().SetColor(1, 1, 1)
        obb_actor.GetProperty().LightingOff()

        obb_actor.GetProperty().SetRepresentationToWireframe()

        r_obb_poly = vtk.vtkPolyData()
        r_obb.GenerateRepresentation(0, r_obb_poly)
        r_obb_mapper = vtk.vtkPolyDataMapper()
        r_obb_mapper.SetInputData(r_obb_poly)
        r_obb_actor = vtk.vtkActor()
        r_obb_actor.SetMapper(r_obb_mapper)
        r_obb_actor.GetProperty().SetColor(1, 1, 1)
        r_obb_actor.GetProperty().LightingOff()
        r_obb_actor.GetProperty().SetRepresentationToWireframe()

        renderer = vtk.vtkRenderer()
        renderer.SetBackground(82/255, 87/255, 110/255)  # same bg color as Paraview
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.AddRenderer(renderer)
        renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        renderWindowInteractor.SetRenderWindow(renderWindow)

        # Visualize coordinate system
        axes = vtk.vtkAxesActor()
        axes.GetXAxisShaftProperty().SetColor(1,1,1)
        widget = vtk.vtkOrientationMarkerWidget()
        widget.SetOutlineColor(0.9300, 0.5700, 0.1300)
        widget.SetOrientationMarker(axes)
        widget.SetInteractor(renderWindowInteractor)
        widget.SetViewport(0.0, 0.0, 0.4, 0.4)
        widget.SetEnabled(1)
        widget.InteractiveOn()

        # renderer.AddActor(polydata_actor)
        # renderer.AddActor(obb_actor)
        renderer.AddActor(r_polydata_actor)
        renderer.AddActor(r_obb_actor)

        renderer.ResetCamera()
        renderWindow.SetSize(600, 600)
        renderWindow.Render()
        renderWindowInteractor.Start()

    np_data = vtk_functions.imgdata_to_arr(imgdata)

    return np_data, omega
Example #31
0
    def run(self, meshNode, LMNode, gridLandmarks, sampleRate):
        surfacePolydata = meshNode.GetPolyData()

        gridPoints = vtk.vtkPoints()

        gridPoints.InsertNextPoint(0, 0, 0)
        gridPoints.InsertNextPoint(0, sampleRate - 1, 0)
        gridPoints.InsertNextPoint(sampleRate - 1, 0, 0)
        for row in range(1, sampleRate - 1):
            for col in range(1, sampleRate - 1):
                if (row + col) < (sampleRate - 1):
                    gridPoints.InsertNextPoint(row, col, 0)

        gridPolydata = vtk.vtkPolyData()
        gridPolydata.SetPoints(gridPoints)

        sourcePoints = vtk.vtkPoints()
        targetPoints = vtk.vtkPoints()

        #sourcePoints.InsertNextPoint(gridPoints.GetPoint(0))
        #sourcePoints.InsertNextPoint(gridPoints.GetPoint(sampleRate-1))
        #sourcePoints.InsertNextPoint(gridPoints.GetPoint(gridPoints.GetNumberOfPoints()-1))
        sourcePoints.InsertNextPoint(gridPoints.GetPoint(0))
        sourcePoints.InsertNextPoint(gridPoints.GetPoint(1))
        sourcePoints.InsertNextPoint(gridPoints.GetPoint(2))

        point = [0, 0, 0]
        for gridVertex in gridLandmarks:
            LMNode.GetMarkupPoint(int(gridVertex - 1), 0, point)
            targetPoints.InsertNextPoint(point)

        #transform grid to triangle
        transform = vtk.vtkThinPlateSplineTransform()
        transform.SetSourceLandmarks(sourcePoints)
        transform.SetTargetLandmarks(targetPoints)
        transform.SetBasisToR()

        transformNode = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLTransformNode", "TPS")
        transformNode.SetAndObserveTransformToParent(transform)

        model = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLModelNode",
                                                   "mesh_resampled")
        model.SetAndObservePolyData(gridPolydata)
        model.SetAndObserveTransformNodeID(transformNode.GetID())
        slicer.vtkSlicerTransformLogic().hardenTransform(model)

        resampledPolydata = model.GetPolyData()

        pointLocator = vtk.vtkPointLocator()
        pointLocator.SetDataSet(surfacePolydata)
        pointLocator.BuildLocator()

        #get surface normal from each landmark point
        rayDirection = [0, 0, 0]
        normalArray = surfacePolydata.GetPointData().GetArray("Normals")
        if (not normalArray):
            normalFilter = vtk.vtkPolyDataNormals()
            normalFilter.ComputePointNormalsOn()
            normalFilter.SetInputData(surfacePolydata)
            normalFilter.Update()
            normalArray = normalFilter.GetOutput().GetPointData().GetArray(
                "Normals")
            if (not normalArray):
                print("Error: no normal array")

        for gridVertex in gridLandmarks:
            LMNode.GetMarkupPoint(int(gridVertex - 1), 0, point)
            closestPointId = pointLocator.FindClosestPoint(point)
            tempNormal = normalArray.GetTuple(closestPointId)
            rayDirection[0] += tempNormal[0]
            rayDirection[1] += tempNormal[1]
            rayDirection[2] += tempNormal[2]

        #calculate average
        for dim in range(len(rayDirection)):
            rayDirection[dim] = rayDirection[dim] / 4

        #set up locater for intersection with normal vector rays
        obbTree = vtk.vtkOBBTree()
        obbTree.SetDataSet(surfacePolydata)
        obbTree.BuildLocator()

        #define new landmark sets
        semilandmarkNodeName = "semiLM_" + str(gridLandmarks[0]) + "_" + str(
            gridLandmarks[1]) + "_" + str(gridLandmarks[2])
        semilandmarkPoints = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLMarkupsFiducialNode", semilandmarkNodeName)

        #get a sample distance for quality control
        m1 = model.GetPolyData().GetPoint(0)
        m2 = model.GetPolyData().GetPoint(1)
        m3 = model.GetPolyData().GetPoint(1)
        d1 = math.sqrt(vtk.vtkMath().Distance2BetweenPoints(m1, m2))
        d2 = math.sqrt(vtk.vtkMath().Distance2BetweenPoints(m2, m3))
        d3 = math.sqrt(vtk.vtkMath().Distance2BetweenPoints(m1, m3))
        sampleDistance = (d1 + d2 + d3)

        # set initial three grid points
        for index in range(0, 3):
            origLMPoint = resampledPolydata.GetPoint(index)
            #landmarkLabel = LMNode.GetNthFiducialLabel(gridLandmarks[index]-1)
            landmarkLabel = str(gridLandmarks[index])
            semilandmarkPoints.AddFiducialFromArray(origLMPoint, landmarkLabel)

        # calculate maximum projection distance
        projectionTolerance = 2
        boundingBox = vtk.vtkBoundingBox()
        boundingBox.AddBounds(surfacePolydata.GetBounds())
        diagonalDistance = boundingBox.GetDiagonalLength()
        #rayLength = math.sqrt(diagonalDistance) * projectionTolerance
        rayLength = sampleDistance

        # get normal projection intersections for remaining semi-landmarks
        print("Target number of points: ",
              resampledPolydata.GetNumberOfPoints())
        for index in range(3, resampledPolydata.GetNumberOfPoints()):
            modelPoint = resampledPolydata.GetPoint(index)
            rayEndPoint = [0, 0, 0]
            for dim in range(len(rayEndPoint)):
                rayEndPoint[
                    dim] = modelPoint[dim] + rayDirection[dim] * rayLength
            intersectionIds = vtk.vtkIdList()
            intersectionPoints = vtk.vtkPoints()
            obbTree.IntersectWithLine(modelPoint, rayEndPoint,
                                      intersectionPoints, intersectionIds)
            #if there are intersections, update the point to most external one.
            if intersectionPoints.GetNumberOfPoints() > 0:
                exteriorPoint = intersectionPoints.GetPoint(
                    intersectionPoints.GetNumberOfPoints() - 1)
                #projectionDistance=math.sqrt(vtk.vtkMath().Distance2BetweenPoints(exteriorPoint, modelPoint))
                semilandmarkPoints.AddFiducialFromArray(exteriorPoint)
            #if there are no intersections, reverse the normal vector
            else:
                for dim in range(len(rayEndPoint)):
                    rayEndPoint[
                        dim] = modelPoint[dim] + rayDirection[dim] * -rayLength
                obbTree.IntersectWithLine(modelPoint, rayEndPoint,
                                          intersectionPoints, intersectionIds)
                if intersectionPoints.GetNumberOfPoints() > 0:
                    exteriorPoint = intersectionPoints.GetPoint(0)
                    semilandmarkPoints.AddFiducialFromArray(exteriorPoint)
                    #projectionDistance=math.sqrt(vtk.vtkMath().Distance2BetweenPoints(exteriorPoint, modelPoint))
                    #if projectionDistance < sampleDistance:
                    #  semilandmarkPoints.AddFiducialFromArray(exteriorPoint)
                    #else:
                    #  closestPointId = pointLocator.FindClosestPoint(modelPoint)
                    #  rayOrigin = surfacePolydata.GetPoint(closestPointId)
                    #  semilandmarkPoints.AddFiducialFromArray(rayOrigin)

                #if none in reverse direction, use closest mesh point
                else:
                    closestPointId = pointLocator.FindClosestPoint(modelPoint)
                    rayOrigin = surfacePolydata.GetPoint(closestPointId)
                    semilandmarkPoints.AddFiducialFromArray(rayOrigin)

        # update lock status and color
        semilandmarkPoints.SetLocked(True)
        semilandmarkPoints.GetDisplayNode().SetColor(random.random(),
                                                     random.random(),
                                                     random.random())
        semilandmarkPoints.GetDisplayNode().SetSelectedColor(
            random.random(), random.random(), random.random())
        semilandmarkPoints.GetDisplayNode().PointLabelsVisibilityOff()
        #clean up
        slicer.mrmlScene.RemoveNode(transformNode)
        slicer.mrmlScene.RemoveNode(model)
        print("Total points:", semilandmarkPoints.GetNumberOfFiducials())
        return semilandmarkPoints
Example #32
0
    def renderthis(self,warunek):
            # open a window and create a renderer           
            self.widget.GetRenderWindow().AddRenderer(self.ren)
   
           # open file            
            openFileDialog = wx.FileDialog(self, "Open STL file", "", self.filename,
                                       "*.stl", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
             
            if openFileDialog.ShowModal() == wx.ID_CANCEL:
                return
            self.filename = openFileDialog.GetPath()
            
            
            # render the data
            reader = vtk.vtkSTLReader()
            reader.SetFileName(self.filename)
            
            reader.Update()
            mesh = reader.GetOutput()         
            
            # To take the polygonal data from the vtkConeSource and
            # create a rendering for the renderer.
            coneMapper = vtk.vtkPolyDataMapper()
            coneMapper.SetInput(reader.GetOutput())
 
            # create an actor for our scene
            if self.isploted:
                coneActor=self.ren.GetActors().GetLastActor()
                self.ren.RemoveActor(coneActor)
                 
            coneActor = vtk.vtkActor()
            coneActor.SetMapper(coneMapper)
            # Add actor
            self.ren.AddActor(coneActor)
           # print self.ren.GetActors().GetNumberOfItems()
           
            #addPoint(self.ren, pSource, color=[1.0,0.0,0.0]) 
            #addPoint(self.ren, pTarget, color=[1.0,0.0,1.0]) 
            
            addLine(self.ren, pp1, pp2)
            addLine(self.ren, pp3, pp4)
            addLine(self.ren, pp5, pp6)
            addLine(self.ren, pp7, pp8)
            
            addLine(self.ren, pp1, pp7)
            addLine(self.ren, pp3, pp5)
            addLine(self.ren, pp4, pp6)
            addLine(self.ren, pp2, pp8)
            
            addLine(self.ren, pp1, pp3)
            addLine(self.ren, pp7, pp5)
            addLine(self.ren, pp4, pp2)
            addLine(self.ren, pp6, pp8)            
            
            if warunek==1:
                addEdges(self.ren)            
            
            
            
            #####################################################################################
            featureEdge=vtk.vtkFeatureEdges()
            featureEdge.FeatureEdgesOff()
            featureEdge.BoundaryEdgesOn()
            featureEdge.NonManifoldEdgesOn()
            featureEdge.SetInput(mesh)
            featureEdge.Update()
            openEdges = featureEdge.GetOutput().GetNumberOfCells()

            if openEdges != 0:
                print "the stl file is not closed"
            
            select = vtk.vtkSelectEnclosedPoints()
            select.SetSurface(mesh)
            
            inside_polydat = vtk.vtkPolyData()
            forcing_polydat = vtk.vtkPolyData()
            interpolation_polydat = vtk.vtkPolyData()
            inside_points = vtk.vtkPoints()
            forcing_points = vtk.vtkPoints()
            interpolation_points = vtk.vtkPoints()
           # for i in range(11):
                #IsInside(i-5,0.1,0.1,mesh)
            global licz 
            global licz2
            global licznik
            
            for j in range(1,lwY+1):
                for i in range(1,lwX+1):
                    licz += 1
                    print (licz/float(stoProcent))*100.0
                    for k in range(1,lwZ+1):
                        sprawdzenie = 0
                        siatkaX[1]=xmin+0.001
                        siatkaX[lwX]=xmax-0.001
                        siatkaY[1]=ymin+0.001
                        siatkaY[lwY]=ymax-0.001
                        siatkaZ[1]=zmin+0.001
                        siatkaZ[lwZ]=zmax-0.001
                        sprawdzenie = IsInsideCheck(siatkaX[i],siatkaY[j],siatkaZ[k],mesh)
                        siatkaX[1]=xmin
                        siatkaX[lwX]=xmax
                        siatkaY[1]=ymin
                        siatkaY[lwY]=ymax
                        siatkaZ[1]=zmin
                        siatkaZ[lwZ]=zmax
                        mesh_point_inside = [siatkaX[i],siatkaY[j],siatkaZ[k]]
                        #mesh_point_forcing = [siatkaX[i]+1.0,siatkaY[j],siatkaZ[k]]
                        
                        maska[licznik] = sprawdzenie
                        licznik=licznik+1
                        if sprawdzenie == 1:
                            inside_points.InsertNextPoint(mesh_point_inside)
                            #forcing_points.InsertNextPoint(mesh_point_forcing)
                            
            licznik=0   
            
            licznik_forcing=0
    
            for j in range(0,lwY):
                for i in range(0,lwX):
                    for k in range(0,lwZ):
                        #print j,i,k
                        maska3D[j][i][k]=maska[licznik]
                        licznik=licznik+1
            
            #print maska3D
            find_forcing_points(lwY,lwX,lwZ,maska3D,forcing_points,siatkaX,siatkaY,siatkaZ,boundary_points,mesh,intersection,maska3D_forcing,interpolation_points,fnix,fniy,fniz,fncx,fncy,fncz)
            
            for j in range(0,lwY):
                for i in range(0,lwX):
                    for k in range(0,lwZ):
                        if maska3D_forcing[j][i][k] > 0:
                            licznik_forcing = licznik_forcing+maska3D_forcing[j][i][k]
                            
            for i in range(0,licznik_forcing):
                print i,fnix[i],fniy[i],fniz[i],fncx[i],fncy[i],fncz[i]
                       
            
            
            odczyt_STL(self.filename,normals,licznik_forcing,fnix,fniy,fniz,fncx,fncy,fncz)
            zp = [0,0,0]
            
            for i in range(0,licznik_forcing):
                if fncx[i]>0 and normals[i][0]<0:
                    normals[i][0]=normals[i][0]*(-1.0)
                if fncx[i]<0 and normals[i][0]>0:
                    normals[i][0]=normals[i][0]*(-1.0)
                if fncy[i]>0 and normals[i][1]<0:
                    normals[i][1]=normals[i][1]*(-1.0)
                if fncy[i]<0 and normals[i][1]>0:
                    normals[i][1]=normals[i][1]*(-1.0)
                if fncz[i]>0 and normals[i][2]<0:
                    normals[i][2]=normals[i][2]*(-1.0)
                if fncz[i]<0 and normals[i][2]>0:
                    normals[i][2]=normals[i][2]*(-1.0)
            
            for i in range(0,licznik_forcing):
                zp1 = [fncx[i],fncy[i],fncz[i]]
                zp2 = [normals[i][0]+fncx[i],normals[i][1]+fncy[i],normals[i][2]+fncz[i]]
                #normals[i][0]=normals[i][0]+fncx[i]
                #normals[i][1]=normals[i][1]+fncy[i]
                #normals[i][2]=normals[i][2]+fncz[i]
                
                addLine(self.ren, zp1, zp2)
                print i,normals[i],zp1,zp2
            
            #print intersection 
            #print "+++++++++++++++++++="
            #print maska3D_forcing
            """
            licznik=0
            for j in range(0,lwY):
                for i in range(0,lwX-1):
                    for k in range(0,lwZ):
                        mesh_point_forcing = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                        if (maska3D[j][i][k] == 0) and (maska3D[j][i+1][k] == 1):
                            forcing_points.InsertNextPoint(mesh_point_forcing)
                        licznik=licznik+1
              """          
                        
            zapis = open('Maska.txt', 'w')
            for i in range(0,lwX*lwY*lwZ):
                zapis.write(str(maska[i]))
                zapis.write('\n')
            zapis.close()		
            print "zapisano Maske"
            inside_polydat.SetPoints(inside_points)
            
            inside = vtk.vtkSphereSource()
            inside.SetRadius(0.02)
            inside.SetPhiResolution(8)
            inside.SetThetaResolution(8)
    
            ballGlyph = vtkGlyph3D()
            ballGlyph.SetColorModeToColorByScalar()
            ballGlyph.SetSourceConnection(inside.GetOutputPort())
            ballGlyph.SetInput(inside_polydat)
      
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(ballGlyph.GetOutputPort())
    
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            actor.GetProperty().SetColor([1.0,0.0,0.0])
    
            self.ren.AddActor(actor)
            ######################################################################################
            forcing_polydat.SetPoints(forcing_points)
            
            forcing = vtk.vtkSphereSource()
            #point.SetCenter(pS)
            forcing.SetRadius(0.02)
            forcing.SetPhiResolution(8)
            forcing.SetThetaResolution(8)
    
            forcingGlyph = vtkGlyph3D()
            forcingGlyph.SetColorModeToColorByScalar()
            forcingGlyph.SetSourceConnection(forcing.GetOutputPort())
            forcingGlyph.SetInput(forcing_polydat)
      
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(forcingGlyph.GetOutputPort())
    
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            actor.GetProperty().SetColor([0.0,1.0,0.0])
    
            self.ren.AddActor(actor)
            #####################################################################################
            """
            interpolation_polydat.SetPoints(interpolation_points)
            
            interpolation = vtk.vtkSphereSource()
            #point.SetCenter(pS)
            interpolation.SetRadius(0.02)
            interpolation.SetPhiResolution(8)
            interpolation.SetThetaResolution(8)
    
            interpolationGlyph = vtkGlyph3D()
            interpolationGlyph.SetColorModeToColorByScalar()
            interpolationGlyph.SetSourceConnection(interpolation.GetOutputPort())
            interpolationGlyph.SetInput(interpolation_polydat)
      
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(interpolationGlyph.GetOutputPort())
    
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            actor.GetProperty().SetColor([0.0,0.0,1.0])
    
            self.ren.AddActor(actor)
            """
            #####################################################################################
            obbTree = vtk.vtkOBBTree()
            obbTree.SetDataSet(mesh)
            obbTree.BuildLocator()
            
            pointsVTKintersection = vtk.vtkPoints()
            obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
            pointsVTKIntersectionData = pointsVTKintersection.GetData()
            noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
            pointsIntersection = []
            for idx in range(noPointsVTKIntersection):
                _tup = pointsVTKIntersectionData.GetTuple3(idx)
                pointsIntersection.append(_tup)
                
            print pointsIntersection
 
            if not self.isploted:
                axes = vtk.vtkAxesActor()
                self.marker = vtk.vtkOrientationMarkerWidget()
                self.marker.SetInteractor( self.widget._Iren )
                self.marker.SetOrientationMarker( axes )
                self.marker.SetViewport(0.75,0,1,0.25)
                self.marker.SetEnabled(1)
 
            self.ren.ResetCamera()
            self.ren.ResetCameraClippingRange()
            #cam = self.ren.GetActiveCamera()
            self.cam.Elevation(50)
            self.cam.Azimuth(40)
            #cam.SetPosition(0,0,1)
            #cam.SetFocalPoint(0,0,-50)
            self.isploted = True
            self.ren.Render()
Example #33
0
    def applyPatch(self,
                   meshNode,
                   LMNode,
                   gridLandmarks,
                   sampleRate,
                   polydataNormalArray,
                   maximumProjectionDistance=.25):
        surfacePolydata = meshNode.GetPolyData()

        gridPoints = vtk.vtkPoints()

        gridPoints.InsertNextPoint(0, 0, 0)
        gridPoints.InsertNextPoint(0, sampleRate - 1, 0)
        gridPoints.InsertNextPoint(sampleRate - 1, 0, 0)
        for row in range(1, sampleRate - 1):
            for col in range(1, sampleRate - 1):
                if (row + col) < (sampleRate - 1):
                    gridPoints.InsertNextPoint(row, col, 0)

        gridPolydata = vtk.vtkPolyData()
        gridPolydata.SetPoints(gridPoints)

        sourcePoints = vtk.vtkPoints()
        targetPoints = vtk.vtkPoints()

        sourcePoints.InsertNextPoint(gridPoints.GetPoint(0))
        sourcePoints.InsertNextPoint(gridPoints.GetPoint(1))
        sourcePoints.InsertNextPoint(gridPoints.GetPoint(2))

        point = [0, 0, 0]
        for gridVertex in gridLandmarks:
            LMNode.GetMarkupPoint(0, int(gridVertex - 1), point)
            targetPoints.InsertNextPoint(point)

        #transform grid to triangle
        transform = vtk.vtkThinPlateSplineTransform()
        transform.SetSourceLandmarks(sourcePoints)
        transform.SetTargetLandmarks(targetPoints)
        transform.SetBasisToR()

        transformNode = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLTransformNode", "TPS")
        transformNode.SetAndObserveTransformToParent(transform)

        model = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLModelNode",
                                                   "mesh_resampled")
        model.SetAndObservePolyData(gridPolydata)
        model.SetAndObserveTransformNodeID(transformNode.GetID())
        slicer.vtkSlicerTransformLogic().hardenTransform(model)

        resampledPolydata = model.GetPolyData()

        pointLocator = vtk.vtkPointLocator()
        pointLocator.SetDataSet(surfacePolydata)
        pointLocator.BuildLocator()

        #get surface normal from each landmark point
        rayDirection = [0, 0, 0]

        for gridVertex in gridLandmarks:
            LMNode.GetMarkupPoint(0, int(gridVertex - 1), point)
            closestPointId = pointLocator.FindClosestPoint(point)
            tempNormal = polydataNormalArray.GetTuple(closestPointId)
            rayDirection[0] += tempNormal[0]
            rayDirection[1] += tempNormal[1]
            rayDirection[2] += tempNormal[2]

        #normalize
        vtk.vtkMath().Normalize(rayDirection)

        # # get normal at each grid point
        # gridNormals = np.zeros((3,3))
        # gridIndex=0
        # for gridVertex in gridLandmarks:
        # print(gridVertex)
        # LMNode.GetMarkupPoint(0,int(gridVertex-1),point)
        # closestPointId = pointLocator.FindClosestPoint(point)
        # tempNormal = polydataNormalArray.GetTuple(closestPointId)
        # print(tempNormal)
        # gridNormals[gridIndex] = tempNormal
        # gridIndex+=1
        # print(gridNormals)

        #set up locater for intersection with normal vector rays
        obbTree = vtk.vtkOBBTree()
        obbTree.SetDataSet(surfacePolydata)
        obbTree.BuildLocator()

        #define new landmark sets
        semilandmarkNodeName = "semiLM_" + str(gridLandmarks[0]) + "_" + str(
            gridLandmarks[1]) + "_" + str(gridLandmarks[2])
        semilandmarkPoints = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLMarkupsFiducialNode", semilandmarkNodeName)

        #get a sample distance for quality control
        m1 = model.GetPolyData().GetPoint(0)
        m2 = model.GetPolyData().GetPoint(1)
        m3 = model.GetPolyData().GetPoint(2)
        d1 = math.sqrt(vtk.vtkMath().Distance2BetweenPoints(m1, m2))
        d2 = math.sqrt(vtk.vtkMath().Distance2BetweenPoints(m2, m3))
        d3 = math.sqrt(vtk.vtkMath().Distance2BetweenPoints(m1, m3))
        sampleDistance = (d1 + d2 + d3)

        # set initial three grid points
        for index in range(0, 3):
            origLMPoint = resampledPolydata.GetPoint(index)
            #landmarkLabel = LMNode.GetNthFiducialLabel(gridLandmarks[index]-1)
            landmarkLabel = str(gridLandmarks[index])
            semilandmarkPoints.AddFiducialFromArray(origLMPoint, landmarkLabel)

        # calculate maximum projection distance
        projectionTolerance = maximumProjectionDistance / .25
        #boundingBox = vtk.vtkBoundingBox()
        #boundingBox.AddBounds(surfacePolydata.GetBounds())
        #diagonalDistance = boundingBox.GetDiagonalLength()
        #rayLength = math.sqrt(diagonalDistance) * projectionTolerance
        rayLength = sampleDistance * projectionTolerance

        # get normal projection intersections for remaining semi-landmarks
        for index in range(3, resampledPolydata.GetNumberOfPoints()):
            modelPoint = resampledPolydata.GetPoint(index)

            # ## get estimated normal vector
            # rayDirection = [0,0,0]
            # distance1=math.sqrt(vtk.vtkMath().Distance2BetweenPoints(modelPoint,resampledPolydata.GetPoint(0)))
            # distance2=math.sqrt(vtk.vtkMath().Distance2BetweenPoints(modelPoint,resampledPolydata.GetPoint(1)))
            # distance3=math.sqrt(vtk.vtkMath().Distance2BetweenPoints(modelPoint,resampledPolydata.GetPoint(2)))
            # distanceTotal = distance1 + distance2 + distance3
            # weights=[(distance3+distance2)/distanceTotal, (distance1+distance3)/distanceTotal,(distance1+distance2)/distanceTotal]

            # for gridIndex in range(0,3):
            # rayDirection+=(weights[gridIndex]*gridNormals[gridIndex])
            # vtk.vtkMath().Normalize(rayDirection)
            # ##

            rayEndPoint = [0, 0, 0]
            for dim in range(len(rayEndPoint)):
                rayEndPoint[
                    dim] = modelPoint[dim] + rayDirection[dim] * rayLength
            intersectionIds = vtk.vtkIdList()
            intersectionPoints = vtk.vtkPoints()
            obbTree.IntersectWithLine(modelPoint, rayEndPoint,
                                      intersectionPoints, intersectionIds)
            #if there are intersections, update the point to most external one.
            if intersectionPoints.GetNumberOfPoints() > 0:
                exteriorPoint = intersectionPoints.GetPoint(
                    intersectionPoints.GetNumberOfPoints() - 1)
                semilandmarkPoints.AddFiducialFromArray(exteriorPoint)
            #if there are no intersections, reverse the normal vector
            else:
                for dim in range(len(rayEndPoint)):
                    rayEndPoint[
                        dim] = modelPoint[dim] + rayDirection[dim] * -rayLength
                obbTree.IntersectWithLine(modelPoint, rayEndPoint,
                                          intersectionPoints, intersectionIds)
                if intersectionPoints.GetNumberOfPoints() > 0:
                    exteriorPoint = intersectionPoints.GetPoint(0)
                    semilandmarkPoints.AddFiducialFromArray(exteriorPoint)
                else:
                    print("No intersection, using closest point")
                    closestPointId = pointLocator.FindClosestPoint(modelPoint)
                    rayOrigin = surfacePolydata.GetPoint(closestPointId)
                    semilandmarkPoints.AddFiducialFromArray(rayOrigin)

        # update lock status and color
        semilandmarkPoints.SetLocked(True)
        semilandmarkPoints.GetDisplayNode().SetColor(random.random(),
                                                     random.random(),
                                                     random.random())
        semilandmarkPoints.GetDisplayNode().SetSelectedColor(
            random.random(), random.random(), random.random())
        semilandmarkPoints.GetDisplayNode().PointLabelsVisibilityOff()
        #clean up
        slicer.mrmlScene.RemoveNode(transformNode)
        slicer.mrmlScene.RemoveNode(model)
        print("Total points:", semilandmarkPoints.GetNumberOfFiducials())
        return semilandmarkPoints
Example #34
0
    def projectPointsPolydata(self, sourcePolydata, targetPolydata,
                              originalPoints, rayLength):
        #set up polydata for projected points to return
        projectedPointData = vtk.vtkPolyData()
        projectedPoints = vtk.vtkPoints()
        projectedPointData.SetPoints(projectedPoints)

        #set up locater for intersection with normal vector rays
        obbTree = vtk.vtkOBBTree()
        obbTree.SetDataSet(targetPolydata)
        obbTree.BuildLocator()

        #set up point locator for finding surface normals and closest point
        pointLocator = vtk.vtkPointLocator()
        pointLocator.SetDataSet(sourcePolydata)
        pointLocator.BuildLocator()

        targetPointLocator = vtk.vtkPointLocator()
        targetPointLocator.SetDataSet(targetPolydata)
        targetPointLocator.BuildLocator()

        #get surface normal from each landmark point
        rayDirection = [0, 0, 0]
        normalArray = sourcePolydata.GetPointData().GetArray("Normals")
        if (not normalArray):
            print("no normal array, calculating....")
            normalFilter = vtk.vtkPolyDataNormals()
            normalFilter.ComputePointNormalsOn()
            normalFilter.SetInputData(sourcePolydata)
            normalFilter.Update()
            normalArray = normalFilter.GetOutput().GetPointData().GetArray(
                "Normals")
            if (not normalArray):
                print("Error: no normal array")
                return projectedPointData
        print('Original points:', originalPoints.GetNumberOfPoints())
        for index in range(originalPoints.GetNumberOfPoints()):
            originalPoint = originalPoints.GetPoint(index)
            # get ray direction from closest normal
            closestPointId = pointLocator.FindClosestPoint(originalPoint)
            rayDirection = normalArray.GetTuple(closestPointId)
            rayEndPoint = [0, 0, 0]
            for dim in range(len(rayEndPoint)):
                rayEndPoint[
                    dim] = originalPoint[dim] + rayDirection[dim] * rayLength
            intersectionIds = vtk.vtkIdList()
            intersectionPoints = vtk.vtkPoints()
            obbTree.IntersectWithLine(originalPoint, rayEndPoint,
                                      intersectionPoints, intersectionIds)
            #if there are intersections, update the point to most external one.
            if intersectionPoints.GetNumberOfPoints() > 0:
                exteriorPoint = intersectionPoints.GetPoint(
                    intersectionPoints.GetNumberOfPoints() - 1)
                projectedPoints.InsertNextPoint(exteriorPoint)
            #if there are no intersections, reverse the normal vector
            else:
                for dim in range(len(rayEndPoint)):
                    rayEndPoint[dim] = originalPoint[
                        dim] + rayDirection[dim] * -rayLength
                obbTree.IntersectWithLine(originalPoint, rayEndPoint,
                                          intersectionPoints, intersectionIds)
                if intersectionPoints.GetNumberOfPoints() > 0:
                    exteriorPoint = intersectionPoints.GetPoint(0)
                    projectedPoints.InsertNextPoint(exteriorPoint)
                #if none in reverse direction, use closest mesh point
                else:
                    closestPointId = targetPointLocator.FindClosestPoint(
                        originalPoint)
                    rayOrigin = targetPolydata.GetPoint(closestPointId)
                    projectedPoints.InsertNextPoint(rayOrigin)
        print('Projected points:', originalPoints.GetNumberOfPoints())
        return projectedPointData
Example #35
0
foo.RotateY(10)
foo.RotateZ(27)
foo.Scale(1, .7, .3)

transPD = vtk.vtkTransformPolyDataFilter()
transPD.SetInputConnection(cylinder.GetOutputPort())
transPD.SetTransform(foo)

dataMapper = vtk.vtkPolyDataMapper()
dataMapper.SetInputConnection(transPD.GetOutputPort())

model = vtk.vtkActor()
model.SetMapper(dataMapper)
model.GetProperty().SetColor(1, 0, 0)

obb = vtk.vtkOBBTree()
obb.SetMaxLevel(10)
obb.SetNumberOfCellsPerNode(5)
obb.AutomaticOff()

boxes = vtk.vtkSpatialRepresentationFilter()
boxes.SetInputConnection(transPD.GetOutputPort())
boxes.SetSpatialRepresentation(obb)
boxes.SetGenerateLeaves(1)
boxes.Update()

output = boxes.GetOutput().GetBlock(boxes.GetMaximumLevel() + 1)
boxEdges = vtk.vtkExtractEdges()
boxEdges.SetInputData(output)

boxMapper = vtk.vtkPolyDataMapper()
Example #36
0
foo.RotateY(10)
foo.RotateZ(27)
foo.Scale(1, .7, .3)

transPD = vtk.vtkTransformPolyDataFilter()
transPD.SetInputConnection(cylinder.GetOutputPort())
transPD.SetTransform(foo)

dataMapper = vtk.vtkPolyDataMapper()
dataMapper.SetInputConnection(transPD.GetOutputPort())

model = vtk.vtkActor()
model.SetMapper(dataMapper)
model.GetProperty().SetColor(1, 0, 0)

obb = vtk.vtkOBBTree()
obb.SetMaxLevel(10)
obb.SetNumberOfCellsPerNode(5)
obb.AutomaticOff()

boxes = vtk.vtkSpatialRepresentationFilter()
boxes.SetInputConnection(transPD.GetOutputPort())
boxes.SetSpatialRepresentation(obb)
boxes.SetGenerateLeaves(1)
boxes.Update()

output = boxes.GetOutput().GetBlock(boxes.GetMaximumLevel() + 1)
boxEdges = vtk.vtkExtractEdges()
boxEdges.SetInputData(output)

boxMapper = vtk.vtkPolyDataMapper()
Example #37
0
def find_forcing_points(lwY, lwX, lwZ, maska3D, forcing_points, siatkaX,
                        siatkaY, siatkaZ, boundary_points, mesh, intersection,
                        maska3D_forcing, interpolation_points, fnix, fniy,
                        fniz, fncx, fncy, fncz):

    obbTree = vtk.vtkOBBTree()
    obbTree.SetDataSet(mesh)
    obbTree.BuildLocator()

    for j in range(0, lwY):
        for i in range(0, lwX):
            for k in range(0, lwZ):
                maska3D_forcing[j][i][k] = 0

    for j in range(0, lwY):
        for i in range(0, lwX):
            for k in range(0, lwZ):

                if i < lwX - 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j][i + 1][k] == 1):

                        maska3D_forcing[j][i][k] = maska3D_forcing[j][i][k] + 1

                if j < lwY - 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j + 1][i][k] == 1):

                        maska3D_forcing[j][i][k] = maska3D_forcing[j][i][k] + 1

                if k < lwZ - 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j][i][k + 1] == 1):

                        maska3D_forcing[j][i][k] = maska3D_forcing[j][i][k] + 1

                if i > 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j][i - 1][k] == 1):

                        maska3D_forcing[j][i][k] = maska3D_forcing[j][i][k] + 1

                if j > 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j - 1][i][k] == 1):

                        maska3D_forcing[j][i][k] = maska3D_forcing[j][i][k] + 1

                if k > 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j][i][k - 1] == 1):

                        maska3D_forcing[j][i][k] = maska3D_forcing[j][i][k] + 1

    for j in range(0, lwY):
        for i in range(0, lwX):
            for k in range(0, lwZ):
                mesh_point_forcing = [
                    siatkaX[i + 1], siatkaY[j + 1], siatkaZ[k + 1]
                ]
                if i < lwX - 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j][i + 1][k] == 1):

                        forcing_points.InsertNextPoint(mesh_point_forcing)
                        fnix.append(i + 1)
                        fniy.append(j + 1)
                        fniz.append(k + 1)
                        fncx.append(siatkaX[i + 1])
                        fncy.append(siatkaY[j + 1])
                        fncz.append(siatkaZ[k + 1])
                        """
                                if(maska3D_forcing[j][i][k] > 0 ):                                
                                
                                    mesh_point_interpolation = [siatkaX[i],siatkaY[j+1],siatkaZ[k+1]]
                                    interpolation_points.InsertNextPoint(mesh_point_interpolation)
                                    
                                
                                    pSource = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                                    pTarget = [siatkaX[i+2],siatkaY[j+1],siatkaZ[k+1]]
                                    
                                    pointsVTKintersection = vtk.vtkPoints()
                                    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
                                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                                    pointsIntersection = []
                                    for idx in range(noPointsVTKIntersection):
                                        _tup = pointsVTKIntersectionData.GetTuple3(idx)
                                        pointsIntersection.append(_tup)
                                    
                                        intersection.append(_tup)
                               """

                if j < lwY - 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j + 1][i][k] == 1):
                        forcing_points.InsertNextPoint(mesh_point_forcing)
                        fnix.append(i + 1)
                        fniy.append(j + 1)
                        fniz.append(k + 1)
                        fncx.append(siatkaX[i + 1])
                        fncy.append(siatkaY[j + 1])
                        fncz.append(siatkaZ[k + 1])
                        """
                                if(maska3D_forcing[j][i][k] > 0):
                                    
                                    mesh_point_interpolation = [siatkaX[i+1],siatkaY[j],siatkaZ[k+1]]
                                    interpolation_points.InsertNextPoint(mesh_point_interpolation)                                    
                                    
                                    pSource = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                                    pTarget = [siatkaX[i+1],siatkaY[j+2],siatkaZ[k+1]]
                                
                                    pointsVTKintersection = vtk.vtkPoints()
                                    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
                                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                                    pointsIntersection = []
                                    for idx in range(noPointsVTKIntersection):
                                        _tup = pointsVTKIntersectionData.GetTuple3(idx)
                                        pointsIntersection.append(_tup)
                                    
                                        intersection.append(_tup)
                                """

                if k < lwZ - 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j][i][k + 1] == 1):
                        forcing_points.InsertNextPoint(mesh_point_forcing)
                        fnix.append(i + 1)
                        fniy.append(j + 1)
                        fniz.append(k + 1)
                        fncx.append(siatkaX[i + 1])
                        fncy.append(siatkaY[j + 1])
                        fncz.append(siatkaZ[k + 1])
                        """
                                if(maska3D_forcing[j][i][k] > 0):
                                    
                                    mesh_point_interpolation = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k]]
                                    interpolation_points.InsertNextPoint(mesh_point_interpolation)                                    
                                    
                                    pSource = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                                    pTarget = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+2]]
                                
                                    pointsVTKintersection = vtk.vtkPoints()
                                    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
                                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                                    pointsIntersection = []
                                    for idx in range(noPointsVTKIntersection):
                                        _tup = pointsVTKIntersectionData.GetTuple3(idx)
                                        pointsIntersection.append(_tup)
                                
                                        intersection.append(_tup)
                                                            
                                """
                if i > 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j][i - 1][k] == 1):
                        forcing_points.InsertNextPoint(mesh_point_forcing)
                        fnix.append(i + 1)
                        fniy.append(j + 1)
                        fniz.append(k + 1)
                        fncx.append(siatkaX[i + 1])
                        fncy.append(siatkaY[j + 1])
                        fncz.append(siatkaZ[k + 1])
                        """
                                if(maska3D_forcing[j][i][k] > 0):
                                    
                                    mesh_point_interpolation = [siatkaX[i+2],siatkaY[j+1],siatkaZ[k+1]]
                                    interpolation_points.InsertNextPoint(mesh_point_interpolation)                                    
                                    
                                    pSource = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                                    pTarget = [siatkaX[i],siatkaY[j+1],siatkaZ[k+1]]
                                
                                    pointsVTKintersection = vtk.vtkPoints()
                                    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
                                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                                    pointsIntersection = []
                                    for idx in range(noPointsVTKIntersection):
                                        _tup = pointsVTKIntersectionData.GetTuple3(idx)
                                        pointsIntersection.append(_tup)
                                        
                                        intersection.append(_tup)
                                   """

                if j > 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j - 1][i][k] == 1):
                        forcing_points.InsertNextPoint(mesh_point_forcing)
                        fnix.append(i + 1)
                        fniy.append(j + 1)
                        fniz.append(k + 1)
                        fncx.append(siatkaX[i + 1])
                        fncy.append(siatkaY[j + 1])
                        fncz.append(siatkaZ[k + 1])
                        """
                                if(maska3D_forcing[j][i][k] > 0):
                                    
                                    mesh_point_interpolation = [siatkaX[i+1],siatkaY[j+2],siatkaZ[k+1]]
                                    interpolation_points.InsertNextPoint(mesh_point_interpolation)                                         
                                    
                                    pSource = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                                    pTarget = [siatkaX[i+1],siatkaY[j],siatkaZ[k+1]]
                                    
                                    pointsVTKintersection = vtk.vtkPoints()
                                    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
                                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                                    pointsIntersection = []
                                    for idx in range(noPointsVTKIntersection):
                                        _tup = pointsVTKIntersectionData.GetTuple3(idx)
                                        pointsIntersection.append(_tup)
                                
                                        intersection.append(_tup)
                                   """

                if k > 1:
                    if (maska3D[j][i][k] == 0) and (maska3D[j][i][k - 1] == 1):
                        forcing_points.InsertNextPoint(mesh_point_forcing)
                        fnix.append(i + 1)
                        fniy.append(j + 1)
                        fniz.append(k + 1)
                        fncx.append(siatkaX[i + 1])
                        fncy.append(siatkaY[j + 1])
                        fncz.append(siatkaZ[k + 1])
                        """
def main():
    parser = _build_args_parser()
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO)

    # make sure all the given files exist
    if not isfile(args.surfaces):
        parser.error('The file "{0}" must exist.'.format(args.surfaces))

    if not isfile(args.surface_map):
        parser.error('The file "{0}" must exist.'.format(args.surface_map))

    if not isfile(args.streamlines):
        parser.error('The file "{0}" must exist.'.format(args.streamlines))

    # make sure that files are not accidently overwritten
    if isfile(args.output):
        if args.overwrite:
            logging.info('Overwriting "{0}".'.format(args.output))
        else:
            parser.error(
                'The file "{0}" already exists. Use -f to overwrite it.'.
                format(args.output))

    if isfile(args.out_tracts):
        if args.overwrite:
            logging.info('Overwriting "{0}".'.format(args.out_tracts))
        else:
            parser.error(
                'The file "{0}" already exists. Use -f to overwrite it.'.
                format(args.out_tracts))

    # load the surfaces
    logging.info('Loading .vtk surfaces and streamlines.')
    all_surfaces = load_vtk(args.surfaces)

    # load surface map
    surface_map = np.load(args.surface_map)

    # load mask for intersections
    surface_mask = np.load(args.surface_mask)

    # find triangles with any vertex within the mask
    vertices = ns.vtk_to_numpy(all_surfaces.GetPolys().GetData())
    triangles = np.vstack([vertices[1::4], vertices[2::4], vertices[3::4]]).T

    surface_mask = surface_mask[triangles]
    surface_mask = np.all(surface_mask, axis=1)
    surface_map = surface_map[triangles[:, 0]]

    # locator for quickly finding intersections
    locator = vtk.vtkOBBTree()
    locator.SetDataSet(all_surfaces)
    locator.BuildLocator()

    # load the streamlines
    streamlines = load_vtk_streamlines(args.streamlines)

    # load label images
    label_img = nib.load(args.aparc)
    label_data = label_img.get_data().astype('int')
    voxel_dim = label_img.get_header()['pixdim'][1:4]

    # calculate transform from voxel to mm coordinates
    affine = np.array(label_img.affine, dtype=float)
    affine = np.linalg.inv(affine)
    transform = affine[:3, :3].T
    offset = affine[:3, 3] + 0.5

    logging.info('Trimming, splitting, and filtering {0} streamlines.'.format(
        len(streamlines)))
    print(args.rois)

    new_streamlines = ROI_Streamlines([], [], [], [], [], [], [])

    for i in xrange(len(streamlines)):
        # just one segment
        # filter as error
        if len(streamlines[i]) < 3:
            continue

        # trim and split cortical intersections
        trimmed_streamlines, tri_in, tri_out = trim_cortical_streamline(
            streamlines[i], i, locator, surface_mask, surface_map)

        # split subcortical intersections
        for j in range(len(trimmed_streamlines)):
            # resample streamline to allow for fine level
            # intersections with subcortical regions
            fiber_len = length(trimmed_streamlines[j])
            n_points = int(fiber_len / SAMPLE_SIZE)

            if n_points < 3:
                continue

            resampled_streamline = set_number_of_points(
                trimmed_streamlines[j], n_points)

            # find voxels that the streamline passes through
            inds = np.dot(resampled_streamline, transform)
            inds = inds + offset

            if inds.min().round(decimals=6) < 0:
                logging.error(
                    'Streamline has points that map to negative voxel indices')

            ii, jj, kk = inds.astype(int).T
            sl_labels = label_data[ii, jj, kk]

            # split fibers among intersecting regions and return all intersections
            split_streamlines = split_subcortical_streamline(
                resampled_streamline, sl_labels, args.rois, tri_in[j],
                tri_out[j])

            # fill the results arrays
            new_streamlines.extend(split_streamlines)

    logging.info('Saving {0} final streamlines.'.format(
        len(new_streamlines.streamlines)))

    # save the results
    new_streamlines.save_streamlines(args.out_tracts)
    new_streamlines.save_intersections(args.output)
Example #39
0
for k in range(0,size_pts_car):
    point=[0.0,0.0, 0.0]
    car_pointsPD_translate.GetPoint(k,point)
    list_of_points.append(point)

list_of_points=np.array(list_of_points)

hull=ConvexHull(list_of_points)
indices=hull.simplices

indices=np.array(indices)
indices=np.int64(indices)



tree=vtk.vtkOBBTree()
tree.SetDataSet(pd_2)
tree.BuildLocator()
intersectPoints=vtk.vtkPoints()

def is_inside(idx,inside_or_outside):
    return not bool(inside_or_outside[idx])

def pt_lat_value(idx,list_of_scalars):
    return not bool(list_of_scalars[idx])



def to_points(triangle,idx_to_point):
    return list(map(lambda x: idx_to_point[x], triangle))
Example #40
0
opTime = timer.GetElapsedTime()
print("    Find cell probing: {0}".format(opTime))

# Time the deletion of the locator. The incremental locator is quite slow due
# to fragmented memory.
timer.StartTimer()
del locator3
timer.StopTimer()
time2 = timer.GetElapsedTime()
print("    Delete BSP Tree Locator: {0}".format(time2))
print("    BSP Tree Locator (Total): {0}".format(time + opTime + time2))
print("\n")

#############################################################
# Time the creation and building of the obb tree
locator4 = vtk.vtkOBBTree()
locator4.LazyEvaluationOff()
locator4.SetDataSet(output)
locator4.AutomaticOn()

timer.StartTimer()
locator4.BuildLocator()
timer.StopTimer()
time = timer.GetElapsedTime()
print("Build OBB Locator: {0}".format(time))

# Probe the dataset with FindClosestPoint() and time it
timer.StartTimer()
for i in range(0, numProbes):
    obbClosest.SetId(
        i,
opTime = timer.GetElapsedTime()
print("    Find cell probing: {0}".format(opTime))

# Time the deletion of the locator. The incremental locator is quite slow due
# to fragmented memory.
timer.StartTimer()
del locator3
timer.StopTimer()
time2 = timer.GetElapsedTime()
print("    Delete BSP Tree Locator: {0}".format(time2))
print("    BSP Tree Locator (Total): {0}".format(time+opTime+time2))
print("\n")

#############################################################
# Time the creation and building of the obb tree
locator4 = vtk.vtkOBBTree()
locator4.LazyEvaluationOff()
locator4.SetDataSet(output)
locator4.AutomaticOn()

timer.StartTimer()
locator4.BuildLocator()
timer.StopTimer()
time = timer.GetElapsedTime()
print("Build OBB Locator: {0}".format(time))

# Probe the dataset with FindClosestPoint() and time it
timer.StartTimer()
for i in range (0,numProbes):
    obbClosest.SetId(i, locator4.FindCell(ProbeCells.GetPoint(i),0.001,genCell,pc,weights))
timer.StopTimer()
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]


# report info [rh, lh]
start_count = [len(rh_lines), len(lh_lines)]
bad_start_count = [0, 0]
bad_pft_count = [0, 0]
end_count = [0, 0]
swap_end_count = [0, 0]
Example #43
0
def ProcessReportNew1(dirToTest):

    clippedRawTireInsideTargetBarPD = ProcessRaw3DClipToFrame(dirToTest)
    # just added 1/26/2016
    clippedRawTireInsideTargetBarPD = ta.KeepOnlyLargestConnectedComponent1(
        clippedRawTireInsideTargetBarPD)

    # aded

    pd = vtk.vtkPolyData()

    obb = vtk.vtkOBBTree()

    obb.SetDataSet(clippedRawTireInsideTargetBarPD)

    #obb.SetInputData(pd)
    #obb.AutomaticOn()
    obb.BuildLocator()
    obb.GenerateRepresentation(0, pd)
    filename = dirToTest + "\\" + "unorientedBB.vtp"
    ta.LogVTK(pd, filename)

    pcaTr = ta.PCAPD(pd)
    orientedBoxPD = ta.TransformPD(pd, pcaTr).GetOutput()
    orientedSwathPD = ta.TransformPD(clippedRawTireInsideTargetBarPD,
                                     pcaTr).GetOutput()

    # check to see the oriented swath isn't upside down
    # to do this clip a region in the top eigtht (z) middle(x)  or the bottom eigth (z) middle (x)
    # no points means it's upside down

    bdsOrientedSwathPD = orientedSwathPD.GetBounds()
    zDiff = (bdsOrientedSwathPD[5] - bdsOrientedSwathPD[4])
    xMid = (bdsOrientedSwathPD[0] + bdsOrientedSwathPD[1]) / 2
    xCheck = 0.02
    #checkClipOrientedSwathPD=ta.ClipPD(orientedSwathPD, (xMid-xCheck,xMid+xCheck,bdsOrientedSwathPD[2],bdsOrientedSwathPD[3],bdsOrientedSwathPD[4],bdsOrientedSwathPD[4]+zDiff/8) )
    checkClipOrientedSwathPD = ta.ClipPD(
        orientedSwathPD,
        (xMid - xCheck, xMid + xCheck, bdsOrientedSwathPD[2],
         bdsOrientedSwathPD[3], bdsOrientedSwathPD[5] - zDiff / 8,
         bdsOrientedSwathPD[5]))

    if (checkClipOrientedSwathPD.GetNumberOfPoints() == 0):
        # flip swath around
        y180Transform = vtk.vtkTransform()
        y180Transform.RotateY(180)
        orientedSwathPD = ta.TransformPD(orientedSwathPD,
                                         y180Transform).GetOutput()

    #ta.LogVTK(orientedSwathPD, "c:\\temp\orientedSwathq.vtp")
    filename = dirToTest + "\\" + "orientedSwathBB.vtp"
    ta.LogVTK(orientedSwathPD, filename)
    filename = dirToTest + "\\" + "orientedBB.vtp"
    ta.LogVTK(orientedBoxPD, filename)

    clippedRawTireInsideTargetBarPD = orientedSwathPD

    numcuts = 100
    bbox = [0, 0, 0, 0, 0, 0]
    bbox = clippedRawTireInsideTargetBarPD.GetBounds()
    #
    minY = bbox[2]
    maxY = bbox[3]

    yInterval = (maxY - minY) / numcuts

    appendedSlicesForHull = vtk.vtkAppendPolyData()
    #

    bds = (-999, 999, 0, 0, -999, 999)
    yCurrent = minY

    smallHullDirectory = dirToTest + "\\" + "smallHullDirectory"
    if not os.path.exists(smallHullDirectory):
        os.makedirs(smallHullDirectory)

    chPD = ta.TopOfConvexHull2(clippedRawTireInsideTargetBarPD)
    #clipPD=ta.ClipPD1(clippedRawTireInsideTargetBarPD,(bds[0],bds[1],     yCurrent, yCurrent+yInterval ,    bds[4],bds[5]),True )
    #chPD=ta.ConvexHullSciPy(clippedRawTireInsideTargetBarPD)

    trchPD = ta.TrimConvexHull2(chPD, -1, 1, -0.9, 0.9, 0, 1)
    topOfHull = trchPD

    #
    #    for i in range(0,numcuts):
    #
    #        clipPD=ta.ClipPD1(clippedRawTireInsideTargetBarPD,(bds[0],bds[1],     yCurrent, yCurrent+yInterval ,    bds[4],bds[5]),True )
    #        chPD=ta.ConvexHullSciPy(clipPD)
    #        #trchPD=ta.TrimConvexHull(chPD)
    #        #trchPD= ta.TrimConvexHull2(chPD,-1,1,-0.5,0.5,0,1)
    #        trchPD= ta.TrimConvexHull2(chPD,-1,1,-0.9,0.9,0,1)
    #
    #        filename=smallHullDirectory+ "\\" + "clitem_" +str(i)+"_.vtp"
    #        ta.LogVTK(clipPD,filename)
    #
    #
    #        filename=smallHullDirectory+ "\\" + "chitem_" +str(i)+"_.vtp"
    #
    #        ta.LogVTK(chPD,filename)
    #
    #        filename=smallHullDirectory+ "\\" + "trchitem_" +str(i)+"_.vtp"
    #
    #        ta.LogVTK(trchPD,filename)
    #        yCurrent=yCurrent+yInterval
    #
    #        appendedSlicesForHull.AddInputData(trchPD)
    #        appendedSlicesForHull.Update()
    #        a=0
    #
    #    filename="c:\\temp\\appendedSlicesForHull.vtp"
    #    ta.LogVTK(appendedSlicesForHull.GetOutput(),filename)
    #    topOfHull=appendedSlicesForHull.GetOutput()

    bigHull = topOfHull
    #topOfHull=ta.TrimConvexHull2(esch.GetOutput(), -1,1,0.5,1)

    filename = dirToTest + "\\" + "trim" + ".vtp"
    ta.LogVTK(topOfHull, filename)

    filename = dirToTest + "\\" + "bigtrim" + ".vtp"
    ta.LogVTK(bigHull, filename)

    # just added 1/26/2017
    croppedToGrooveShouldTopOfHull = ta.ThresholdPointOrCellData(
        topOfHull, False, "zn", 0.9, 1)

    #
    filename = dirToTest + "\\" + "croppedToGrooveShouldTopOfHull.vtp"
    ta.LogVTK(croppedToGrooveShouldTopOfHull, filename)

    bdsHull = croppedToGrooveShouldTopOfHull.GetBounds()
    bds = clippedRawTireInsideTargetBarPD.GetBounds()
    clippedToTopOfHullClippedRawTireInsideTargetBarPD = ta.ClipPD1(
        clippedRawTireInsideTargetBarPD,
        (bdsHull[0], bdsHull[1], bdsHull[2], bdsHull[3], bds[4], bds[5]), True)
    filename = dirToTest + "\\" + "clippedToTopOfHullClippedRawTireInsideTargetBarPD.vtp"
    ta.LogVTK(clippedToTopOfHullClippedRawTireInsideTargetBarPD, filename)

    #clippedToTopOfHullOrientedClippedRawTireInsideTargetBarPD=orientedClippedRawTireInsideTargetBarPD
    treadDepth = ta.ComputeDistanceNew(
        0, clippedToTopOfHullClippedRawTireInsideTargetBarPD,
        croppedToGrooveShouldTopOfHull)

    filename = dirToTest + "\\" + "td1.vtp"
    ta.LogVTK(treadDepth.GetOutput(), filename)

    treadDepthWith32nds = Add32ndsToSwath(treadDepth.GetOutput())
    filename = dirToTest + "\\" + "td32nds.vtp"
    ta.LogVTK(treadDepthWith32nds, filename)

    tireSwath = treadDepthWith32nds
    tireSwathBds = tireSwath.GetBounds()

    #
    blockSwathDecPD, grooveSwathDecPD = ModifySwathForDisplay(tireSwath)

    midTireSlicePD, midProfileLine = ReturnMiddleProfile(tireSwath)
    midTireSliceActor = ReturnProfileActor(midProfileLine)

    rotatedMidTireSlicePD = GenerateTransformedSlice(midTireSlicePD, tireSwath)
    rotatedMidTireSliceActor = ReturnProfileActor(rotatedMidTireSlicePD)

    #
    #    filename=dirToTest+"\\"+ "act_midTireSlicePD.vtp"
    #    ta.LogVTK(midTireSlicePD,filename)
    #    filename=dirToTest+"\\"+ "act_rotatedMidTireSlicePD.vtp"
    #    ta.LogVTK(rotatedMidTireSlicePD,filename)
    #

    #
    deepGroovePointList = ReturnMidTireProfileInformation(
        rotatedMidTireSlicePD)
    lowerLUT = int(round(min(deepGroovePointList[:, 3] - 0.5)))
    upperLUT = int(round(max(deepGroovePointList[:, 3] + 0.5)))

    lut = GenLUT(lowerLUT, upperLUT)
    lutRange = (lowerLUT, upperLUT)

    #
    textActorList = GenerateTextAnnotationForGrooves(tireSwathBds[3] + 0.001,
                                                     deepGroovePointList)

    #
    blockSwathDecActor, grooveSwathDecActor = PrepareBlocksAndGroovesForRendering(
        blockSwathDecPD, grooveSwathDecPD, lut, lutRange)

    #scalar_bar=GenerateLegend(upperLUT-lowerLUT+1, "Groove Depth (32nds) ", (.1,0.05) , (0.8,0.2), 0.34,lut)
    scalar_bar = GenerateLegend(upperLUT - lowerLUT + 1,
                                "Groove Depth (32nds) ", (.1, 0.05),
                                (0.8, 0.1), 0.5, lut)

    #    metaDataFile= dirToTest+"\\"+ commonSettings.metaDataFile

    print("\n path is ", dirToTest)

    actorList1 = []
    actorList2 = []
    actorList3 = []
    actorList = []

    #    actorList1.append(scalar_bar)

    #    for item in textActorList:
    #        actorList3.append ( item )
    actorList2 = textActorList
    #actorList3.append ( titleActor2 )

    actorList2.append(midTireSliceActor)

    actorList2.append(rotatedMidTireSliceActor)

    actorList2.append(blockSwathDecActor)
    actorList2.append(grooveSwathDecActor)

    actorList2.append(scalar_bar)

    # top of report
    #ren1 = vtk.vtkRenderer()
    ren2 = vtk.vtkRenderer()
    #ren3 = vtk.vtkRenderer()

    renWin = vtk.vtkRenderWindow()
    #    ren1.AddActor2D(scalar_bar)
    #RenderActors(actorList1,ren1)
    RenderActors(actorList2, ren2)
    #RenderActors(actorList3,ren3)

    #renWin.AddRenderer(ren1)
    renWin.AddRenderer(ren2)
    #renWin.AddRenderer(ren3)

    #    ren1.SetViewport(0, 0, 0.1, 1)
    #    ren2.SetViewport(0.1, 0.0, 1, 0.9)
    #    ren3.SetViewport(0.1, 0.91, 1, 1)

    #    ren1.SetViewport(0, 0, 1, 0.3)
    #    ren2.SetViewport(0, 0.31, 1, 0.9)
    #    ren3.SetViewport(0, 0.91, 1, 1)

    ren2.SetViewport(0, 0, 1, 1)
    #ren3.SetViewport(0, 0.91, 1, 1)

    renderWindowX = 1000
    renderWindowY = 772

    renWin.SetSize(renderWindowX, renderWindowY)
    #ren1.SetBackground(0.1, 0.2, 0.4)
    #    ren1.SetBackground(1,1,1)
    ren2.SetBackground(1, 1, 1)
    #    ren3.SetBackground(1,1,1)

    camera = vtk.vtkCamera()
    camera.SetPosition(0, 0, 0.44)
    ren2.SetActiveCamera(camera)
    #    camera.SetFocalPoint(0, 0, 0)
    #ren2.GetActiveCamera().Zoom(1.5)

    renWin.Render()

    reportname = "TireAuditReport"

    reportdirToTest = dirToTest + "\\" + reportname
    reportdirToTestJPG = dirToTest + "\\" + reportname + ".png"

    #ExportAsPDF(reportdirToTest,renWin)
    ExportAsPNG(reportdirToTestJPG, renWin)
    #ExportAsPDF(reportdirToTest,renWin)

    #    renWin = ren.GetRenderWindow()
    renWin.Finalize()
    #    ren.TerminateApp()

    del renWin, ren2
    print("\n*** report path is ", reportdirToTest)
    AddLogo(reportdirToTestJPG)

    print("\n hello")
Example #44
0
    def renderthis(self, warunek):
        # open a window and create a renderer
        self.widget.GetRenderWindow().AddRenderer(self.ren)

        # open file
        openFileDialog = wx.FileDialog(self, "Open STL file", "",
                                       self.filename, "*.stl",
                                       wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

        if openFileDialog.ShowModal() == wx.ID_CANCEL:
            return
        self.filename = openFileDialog.GetPath()

        # render the data
        reader = vtk.vtkSTLReader()
        reader.SetFileName(self.filename)

        reader.Update()
        mesh = reader.GetOutput()

        # To take the polygonal data from the vtkConeSource and
        # create a rendering for the renderer.
        coneMapper = vtk.vtkPolyDataMapper()
        coneMapper.SetInput(reader.GetOutput())

        # create an actor for our scene
        if self.isploted:
            coneActor = self.ren.GetActors().GetLastActor()
            self.ren.RemoveActor(coneActor)

        coneActor = vtk.vtkActor()
        coneActor.SetMapper(coneMapper)
        # Add actor
        self.ren.AddActor(coneActor)
        # print self.ren.GetActors().GetNumberOfItems()

        #addPoint(self.ren, pSource, color=[1.0,0.0,0.0])
        #addPoint(self.ren, pTarget, color=[1.0,0.0,1.0])

        addLine(self.ren, pp1, pp2)
        addLine(self.ren, pp3, pp4)
        addLine(self.ren, pp5, pp6)
        addLine(self.ren, pp7, pp8)

        addLine(self.ren, pp1, pp7)
        addLine(self.ren, pp3, pp5)
        addLine(self.ren, pp4, pp6)
        addLine(self.ren, pp2, pp8)

        addLine(self.ren, pp1, pp3)
        addLine(self.ren, pp7, pp5)
        addLine(self.ren, pp4, pp2)
        addLine(self.ren, pp6, pp8)

        if warunek == 1:
            addEdges(self.ren)

        #####################################################################################
        featureEdge = vtk.vtkFeatureEdges()
        featureEdge.FeatureEdgesOff()
        featureEdge.BoundaryEdgesOn()
        featureEdge.NonManifoldEdgesOn()
        featureEdge.SetInput(mesh)
        featureEdge.Update()
        openEdges = featureEdge.GetOutput().GetNumberOfCells()

        if openEdges != 0:
            print "the stl file is not closed"

        select = vtk.vtkSelectEnclosedPoints()
        select.SetSurface(mesh)

        inside_polydat = vtk.vtkPolyData()
        forcing_polydat = vtk.vtkPolyData()
        interpolation_polydat = vtk.vtkPolyData()
        inside_points = vtk.vtkPoints()
        forcing_points = vtk.vtkPoints()
        interpolation_points = vtk.vtkPoints()
        # for i in range(11):
        #IsInside(i-5,0.1,0.1,mesh)
        global licz
        global licz2
        global licznik

        for j in range(1, lwY + 1):
            for i in range(1, lwX + 1):
                licz += 1
                print(licz / float(stoProcent)) * 100.0
                for k in range(1, lwZ + 1):
                    sprawdzenie = 0
                    siatkaX[1] = xmin + 0.001
                    siatkaX[lwX] = xmax - 0.001
                    siatkaY[1] = ymin + 0.001
                    siatkaY[lwY] = ymax - 0.001
                    siatkaZ[1] = zmin + 0.001
                    siatkaZ[lwZ] = zmax - 0.001
                    sprawdzenie = IsInsideCheck(siatkaX[i], siatkaY[j],
                                                siatkaZ[k], mesh)
                    siatkaX[1] = xmin
                    siatkaX[lwX] = xmax
                    siatkaY[1] = ymin
                    siatkaY[lwY] = ymax
                    siatkaZ[1] = zmin
                    siatkaZ[lwZ] = zmax
                    mesh_point_inside = [siatkaX[i], siatkaY[j], siatkaZ[k]]
                    #mesh_point_forcing = [siatkaX[i]+1.0,siatkaY[j],siatkaZ[k]]

                    maska[licznik] = sprawdzenie
                    licznik = licznik + 1
                    if sprawdzenie == 1:
                        inside_points.InsertNextPoint(mesh_point_inside)
                        #forcing_points.InsertNextPoint(mesh_point_forcing)

        licznik = 0

        licznik_forcing = 0

        for j in range(0, lwY):
            for i in range(0, lwX):
                for k in range(0, lwZ):
                    #print j,i,k
                    maska3D[j][i][k] = maska[licznik]
                    licznik = licznik + 1

        #print maska3D
        find_forcing_points(lwY, lwX, lwZ, maska3D, forcing_points, siatkaX,
                            siatkaY, siatkaZ, boundary_points, mesh,
                            intersection, maska3D_forcing,
                            interpolation_points, fnix, fniy, fniz, fncx, fncy,
                            fncz)

        for j in range(0, lwY):
            for i in range(0, lwX):
                for k in range(0, lwZ):
                    if maska3D_forcing[j][i][k] > 0:
                        licznik_forcing = licznik_forcing + maska3D_forcing[j][
                            i][k]

        for i in range(0, licznik_forcing):
            print i, fnix[i], fniy[i], fniz[i], fncx[i], fncy[i], fncz[i]

        odczyt_STL(self.filename, normals, licznik_forcing, fnix, fniy, fniz,
                   fncx, fncy, fncz)
        zp = [0, 0, 0]

        for i in range(0, licznik_forcing):
            if fncx[i] > 0 and normals[i][0] < 0:
                normals[i][0] = normals[i][0] * (-1.0)
            if fncx[i] < 0 and normals[i][0] > 0:
                normals[i][0] = normals[i][0] * (-1.0)
            if fncy[i] > 0 and normals[i][1] < 0:
                normals[i][1] = normals[i][1] * (-1.0)
            if fncy[i] < 0 and normals[i][1] > 0:
                normals[i][1] = normals[i][1] * (-1.0)
            if fncz[i] > 0 and normals[i][2] < 0:
                normals[i][2] = normals[i][2] * (-1.0)
            if fncz[i] < 0 and normals[i][2] > 0:
                normals[i][2] = normals[i][2] * (-1.0)

        for i in range(0, licznik_forcing):
            zp1 = [fncx[i], fncy[i], fncz[i]]
            zp2 = [
                normals[i][0] + fncx[i], normals[i][1] + fncy[i],
                normals[i][2] + fncz[i]
            ]
            #normals[i][0]=normals[i][0]+fncx[i]
            #normals[i][1]=normals[i][1]+fncy[i]
            #normals[i][2]=normals[i][2]+fncz[i]

            addLine(self.ren, zp1, zp2)
            print i, normals[i], zp1, zp2

        #print intersection
        #print "+++++++++++++++++++="
        #print maska3D_forcing
        """
            licznik=0
            for j in range(0,lwY):
                for i in range(0,lwX-1):
                    for k in range(0,lwZ):
                        mesh_point_forcing = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                        if (maska3D[j][i][k] == 0) and (maska3D[j][i+1][k] == 1):
                            forcing_points.InsertNextPoint(mesh_point_forcing)
                        licznik=licznik+1
              """

        zapis = open('Maska.txt', 'w')
        for i in range(0, lwX * lwY * lwZ):
            zapis.write(str(maska[i]))
            zapis.write('\n')
        zapis.close()
        print "zapisano Maske"
        inside_polydat.SetPoints(inside_points)

        inside = vtk.vtkSphereSource()
        inside.SetRadius(0.02)
        inside.SetPhiResolution(8)
        inside.SetThetaResolution(8)

        ballGlyph = vtkGlyph3D()
        ballGlyph.SetColorModeToColorByScalar()
        ballGlyph.SetSourceConnection(inside.GetOutputPort())
        ballGlyph.SetInput(inside_polydat)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(ballGlyph.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor([1.0, 0.0, 0.0])

        self.ren.AddActor(actor)
        ######################################################################################
        forcing_polydat.SetPoints(forcing_points)

        forcing = vtk.vtkSphereSource()
        #point.SetCenter(pS)
        forcing.SetRadius(0.02)
        forcing.SetPhiResolution(8)
        forcing.SetThetaResolution(8)

        forcingGlyph = vtkGlyph3D()
        forcingGlyph.SetColorModeToColorByScalar()
        forcingGlyph.SetSourceConnection(forcing.GetOutputPort())
        forcingGlyph.SetInput(forcing_polydat)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(forcingGlyph.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor([0.0, 1.0, 0.0])

        self.ren.AddActor(actor)
        #####################################################################################
        """
            interpolation_polydat.SetPoints(interpolation_points)
            
            interpolation = vtk.vtkSphereSource()
            #point.SetCenter(pS)
            interpolation.SetRadius(0.02)
            interpolation.SetPhiResolution(8)
            interpolation.SetThetaResolution(8)
    
            interpolationGlyph = vtkGlyph3D()
            interpolationGlyph.SetColorModeToColorByScalar()
            interpolationGlyph.SetSourceConnection(interpolation.GetOutputPort())
            interpolationGlyph.SetInput(interpolation_polydat)
      
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(interpolationGlyph.GetOutputPort())
    
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            actor.GetProperty().SetColor([0.0,0.0,1.0])
    
            self.ren.AddActor(actor)
            """
        #####################################################################################
        obbTree = vtk.vtkOBBTree()
        obbTree.SetDataSet(mesh)
        obbTree.BuildLocator()

        pointsVTKintersection = vtk.vtkPoints()
        obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection,
                                  None)

        pointsVTKIntersectionData = pointsVTKintersection.GetData()
        noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
        pointsIntersection = []
        for idx in range(noPointsVTKIntersection):
            _tup = pointsVTKIntersectionData.GetTuple3(idx)
            pointsIntersection.append(_tup)

        print pointsIntersection

        if not self.isploted:
            axes = vtk.vtkAxesActor()
            self.marker = vtk.vtkOrientationMarkerWidget()
            self.marker.SetInteractor(self.widget._Iren)
            self.marker.SetOrientationMarker(axes)
            self.marker.SetViewport(0.75, 0, 1, 0.25)
            self.marker.SetEnabled(1)

        self.ren.ResetCamera()
        self.ren.ResetCameraClippingRange()
        #cam = self.ren.GetActiveCamera()
        self.cam.Elevation(50)
        self.cam.Azimuth(40)
        #cam.SetPosition(0,0,1)
        #cam.SetFocalPoint(0,0,-50)
        self.isploted = True
        self.ren.Render()
Example #45
0
def find_forcing_points(lwY,lwX,lwZ,maska3D,forcing_points,siatkaX,siatkaY,siatkaZ,boundary_points,mesh,intersection,maska3D_forcing,interpolation_points,fnix,fniy,fniz,fncx,fncy,fncz):
    
            obbTree = vtk.vtkOBBTree()
            obbTree.SetDataSet(mesh)
            obbTree.BuildLocator()
            
            for j in range(0,lwY):
                for i in range(0,lwX):
                    for k in range(0,lwZ):
                        maska3D_forcing[j][i][k]=0
            
            for j in range(0,lwY):
                for i in range(0,lwX):
                    for k in range(0,lwZ):
                        
                        if i<lwX-1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j][i+1][k] == 1):
                                
                                maska3D_forcing[j][i][k]=maska3D_forcing[j][i][k]+1
                           
                        if j<lwY-1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j+1][i][k] == 1):
                                
                                maska3D_forcing[j][i][k]=maska3D_forcing[j][i][k]+1   
                                
                        if k<lwZ-1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j][i][k+1] == 1):
                                
                                maska3D_forcing[j][i][k]=maska3D_forcing[j][i][k]+1
                             
                        if i>1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j][i-1][k] == 1):
                                
                                maska3D_forcing[j][i][k]=maska3D_forcing[j][i][k]+1
                        
                        if j>1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j-1][i][k] == 1):
                                
                                maska3D_forcing[j][i][k]=maska3D_forcing[j][i][k]+1
                         
                        if k>1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j][i][k-1] == 1):
                                
                                maska3D_forcing[j][i][k]=maska3D_forcing[j][i][k]+1
                       
                        
            for j in range(0,lwY):
                for i in range(0,lwX):
                    for k in range(0,lwZ):
                        mesh_point_forcing = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                        if i<lwX-1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j][i+1][k] == 1):
                                
                               
                                forcing_points.InsertNextPoint(mesh_point_forcing)
                                fnix.append(i+1)
                                fniy.append(j+1)
                                fniz.append(k+1)
                                fncx.append(siatkaX[i+1])
                                fncy.append(siatkaY[j+1])
                                fncz.append(siatkaZ[k+1])
                                """
                                if(maska3D_forcing[j][i][k] > 0 ):                                
                                
                                    mesh_point_interpolation = [siatkaX[i],siatkaY[j+1],siatkaZ[k+1]]
                                    interpolation_points.InsertNextPoint(mesh_point_interpolation)
                                    
                                
                                    pSource = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                                    pTarget = [siatkaX[i+2],siatkaY[j+1],siatkaZ[k+1]]
                                    
                                    pointsVTKintersection = vtk.vtkPoints()
                                    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
                                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                                    pointsIntersection = []
                                    for idx in range(noPointsVTKIntersection):
                                        _tup = pointsVTKIntersectionData.GetTuple3(idx)
                                        pointsIntersection.append(_tup)
                                    
                                        intersection.append(_tup)
                               """
                               
                        if j<lwY-1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j+1][i][k] == 1):
                                forcing_points.InsertNextPoint(mesh_point_forcing)
                                fnix.append(i+1)
                                fniy.append(j+1)
                                fniz.append(k+1)
                                fncx.append(siatkaX[i+1])
                                fncy.append(siatkaY[j+1])
                                fncz.append(siatkaZ[k+1])
                                """
                                if(maska3D_forcing[j][i][k] > 0):
                                    
                                    mesh_point_interpolation = [siatkaX[i+1],siatkaY[j],siatkaZ[k+1]]
                                    interpolation_points.InsertNextPoint(mesh_point_interpolation)                                    
                                    
                                    pSource = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                                    pTarget = [siatkaX[i+1],siatkaY[j+2],siatkaZ[k+1]]
                                
                                    pointsVTKintersection = vtk.vtkPoints()
                                    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
                                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                                    pointsIntersection = []
                                    for idx in range(noPointsVTKIntersection):
                                        _tup = pointsVTKIntersectionData.GetTuple3(idx)
                                        pointsIntersection.append(_tup)
                                    
                                        intersection.append(_tup)
                                """
                                
                        if k<lwZ-1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j][i][k+1] == 1):
                                forcing_points.InsertNextPoint(mesh_point_forcing)
                                fnix.append(i+1)
                                fniy.append(j+1)
                                fniz.append(k+1)
                                fncx.append(siatkaX[i+1])
                                fncy.append(siatkaY[j+1])
                                fncz.append(siatkaZ[k+1])
                                """
                                if(maska3D_forcing[j][i][k] > 0):
                                    
                                    mesh_point_interpolation = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k]]
                                    interpolation_points.InsertNextPoint(mesh_point_interpolation)                                    
                                    
                                    pSource = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                                    pTarget = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+2]]
                                
                                    pointsVTKintersection = vtk.vtkPoints()
                                    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
                                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                                    pointsIntersection = []
                                    for idx in range(noPointsVTKIntersection):
                                        _tup = pointsVTKIntersectionData.GetTuple3(idx)
                                        pointsIntersection.append(_tup)
                                
                                        intersection.append(_tup)
                                                            
                                """
                        if i>1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j][i-1][k] == 1):
                                forcing_points.InsertNextPoint(mesh_point_forcing)
                                fnix.append(i+1)
                                fniy.append(j+1)
                                fniz.append(k+1)
                                fncx.append(siatkaX[i+1])
                                fncy.append(siatkaY[j+1])
                                fncz.append(siatkaZ[k+1])
                                """
                                if(maska3D_forcing[j][i][k] > 0):
                                    
                                    mesh_point_interpolation = [siatkaX[i+2],siatkaY[j+1],siatkaZ[k+1]]
                                    interpolation_points.InsertNextPoint(mesh_point_interpolation)                                    
                                    
                                    pSource = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                                    pTarget = [siatkaX[i],siatkaY[j+1],siatkaZ[k+1]]
                                
                                    pointsVTKintersection = vtk.vtkPoints()
                                    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
                                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                                    pointsIntersection = []
                                    for idx in range(noPointsVTKIntersection):
                                        _tup = pointsVTKIntersectionData.GetTuple3(idx)
                                        pointsIntersection.append(_tup)
                                        
                                        intersection.append(_tup)
                                   """                          
                                
                        if j>1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j-1][i][k] == 1):
                                forcing_points.InsertNextPoint(mesh_point_forcing)
                                fnix.append(i+1)
                                fniy.append(j+1)
                                fniz.append(k+1)
                                fncx.append(siatkaX[i+1])
                                fncy.append(siatkaY[j+1])
                                fncz.append(siatkaZ[k+1])
                                """
                                if(maska3D_forcing[j][i][k] > 0):
                                    
                                    mesh_point_interpolation = [siatkaX[i+1],siatkaY[j+2],siatkaZ[k+1]]
                                    interpolation_points.InsertNextPoint(mesh_point_interpolation)                                         
                                    
                                    pSource = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]]
                                    pTarget = [siatkaX[i+1],siatkaY[j],siatkaZ[k+1]]
                                    
                                    pointsVTKintersection = vtk.vtkPoints()
                                    obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None)
            
                                    pointsVTKIntersectionData = pointsVTKintersection.GetData()
                                    noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()
                                    pointsIntersection = []
                                    for idx in range(noPointsVTKIntersection):
                                        _tup = pointsVTKIntersectionData.GetTuple3(idx)
                                        pointsIntersection.append(_tup)
                                
                                        intersection.append(_tup)
                                   """                         
                                
                        if k>1:
                            if (maska3D[j][i][k] == 0) and (maska3D[j][i][k-1] == 1):
                                forcing_points.InsertNextPoint(mesh_point_forcing)
                                fnix.append(i+1)
                                fniy.append(j+1)
                                fniz.append(k+1)
                                fncx.append(siatkaX[i+1])
                                fncy.append(siatkaY[j+1])
                                fncz.append(siatkaZ[k+1])
                                """
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)
rh_out_tree = vtk.vtkOBBTree()
rh_out_tree.SetDataSet(rh_out_mesh.get_polydata())
rh_out_tree.BuildLocator()

lh_out_mesh = TriMesh_Vtk(args.lh_out_surface, None)