Beispiel #1
0
def ac_resampling_spline(acontour, resolution, flag = False):
    import vtk
    points = vtk.vtkPoints()
    for i in range(acontour.shape[1] - 1):
        points.InsertPoint(i, acontour[0, i], acontour[1, i], 0)
        
    para_spline = vtk.vtkParametricSpline()
    para_spline.SetPoints(points)
    para_spline.ClosedOn()
    
    pt = [0.0, 0.0, 0.0]
    t = 0.05
    para_spline.Evaluate([t, t, t], pt, [0] * 9)
    l = npy.sqrt((pt[0] - acontour[0, 0]) ** 2 + (pt[1] - acontour[1, 0]) ** 2) / t
    if flag:
        return l # Return the length of the contour
    cnt = max(int(l / resolution + 0.5), 5)
    
    resampled = npy.zeros([2, cnt], dtype = npy.float32)
    resampled[:, 0] = acontour[:, 0]
    for i in range(1, cnt):
        t = i * 1.0 / cnt
        pt = [0.0, 0.0, 0.0]
        para_spline.Evaluate([t, t, t], pt, [0] * 9)
        resampled[:, i] = pt[:2]
    return resampled
Beispiel #2
0
    def Get_Interpolated_CtrlPoints(self, num_of_points):
        '''
        Input:
            num_of_points: Number of contorl points after interpolation
        Output: numpy array (3*n), position of interpolated contorl points
        Description: Get a specific number of control points through interpolation
        '''
        Points = vtk.vtkPoints()
        for i in range(self._ctrl_points.shape[0]):
            Points.InsertPoint(i, self._ctrl_points[i][0],
                               self._ctrl_points[i][1],
                               self._ctrl_points[i][2])
        Points.Modified()

        ParametricSpline = vtk.vtkParametricSpline()
        ParametricSpline.SetPoints(Points)
        if self._is_closer:
            ParametricSpline.ClosedOn()
        else:
            ParametricSpline.ClosedOff()
        ParametricSpline.Modified()

        ParametricFunctionSource = vtk.vtkParametricFunctionSource()
        ParametricFunctionSource.SetParametricFunction(ParametricSpline)
        ParametricFunctionSource.SetUResolution(num_of_points)
        ParametricFunctionSource.Update()
        points = np.array(
            ParametricFunctionSource.GetOutput().GetPoints().GetData())
        return points
Beispiel #3
0
def ac_resampling_spline(acontour, resolution, flag=False):
    import vtk
    points = vtk.vtkPoints()
    for i in range(acontour.shape[1] - 1):
        points.InsertPoint(i, acontour[0, i], acontour[1, i], 0)

    para_spline = vtk.vtkParametricSpline()
    para_spline.SetPoints(points)
    para_spline.ClosedOn()

    pt = [0.0, 0.0, 0.0]
    t = 0.05
    para_spline.Evaluate([t, t, t], pt, [0] * 9)
    l = npy.sqrt((pt[0] - acontour[0, 0])**2 + (pt[1] - acontour[1, 0])**2) / t
    if flag:
        return l  # Return the length of the contour
    cnt = max(int(l / resolution + 0.5), 5)

    resampled = npy.zeros([2, cnt], dtype=npy.float32)
    resampled[:, 0] = acontour[:, 0]
    for i in range(1, cnt):
        t = i * 1.0 / cnt
        pt = [0.0, 0.0, 0.0]
        para_spline.Evaluate([t, t, t], pt, [0] * 9)
        resampled[:, i] = pt[:2]
    return resampled
    def _create_geometry(self):
        self._spline_source = vtk.vtkParametricFunctionSource()

        s = vtk.vtkParametricSpline()

        if False:
            # these are quite ugly...
            # later: factor this out into method, so that we can
            # experiment live with different spline params.  For now
            # the vtkCardinal spline that is used is muuuch prettier.
            ksplines = []
            for i in range(3):
                ksplines.append(vtk.vtkKochanekSpline())
                ksplines[-1].SetDefaultTension(0)
                ksplines[-1].SetDefaultContinuity(0)
                ksplines[-1].SetDefaultBias(0)
            
            s.SetXSpline(ksplines[0])
            s.SetYSpline(ksplines[1])
            s.SetZSpline(ksplines[2])

        pts = vtk.vtkPoints()
        s.SetPoints(pts)
        self._spline_source.SetParametricFunction(s)
        
        m = vtk.vtkPolyDataMapper()
        m.SetInputConnection(self._spline_source.GetOutputPort())

        a = vtk.vtkActor()
        a.SetMapper(m)

        a.GetProperty().SetColor(self.line_colour)
        a.GetProperty().SetLineWidth(self._normal_width)

        self.props = [a]
Beispiel #5
0
def augmentCenterline(ori_points, multiple, times):
    if multiple <= 1:
        multiple = 1.0
    multiple = int(times * multiple + 0.5)
    trans_points = npy.array([[-1, -1, -1, -1]], dtype = npy.float32)
    ind = ori_points[:, 2].argsort()
    ori_points = ori_points[ind]
    for cnt in range(3):
        resampled_points = ori_points[npy.where(npy.round(ori_points[:, -1]) == cnt)]
        
        count = resampled_points.shape[0]
        points = vtk.vtkPoints()
        for i in range(count):
            points.InsertPoint(i, resampled_points[i, 0], resampled_points[i, 1], resampled_points[i, 2])

        para_spline = vtk.vtkParametricSpline()
        para_spline.SetPoints(points)
        para_spline.ClosedOff()
        
        numberOfOutputPoints = count * multiple
        
        for i in range(0, numberOfOutputPoints):
            t = i * 1.0 / numberOfOutputPoints
            pt = [0.0, 0.0, 0.0]
            para_spline.Evaluate([t, t, t], pt, [0] * 9)
            trans_points = npy.append(trans_points, [[pt[0], pt[1], pt[2], cnt]], axis = 0)
    return trans_points    
Beispiel #6
0
    def KeyPressCallback(self, obj, event):
        ch = self.window_interactor.GetKeySym()
        if ch == 'Return':
            trans = loadTransform()
            num = 0
            for transform in trans:
                self.point_data_result = applyTransform(
                    self.tmp_data_move, transform)
                self.point_data_result[:, :3] /= self.tmp_space
                for cnt in range(3, 6):
                    point_result = self.point_data_result[npy.where(
                        npy.round(self.point_data_result[:, -1]) == cnt - 3)]
                    point_move = self.point_data_move[npy.where(
                        npy.round(self.point_data_move[:, -1]) == cnt - 3)]
                    if not point_result.shape[0]:
                        continue

                    self.cells = vtk.vtkCellArray()
                    self.points = vtk.vtkPoints()
                    l = 0
                    for i in range(self.zmin, self.zmax + 1):
                        data = point_result[npy.where(
                            npy.round(point_move[:, 2]) == i)]
                        if data is not None:
                            if data.shape[0] == 0:
                                continue
                            count = data.shape[0]
                            points = vtk.vtkPoints()
                            for j in range(count):
                                points.InsertPoint(j, data[j, 0], data[j, 1],
                                                   data[j, 2])

                            para_spline = vtk.vtkParametricSpline()
                            para_spline.SetXSpline(vtk.vtkKochanekSpline())
                            para_spline.SetYSpline(vtk.vtkKochanekSpline())
                            para_spline.SetZSpline(vtk.vtkKochanekSpline())
                            para_spline.SetPoints(points)
                            para_spline.ClosedOn()

                            # The number of output points set to 10 times of input points
                            numberOfOutputPoints = count * 10
                            self.cells.InsertNextCell(numberOfOutputPoints)
                            for k in range(0, numberOfOutputPoints):
                                t = k * 1.0 / numberOfOutputPoints
                                pt = [0.0, 0.0, 0.0]
                                para_spline.Evaluate([t, t, t], pt, [0] * 9)
                                if pt[0] != pt[0]:
                                    print pt
                                    continue
                                self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                                self.cells.InsertCellPoint(l)
                                l += 1

                    self.contours[cnt].SetPoints(self.points)
                    self.contours[cnt].SetPolys(self.cells)
                    self.contours[cnt].Update()

                self.render_window.Render()
                saveGif(self.render_window, num)
                num += 1
Beispiel #7
0
def getPointsOntheSpline(data, center, numberOfOutputPoints):
    ind = sortContourPoints(data)
    data[:, :] = data[ind, :]

    count = data.shape[0]
    points = vtk.vtkPoints()
    for j in range(count):
        points.InsertPoint(j, data[j, 0], data[j, 1], 0)

    para_spline = vtk.vtkParametricSpline()
    para_spline.SetPoints(points)
    para_spline.ClosedOn()

    result = npy.empty([numberOfOutputPoints, 3], dtype=npy.float32)

    for k in range(0, numberOfOutputPoints):
        t = k * 1.0 / numberOfOutputPoints
        pt = [0.0, 0.0, 0.0]
        para_spline.Evaluate([t, t, t], pt, [0] * 9)
        result[k, :2] = pt[:2]

    result[:, 2] = npy.arctan2(result[:, 1] - center[1],
                               result[:, 0] - center[0])
    ind = result[:, 2].argsort()
    return result[ind, :]
Beispiel #8
0
def augmentCenterline(ori_points, multiple, times):
    if multiple <= 1:
        multiple = 1.0
    multiple = int(times * multiple + 0.5)
    trans_points = npy.array([[-1, -1, -1, -1]], dtype=npy.float32)
    ind = ori_points[:, 2].argsort()
    ori_points = ori_points[ind]
    for cnt in range(3):
        resampled_points = ori_points[npy.where(
            npy.round(ori_points[:, -1]) == cnt)]

        count = resampled_points.shape[0]
        points = vtk.vtkPoints()
        for i in range(count):
            points.InsertPoint(i, resampled_points[i, 0],
                               resampled_points[i, 1], resampled_points[i, 2])

        para_spline = vtk.vtkParametricSpline()
        para_spline.SetPoints(points)
        para_spline.ClosedOff()

        numberOfOutputPoints = count * multiple

        for i in range(0, numberOfOutputPoints):
            t = i * 1.0 / numberOfOutputPoints
            pt = [0.0, 0.0, 0.0]
            para_spline.Evaluate([t, t, t], pt, [0] * 9)
            trans_points = npy.append(trans_points,
                                      [[pt[0], pt[1], pt[2], cnt]],
                                      axis=0)
    return trans_points
Beispiel #9
0
    def _create_geometry(self):
        self._spline_source = vtk.vtkParametricFunctionSource()

        s = vtk.vtkParametricSpline()

        if False:
            # these are quite ugly...
            # later: factor this out into method, so that we can
            # experiment live with different spline params.  For now
            # the vtkCardinal spline that is used is muuuch prettier.
            ksplines = []
            for i in range(3):
                ksplines.append(vtk.vtkKochanekSpline())
                ksplines[-1].SetDefaultTension(0)
                ksplines[-1].SetDefaultContinuity(0)
                ksplines[-1].SetDefaultBias(0)

            s.SetXSpline(ksplines[0])
            s.SetYSpline(ksplines[1])
            s.SetZSpline(ksplines[2])

        pts = vtk.vtkPoints()
        s.SetPoints(pts)
        self._spline_source.SetParametricFunction(s)

        m = vtk.vtkPolyDataMapper()
        m.SetInput(self._spline_source.GetOutput())

        a = vtk.vtkActor()
        a.SetMapper(m)

        a.GetProperty().SetColor(self.line_colour)
        a.GetProperty().SetLineWidth(self._normal_width)

        self.props = [a]
Beispiel #10
0
 def KeyPressCallback(self, obj, event):
     ch = self.window_interactor.GetKeySym()
     if ch == 'Return':
         trans = loadTransform()
         num = 0
         for transform in trans:
             self.point_data_result = applyTransform(self.tmp_data_move, transform)
             self.point_data_result[:, :3] /= self.tmp_space
             for cnt in range(3, 6):
                 point_result = self.point_data_result[npy.where(npy.round(self.point_data_result[:, -1]) == cnt - 3)]
                 point_move = self.point_data_move[npy.where(npy.round(self.point_data_move[:, -1]) == cnt - 3)]
                 if not point_result.shape[0]:
                     continue
                     
                 self.cells = vtk.vtkCellArray()
                 self.points = vtk.vtkPoints()
                 l = 0
                 for i in range(self.zmin, self.zmax + 1):
                     data = point_result[npy.where(npy.round(point_move[:, 2]) == i)]
                     if data is not None:
                         if data.shape[0] == 0:
                             continue
                         count = data.shape[0]
                         points = vtk.vtkPoints()
                         for j in range(count):
                             points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2])
                         
                         para_spline = vtk.vtkParametricSpline()
                         para_spline.SetXSpline(vtk.vtkKochanekSpline())
                         para_spline.SetYSpline(vtk.vtkKochanekSpline())
                         para_spline.SetZSpline(vtk.vtkKochanekSpline())
                         para_spline.SetPoints(points)
                         para_spline.ClosedOn()
                         
                         # The number of output points set to 10 times of input points
                         numberOfOutputPoints = count * 10
                         self.cells.InsertNextCell(numberOfOutputPoints)
                         for k in range(0, numberOfOutputPoints):
                             t = k * 1.0 / numberOfOutputPoints
                             pt = [0.0, 0.0, 0.0]
                             para_spline.Evaluate([t, t, t], pt, [0] * 9)
                             if pt[0] != pt[0]:
                                 print pt
                                 continue
                             self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                             self.cells.InsertCellPoint(l)
                             l += 1
     
                 self.contours[cnt].SetPoints(self.points)
                 self.contours[cnt].SetPolys(self.cells)
                 self.contours[cnt].Update()
                 
             self.render_window.Render()
             saveGif(self.render_window, num)
             num += 1
Beispiel #11
0
 def set_centerline(self, resolution):
     xmin,xmax, ymin,ymax, zmin,zmax = self.obj.GetBounds()
     center = self.obj.GetCenter() # colon center
     step = [zmin, (zmin+center[2])/2, center[2], (zmax+center[2])/2, zmax]
     posx, posy, posx2, posy2 = [], [], [], []
     negx, negy, negx2, negy2 = [], [], [], []
     N = self.obj.GetNumberOfPoints()
     for i in range(N):
         p = [0] * 3
         self.obj.GetPoint(i, p)
         if p[2]>step[3]:
             posx.append(p[0])
             posy.append(p[1])
         elif p[2]>step[2]:
             posx2.append(p[0])
             posy2.append(p[1])
         elif p[2]>step[1]:
             negx2.append(p[0])
             negy2.append(p[1])
         else:
             negx.append(p[0])
             negy.append(p[1])
     # key points
     c_posx, c_posy = np.average(np.array(posx)), np.average(np.array(posy))
     c_posx2, c_posy2 = np.average(np.array(posx2)), np.average(np.array(posy2))
     c_negx, c_negy = np.average(np.array(negx)), np.average(np.array(negy))
     c_negx2, c_negy2 = np.average(np.array(negx2)), np.average(np.array(negy2))
     pts = vtk.vtkPoints()
     # pts.InsertNextPoint([c_posx, c_posy, zmax])
     pts.InsertNextPoint([np.average(np.array(posx)), np.average(np.array(posy)), step[4]])
     pts.InsertNextPoint([np.average(np.array(posx2)), np.average(np.array(posy2)), step[3]])
     #pts.InsertNextPoint([center[0], center[1], zmin])
     #pts.InsertNextPoint([(c_negx2+c_posx2)/2, (c_negy2+c_posy2)/2, 0])
     pts.InsertNextPoint([np.average(np.array(negx2+posx2)), np.average(np.array(negy2+posy2)), step[2]])
     pts.InsertNextPoint([np.average(np.array(negx2)), np.average(np.array(negy2)), step[1]])
     pts.InsertNextPoint([np.average(np.array(negx)), np.average(np.array(negy)), step[0]])
     # pts.InsertNextPoint([c_negx, c_negy, zmin])
     #pts.InsertNextPoint([center[0], center[1], zmax])
     
     # spline from keypoints
     spline = vtk.vtkParametricSpline() 
     spline.SetPoints(pts)
     function = vtk.vtkParametricFunctionSource()
     function.SetParametricFunction(spline)
     function.Update()
     function.SetUResolution(resolution)
     function.Update()
     self.centerline = function.GetOutput() # centerline
     self.cl_scale = (zmax-zmin)/resolution
     
     # centerline direction, [0, 0, 1]
     self.direction = [0, 0, zmax-zmin]
     self.math.Normalize(self.direction) 
Beispiel #12
0
def get_spline_actor(surface_data, chassis_cg_path, surface_bounds):
    # Iterate over chassis CG points and create a spline which marks the driving path.
    # Return the spline as a vtkActor for being added later to the renderer.

    # Update the pipeline so that vtkCellLocator finds cells
    surface_data.Update()

    # Define a cellLocator to be able to compute intersections between lines
    # and the surface
    locator = vtkCellLocator()
    locator.SetDataSet(surface_data.GetOutput())
    locator.BuildLocator()

    tolerance = 0.01  # Set intersection searching tolerance

    # Make a list of points. Each point is the intersection of a vertical line
    # defined by p1 and p2 and the surface.
    points = vtkPoints()
    for chassis_cg in chassis_cg_path:
        p1 = [chassis_cg[0], chassis_cg[1], surface_bounds[4]]
        p2 = [chassis_cg[0], chassis_cg[1], surface_bounds[5]]

        t = mutable(0)
        pos = [0.0, 0.0, 0.0]
        pcoords = [0.0, 0.0, 0.0]
        subId = mutable(0)
        locator.IntersectWithLine(p1, p2, tolerance, t, pos, pcoords, subId)

        # Add a slight offset in z
        pos[2] += 0.05

        # Add the x, y, z position of the intersection
        points.InsertNextPoint(pos)

    # Create a spline and add the pointsoi
    spline = vtkParametricSpline()
    spline.SetPoints(points)
    spline_function = vtkParametricFunctionSource()
    spline_function.SetUResolution(len(chassis_cg_path))
    spline_function.SetParametricFunction(spline)

    # Map the spline
    spline_mapper = vtkPolyDataMapper()
    spline_mapper.SetInputConnection(spline_function.GetOutputPort())

    # Define the line actor
    spline_actor = vtkActor()
    spline_actor.SetMapper(spline_mapper)
    spline_actor.GetProperty().SetColor([0, 0.7, 0])
    spline_actor.GetProperty().SetLineWidth(10)

    return spline_actor
Beispiel #13
0
 def _createTube(self):
     logging.debug("In MultiSliceContour::createTube()")
     
     points = vtk.vtkPoints()
     for point in self._originalPoints:
         points.InsertNextPoint(point)
                
     self._parametricSpline = vtk.vtkParametricSpline()
     self._parametricSpline.SetPoints(points)
     
     self._parametricFuntionSource = vtk.vtkParametricFunctionSource()
     self._parametricFuntionSource.SetParametricFunction(self._parametricSpline)
     self._parametricFuntionSource.SetUResolution(100)
     
     self._tubeFilter = vtk.vtkTubeFilter()
     self._tubeFilter.SetNumberOfSides(10)
     self._tubeFilter.SetRadius(self._radius)
     self._tubeFilter.SetInputConnection(self._parametricFuntionSource.GetOutputPort())
     
     self._tubeActor = []
     self._cubes = []
     i = 0
     for cutter in self._cutters:
         cutter.SetInputConnection(self._tubeFilter.GetOutputPort())
         cutter.Update()
         
         cube = vtk.vtkBox()
         #TODO change imagebounds to planesourceRange
         cube.SetBounds(self._scene.slice[i].getBounds())
         clip = vtk.vtkClipPolyData()
         clip.SetClipFunction(cube)
         clip.SetInputConnection(cutter.GetOutputPort())
         clip.InsideOutOn()
         clip.Update()          
         self._cubes.append(cube)
         
         tubeMapper=vtk.vtkPolyDataMapper()
         tubeMapper.ScalarVisibilityOff()
         tubeMapper.SetInputConnection(clip.GetOutputPort())
         tubeMapper.GlobalImmediateModeRenderingOn()
         
         tubeActor = vtk.vtkActor()
         tubeActor.SetMapper(tubeMapper)
         tubeActor.GetProperty().LightingOff()
         tubeActor.GetProperty().SetColor(self.lineColor)
         tubeActor.SetUserTransform(self._scene.slice[i].resliceTransform.GetInverse())
         
         
         self._tubeActor.append(tubeActor)
         self._scene.renderer.AddActor(tubeActor)
         i = i+1                
Beispiel #14
0
 def makeSpline(self,lst):
     points = vtk.vtkPoints()
     for i in range(len(lst)):
         v=lst[i]
         points.InsertPoint(i,v[0],v[1],v[2])
     spline=vtk.vtkParametricSpline()
     spline.SetPoints(points)
     spline.ClosedOff()
     splineSource=vtk.vtkParametricFunctionSource()
     splineSource.SetParametricFunction(spline)
     mapper=vtk.vtkPolyDataMapper()
     mapper.SetInputConnection(splineSource.GetOutputPort())
     actor = vtk.vtkActor()
     actor.SetMapper(mapper)
     self.ren.AddActor(actor)
Beispiel #15
0
def get_parametric_pts(pts, spline_name="cardinal", num_pts=-1, as_np=True):
    vtkpts = np_to_points(pts)
    spline = vtk.vtkParametricSpline()
    spline.SetXSpline(VTK_SPLINE_DICT[spline_name]())
    spline.SetYSpline(VTK_SPLINE_DICT[spline_name]())
    spline.SetZSpline(VTK_SPLINE_DICT[spline_name]())
    spline.SetPoints(vtkpts)
    ret = vtk.vtkParametricFunctionSource()
    ret.SetParametricFunction(spline)
    if num_pts > 0:
        ret.SetUResolution(num_pts)
    ret.Update()
    if as_np:
        from vtk.util.numpy_support import vtk_to_numpy
        return vtk_to_numpy(ret.GetOutput().GetPoints().GetData())
    return ret
 def drawParametricSpline(self, IDList):
     points = vtk.vtkPoints()
     for i in IDList:
         p = self.pointCloud.vtkPoints.GetPoint(i)
         points.InsertNextPoint(p)
     spline = vtk.vtkParametricSpline()
     spline.SetPoints(points)
     functionSource = vtk.vtkParametricFunctionSource()
     functionSource.SetParametricFunction(spline)
     functionSource.Update()
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInputConnection(functionSource.GetOutputPort())
     actor = vtk.vtkActor()
     actor.SetMapper(mapper)
     self.renderer.AddActor(actor)
     self.refresh_renderer()
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Create three points. 
        origin = [0.0, 0.0, 0.0]
        p0 = [1.0, 0.0, 0.0]
        p1 = [0.0, 1.0, 0.0]
        p2 = [0.0, 1.0, 2.0]
        p3 = [1.0, 2.0, 3.0]

        # Create a vtkPoints object and store the points in it.
        points = vtk.vtkPoints()
        points.InsertNextPoint(origin)
        points.InsertNextPoint(p0)
        points.InsertNextPoint(p1)
        points.InsertNextPoint(p2)
        points.InsertNextPoint(p3)

        spline = vtk.vtkParametricSpline()
        spline.SetPoints(points)

        functionSource = vtk.vtkParametricFunctionSource()
        functionSource.SetParametricFunction(spline)
        functionSource.Update()
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(functionSource.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Beispiel #18
0
def tubeFromCOMList(COMList, radius, debug=False):
    """
    Input: image-space positions along the tube centreline.
    Output: VTK tube
    Note: positions do not have to be continuous - the tube is interpolated in real space
    """
    points = vtk.vtkPoints()
    for i, pt in enumerate(COMList):
        points.InsertPoint(i, pt[0], pt[1], pt[2])

    # Fit a spline to the points
    if debug:
        print("Fitting spline")
    spline = vtk.vtkParametricSpline()
    spline.SetPoints(points)

    functionSource = vtk.vtkParametricFunctionSource()
    functionSource.SetParametricFunction(spline)
    functionSource.SetUResolution(10 * points.GetNumberOfPoints())
    functionSource.Update()

    # Generate the radius scalars
    tubeRadius = vtk.vtkDoubleArray()
    n = functionSource.GetOutput().GetNumberOfPoints()
    tubeRadius.SetNumberOfTuples(n)
    tubeRadius.SetName("TubeRadius")
    for i in range(n):
        # We can set the radius based on the given propagated segmentations in that slice?
        # Typically segmentations are elliptical, this could be an issue so for now a constant
        # radius is used
        tubeRadius.SetTuple1(i, radius)

    # Add the scalars to the polydata
    tubePolyData = vtk.vtkPolyData()
    tubePolyData = functionSource.GetOutput()
    tubePolyData.GetPointData().AddArray(tubeRadius)
    tubePolyData.GetPointData().SetActiveScalars("TubeRadius")

    # Create the tubes
    tuber = vtk.vtkTubeFilter()
    tuber.SetInputData(tubePolyData)
    tuber.SetNumberOfSides(50)
    tuber.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
    tuber.Update()

    return tuber
Beispiel #19
0
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Create source
        pointSource = vtk.vtkPointSource()
        pointSource.SetNumberOfPoints(5)
        pointSource.Update()

        points = pointSource.GetOutput().GetPoints()
        xSpline = vtk.vtkKochanekSpline()
        ySpline = vtk.vtkKochanekSpline()
        zSpline = vtk.vtkKochanekSpline()

        spline = vtk.vtkParametricSpline()
        spline.SetXSpline(xSpline)
        spline.SetYSpline(ySpline)
        spline.SetZSpline(zSpline)
        spline.SetPoints(points)

        functionSource = vtk.vtkParametricFunctionSource()
        functionSource.SetParametricFunction(spline)
        functionSource.Update()

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(functionSource.GetOutputPort())

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Beispiel #20
0
def getControlPoints(points, step):
    ctrl_pts = npy.array([[-1, -1, -1.0]])

    ind = points[:, 2].argsort()
    points_sort = points[ind]

    for cnt in range(3):
        resampled_points = points_sort[npy.where(
            npy.round(points_sort[:, -1]) == cnt)]
        zmin = int(npy.ceil(resampled_points[0, 2]))
        zmax = int(resampled_points[-1, 2])

        count = resampled_points.shape[0]
        points = vtk.vtkPoints()
        for i in range(count):
            points.InsertPoint(i, resampled_points[i, 0],
                               resampled_points[i, 1], resampled_points[i, 2])

        para_spline = vtk.vtkParametricSpline()
        para_spline.SetPoints(points)
        para_spline.ClosedOff()

        znow = zmin
        old_pt = [0.0, 0.0, 0.0]
        numberOfOutputPoints = int((zmax - zmin + 1) * 10)

        for i in range(0, numberOfOutputPoints):
            t = i * 1.0 / numberOfOutputPoints
            pt = [0.0, 0.0, 0.0]
            para_spline.Evaluate([t, t, t], pt, [0] * 9)
            if pt[2] >= znow:
                if pt[2] - znow < znow - old_pt[2]:
                    new_point = pt
                else:
                    new_point = old_pt
                ctrl_pts = npy.append(ctrl_pts,
                                      [[new_point[0], new_point[1], znow]],
                                      axis=0)
                znow += step
                if znow > zmax:
                    break
            old_pt = pt

    ctrl_pts = ctrl_pts[1:, :]
    return ctrl_pts
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Create source
        pointSource = vtk.vtkPointSource()
        pointSource.SetNumberOfPoints(5)
        pointSource.Update()

        points = pointSource.GetOutput().GetPoints()
        xSpline = vtk.vtkKochanekSpline()
        ySpline = vtk.vtkKochanekSpline()
        zSpline = vtk.vtkKochanekSpline()

        spline = vtk.vtkParametricSpline()
        spline.SetXSpline(xSpline)
        spline.SetYSpline(ySpline)
        spline.SetZSpline(zSpline)
        spline.SetPoints(points)

        functionSource = vtk.vtkParametricFunctionSource()
        functionSource.SetParametricFunction(spline)
        functionSource.Update()
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(functionSource.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Beispiel #22
0
def Spline(points, n_points=None):
    """Create a spline from points.

    Parameters
    ----------
    points : np.ndarray
        Array of points to build a spline out of.  Array must be 3D
        and directionally ordered.

    n_points : int, optional
        Number of points to interpolate along the points array.

    Returns
    -------
    spline : pyvista.PolyData
        Line mesh of spline.

    Examples
    --------
    Construct a spline

    >>> import numpy as np
    >>> import pyvista as pv
    >>> theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
    >>> z = np.linspace(-2, 2, 100)
    >>> r = z**2 + 1
    >>> x = r * np.sin(theta)
    >>> y = r * np.cos(theta)
    >>> points = np.column_stack((x, y, z))
    >>> spline = pv.Spline(points, 1000)

    """
    spline_function = vtk.vtkParametricSpline()
    spline_function.SetPoints(pyvista.vtk_points(points, False))

    # get interpolation density
    u_res = n_points
    if u_res is None:
        u_res = points.shape[0]

    u_res -= 1
    spline = surface_from_para(spline_function, u_res)
    return spline.compute_arc_length()
Beispiel #23
0
def getControlPoints(points, step):
    ctrl_pts = npy.array([[-1, -1, -1.0]])
    
    ind = points[:, 2].argsort()
    points_sort = points[ind]
    
    for cnt in range(3):
        resampled_points = points_sort[npy.where(npy.round(points_sort[:, -1]) == cnt)]
        zmin = int(npy.ceil(resampled_points[0, 2]))
        zmax = int(resampled_points[-1, 2])
        
        count = resampled_points.shape[0]
        points = vtk.vtkPoints()
        for i in range(count):
            points.InsertPoint(i, resampled_points[i, 0], resampled_points[i, 1], resampled_points[i, 2])

        para_spline = vtk.vtkParametricSpline()
        para_spline.SetPoints(points)
        para_spline.ClosedOff()
        
        znow = zmin
        old_pt = [0.0, 0.0, 0.0]
        numberOfOutputPoints = int((zmax - zmin + 1) * 10)
        
        for i in range(0, numberOfOutputPoints):
            t = i * 1.0 / numberOfOutputPoints
            pt = [0.0, 0.0, 0.0]
            para_spline.Evaluate([t, t, t], pt, [0] * 9)
            if pt[2] >= znow:
                if pt[2] - znow < znow - old_pt[2]:
                    new_point = pt
                else:
                    new_point = old_pt
                ctrl_pts = npy.append(ctrl_pts, [[new_point[0], new_point[1], znow]], axis = 0)
                znow += step
                if znow > zmax:
                    break
            old_pt = pt
    
    ctrl_pts = ctrl_pts[1:, :]
    return ctrl_pts
Beispiel #24
0
def getPointsOntheSpline(data, center, numberOfOutputPoints):
    ind = sortContourPoints(data)
    data[:, :] = data[ind, :]
        
    count = data.shape[0]
    points = vtk.vtkPoints()
    for j in range(count):
        points.InsertPoint(j, data[j, 0], data[j, 1], 0)
    
    para_spline = vtk.vtkParametricSpline()
    para_spline.SetPoints(points)
    para_spline.ClosedOn()
    
    result = npy.empty([numberOfOutputPoints, 3], dtype = npy.float32)
    
    for k in range(0, numberOfOutputPoints):
        t = k * 1.0 / numberOfOutputPoints
        pt = [0.0, 0.0, 0.0]
        para_spline.Evaluate([t, t, t], pt, [0] * 9)
        result[k, :2] = pt[:2]
        
    result[:, 2] = npy.arctan2(result[:, 1] - center[1], result[:, 0] - center[0])
    ind = result[:, 2].argsort()
    return result[ind, :]
    def setWidgetView(self, widget):
        super(ComparingSurfaceView, self).setWidgetView(widget, [[1, 0, 0], [1, 0, 0], [1, 0, 0]])
        
        point_array_fix = self.parent.getData('fix').pointSet
        point_data_fix = npy.array(point_array_fix.getData('Contour'))
        
        if point_data_fix is None or not point_data_fix.shape[0]:
            return
        zmin = int(npy.min(point_data_fix[:, 2]) + 0.5)
        zmax = int(npy.max(point_data_fix[:, 2]) + 0.5)
        
        point_data_fix[:, :2] *= self.spacing[:2]
        
        for cnt in range(3, 6):
            self.contours.append(vtk.vtkPolyData())
            self.delaunay3D.append(vtk.vtkDelaunay3D())
            self.delaunayMapper.append(vtk.vtkDataSetMapper())
            self.surface_actor.append(vtk.vtkActor())
            
            point_fix = point_data_fix[npy.where(npy.round(point_data_fix[:, -1]) == cnt - 3)]
            if not point_fix.shape[0]:
                continue
                
            self.cells = vtk.vtkCellArray()
            self.points = vtk.vtkPoints()
            l = 0
            for i in range(zmin, zmax + 1):
                data = point_fix[npy.where(npy.round(point_fix[:, 2]) == i)]
                if data is not None:
                    if data.shape[0] == 0:
                        continue
                    count = data.shape[0]
                    points = vtk.vtkPoints()
                    for j in range(count):
                        points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2])
                    
                    para_spline = vtk.vtkParametricSpline()
                    para_spline.SetXSpline(vtk.vtkKochanekSpline())
                    para_spline.SetYSpline(vtk.vtkKochanekSpline())
                    para_spline.SetZSpline(vtk.vtkKochanekSpline())
                    para_spline.SetPoints(points)
                    para_spline.ClosedOn()
                    
                    # The number of output points set to 10 times of input points
                    numberOfOutputPoints = count * 10
                    self.cells.InsertNextCell(numberOfOutputPoints)
                    for k in range(0, numberOfOutputPoints):
                        t = k * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[0] != pt[0]:
                            print pt
                            continue
                        self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                        self.cells.InsertCellPoint(l)
                        l += 1

            self.contours[cnt].SetPoints(self.points)
            self.contours[cnt].SetPolys(self.cells)
            
            self.delaunay3D[cnt].SetInput(self.contours[cnt])
            self.delaunay3D[cnt].SetAlpha(2)
            
            self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput())
            
            self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt])
            self.surface_actor[cnt].GetProperty().SetDiffuseColor(0, 0, 1)
            self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1)
            self.surface_actor[cnt].GetProperty().SetSpecular(0.4)
            self.surface_actor[cnt].GetProperty().SetSpecularPower(50)
            
            self.renderer.AddViewProp(self.surface_actor[cnt])
        
        self.render_window.Render()
Beispiel #26
0
    def setWidgetView(self, widget):
        super(SurfaceGifView, self).setWidgetView(widget)
        
        self.point_array_move = self.parent.getData('move').pointSet
        self.point_data_move = npy.array(self.point_array_move.getData('Contour'))
        self.point_array_fix = self.parent.getData('fix').pointSet
        self.point_data_fix = npy.array(self.point_array_fix.getData('Contour'))
        
        if self.point_data_move is None or not self.point_data_move.shape[0]:
            return
        if self.point_data_fix is None or not self.point_data_fix.shape[0]:
            return
        
        #self.spacing = [1, 1, 1]
        self.spacing = self.parent.getData().getResolution().tolist()
        self.spacing_move = self.parent.getData('move').getResolution().tolist()
        self.tmp_space = self.spacing[-1]
        self.spacing = [float(x) / self.tmp_space for x in self.spacing]
        #point_data_move[:, :2] *= self.spacing_move[:2]
        self.point_data_fix[:, :2] *= self.spacing[:2]
        self.zmin = int(npy.min(self.point_data_fix[:, 2]) + 0.5)
        self.zmax = int(npy.max(self.point_data_fix[:, 2]) + 0.5)
        
        self.renderer = vtk.vtkRenderer()
        self.render_window = widget.GetRenderWindow()
        self.render_window.AddRenderer(self.renderer)
        self.window_interactor = vtk.vtkRenderWindowInteractor()
        self.render_window.SetInteractor(self.window_interactor)
        
        self.contours = []
        self.delaunay3D = []
        self.delaunayMapper = []
        self.surface_actor = []
        
        for cnt in range(3):
            self.contours.append(vtk.vtkPolyData())
            self.delaunay3D.append(vtk.vtkDelaunay3D())
            self.delaunayMapper.append(vtk.vtkDataSetMapper())
            self.surface_actor.append(vtk.vtkActor())
            
            point_fix = self.point_data_fix[npy.where(npy.round(self.point_data_fix[:, -1]) == cnt)]
            if not point_fix.shape[0]:
                continue
                
            self.cells = vtk.vtkCellArray()
            self.points = vtk.vtkPoints()
            l = 0
            for i in range(self.zmin, self.zmax + 1):
                data = point_fix[npy.where(npy.round(point_fix[:, 2]) == i)]
                if data is not None:
                    if data.shape[0] == 0:
                        continue
                    count = data.shape[0]
                    points = vtk.vtkPoints()
                    for j in range(count):
                        points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2])
                    
                    para_spline = vtk.vtkParametricSpline()
                    para_spline.SetPoints(points)
                    para_spline.ClosedOn()
                    
                    # The number of output points set to 10 times of input points
                    numberOfOutputPoints = count * 10
                    self.cells.InsertNextCell(numberOfOutputPoints)
                    for k in range(0, numberOfOutputPoints):
                        t = k * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[0] != pt[0]:
                            print pt
                            continue
                        self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                        self.cells.InsertCellPoint(l)
                        l += 1

            self.contours[cnt].SetPoints(self.points)
            self.contours[cnt].SetPolys(self.cells)
            
            self.delaunay3D[cnt].SetInput(self.contours[cnt])
            self.delaunay3D[cnt].SetAlpha(2)
            
            self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput())
            
            self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt])
            self.surface_actor[cnt].GetProperty().SetDiffuseColor(0, 0, 1)
            self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1)
            self.surface_actor[cnt].GetProperty().SetSpecular(0.4)
            self.surface_actor[cnt].GetProperty().SetSpecularPower(50)
            
            self.renderer.AddViewProp(self.surface_actor[cnt])
        
        self.renderer.ResetCamera()
        point = self.renderer.GetActiveCamera().GetFocalPoint()
        dis = self.renderer.GetActiveCamera().GetDistance()
        self.renderer.GetActiveCamera().SetViewUp(0, 0, 1)
        self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis, point[2])
        self.renderer.ResetCameraClippingRange()
        self.render_window.Render()
        
        # Manually set to trackball style
        self.window_interactor.SetKeyCode('t')
        self.window_interactor.CharEvent()
        self.window_interactor.GetInteractorStyle().AddObserver("KeyPressEvent", self.KeyPressCallback)
        self.window_interactor.GetInteractorStyle().AddObserver("CharEvent", self.KeyPressCallback)
        
        self.tmp_data_move = npy.array(self.point_data_move)
        self.tmp_data_move[:, :3] *= self.spacing_move[:3]
        
        self.spacing_move = [float(x) / self.spacing_move[-1] for x in self.spacing_move]
        self.point_data_move[:, :2] *= self.spacing_move[:2]
        self.zmin = int(npy.min(self.point_data_move[:, 2]) + 0.5)
        self.zmax = int(npy.max(self.point_data_move[:, 2]) + 0.5)
        
        self.point_data_result = self.point_data_move
        
        for cnt in range(3, 6):
            self.contours.append(vtk.vtkPolyData())
            self.delaunay3D.append(vtk.vtkDelaunay3D())
            self.delaunayMapper.append(vtk.vtkDataSetMapper())
            self.surface_actor.append(vtk.vtkActor())
            
            point_result = self.point_data_result[npy.where(npy.round(self.point_data_result[:, -1]) == cnt - 3)]
            point_move = self.point_data_move[npy.where(npy.round(self.point_data_move[:, -1]) == cnt - 3)]
            if not point_result.shape[0]:
                continue
                
            self.cells = vtk.vtkCellArray()
            self.points = vtk.vtkPoints()
            l = 0
            for i in range(self.zmin, self.zmax + 1):
                data = point_result[npy.where(npy.round(point_move[:, 2]) == i)]
                if data is not None:
                    if data.shape[0] == 0:
                        continue
                    count = data.shape[0]
                    points = vtk.vtkPoints()
                    for j in range(count):
                        points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2])
                    
                    para_spline = vtk.vtkParametricSpline()
                    para_spline.SetXSpline(vtk.vtkKochanekSpline())
                    para_spline.SetYSpline(vtk.vtkKochanekSpline())
                    para_spline.SetZSpline(vtk.vtkKochanekSpline())
                    para_spline.SetPoints(points)
                    para_spline.ClosedOn()
                    
                    # The number of output points set to 10 times of input points
                    numberOfOutputPoints = count * 10
                    self.cells.InsertNextCell(numberOfOutputPoints)
                    for k in range(0, numberOfOutputPoints):
                        t = k * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[0] != pt[0]:
                            print pt
                            continue
                        self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                        self.cells.InsertCellPoint(l)
                        l += 1

            self.contours[cnt].SetPoints(self.points)
            self.contours[cnt].SetPolys(self.cells)
            
            self.delaunay3D[cnt].SetInput(self.contours[cnt])
            self.delaunay3D[cnt].SetAlpha(2)
            
            self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput())
            
            self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt])
            self.surface_actor[cnt].GetProperty().SetDiffuseColor(1, 0, 0)
            self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1)
            self.surface_actor[cnt].GetProperty().SetSpecular(0.4)
            self.surface_actor[cnt].GetProperty().SetSpecularPower(50)
            
            self.renderer.AddViewProp(self.surface_actor[cnt])
        
        self.render_window.Render()
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.2, 0.3, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        points = vtk.vtkPoints()
        points.InsertPoint(0, 1, 0, 0)
        points.InsertPoint(1, 2, 0, 0)
        points.InsertPoint(2, 3, 1, 0)
        points.InsertPoint(3, 4, 1, 0)
        points.InsertPoint(4, 5, 0, 0)
        points.InsertPoint(5, 6, 0, 0)

        # Fit a spline to the points
        spline = vtk.vtkParametricSpline()
        spline.SetPoints(points)
        functionSource = vtk.vtkParametricFunctionSource()
        functionSource.SetParametricFunction(spline)
        functionSource.SetUResolution(10 * points.GetNumberOfPoints())
        functionSource.Update()

        # Interpolate the scalars
        interpolatedRadius = vtk.vtkTupleInterpolator()
        interpolatedRadius.SetInterpolationTypeToLinear()
        interpolatedRadius.SetNumberOfComponents(1)
        #interpolatedRadius.AddTuple(0, [0.2,]) ### ??? Donesn't work for Python
        #interpolatedRadius.AddTuple(1, (0.2,))
        #interpolatedRadius.AddTuple(2, (0.2,))
        #interpolatedRadius.AddTuple(3, (0.1,))
        #interpolatedRadius.AddTuple(4, (0.1,))
        #interpolatedRadius.AddTuple(5, (0.1,))

        # Generate the radius scalars
        tubeRadius = vtk.vtkDoubleArray()
        n = functionSource.GetOutput().GetNumberOfPoints()
        tubeRadius.SetNumberOfTuples(n)
        tubeRadius.SetName("TubeRadius")

        tMin = interpolatedRadius.GetMinimumT()
        tMax = interpolatedRadius.GetMaximumT()
        for i in range(n):
            t = (tMax - tMin) / (n - 1) * i + tMin
            r = 1.0
            #interpolatedRadius.InterpolateTuple(t, r) ### ??? Donesn't work for Python
            tubeRadius.SetTuple1(i, r)

        # Add the scalars to the polydata
        tubePolyData = functionSource.GetOutput()
        tubePolyData.GetPointData().AddArray(tubeRadius)
        tubePolyData.GetPointData().SetActiveScalars("TubeRadius")

        # Create the tubes
        tuber = vtk.vtkTubeFilter()
        tuber.SetInput(tubePolyData)
        tuber.SetNumberOfSides(20)
        tuber.SetVaryRadiusToVaryRadiusByAbsoluteScalar()

        # Setup actors and mappers
        lineMapper = vtk.vtkPolyDataMapper()
        lineMapper.SetInput(tubePolyData)
        lineMapper.SetScalarRange(tubePolyData.GetScalarRange())

        tubeMapper = vtk.vtkPolyDataMapper()
        tubeMapper.SetInputConnection(tuber.GetOutputPort())
        tubeMapper.SetScalarRange(tubePolyData.GetScalarRange())

        lineActor = vtk.vtkActor()
        lineActor.SetMapper(lineMapper)
        tubeActor = vtk.vtkActor()
        tubeActor.SetMapper(tubeMapper)

        self.ren.AddActor(tubeActor)
        self.ren.AddActor(lineActor)
        self.ren.ResetCamera()

        self._initialized = False
def main():
    named_colors = vtk.vtkNamedColors()

    # Make a 32 x 32 grid.
    size = 32

    # Define z values for the topography.
    # Comment out the following line if you want a different random
    #  distribution each time the script is run.
    np.random.seed(3)
    topography = np.random.randint(0, 5, (size, size))

    # Define points, triangles and colors
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    points = vtk.vtkPoints()
    triangles = vtk.vtkCellArray()

    # Build the meshgrid manually.
    count = 0
    for i in range(size - 1):
        for j in range(size - 1):
            z1 = topography[i][j]
            z2 = topography[i][j + 1]
            z3 = topography[i + 1][j]

            # Triangle 1
            points.InsertNextPoint(i, j, z1)
            points.InsertNextPoint(i, (j + 1), z2)
            points.InsertNextPoint((i + 1), j, z3)

            triangle = vtk.vtkTriangle()
            triangle.GetPointIds().SetId(0, count)
            triangle.GetPointIds().SetId(1, count + 1)
            triangle.GetPointIds().SetId(2, count + 2)

            triangles.InsertNextCell(triangle)

            z1 = topography[i][j + 1]
            z2 = topography[i + 1][j + 1]
            z3 = topography[i + 1][j]

            # Triangle 2
            points.InsertNextPoint(i, (j + 1), z1)
            points.InsertNextPoint((i + 1), (j + 1), z2)
            points.InsertNextPoint((i + 1), j, z3)

            triangle = vtk.vtkTriangle()
            triangle.GetPointIds().SetId(0, count + 3)
            triangle.GetPointIds().SetId(1, count + 4)
            triangle.GetPointIds().SetId(2, count + 5)

            count += 6

            triangles.InsertNextCell(triangle)

            # Add some color.
            r = [int(i / float(size) * 255), int(j / float(size) * 255), 0]
            colors.InsertNextTypedTuple(r)
            colors.InsertNextTypedTuple(r)
            colors.InsertNextTypedTuple(r)
            colors.InsertNextTypedTuple(r)
            colors.InsertNextTypedTuple(r)
            colors.InsertNextTypedTuple(r)

    # Create a polydata object.
    trianglePolyData = vtk.vtkPolyData()

    # Add the geometry and topology to the polydata.
    trianglePolyData.SetPoints(points)
    trianglePolyData.GetPointData().SetScalars(colors)
    trianglePolyData.SetPolys(triangles)

    # Clean the polydata so that the edges are shared!
    cleanPolyData = vtk.vtkCleanPolyData()
    cleanPolyData.SetInputData(trianglePolyData)

    # Use a filter to smooth the data (will add triangles and smooth).
    smooth_loop = vtk.vtkLoopSubdivisionFilter()
    smooth_loop.SetNumberOfSubdivisions(3)
    smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort())

    # Create a mapper and actor for smoothed dataset.
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(smooth_loop.GetOutputPort())
    actor_loop = vtk.vtkActor()
    actor_loop.SetMapper(mapper)
    actor_loop.GetProperty().SetInterpolationToFlat()

    # Update the pipeline so that vtkCellLocator finds cells!
    smooth_loop.Update()

    # Define a cellLocator to be able to compute intersections between lines.
    # and the surface
    locator = vtk.vtkCellLocator()
    locator.SetDataSet(smooth_loop.GetOutput())
    locator.BuildLocator()

    maxloop = 1000
    dist = 20.0 / maxloop
    tolerance = 0.001

    # Make a list of points. Each point is the intersection of a vertical line
    # defined by p1 and p2 and the surface.
    points = vtk.vtkPoints()
    for i in range(maxloop):
        p1 = [2 + i * dist, 16, -1]
        p2 = [2 + i * dist, 16, 6]

        # Outputs (we need only pos which is the x, y, z position
        # of the intersection)
        t = vtk.mutable(0)
        pos = [0.0, 0.0, 0.0]
        pcoords = [0.0, 0.0, 0.0]
        subId = vtk.mutable(0)
        locator.IntersectWithLine(p1, p2, tolerance, t, pos, pcoords, subId)

        # Add a slight offset in z.
        pos[2] += 0.01
        # Add the x, y, z position of the intersection.
        points.InsertNextPoint(pos)

    # Create a spline and add the points
    spline = vtk.vtkParametricSpline()
    spline.SetPoints(points)
    functionSource = vtk.vtkParametricFunctionSource()
    functionSource.SetUResolution(maxloop)
    functionSource.SetParametricFunction(spline)

    # Map the spline
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(functionSource.GetOutputPort())

    # Define the line actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(named_colors.GetColor3d("Red"))
    actor.GetProperty().SetLineWidth(3)

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add actors and render
    renderer.AddActor(actor)
    renderer.AddActor(actor_loop)

    renderer.SetBackground(named_colors.GetColor3d("Cornsilk"))
    renderWindow.SetSize(800, 800)
    renderWindow.Render()
    renderer.GetActiveCamera().SetPosition(-32.471276, 53.258788, 61.209332)
    renderer.GetActiveCamera().SetFocalPoint(15.500000, 15.500000, 2.000000)
    renderer.GetActiveCamera().SetViewUp(0.348057, -0.636740, 0.688055)
    renderer.ResetCameraClippingRange()
    renderWindow.Render()

    renderWindowInteractor.Start()
def main():
    # Generate  some random points
    numberOfPoints = 8
    pointSource = vtk.vtkPointSource()
    pointSource.SetNumberOfPoints(numberOfPoints)
    pointSource.Update()

    points = pointSource.GetOutput().GetPoints()

    spline = vtk.vtkParametricSpline()
    spline.SetPoints(points)

    functionSource = vtk.vtkParametricFunctionSource()
    functionSource.SetParametricFunction(spline)
    functionSource.SetUResolution(10 * numberOfPoints)
    functionSource.SetVResolution(10 * numberOfPoints)
    functionSource.SetWResolution(10 * numberOfPoints)

    # Create the frame
    frame = vtk.vtkFrenetSerretFrame()
    frame.SetInputConnection(functionSource.GetOutputPort())
    frame.ConsistentNormalsOn()
    frame.Update()

    # Setup renderer
    renderer =  vtk.vtkRenderer()
    renderer.SetBackground(.4, .5, .7)
    
    # for each vector, create a Glyph3D and DeepCopy the output
    arrow_radius = .05
    
    for vector, color in zip(["FSNormals", "FSTangents","FSBinormals"], [(0.8900, 0.8100, 0.3400), (1.0000, 0.3882, 0.2784), (0.1804,0.5451,0.3412)]):
        polyData = MakeGlyphs(frame, arrow_radius, vector)
    
        # Setup actors and mappers
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputData(normalsPolyData)

        glyphActor = vtk.vtkActor()
        glyphActor.SetMapper(mapper)
        glyphActor.GetProperty().SetColor(color)
        
        renderer.AddActor(glyphActor)

    # Display spline
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(functionSource.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    renderer.AddActor(actor)

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

    # Pick a good view
    renderer.ResetCamera()
    renderer.GetActiveCamera().Azimuth(120)
    renderer.GetActiveCamera().Elevation(30)
    renderer.GetActiveCamera().Dolly(1.8)
    renderer.ResetCameraClippingRange()

    renderWindow.SetSize(640, 480)
    renderWindow.Render()
    renderWindowInteractor.Start()
Beispiel #30
0
    # Outputs (we need only pos which is the x, y, z position
    # of the intersection)
    t = vtk.mutable(0)
    pos = [0.0, 0.0, 0.0]
    pcoords = [0.0, 0.0, 0.0]
    subId = vtk.mutable(0)
    locator.IntersectWithLine(p1, p2, tolerance, t, pos, pcoords, subId)

    # Add a slight offset in z
    pos[2] += 0.01
    # Add the x, y, z position of the intersection
    points.InsertNextPoint(pos)

# Create a spline and add the points
spline = vtk.vtkParametricSpline()
spline.SetPoints(points)
functionSource = vtk.vtkParametricFunctionSource()
functionSource.SetUResolution(maxloop)
functionSource.SetParametricFunction(spline)

# Map the spline
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(functionSource.GetOutputPort())

# Define the line actor
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor([1.0, 0.0, 0.0])
actor.GetProperty().SetLineWidth(3)
    def testParametricFunctions(self):
        # ------------------------------------------------------------
        # Get a texture
        # ------------------------------------------------------------
        textureReader = vtk.vtkJPEGReader()
        textureReader.SetFileName(VTK_DATA_ROOT + "/Data/beach.jpg")
        texture = vtk.vtkTexture()
        texture.SetInputConnection(textureReader.GetOutputPort())

        # ------------------------------------------------------------
        # For each parametric surface:
        # 1) Create it
        # 2) Assign mappers and actors
        # 3) Position this object
        # 5) Add a label
        # ------------------------------------------------------------

        # ------------------------------------------------------------
        # Create a torus
        # ------------------------------------------------------------
        torus = vtk.vtkParametricTorus()
        torusSource = vtk.vtkParametricFunctionSource()
        torusSource.SetParametricFunction(torus)
        torusSource.SetScalarModeToPhase()

        torusMapper = vtk.vtkPolyDataMapper()
        torusMapper.SetInputConnection(torusSource.GetOutputPort())
        torusMapper.SetScalarRange(0, 360)

        torusActor = vtk.vtkActor()
        torusActor.SetMapper(torusMapper)
        torusActor.SetPosition(0, 12, 0)

        torusTextMapper = vtk.vtkTextMapper()
        torusTextMapper.SetInput("Torus")
        torusTextMapper.GetTextProperty().SetJustificationToCentered()
        torusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        torusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        torusTextMapper.GetTextProperty().SetFontSize(14)
        torusTextActor = vtk.vtkActor2D()
        torusTextActor.SetMapper(torusTextMapper)
        torusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        torusTextActor.GetPositionCoordinate().SetValue(0, 9.5, 0)

        # ------------------------------------------------------------
        # Create a klein bottle
        # ------------------------------------------------------------
        klein = vtk.vtkParametricKlein()
        kleinSource = vtk.vtkParametricFunctionSource()
        kleinSource.SetParametricFunction(klein)
        kleinSource.SetScalarModeToU0V0()

        kleinMapper = vtk.vtkPolyDataMapper()
        kleinMapper.SetInputConnection(kleinSource.GetOutputPort())
        kleinMapper.SetScalarRange(0, 3)

        kleinActor = vtk.vtkActor()
        kleinActor.SetMapper(kleinMapper)
        kleinActor.SetPosition(8, 10.5, 0)

        kleinTextMapper = vtk.vtkTextMapper()
        kleinTextMapper.SetInput("Klein")
        kleinTextMapper.GetTextProperty().SetJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        kleinTextMapper.GetTextProperty().SetFontSize(14)
        kleinTextActor = vtk.vtkActor2D()
        kleinTextActor.SetMapper(kleinTextMapper)
        kleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        kleinTextActor.GetPositionCoordinate().SetValue(8, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Figure-8 Klein
        # ------------------------------------------------------------
        klein2 = vtk.vtkParametricFigure8Klein()
        klein2Source = vtk.vtkParametricFunctionSource()
        klein2Source.SetParametricFunction(klein2)
        klein2Source.GenerateTextureCoordinatesOn()

        klein2Mapper = vtk.vtkPolyDataMapper()
        klein2Mapper.SetInputConnection(klein2Source.GetOutputPort())
        klein2Mapper.SetScalarRange(0, 3)

        klein2Actor = vtk.vtkActor()
        klein2Actor.SetMapper(klein2Mapper)
        klein2Actor.SetPosition(16, 12, 0)
        klein2Actor.SetTexture(texture)


        fig8KleinTextMapper = vtk.vtkTextMapper()
        fig8KleinTextMapper.SetInput("Fig-8.Klein")
        fig8KleinTextMapper.GetTextProperty().SetJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        fig8KleinTextMapper.GetTextProperty().SetFontSize(14)
        fig8KleinTextActor = vtk.vtkActor2D()
        fig8KleinTextActor.SetMapper(fig8KleinTextMapper)
        fig8KleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        fig8KleinTextActor.GetPositionCoordinate().SetValue(16, 9.5, 0)

        # ------------------------------------------------------------
        # Create a mobius strip
        # ------------------------------------------------------------
        mobius = vtk.vtkParametricMobius()
        mobiusSource = vtk.vtkParametricFunctionSource()
        mobiusSource.SetParametricFunction(mobius)
        mobiusSource.GenerateTextureCoordinatesOn()

        mobiusMapper = vtk.vtkPolyDataMapper()
        mobiusMapper.SetInputConnection(mobiusSource.GetOutputPort())

        mobiusActor = vtk.vtkActor()
        mobiusActor.SetMapper(mobiusMapper)
        mobiusActor.RotateX(45)
        mobiusActor.SetPosition(24, 12, 0)
        mobiusActor.SetTexture(texture)

        mobiusTextMapper = vtk.vtkTextMapper()
        mobiusTextMapper.SetInput("Mobius")
        mobiusTextMapper.GetTextProperty().SetJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        mobiusTextMapper.GetTextProperty().SetFontSize(14)
        mobiusTextActor = vtk.vtkActor2D()
        mobiusTextActor.SetMapper(mobiusTextMapper)
        mobiusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        mobiusTextActor.GetPositionCoordinate().SetValue(24, 9.5, 0)

        # ------------------------------------------------------------
        # Create a super toroid
        # ------------------------------------------------------------
        toroid = vtk.vtkParametricSuperToroid()
        toroid.SetN1(2)
        toroid.SetN2(3)
        toroidSource = vtk.vtkParametricFunctionSource()
        toroidSource.SetParametricFunction(toroid)
        toroidSource.SetScalarModeToU()

        toroidMapper = vtk.vtkPolyDataMapper()
        toroidMapper.SetInputConnection(toroidSource.GetOutputPort())
        toroidMapper.SetScalarRange(0, 6.28)

        toroidActor = vtk.vtkActor()
        toroidActor.SetMapper(toroidMapper)
        toroidActor.SetPosition(0, 4, 0)

        superToroidTextMapper = vtk.vtkTextMapper()
        superToroidTextMapper.SetInput("Super.Toroid")
        superToroidTextMapper.GetTextProperty().SetJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superToroidTextMapper.GetTextProperty().SetFontSize(14)
        superToroidTextActor = vtk.vtkActor2D()
        superToroidTextActor.SetMapper(superToroidTextMapper)
        superToroidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superToroidTextActor.GetPositionCoordinate().SetValue(0, 1.5, 0)

        # ------------------------------------------------------------
        # Create a super ellipsoid
        # ------------------------------------------------------------
        superEllipsoid = vtk.vtkParametricSuperEllipsoid()
        superEllipsoid.SetXRadius(1.25)
        superEllipsoid.SetYRadius(1.5)
        superEllipsoid.SetZRadius(1.0)
        superEllipsoid.SetN1(1.1)
        superEllipsoid.SetN2(1.75)
        superEllipsoidSource = vtk.vtkParametricFunctionSource()
        superEllipsoidSource.SetParametricFunction(superEllipsoid)
        superEllipsoidSource.SetScalarModeToV()

        superEllipsoidMapper = vtk.vtkPolyDataMapper()
        superEllipsoidMapper.SetInputConnection(superEllipsoidSource.GetOutputPort())
        superEllipsoidMapper.SetScalarRange(0, 3.14)

        superEllipsoidActor = vtk.vtkActor()
        superEllipsoidActor.SetMapper(superEllipsoidMapper)
        superEllipsoidActor.SetPosition(8, 4, 0)

        superEllipsoidTextMapper = vtk.vtkTextMapper()
        superEllipsoidTextMapper.SetInput("Super.Ellipsoid")
        superEllipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superEllipsoidTextMapper.GetTextProperty().SetFontSize(14)
        superEllipsoidTextActor = vtk.vtkActor2D()
        superEllipsoidTextActor.SetMapper(superEllipsoidTextMapper)
        superEllipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superEllipsoidTextActor.GetPositionCoordinate().SetValue(8, 1.5, 0)

        # ------------------------------------------------------------
        # Create an open 1D spline
        # ------------------------------------------------------------
        math = vtk.vtkMath()
        inputPoints = vtk.vtkPoints()
        for i in range(0, 10):
            x = math.Random(-1, 1)
            y = math.Random(-1, 1)
            z = math.Random(-1, 1)
            inputPoints.InsertPoint(i,x,y,z)

        spline = vtk.vtkParametricSpline()
        spline.SetPoints(inputPoints)
        spline.ClosedOff()
        splineSource = vtk.vtkParametricFunctionSource()
        splineSource.SetParametricFunction(spline)

        splineMapper = vtk.vtkPolyDataMapper()
        splineMapper.SetInputConnection(splineSource.GetOutputPort())

        splineActor = vtk.vtkActor()
        splineActor.SetMapper(splineMapper)
        splineActor.SetPosition(16, 4, 0)
        splineActor.GetProperty().SetColor(0, 0, 0)

        splineTextMapper = vtk.vtkTextMapper()
        splineTextMapper.SetInput("Open.Spline")
        splineTextMapper.GetTextProperty().SetJustificationToCentered()
        splineTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        splineTextMapper.GetTextProperty().SetColor(1, 0, 0)
        splineTextMapper.GetTextProperty().SetFontSize(14)
        splineTextActor = vtk.vtkActor2D()
        splineTextActor.SetMapper(splineTextMapper)
        splineTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        splineTextActor.GetPositionCoordinate().SetValue(16, 1.5, 0)

        # ------------------------------------------------------------
        # Create a closed 1D spline
        # ------------------------------------------------------------
        spline2 = vtk.vtkParametricSpline()
        spline2.SetPoints(inputPoints)
        spline2.ClosedOn()
        spline2Source = vtk.vtkParametricFunctionSource()
        spline2Source.SetParametricFunction(spline2)

        spline2Mapper = vtk.vtkPolyDataMapper()
        spline2Mapper.SetInputConnection(spline2Source.GetOutputPort())

        spline2Actor = vtk.vtkActor()
        spline2Actor.SetMapper(spline2Mapper)
        spline2Actor.SetPosition(24, 4, 0)
        spline2Actor.GetProperty().SetColor(0, 0, 0)

        spline2TextMapper = vtk.vtkTextMapper()
        spline2TextMapper.SetInput("Closed.Spline")
        spline2TextMapper.GetTextProperty().SetJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetColor(1, 0, 0)
        spline2TextMapper.GetTextProperty().SetFontSize(14)
        spline2TextActor = vtk.vtkActor2D()
        spline2TextActor.SetMapper(spline2TextMapper)
        spline2TextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        spline2TextActor.GetPositionCoordinate().SetValue(24, 1.5, 0)

        # ------------------------------------------------------------
        # Create a spiral conic
        # ------------------------------------------------------------
        sconic = vtk.vtkParametricConicSpiral()
        sconic.SetA(0.8)
        sconic.SetB(2.5)
        sconic.SetC(0.4)
        sconicSource = vtk.vtkParametricFunctionSource()
        sconicSource.SetParametricFunction(sconic)
        sconicSource.SetScalarModeToDistance()

        sconicMapper = vtk.vtkPolyDataMapper()
        sconicMapper.SetInputConnection(sconicSource.GetOutputPort())
        sconicActor = vtk.vtkActor()
        sconicActor.SetMapper(sconicMapper)
        sconicMapper.SetScalarRange(0, 9)
        sconicActor.SetPosition(0, -4, 0)
        sconicActor.SetScale(1.2, 1.2, 1.2)

        sconicTextMapper = vtk.vtkTextMapper()
        sconicTextMapper.SetInput("Spiral.Conic")
        sconicTextMapper.GetTextProperty().SetJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetColor(1, 0, 0)
        sconicTextMapper.GetTextProperty().SetFontSize(14)
        sconicTextActor = vtk.vtkActor2D()
        sconicTextActor.SetMapper(sconicTextMapper)
        sconicTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        sconicTextActor.GetPositionCoordinate().SetValue(0, -6.5, 0)

        # ------------------------------------------------------------
        # Create Boy's surface
        # ------------------------------------------------------------
        boy = vtk.vtkParametricBoy()
        boySource = vtk.vtkParametricFunctionSource()
        boySource.SetParametricFunction(boy)
        boySource.SetScalarModeToModulus()

        boyMapper = vtk.vtkPolyDataMapper()
        boyMapper.SetInputConnection(boySource.GetOutputPort())
        boyMapper.SetScalarRange(0, 2)
        boyActor = vtk.vtkActor()
        boyActor.SetMapper(boyMapper)
        boyActor.SetPosition(8, -4, 0)
        boyActor.SetScale(1.5, 1.5, 1.5)

        boyTextMapper = vtk.vtkTextMapper()
        boyTextMapper.SetInput("Boy")
        boyTextMapper.GetTextProperty().SetJustificationToCentered()
        boyTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        boyTextMapper.GetTextProperty().SetColor(1, 0, 0)
        boyTextMapper.GetTextProperty().SetFontSize(14)
        boyTextActor = vtk.vtkActor2D()
        boyTextActor.SetMapper(boyTextMapper)
        boyTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        boyTextActor.GetPositionCoordinate().SetValue(8, -6.5, 0)

        # ------------------------------------------------------------
        # Create a cross cap
        # ------------------------------------------------------------
        crossCap = vtk.vtkParametricCrossCap()
        crossCapSource = vtk.vtkParametricFunctionSource()
        crossCapSource.SetParametricFunction(crossCap)
        crossCapSource.SetScalarModeToY()

        crossCapMapper = vtk.vtkPolyDataMapper()
        crossCapMapper.SetInputConnection(crossCapSource.GetOutputPort())
        crossCapActor = vtk.vtkActor()
        crossCapActor.SetMapper(crossCapMapper)
        crossCapActor.RotateX(65)
        crossCapActor.SetPosition(16, -4, 0)
        crossCapActor.SetScale(1.5, 1.5, 1.5)

        crossCapTextMapper = vtk.vtkTextMapper()
        crossCapTextMapper.SetInput("Cross.Cap")
        crossCapTextMapper.GetTextProperty().SetJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetColor(1, 0, 0)
        crossCapTextMapper.GetTextProperty().SetFontSize(14)
        crossCapTextActor = vtk.vtkActor2D()
        crossCapTextActor.SetMapper(crossCapTextMapper)
        crossCapTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        crossCapTextActor.GetPositionCoordinate().SetValue(16, -6.5, 0)

        # ------------------------------------------------------------
        # Create Dini's surface
        # ------------------------------------------------------------
        dini = vtk.vtkParametricDini()
        diniSource = vtk.vtkParametricFunctionSource()
        diniSource.SetScalarModeToDistance()
        diniSource.SetParametricFunction(dini)

        diniMapper = vtk.vtkPolyDataMapper()
        diniMapper.SetInputConnection(diniSource.GetOutputPort())

        diniActor = vtk.vtkActor()
        diniActor.SetMapper(diniMapper)
        diniActor.RotateX(-90)
        diniActor.SetPosition(24, -3, 0)
        diniActor.SetScale(1.5, 1.5, 0.5)

        diniTextMapper = vtk.vtkTextMapper()
        diniTextMapper.SetInput("Dini")
        diniTextMapper.GetTextProperty().SetJustificationToCentered()
        diniTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        diniTextMapper.GetTextProperty().SetColor(1, 0, 0)
        diniTextMapper.GetTextProperty().SetFontSize(14)
        diniTextActor = vtk.vtkActor2D()
        diniTextActor.SetMapper(diniTextMapper)
        diniTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        diniTextActor.GetPositionCoordinate().SetValue(24, -6.5, 0)

        # ------------------------------------------------------------
        # Create Enneper's surface
        # ------------------------------------------------------------
        enneper = vtk.vtkParametricEnneper()
        enneperSource = vtk.vtkParametricFunctionSource()
        enneperSource.SetParametricFunction(enneper)
        enneperSource.SetScalarModeToQuadrant()

        enneperMapper = vtk.vtkPolyDataMapper()
        enneperMapper.SetInputConnection(enneperSource.GetOutputPort())
        enneperMapper.SetScalarRange(1, 4)

        enneperActor = vtk.vtkActor()
        enneperActor.SetMapper(enneperMapper)
        enneperActor.SetPosition(0, -12, 0)
        enneperActor.SetScale(0.25, 0.25, 0.25)

        enneperTextMapper = vtk.vtkTextMapper()
        enneperTextMapper.SetInput("Enneper")
        enneperTextMapper.GetTextProperty().SetJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetColor(1, 0, 0)
        enneperTextMapper.GetTextProperty().SetFontSize(14)
        enneperTextActor = vtk.vtkActor2D()
        enneperTextActor.SetMapper(enneperTextMapper)
        enneperTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        enneperTextActor.GetPositionCoordinate().SetValue(0, -14.5, 0)

        # ------------------------------------------------------------
        # Create an ellipsoidal surface
        # ------------------------------------------------------------
        ellipsoid = vtk.vtkParametricEllipsoid()
        ellipsoid.SetXRadius(1)
        ellipsoid.SetYRadius(0.75)
        ellipsoid.SetZRadius(0.5)
        ellipsoidSource = vtk.vtkParametricFunctionSource()
        ellipsoidSource.SetParametricFunction(ellipsoid)
        ellipsoidSource.SetScalarModeToZ()

        ellipsoidMapper = vtk.vtkPolyDataMapper()
        ellipsoidMapper.SetInputConnection(ellipsoidSource.GetOutputPort())
        ellipsoidMapper.SetScalarRange(-0.5, 0.5)

        ellipsoidActor = vtk.vtkActor()
        ellipsoidActor.SetMapper(ellipsoidMapper)
        ellipsoidActor.SetPosition(8, -12, 0)
        ellipsoidActor.SetScale(1.5, 1.5, 1.5)

        ellipsoidTextMapper = vtk.vtkTextMapper()
        ellipsoidTextMapper.SetInput("Ellipsoid")
        ellipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        ellipsoidTextMapper.GetTextProperty().SetFontSize(14)
        ellipsoidTextActor = vtk.vtkActor2D()
        ellipsoidTextActor.SetMapper(ellipsoidTextMapper)
        ellipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        ellipsoidTextActor.GetPositionCoordinate().SetValue(8, -14.5, 0)

        # ------------------------------------------------------------
        # Create an surface with random hills on it.
        # Note that for testing, we will disable the
        # random generation of the surfaces. This is
        # because random number generators do not
        # return the same result on different operating
        # systems.
        # ------------------------------------------------------------
        randomHills = vtk.vtkParametricRandomHills()
        randomHills.AllowRandomGenerationOff()
        randomHills.GenerateTheHills()
        randomHillsSource = vtk.vtkParametricFunctionSource()
        randomHillsSource.SetParametricFunction(randomHills)
        randomHillsSource.GenerateTextureCoordinatesOn()

        randomHillsMapper = vtk.vtkPolyDataMapper()
        randomHillsMapper.SetInputConnection(randomHillsSource.GetOutputPort())

        randomHillsActor = vtk.vtkActor()
        randomHillsActor.SetMapper(randomHillsMapper)
        randomHillsActor.SetPosition(16, -14, 0)
        randomHillsActor.SetScale(0.2, 0.2, 0.2)
        randomHillsActor.SetTexture(texture)

        randomHillsTextMapper = vtk.vtkTextMapper()
        randomHillsTextMapper.SetInput("Random.Hills")
        randomHillsTextMapper.GetTextProperty().SetJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetColor(1, 0, 0)
        randomHillsTextMapper.GetTextProperty().SetFontSize(14)
        randomHillsTextActor = vtk.vtkActor2D()
        randomHillsTextActor.SetMapper(randomHillsTextMapper)
        randomHillsTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        randomHillsTextActor.GetPositionCoordinate().SetValue(16, -14.5, 0)

        # ------------------------------------------------------------
        # Create an Steiner's Roman Surface.
        # ------------------------------------------------------------
        roman = vtk.vtkParametricRoman()
        roman.SetRadius(1.5)
        romanSource = vtk.vtkParametricFunctionSource()
        romanSource.SetParametricFunction(roman)
        romanSource.SetScalarModeToX()

        romanMapper = vtk.vtkPolyDataMapper()
        romanMapper.SetInputConnection(romanSource.GetOutputPort())

        romanActor = vtk.vtkActor()
        romanActor.SetMapper(romanMapper)
        romanActor.SetPosition(24, -12, 0)

        romanTextMapper = vtk.vtkTextMapper()
        romanTextMapper.SetInput("Roman")
        romanTextMapper.GetTextProperty().SetJustificationToCentered()
        romanTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        romanTextMapper.GetTextProperty().SetColor(1, 0, 0)
        romanTextMapper.GetTextProperty().SetFontSize(14)
        romanTextActor = vtk.vtkActor2D()
        romanTextActor.SetMapper(romanTextMapper)
        romanTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        romanTextActor.GetPositionCoordinate().SetValue(24, -14.5, 0)

        # ------------------------------------------------------------
        # Create the RenderWindow, Renderer and both Actors
        # ------------------------------------------------------------
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # add actors
        ren.AddViewProp(torusActor)
        ren.AddViewProp(kleinActor)
        ren.AddViewProp(klein2Actor)
        ren.AddViewProp(toroidActor)
        ren.AddViewProp(superEllipsoidActor)
        ren.AddViewProp(mobiusActor)
        ren.AddViewProp(splineActor)
        ren.AddViewProp(spline2Actor)
        ren.AddViewProp(sconicActor)
        ren.AddViewProp(boyActor)
        ren.AddViewProp(crossCapActor)
        ren.AddViewProp(diniActor)
        ren.AddViewProp(enneperActor)
        ren.AddViewProp(ellipsoidActor)
        ren.AddViewProp(randomHillsActor)
        ren.AddViewProp(romanActor)
        #add text actors
        ren.AddViewProp(torusTextActor)
        ren.AddViewProp(kleinTextActor)
        ren.AddViewProp(fig8KleinTextActor)
        ren.AddViewProp(mobiusTextActor)
        ren.AddViewProp(superToroidTextActor)
        ren.AddViewProp(superEllipsoidTextActor)
        ren.AddViewProp(splineTextActor)
        ren.AddViewProp(spline2TextActor)
        ren.AddViewProp(sconicTextActor)
        ren.AddViewProp(boyTextActor)
        ren.AddViewProp(crossCapTextActor)
        ren.AddViewProp(diniTextActor)
        ren.AddViewProp(enneperTextActor)
        ren.AddViewProp(ellipsoidTextActor)
        ren.AddViewProp(randomHillsTextActor)
        ren.AddViewProp(romanTextActor)

        ren.SetBackground(0.7, 0.8, 1)
        renWin.SetSize(500, 500)
        ren.ResetCamera()
        ren.GetActiveCamera().Zoom(1.3)

        iren.Initialize()
        renWin.Render()
        #iren.Start()
        img_file = "TestParametricFunctions.png"
        vtk.test.Testing.compareImage(iren.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25)
        vtk.test.Testing.interact()
Beispiel #32
0
    #vtk.vtkParametricPseudosphere(),
    #vtk.vtkParametricRoman(),
    vtk.vtkParametricCatalanMinimal(),
    vtk.vtkParametricEnneper(),
    vtk.vtkParametricHenneberg(),
    vtk.vtkParametricPluckerConoid(),
    vtk.vtkParametricRandomHills(),
    #vtk.vtkParametricSpline(),
    #vtk.vtkParametricEllipsoid(),
    #vtk.vtkParametricSuperEllipsoid(),
    #vtk.vtkParametricSuperToroid(),
    #vtk.vtkParametricTorus(),
]

lst2 = [
    vtk.vtkParametricCatalanMinimal(),  # 4 lobi - brutto
    vtk.vtkParametricEllipsoid(),  # e' una palla -- vedere params
    vtk.vtkParametricEnneper(),  # grosso -- farfalla
    vtk.vtkParametricHenneberg(),  # grosso -- farfalla
    vtk.vtkParametricPluckerConoid(),  # grosso
    vtk.vtkParametricRandomHills(),  # grosso -- dem procedurale
    vtk.vtkParametricSpline(),  # --- vuole params
    vtk.vtkParametricSuperEllipsoid(),  # palla
    vtk.vtkParametricSuperToroid(),  # toro
    vtk.vtkParametricTorus(),  # toro uguale
]

x0 = 140
for i, f in enumerate(lst):
    Show(f, (0, i * 10 - x0, 0))
Beispiel #33
0
    def setWidgetView(self, widget, color=[[1, 0, 0], [0, 1, 0], [0, 0, 1]]):
        super(SurfaceView, self).setWidgetView(widget)

        if type(self.parent) is MdiChildRegistration:
            point_array_move = self.parent.getData('move').pointSet
            point_data_move = npy.array(point_array_move.getData('Contour'))
            point_data_result = npy.array(point_data_move)

            if point_data_result is None or not point_data_result.shape[0]:
                return

            self.spacing_mov = self.parent.getData(
                'move').getResolution().tolist()
            self.spacing = self.parent.getData().getResolution().tolist()

            para = npy.array(
                self.parent.getData().getInfo().getData('transform'))
            R = ml.mat(para[:9].reshape(3, 3))
            T = ml.mat(para[9:12].reshape(3, 1))

            T = R.I * T
            T = -T
            point_data_result[:, :3] *= self.spacing_mov[:3]
            point_data_result[:, :3] = ml.mat(
                point_data_result[:, :3]) * R + ml.ones(
                    (point_data_result.shape[0], 1)) * T.T
            point_data_result[:, :3] /= self.spacing[:3]
        else:
            point_array_result = self.parent.getData().pointSet
            point_data_result = npy.array(
                point_array_result.getData('Contour'))
            point_array_move = point_array_result
            point_data_move = npy.array(point_array_move.getData('Contour'))

        zmin = int(npy.min(point_data_move[:, 2]) + 0.5)
        zmax = int(npy.max(point_data_move[:, 2]) + 0.5)
        self.spacing = self.parent.getData().getResolution().tolist()
        self.spacing = [float(x) / self.spacing[-1] for x in self.spacing]
        point_data_result[:, :2] *= self.spacing[:2]

        self.renderer = vtk.vtkRenderer()
        self.render_window = widget.GetRenderWindow()
        self.render_window.AddRenderer(self.renderer)
        self.window_interactor = vtk.vtkRenderWindowInteractor()
        self.render_window.SetInteractor(self.window_interactor)

        self.contours = []
        self.delaunay3D = []
        self.delaunayMapper = []
        self.surface_actor = []

        for cnt in range(3):
            self.contours.append(vtk.vtkPolyData())
            self.delaunay3D.append(vtk.vtkDelaunay3D())
            self.delaunayMapper.append(vtk.vtkDataSetMapper())
            self.surface_actor.append(vtk.vtkActor())

            point_result = point_data_result[npy.where(
                npy.round(point_data_result[:, -1]) == cnt)]
            point_move = point_data_move[npy.where(
                npy.round(point_data_move[:, -1]) == cnt)]
            if not point_result.shape[0]:
                continue

            self.cells = vtk.vtkCellArray()
            self.points = vtk.vtkPoints()
            l = 0
            for i in range(zmin, zmax + 1):
                data = point_result[npy.where(
                    npy.round(point_move[:, 2]) == i)]
                if data is not None:
                    if data.shape[0] == 0:
                        continue
                    count = data.shape[0]
                    points = vtk.vtkPoints()
                    for j in range(count):
                        points.InsertPoint(j, data[j, 0], data[j, 1], data[j,
                                                                           2])

                    para_spline = vtk.vtkParametricSpline()
                    para_spline.SetPoints(points)
                    para_spline.ClosedOn()

                    # The number of output points set to 10 times of input points
                    numberOfOutputPoints = count * 10
                    self.cells.InsertNextCell(numberOfOutputPoints)
                    for k in range(0, numberOfOutputPoints):
                        t = k * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[0] != pt[0]:
                            print pt
                            continue
                        self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                        self.cells.InsertCellPoint(l)
                        l += 1

            self.contours[cnt].SetPoints(self.points)
            self.contours[cnt].SetPolys(self.cells)

            self.delaunay3D[cnt].SetInput(self.contours[cnt])
            self.delaunay3D[cnt].SetAlpha(2)

            self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput())

            self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt])
            self.surface_actor[cnt].GetProperty().SetDiffuseColor(
                color[cnt][0], color[cnt][1], color[cnt][2])
            self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1)
            self.surface_actor[cnt].GetProperty().SetSpecular(0.4)
            self.surface_actor[cnt].GetProperty().SetSpecularPower(50)

            self.renderer.AddViewProp(self.surface_actor[cnt])

        self.renderer.ResetCamera()
        point = self.renderer.GetActiveCamera().GetFocalPoint()
        dis = self.renderer.GetActiveCamera().GetDistance()
        self.renderer.GetActiveCamera().SetViewUp(0, 0, 1)
        self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis,
                                                    point[2])
        self.renderer.ResetCameraClippingRange()
        self.render_window.Render()

        # Manually set to trackball style
        self.window_interactor.SetKeyCode('t')
        self.window_interactor.CharEvent()
        self.window_interactor.GetInteractorStyle().AddObserver(
            "KeyPressEvent", self.KeyPressCallback)
        self.window_interactor.GetInteractorStyle().AddObserver(
            "CharEvent", self.KeyPressCallback)
def show_branches_3d(branches_points,
                     branch_idx,
                     show_shape,
                     bg_image_path=None,
                     fix_color=False,
                     vessel_stl=None,
                     liver_stl=None,
                     show_window=True,
                     save_name=None,
                     save_dir=None):
    lines_actors = []
    sid = 0
    for bid in branch_idx:
        branch_points = branches_points[sid:sid + bid, :]
        sid += bid

        vtk_points = vtk.vtkPoints()
        for i, bp in enumerate(branch_points):
            vtk_points.InsertPoint(i, *bp)

        spline = vtk.vtkParametricSpline()
        spline.SetPoints(vtk_points)

        spline_source = vtk.vtkParametricFunctionSource()
        spline_source.SetParametricFunction(spline)
        spline_source.Update()

        spline_mapper = vtk.vtkPolyDataMapper()
        spline_mapper.SetInputData(spline_source.GetOutput())

        spline_actor = vtk.vtkActor()
        spline_actor.SetMapper(spline_mapper)
        if not fix_color:
            if bid == 0:
                spline_actor.GetProperty().SetColor(1.0, .0, .0)
            else:
                color = np.random.rand(3)
                while (color == [1.0, .0, .0]).all():
                    continue
                spline_actor.GetProperty().SetColor(np.random.rand(3))
        else:
            spline_actor.GetProperty().SetColor(1.0, 1.0, 0.0)

        spline_actor.GetProperty().SetLineWidth(3)
        lines_actors.append(spline_actor)

    scene_renderer = vtk.vtkRenderer()
    for actor in lines_actors:
        scene_renderer.AddActor(actor)

    if vessel_stl is not None:
        for v_stl in vessel_stl:
            vessel_actor = make_stl_actor(v_stl, [1.0, 0.2, 0.1], 0.4)  # 浅红
            scene_renderer.AddActor(vessel_actor)

    if liver_stl is not None:
        liver_actor = make_stl_actor(liver_stl, [.0, 0.2, 1.], 0.1)
        scene_renderer.AddActor(liver_actor)

    render_window = vtk.vtkRenderWindow()
    iren = vtk.vtkRenderWindowInteractor()

    if bg_image_path is None:
        scene_renderer.SetBackground(1, 1, 1)
        render_window.AddRenderer(scene_renderer)
        render_window.SetSize(*show_shape)
        iren.SetRenderWindow(render_window)
    else:
        bg_image_data, background_renderer = get_background_render(
            bg_image_path)

        # Set up the render window and renderers such that there is
        # a background layer and a foreground layer
        background_renderer.SetLayer(0)
        background_renderer.InteractiveOff()
        scene_renderer.SetLayer(1)
        render_window.SetNumberOfLayers(2)
        render_window.AddRenderer(background_renderer)
        render_window.AddRenderer(scene_renderer)

        iren.SetRenderWindow(render_window)

        # Render once to figure out where the background camera will be
        render_window.Render()

        # Set up the background camera to fill the renderer with the image
        origin = bg_image_data.GetOrigin()
        spacing = bg_image_data.GetSpacing()
        extent = bg_image_data.GetExtent()

        camera = background_renderer.GetActiveCamera()
        camera.ParallelProjectionOn()

        xc = origin[0] + 0.5 * (extent[0] + extent[1]) * spacing[0]
        yc = origin[1] + 0.5 * (extent[2] + extent[3]) * spacing[1]
        # xd = (extent[1] - extent[0] + 1) * spacing[0]
        yd = (extent[3] - extent[2] + 1) * spacing[1]
        d = camera.GetDistance()
        camera.SetParallelScale(0.5 * yd)
        camera.SetFocalPoint(xc, yc, 0.0)
        camera.SetPosition(xc, yc, d)

    # camera
    # camera = vtk.vtkCamera()
    # camera.SetPosition(source_point)
    # focal_point = np.sum((origin_2d - source_point) * plane_normal) * plane_normal + source_point
    # camera.SetFocalPoint(focal_point)
    # camera.ComputeViewPlaneNormal()
    # ren1.SetActiveCamera(camera)

    if show_window:
        render_window.Render()

        interactor = vtk.vtkRenderWindowInteractor()
        interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
        interactor.SetRenderWindow(render_window)

        render_window.Render()
        if save_name is None:
            iren.Start()

    if save_name is not None:
        render_window.Render()
        windowToImageFilter = vtk.vtkWindowToImageFilter()
        windowToImageFilter.SetInput(render_window)
        # windowToImageFilter.SetMagnification(3)
        windowToImageFilter.SetInputBufferTypeToRGBA()
        windowToImageFilter.ReadFrontBufferOff()
        windowToImageFilter.Update()

        pngWriter = vtk.vtkPNGWriter()
        if save_dir is None:
            pngWriter.SetFileName("data/centerline_projections/" + save_name)
        else:
            pngWriter.SetFileName(os.path.join(save_dir, save_name))

        pngWriter.SetInputData(windowToImageFilter.GetOutput())
        pngWriter.Write()
        print("saved as %s" % save_name)
    del render_window
Beispiel #35
0
def augmentPointset(ori_points, multiple, opt_size, bif, nn=-1):
    if multiple <= 1:
        return ori_points
    if nn < 0:
        zmin = int(npy.min(ori_points[:, 2]) + 0.5)
        zmax = int(npy.max(ori_points[:, 2]) + 0.5)
        nn = int((opt_size - ori_points.shape[0]) / ((2 * zmax - zmin - bif)) /
                 (multiple - 1) + 0.5) + 1
        #print nn

    new_points = npy.array([[-1, -1, -1, -1]], dtype=npy.float32)
    zmin = [0, 0, 0]
    zmax = [0, 0, 0]
    resampled_points = [None, None, None]
    for cnt in range(3):
        temp_result = ori_points[npy.where(
            npy.round(ori_points[:, -1]) == cnt)]
        if not temp_result.shape[0]:
            continue
        zmin[cnt] = int(npy.min(temp_result[:, 2]) + 0.5)
        zmax[cnt] = int(npy.max(temp_result[:, 2]) + 0.5)
        resampled_points[cnt] = npy.zeros(
            [(zmax[cnt] - zmin[cnt] + 1) * nn, 4], dtype=npy.float32)
        resampled_index = 0

        for z in range(zmin[cnt], zmax[cnt] + 1):
            data_result = temp_result[npy.where(
                npy.round(temp_result[:, 2]) == z)]
            if data_result is not None:
                if data_result.shape[0] == 0:
                    continue

                #center_result = npy.mean(data_result[:, :2], axis = 0)
                center_result = calCentroidFromContour(data_result[:, :2])[0]
                points_result = getPointsOntheSpline(data_result,
                                                     center_result, 900)

                i = 0
                for k in range(-nn / 2 + 1, nn / 2 + 1):
                    angle = k * 2 * npy.pi / nn

                    while i < 900 and points_result[i, 2] < angle:
                        i += 1
                    if i == 900 or (i > 0 and angle - points_result[i - 1, 2] <
                                    points_result[i, 2] - angle):
                        ind_result = i - 1
                    else:
                        ind_result = i

                    resampled_points[cnt][resampled_index, :2] = points_result[
                        ind_result, :2]
                    resampled_points[cnt][resampled_index, 2] = z
                    resampled_points[cnt][resampled_index, 3] = k + 4
                    resampled_index += 1
    trans_points = npy.array(ori_points)
    for cnt in range(3):
        for k in range(0, nn):
            data = resampled_points[cnt][npy.where(
                npy.round(resampled_points[cnt][:, -1]) == k)]
            count = data.shape[0]
            if count == 0:
                continue
            points = vtk.vtkPoints()
            for i in range(count):
                points.InsertPoint(i, data[i, 0], data[i, 1], data[i, 2])

            para_spline = vtk.vtkParametricSpline()
            para_spline.SetPoints(points)
            para_spline.ClosedOff()

            deltaz = 1.0 / multiple
            old_pt = [0.0, 0.0, 0.0]
            numberOfOutputPoints = int((zmax[cnt] - zmin[cnt] + 1) * 10)
            i = 0

            for z in range(zmin[cnt], zmax[cnt] + 1):
                znow = float(z)
                for dd in range(1, multiple):
                    znow += deltaz
                    while i < numberOfOutputPoints:
                        t = i * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[2] >= znow:
                            if pt[2] - znow < znow - old_pt[2]:
                                new_point = pt
                            else:
                                new_point = old_pt
                            trans_points = npy.append(
                                trans_points,
                                [[new_point[0], new_point[1], znow, cnt]],
                                axis=0)

                            old_pt = pt
                            break
                        i += 1
    return trans_points
Beispiel #36
0
def resliceTheResultPoints(moving_points, moving_center, nn, moving_res, fixed_res, discard, R, T, C = npy.asmatrix([0, 0, 0]).T):
    resampled_points = [None, None, None]
    nearbif_points = [None, None, None]
    nearbif_center = [None, None]
    bif_slice = 0
    
    for cnt in range(3):
        temp_result = moving_points[npy.where(npy.round(moving_points[:, -1]) == cnt)].copy()
        if not temp_result.shape[0]:
            continue
        zmin = int(npy.min(temp_result[:, 2]) + 0.5)
        zmax = int(npy.max(temp_result[:, 2]) + 0.5)
        
        resampled_points[cnt] = npy.zeros([(zmax - zmin + 1) * nn, 4], dtype = npy.float32)
        resampled_index = 0
        
        for z in range(zmin, zmax + 1):
            data_result = temp_result[npy.where(npy.round(temp_result[:, 2]) == z)]
            if data_result is not None:
                if data_result.shape[0] == 0:
                    continue
                
                center_result = calCentroidFromContour(data_result[:, :2])[0]
                points_result = getPointsOntheSpline(data_result, center_result, 900)
                if cnt > 0 and z == zmin:
                    nearbif_points[cnt] = points_result
                    nearbif_center[cnt - 1] = center_result
                    bif_slice = z
                elif cnt == 0 and z == zmax - 1:
                    nearbif_points[cnt] = points_result
                    
                i = 0
                for k in range(- nn / 2 + 1, nn / 2 + 1):
                    angle = k * 360 / nn / 180.0 * npy.pi
                    
                    while i < 900 and points_result[i, 2] < angle:
                        i += 1
                    if i == 900 or (i > 0 and angle - points_result[i - 1, 2] < points_result[i, 2] - angle):
                        ind_result = i - 1
                    else:
                        ind_result = i
                    
                    resampled_points[cnt][resampled_index, :2] = points_result[ind_result, :2]
                    resampled_points[cnt][resampled_index, 2] = z
                    resampled_points[cnt][resampled_index, 3] = k + nn / 2 - 1
                    resampled_index += 1
    
    nearbif_angle = [npy.arctan2(nearbif_center[1][1] - nearbif_center[0][1], nearbif_center[1][0] - nearbif_center[0][0]), 
                     npy.arctan2(nearbif_center[0][1] - nearbif_center[1][1], nearbif_center[0][0] - nearbif_center[1][0])]
    point_near_bif = npy.zeros([2, 2], dtype = npy.float32)
    for cnt in range(2):
        ind = npy.argmin(npy.abs(nearbif_points[cnt + 1][:, 2] - nearbif_angle[cnt]))
        point_near_bif[cnt, :] = nearbif_points[cnt + 1][ind, :2]
    bif_points = npy.zeros([3, 3], dtype = npy.float32)
    bif_points[0, :2] = npy.mean(point_near_bif, axis = 0)
    bif_points[0, 2] = bif_slice
    nearbif_angle = [npy.arctan2(nearbif_center[1][0] - nearbif_center[0][0], nearbif_center[0][1] - nearbif_center[1][1]), 
                     npy.arctan2(nearbif_center[0][0] - nearbif_center[1][0], nearbif_center[1][1] - nearbif_center[0][1])]
    nearbif_points[0][:, 2] = npy.arctan2(nearbif_points[0][:, 1] - bif_points[0, 1], nearbif_points[0][:, 0] - bif_points[0, 0])
    for cnt in range(1, 3):
        ind = npy.argmin(npy.abs(nearbif_points[0][:, 2] - nearbif_angle[cnt - 1]))
        bif_points[cnt, :2] = nearbif_points[0][ind, :2]
    bif_points[1:, 2] = bif_slice - 1
    
    # Apply the transformation on the resampled points
    for cnt in range(3):
        resampled_points[cnt][:, :3] = applyTransformForPoints(resampled_points[cnt][:, :3], moving_res, fixed_res, R, T, C)
    bif_points = applyTransformForPoints(bif_points, moving_res, fixed_res, R, T, C)

    # Resample the points near the bifurcation
    points = vtk.vtkPoints()
    points.InsertPoint(0, bif_points[1, 0], bif_points[1, 1], bif_points[1, 2])
    points.InsertPoint(1, bif_points[0, 0], bif_points[0, 1], bif_points[0, 2])
    points.InsertPoint(2, bif_points[2, 0], bif_points[2, 1], bif_points[2, 2])

    para_spline = vtk.vtkParametricSpline()
    para_spline.SetPoints(points)
    para_spline.ClosedOff()
    
    numberOfOutputPoints = 6
    new_bif_points = npy.zeros([numberOfOutputPoints + 1, 4], dtype = npy.float32)
    
    for i in range(0, numberOfOutputPoints + 1):
        t = i * 1.0 / numberOfOutputPoints
        pt = [0.0, 0.0, 0.0]
        para_spline.Evaluate([t, t, t], pt, [0] * 9)
        new_bif_points[i, :3] = pt
    new_bif_points[:, 3] = 0
    
    # Reslice the result points
    trans_points = npy.array([[-1, -1, -1, -1]], dtype = npy.float32)
    bif_slice = int(npy.ceil(bif_points[0, 2]))
    
    for cnt in range(3):
        zmin = int(npy.ceil(npy.max(resampled_points[cnt][:nn, 2])))
        zmax = int(npy.min(resampled_points[cnt][-nn:, 2]))
        if not discard:
            if cnt == 0:
                zmax = bif_slice
            else:
                zmin = bif_slice
        
        for k in range(0, nn):
            data = resampled_points[cnt][npy.where(npy.round(resampled_points[cnt][:, -1]) == k)]
            if not discard:
                if cnt == 0:
                    dis1 = npy.hypot(data[-1, 0] - resampled_points[1][nn:nn * 2, 0], data[-1, 1] - resampled_points[1][nn:nn * 2, 1])
                    #dis1 = npy.hypot(data[-1, 0] - nearbif_points[1][:, 0], data[-1, 1] - nearbif_points[1][:, 1])
                    ind1 = npy.argmin(dis1)
                    dis2 = npy.hypot(data[-1, 0] - resampled_points[2][nn:nn * 2, 0], data[-1, 1] - resampled_points[2][nn:nn * 2, 1])
                    ind2 = npy.argmin(dis2)
                    if dis1[ind1] < dis2[ind2]:
                        data_add = resampled_points[1][npy.where((npy.round(resampled_points[1][:, -1]) == ind1) & (resampled_points[1][:, 2] <= zmax + 1))]
                    else:
                        data_add = resampled_points[2][npy.where((npy.round(resampled_points[2][:, -1]) == ind2) & (resampled_points[2][:, 2] <= zmax + 1))]
                    data = npy.append(data, data_add[1:, :], axis = 0)
                else:
                    dis1 = npy.hypot(data[0, 0] - resampled_points[0][-nn * 2:-nn, 0], data[0, 1] - resampled_points[0][-nn * 2:-nn, 1])
                    ind1 = npy.argmin(dis1)
                    dis2 = npy.sqrt(npy.sum((new_bif_points[:, :3] - data[0, :3]) ** 2, axis = 1))
                    ind2 = npy.argmin(dis2)
                    if dis1[ind1] < dis2[ind2]:
                        data_add = resampled_points[0][npy.where((npy.round(resampled_points[0][:, -1]) == ind1) & (resampled_points[0][:, 2] >= zmin - 1))]
                    else:
                        data_add = new_bif_points[ind2, :].reshape(1, -1)
                    data = npy.append(data_add[:-1, :], data, axis = 0)
                
            count = data.shape[0]
            if count == 0:
                continue
            points = vtk.vtkPoints()
            for i in range(count):
                points.InsertPoint(i, data[i, 0], data[i, 1], data[i, 2])
    
            para_spline = vtk.vtkParametricSpline()
            para_spline.SetPoints(points)
            para_spline.ClosedOff()
            
            znow = zmin
            old_pt = [0.0, 0.0, 0.0]
            numberOfOutputPoints = int((zmax - zmin + 3) * nn)
            
            for i in range(0, numberOfOutputPoints):
                t = i * 1.0 / numberOfOutputPoints
                pt = [0.0, 0.0, 0.0]
                para_spline.Evaluate([t, t, t], pt, [0] * 9)
                if pt[2] >= znow:
                    if pt[2] - znow < znow - old_pt[2]:
                        new_point = pt
                    else:
                        new_point = old_pt
                    trans_points = npy.append(trans_points, [[new_point[0], new_point[1], znow, cnt]], axis = 0)
                    znow += 1
                    if znow > zmax:
                        break
                old_pt = pt
    
    new_trans_points = npy.array([[-1, -1, -1, -1]], dtype = npy.float32)
    for cnt in range(3):
        temp_result = trans_points[npy.where(npy.round(trans_points[:, -1]) == cnt)]
        if not temp_result.shape[0]:
            continue
        zmin = int(npy.min(temp_result[:, 2]) + 0.5)
        zmax = int(npy.max(temp_result[:, 2]) + 0.5)
        for z in range(zmin, zmax + 1):
            data_result = temp_result[npy.where(npy.round(temp_result[:, 2]) == z)]
            if data_result is not None:
                if data_result.shape[0] == 0:
                    continue
                
                ind = sortContourPoints(data_result)
                data_result[:, :] = data_result[ind, :]

                for x in data_result:
                    if isDifferent(new_trans_points[-1, :], x):
                        new_trans_points = npy.append(new_trans_points, x.reshape(1, -1), axis = 0)
                    
                        
    result_center_points = npy.array([[-1, -1, -1, -1]], dtype = npy.float32)
    if moving_center is not None and moving_center.shape[0] > 1:
        result_center = moving_center[npy.where(moving_center[:, 0] >= 0)]
        
        result_center[:, :3] = applyTransformForPoints(result_center[:, :3], moving_res, fixed_res, R, T, C)
        ind = result_center[:, 2].argsort()
        result_center = result_center[ind]
        
        result_center_points = npy.array([[-1, -1, -1, -1]], dtype = npy.float32)
        for cnt in range(3):
            resampled_points = result_center[npy.where(npy.round(result_center[:, -1]) == cnt)]
            zmin = int(npy.ceil(resampled_points[0, 2]))
            zmax = int(resampled_points[-1, 2])
            
            count = resampled_points.shape[0]
            points = vtk.vtkPoints()
            for i in range(count):
                points.InsertPoint(i, resampled_points[i, 0], resampled_points[i, 1], resampled_points[i, 2])
    
            para_spline = vtk.vtkParametricSpline()
            para_spline.SetPoints(points)
            para_spline.ClosedOff()
            
            znow = zmin
            old_pt = [0.0, 0.0, 0.0]
            numberOfOutputPoints = int((zmax - zmin + 1) * 10)
            
            for i in range(0, numberOfOutputPoints):
                t = i * 1.0 / numberOfOutputPoints
                pt = [0.0, 0.0, 0.0]
                para_spline.Evaluate([t, t, t], pt, [0] * 9)
                if pt[2] >= znow:
                    if pt[2] - znow < znow - old_pt[2]:
                        new_point = pt
                    else:
                        new_point = old_pt
                    result_center_points = npy.append(result_center_points, [[new_point[0], new_point[1], znow, cnt]], axis = 0)
                    znow += 1
                    if znow > zmax:
                        break
                old_pt = pt
    return new_trans_points, result_center_points
Beispiel #37
0
def resliceTheResultPoints(moving_points,
                           moving_center,
                           nn,
                           moving_res,
                           fixed_res,
                           discard,
                           R,
                           T,
                           C=npy.asmatrix([0, 0, 0]).T):
    resampled_points = [None, None, None]
    nearbif_points = [None, None, None]
    nearbif_center = [None, None]
    bif_slice = 0

    for cnt in range(3):
        temp_result = moving_points[npy.where(
            npy.round(moving_points[:, -1]) == cnt)].copy()
        if not temp_result.shape[0]:
            continue
        zmin = int(npy.min(temp_result[:, 2]) + 0.5)
        zmax = int(npy.max(temp_result[:, 2]) + 0.5)

        resampled_points[cnt] = npy.zeros([(zmax - zmin + 1) * nn, 4],
                                          dtype=npy.float32)
        resampled_index = 0

        for z in range(zmin, zmax + 1):
            data_result = temp_result[npy.where(
                npy.round(temp_result[:, 2]) == z)]
            if data_result is not None:
                if data_result.shape[0] == 0:
                    continue

                center_result = calCentroidFromContour(data_result[:, :2])[0]
                points_result = getPointsOntheSpline(data_result,
                                                     center_result, 900)
                if cnt > 0 and z == zmin:
                    nearbif_points[cnt] = points_result
                    nearbif_center[cnt - 1] = center_result
                    bif_slice = z
                elif cnt == 0 and z == zmax - 1:
                    nearbif_points[cnt] = points_result

                i = 0
                for k in range(-nn / 2 + 1, nn / 2 + 1):
                    angle = k * 360 / nn / 180.0 * npy.pi

                    while i < 900 and points_result[i, 2] < angle:
                        i += 1
                    if i == 900 or (i > 0 and angle - points_result[i - 1, 2] <
                                    points_result[i, 2] - angle):
                        ind_result = i - 1
                    else:
                        ind_result = i

                    resampled_points[cnt][resampled_index, :2] = points_result[
                        ind_result, :2]
                    resampled_points[cnt][resampled_index, 2] = z
                    resampled_points[cnt][resampled_index, 3] = k + nn / 2 - 1
                    resampled_index += 1

    nearbif_angle = [
        npy.arctan2(nearbif_center[1][1] - nearbif_center[0][1],
                    nearbif_center[1][0] - nearbif_center[0][0]),
        npy.arctan2(nearbif_center[0][1] - nearbif_center[1][1],
                    nearbif_center[0][0] - nearbif_center[1][0])
    ]
    point_near_bif = npy.zeros([2, 2], dtype=npy.float32)
    for cnt in range(2):
        ind = npy.argmin(
            npy.abs(nearbif_points[cnt + 1][:, 2] - nearbif_angle[cnt]))
        point_near_bif[cnt, :] = nearbif_points[cnt + 1][ind, :2]
    bif_points = npy.zeros([3, 3], dtype=npy.float32)
    bif_points[0, :2] = npy.mean(point_near_bif, axis=0)
    bif_points[0, 2] = bif_slice
    nearbif_angle = [
        npy.arctan2(nearbif_center[1][0] - nearbif_center[0][0],
                    nearbif_center[0][1] - nearbif_center[1][1]),
        npy.arctan2(nearbif_center[0][0] - nearbif_center[1][0],
                    nearbif_center[1][1] - nearbif_center[0][1])
    ]
    nearbif_points[0][:, 2] = npy.arctan2(
        nearbif_points[0][:, 1] - bif_points[0, 1],
        nearbif_points[0][:, 0] - bif_points[0, 0])
    for cnt in range(1, 3):
        ind = npy.argmin(
            npy.abs(nearbif_points[0][:, 2] - nearbif_angle[cnt - 1]))
        bif_points[cnt, :2] = nearbif_points[0][ind, :2]
    bif_points[1:, 2] = bif_slice - 1

    # Apply the transformation on the resampled points
    for cnt in range(3):
        resampled_points[cnt][:, :3] = applyTransformForPoints(
            resampled_points[cnt][:, :3], moving_res, fixed_res, R, T, C)
    bif_points = applyTransformForPoints(bif_points, moving_res, fixed_res, R,
                                         T, C)

    # Resample the points near the bifurcation
    points = vtk.vtkPoints()
    points.InsertPoint(0, bif_points[1, 0], bif_points[1, 1], bif_points[1, 2])
    points.InsertPoint(1, bif_points[0, 0], bif_points[0, 1], bif_points[0, 2])
    points.InsertPoint(2, bif_points[2, 0], bif_points[2, 1], bif_points[2, 2])

    para_spline = vtk.vtkParametricSpline()
    para_spline.SetPoints(points)
    para_spline.ClosedOff()

    numberOfOutputPoints = 6
    new_bif_points = npy.zeros([numberOfOutputPoints + 1, 4],
                               dtype=npy.float32)

    for i in range(0, numberOfOutputPoints + 1):
        t = i * 1.0 / numberOfOutputPoints
        pt = [0.0, 0.0, 0.0]
        para_spline.Evaluate([t, t, t], pt, [0] * 9)
        new_bif_points[i, :3] = pt
    new_bif_points[:, 3] = 0

    # Reslice the result points
    trans_points = npy.array([[-1, -1, -1, -1]], dtype=npy.float32)
    bif_slice = int(npy.ceil(bif_points[0, 2]))

    for cnt in range(3):
        zmin = int(npy.ceil(npy.max(resampled_points[cnt][:nn, 2])))
        zmax = int(npy.min(resampled_points[cnt][-nn:, 2]))
        if not discard:
            if cnt == 0:
                zmax = bif_slice
            else:
                zmin = bif_slice

        for k in range(0, nn):
            data = resampled_points[cnt][npy.where(
                npy.round(resampled_points[cnt][:, -1]) == k)]
            if not discard:
                if cnt == 0:
                    dis1 = npy.hypot(
                        data[-1, 0] - resampled_points[1][nn:nn * 2, 0],
                        data[-1, 1] - resampled_points[1][nn:nn * 2, 1])
                    #dis1 = npy.hypot(data[-1, 0] - nearbif_points[1][:, 0], data[-1, 1] - nearbif_points[1][:, 1])
                    ind1 = npy.argmin(dis1)
                    dis2 = npy.hypot(
                        data[-1, 0] - resampled_points[2][nn:nn * 2, 0],
                        data[-1, 1] - resampled_points[2][nn:nn * 2, 1])
                    ind2 = npy.argmin(dis2)
                    if dis1[ind1] < dis2[ind2]:
                        data_add = resampled_points[1][npy.where(
                            (npy.round(resampled_points[1][:, -1]) == ind1)
                            & (resampled_points[1][:, 2] <= zmax + 1))]
                    else:
                        data_add = resampled_points[2][npy.where(
                            (npy.round(resampled_points[2][:, -1]) == ind2)
                            & (resampled_points[2][:, 2] <= zmax + 1))]
                    data = npy.append(data, data_add[1:, :], axis=0)
                else:
                    dis1 = npy.hypot(
                        data[0, 0] - resampled_points[0][-nn * 2:-nn, 0],
                        data[0, 1] - resampled_points[0][-nn * 2:-nn, 1])
                    ind1 = npy.argmin(dis1)
                    dis2 = npy.sqrt(
                        npy.sum((new_bif_points[:, :3] - data[0, :3])**2,
                                axis=1))
                    ind2 = npy.argmin(dis2)
                    if dis1[ind1] < dis2[ind2]:
                        data_add = resampled_points[0][npy.where(
                            (npy.round(resampled_points[0][:, -1]) == ind1)
                            & (resampled_points[0][:, 2] >= zmin - 1))]
                    else:
                        data_add = new_bif_points[ind2, :].reshape(1, -1)
                    data = npy.append(data_add[:-1, :], data, axis=0)

            count = data.shape[0]
            if count == 0:
                continue
            points = vtk.vtkPoints()
            for i in range(count):
                points.InsertPoint(i, data[i, 0], data[i, 1], data[i, 2])

            para_spline = vtk.vtkParametricSpline()
            para_spline.SetPoints(points)
            para_spline.ClosedOff()

            znow = zmin
            old_pt = [0.0, 0.0, 0.0]
            numberOfOutputPoints = int((zmax - zmin + 3) * nn)

            for i in range(0, numberOfOutputPoints):
                t = i * 1.0 / numberOfOutputPoints
                pt = [0.0, 0.0, 0.0]
                para_spline.Evaluate([t, t, t], pt, [0] * 9)
                if pt[2] >= znow:
                    if pt[2] - znow < znow - old_pt[2]:
                        new_point = pt
                    else:
                        new_point = old_pt
                    trans_points = npy.append(
                        trans_points,
                        [[new_point[0], new_point[1], znow, cnt]],
                        axis=0)
                    znow += 1
                    if znow > zmax:
                        break
                old_pt = pt

    new_trans_points = npy.array([[-1, -1, -1, -1]], dtype=npy.float32)
    for cnt in range(3):
        temp_result = trans_points[npy.where(
            npy.round(trans_points[:, -1]) == cnt)]
        if not temp_result.shape[0]:
            continue
        zmin = int(npy.min(temp_result[:, 2]) + 0.5)
        zmax = int(npy.max(temp_result[:, 2]) + 0.5)
        for z in range(zmin, zmax + 1):
            data_result = temp_result[npy.where(
                npy.round(temp_result[:, 2]) == z)]
            if data_result is not None:
                if data_result.shape[0] == 0:
                    continue

                ind = sortContourPoints(data_result)
                data_result[:, :] = data_result[ind, :]

                for x in data_result:
                    if isDifferent(new_trans_points[-1, :], x):
                        new_trans_points = npy.append(new_trans_points,
                                                      x.reshape(1, -1),
                                                      axis=0)

    result_center_points = npy.array([[-1, -1, -1, -1]], dtype=npy.float32)
    if moving_center is not None and moving_center.shape[0] > 1:
        result_center = moving_center[npy.where(moving_center[:, 0] >= 0)]

        result_center[:, :3] = applyTransformForPoints(result_center[:, :3],
                                                       moving_res, fixed_res,
                                                       R, T, C)
        ind = result_center[:, 2].argsort()
        result_center = result_center[ind]

        result_center_points = npy.array([[-1, -1, -1, -1]], dtype=npy.float32)
        for cnt in range(3):
            resampled_points = result_center[npy.where(
                npy.round(result_center[:, -1]) == cnt)]
            zmin = int(npy.ceil(resampled_points[0, 2]))
            zmax = int(resampled_points[-1, 2])

            count = resampled_points.shape[0]
            points = vtk.vtkPoints()
            for i in range(count):
                points.InsertPoint(i, resampled_points[i, 0],
                                   resampled_points[i, 1], resampled_points[i,
                                                                            2])

            para_spline = vtk.vtkParametricSpline()
            para_spline.SetPoints(points)
            para_spline.ClosedOff()

            znow = zmin
            old_pt = [0.0, 0.0, 0.0]
            numberOfOutputPoints = int((zmax - zmin + 1) * 10)

            for i in range(0, numberOfOutputPoints):
                t = i * 1.0 / numberOfOutputPoints
                pt = [0.0, 0.0, 0.0]
                para_spline.Evaluate([t, t, t], pt, [0] * 9)
                if pt[2] >= znow:
                    if pt[2] - znow < znow - old_pt[2]:
                        new_point = pt
                    else:
                        new_point = old_pt
                    result_center_points = npy.append(
                        result_center_points,
                        [[new_point[0], new_point[1], znow, cnt]],
                        axis=0)
                    znow += 1
                    if znow > zmax:
                        break
                old_pt = pt
    return new_trans_points, result_center_points
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.2, 0.3, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        points = vtk.vtkPoints()
        points.InsertPoint(0, 1, 0, 0)
        points.InsertPoint(1, 2, 0, 0)
        points.InsertPoint(2, 3, 1, 0)
        points.InsertPoint(3, 4, 1, 0)
        points.InsertPoint(4, 5, 0, 0)
        points.InsertPoint(5, 6, 0, 0)

        # Fit a spline to the points
        spline = vtk.vtkParametricSpline()
        spline.SetPoints(points)
        functionSource = vtk.vtkParametricFunctionSource()
        functionSource.SetParametricFunction(spline)
        functionSource.SetUResolution(10 * points.GetNumberOfPoints())
        functionSource.Update()

        # Interpolate the scalars
        interpolatedRadius = vtk.vtkTupleInterpolator()
        interpolatedRadius.SetInterpolationTypeToLinear()
        interpolatedRadius.SetNumberOfComponents(1)
        #interpolatedRadius.AddTuple(0, [0.2,]) ### ??? Donesn't work for Python
        #interpolatedRadius.AddTuple(1, (0.2,))
        #interpolatedRadius.AddTuple(2, (0.2,))
        #interpolatedRadius.AddTuple(3, (0.1,))
        #interpolatedRadius.AddTuple(4, (0.1,))
        #interpolatedRadius.AddTuple(5, (0.1,))

        # Generate the radius scalars
        tubeRadius = vtk.vtkDoubleArray()
        n = functionSource.GetOutput().GetNumberOfPoints()
        tubeRadius.SetNumberOfTuples(n)
        tubeRadius.SetName("TubeRadius")

        tMin = interpolatedRadius.GetMinimumT()
        tMax = interpolatedRadius.GetMaximumT()
        for i in range(n):
            t = (tMax - tMin) / (n - 1) * i + tMin
            r = 1.0
            #interpolatedRadius.InterpolateTuple(t, r) ### ??? Donesn't work for Python
            tubeRadius.SetTuple1(i, r)

        # Add the scalars to the polydata
        tubePolyData = functionSource.GetOutput()
        tubePolyData.GetPointData().AddArray(tubeRadius)
        tubePolyData.GetPointData().SetActiveScalars("TubeRadius")

        # Create the tubes
        tuber = vtk.vtkTubeFilter()
        tuber.SetInput(tubePolyData)
        tuber.SetNumberOfSides(20)
        tuber.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
 
        # Setup actors and mappers
        lineMapper = vtk.vtkPolyDataMapper()
        lineMapper.SetInput(tubePolyData)
        lineMapper.SetScalarRange(tubePolyData.GetScalarRange())

        tubeMapper = vtk.vtkPolyDataMapper()
        tubeMapper.SetInputConnection(tuber.GetOutputPort())
        tubeMapper.SetScalarRange(tubePolyData.GetScalarRange())
 
        lineActor = vtk.vtkActor()
        lineActor.SetMapper(lineMapper)
        tubeActor = vtk.vtkActor()
        tubeActor.SetMapper(tubeMapper)
 
        self.ren.AddActor(tubeActor)
        self.ren.AddActor(lineActor)
        self.ren.ResetCamera()

        self._initialized = False
Beispiel #39
0
    def ParametricObjects(self):

        parametricObjects = list()
        parametricObjects.append(vtk.vtkParametricBoy())
        parametricObjects.append(vtk.vtkParametricConicSpiral())
        parametricObjects.append(vtk.vtkParametricCrossCap())
        parametricObjects.append(vtk.vtkParametricDini())

        parametricObjects.append(vtk.vtkParametricEllipsoid())
        parametricObjects[-1].SetXRadius(0.5)
        parametricObjects[-1].SetYRadius(2.0)
        parametricObjects.append(vtk.vtkParametricEnneper())
        parametricObjects.append(vtk.vtkParametricFigure8Klein())
        parametricObjects.append(vtk.vtkParametricKlein())

        parametricObjects.append(vtk.vtkParametricMobius())
        parametricObjects.append(vtk.vtkParametricRandomHills())
        parametricObjects[-1].AllowRandomGenerationOff()
        parametricObjects.append(vtk.vtkParametricRoman())
        parametricObjects.append(vtk.vtkParametricSuperEllipsoid())
        parametricObjects[-1].SetN1(0.5)
        parametricObjects[-1].SetN2(0.1)

        parametricObjects.append(vtk.vtkParametricSuperToroid())
        parametricObjects[-1].SetN1(0.2)
        parametricObjects[-1].SetN2(3.0)
        parametricObjects.append(vtk.vtkParametricTorus())
        parametricObjects.append(vtk.vtkParametricSpline())
        # Add some points to the parametric spline.
        # You can use vtkRandom instead of the python random methods.
        inputPoints = vtk.vtkPoints()
        random.seed(8775070)
        for i in range(10):
            x = random.uniform(0.0, 1.0)
            y = random.uniform(0.0, 1.0)
            z = random.uniform(0.0, 1.0)
            inputPoints.InsertNextPoint(x, y, z)
        parametricObjects[-1].SetPoints(inputPoints)

        # There are only 15 objects.
        #parametricObjects.append(vtk.??)

        parametricFunctionSources = list()
        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()

        # Create a common text property.
        textProperty = vtk.vtkTextProperty()
        textProperty.SetFontSize(10)
        textProperty.SetJustificationToCentered()

        # Create a parametric function source, renderer, mapper
        # and actor for each object.
        for idx, item in enumerate(parametricObjects):
            parametricFunctionSources.append(vtk.vtkParametricFunctionSource())
            parametricFunctionSources[idx].SetParametricFunction(item)
            parametricFunctionSources[idx].Update()

            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(
                parametricFunctionSources[idx].GetOutputPort())

            actors.append(vtk.vtkActor())
            actors[idx].SetMapper(mappers[idx])

            textmappers.append(vtk.vtkTextMapper())
            textmappers[idx].SetInput(item.GetClassName())
            textmappers[idx].SetTextProperty(textProperty)

            textactors.append(vtk.vtkActor2D())
            textactors[idx].SetMapper(textmappers[idx])
            textactors[idx].SetPosition(100, 16)

            renderers.append(vtk.vtkRenderer())

        gridDimensions = 4

        for idx in range(len(parametricObjects)):
            if idx < gridDimensions * gridDimensions:
                renderers.append(vtk.vtkRenderer)

        rendererSize = 200

        # Create the RenderWindow
        #
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.SetSize(rendererSize * gridDimensions,
                             rendererSize * gridDimensions)

        # Add and position the renders to the render window.
        viewport = list()
        for row in range(gridDimensions):
            for col in range(gridDimensions):
                idx = row * gridDimensions + col

                viewport[:] = []
                viewport.append(
                    float(col) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(gridDimensions - (row + 1)) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(col + 1) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(gridDimensions - row) * rendererSize /
                    (gridDimensions * rendererSize))

                if idx > (len(parametricObjects) - 1):
                    continue

                renderers[idx].SetViewport(viewport)
                renderWindow.AddRenderer(renderers[idx])

                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.2, 0.3, 0.4)
                renderers[idx].ResetCamera()
                renderers[idx].GetActiveCamera().Azimuth(30)
                renderers[idx].GetActiveCamera().Elevation(-30)
                renderers[idx].ResetCameraClippingRange()

        interactor = vtk.vtkRenderWindowInteractor()
        interactor.SetRenderWindow(renderWindow)

        renderWindow.Render()

        interactor.Start()
def main():
    colors = vtk.vtkNamedColors()

    colors.SetColor("BkgColor", [26, 51, 102, 255])

    parametricObjects = list()
    parametricObjects.append(vtk.vtkParametricBoy())
    parametricObjects.append(vtk.vtkParametricConicSpiral())
    parametricObjects.append(vtk.vtkParametricCrossCap())
    parametricObjects.append(vtk.vtkParametricDini())

    parametricObjects.append(vtk.vtkParametricEllipsoid())
    parametricObjects[-1].SetXRadius(0.5)
    parametricObjects[-1].SetYRadius(2.0)
    parametricObjects.append(vtk.vtkParametricEnneper())
    parametricObjects.append(vtk.vtkParametricFigure8Klein())
    parametricObjects.append(vtk.vtkParametricKlein())

    parametricObjects.append(vtk.vtkParametricMobius())
    parametricObjects[-1].SetRadius(2)
    parametricObjects[-1].SetMinimumV(-0.5)
    parametricObjects[-1].SetMaximumV(0.5)
    parametricObjects.append(vtk.vtkParametricRandomHills())
    parametricObjects[-1].AllowRandomGenerationOff()
    parametricObjects.append(vtk.vtkParametricRoman())
    parametricObjects.append(vtk.vtkParametricSuperEllipsoid())
    parametricObjects[-1].SetN1(0.5)
    parametricObjects[-1].SetN2(0.1)

    parametricObjects.append(vtk.vtkParametricSuperToroid())
    parametricObjects[-1].SetN1(0.2)
    parametricObjects[-1].SetN2(3.0)
    parametricObjects.append(vtk.vtkParametricTorus())
    parametricObjects.append(vtk.vtkParametricSpline())
    # Add some points to the parametric spline.
    inputPoints = vtk.vtkPoints()
    rng = vtk.vtkMinimalStandardRandomSequence()
    rng.SetSeed(8775070)
    for i in range(0, 10):
        rng.Next()
        x = rng.GetRangeValue(0.0, 1.0)
        rng.Next()
        y = rng.GetRangeValue(0.0, 1.0)
        rng.Next()
        z = rng.GetRangeValue(0.0, 1.0)
        inputPoints.InsertNextPoint(x, y, z)
    parametricObjects[-1].SetPoints(inputPoints)

    parametricFunctionSources = list()
    renderers = list()
    mappers = list()
    actors = list()
    textmappers = list()
    textactors = list()

    # Create one text property for all
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(12)
    textProperty.SetJustificationToCentered()

    backProperty = vtk.vtkProperty()
    backProperty.SetColor(colors.GetColor3d("Tomato"))

    # Create a parametric function source, renderer, mapper, and actor
    # for each object
    for i in range(0, len(parametricObjects)):
        parametricFunctionSources.append(vtk.vtkParametricFunctionSource())
        parametricFunctionSources[i].SetParametricFunction(parametricObjects[i])
        parametricFunctionSources[i].SetUResolution(51)
        parametricFunctionSources[i].SetVResolution(51)
        parametricFunctionSources[i].SetWResolution(51)
        parametricFunctionSources[i].Update()

        mappers.append(vtk.vtkPolyDataMapper())
        mappers[i].SetInputConnection(parametricFunctionSources[i].GetOutputPort())

        actors.append(vtk.vtkActor())
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d("Banana"))
        actors[i].GetProperty().SetSpecular(.5)
        actors[i].GetProperty().SetSpecularPower(20)
        actors[i].SetBackfaceProperty(backProperty)

        textmappers.append(vtk.vtkTextMapper())
        textmappers[i].SetInput(parametricObjects[i].GetClassName())
        textmappers[i].SetTextProperty(textProperty)

        textactors.append(vtk.vtkActor2D())
        textactors[i].SetMapper(textmappers[i])
        textactors[i].SetPosition(100, 16)

        renderers.append(vtk.vtkRenderer())
        renderers[i].AddActor(actors[i])
        renderers[i].AddActor(textactors[i])
        renderers[i].SetBackground(colors.GetColor3d("BkgColor"))

    # Setup the viewports
    xGridDimensions = 4
    yGridDimensions = 4
    rendererSize = 200
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Parametric Objects Demonstration")
    renderWindow.SetSize(rendererSize * xGridDimensions, rendererSize * yGridDimensions)
    for row in range(0, yGridDimensions):
        for col in range(0, xGridDimensions):
            index = row * xGridDimensions + col

            # (xmin, ymin, xmax, ymax)
            viewport = [float(col) / xGridDimensions,
                        float(yGridDimensions - (row + 1)) / yGridDimensions,
                        float(col + 1) / xGridDimensions,
                        float(yGridDimensions - row) / yGridDimensions]

            if index > (len(actors) - 1):
                # Add a renderer even if there is no actor.
                # This makes the render window background all the same color.
                ren = vtk.vtkRenderer()
                ren.SetBackground(colors.GetColor3d("BkgColor"))
                ren.SetViewport(viewport)
                renderWindow.AddRenderer(ren)
                continue

            renderers[index].SetViewport(viewport)
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(-30)
            renderers[index].GetActiveCamera().Zoom(0.9)
            renderers[index].ResetCameraClippingRange()
            renderWindow.AddRenderer(renderers[index])

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    renderWindow.Render()
    interactor.Start()
    def testParametricFunctions(self):
        # ------------------------------------------------------------
        # Get a texture
        # ------------------------------------------------------------
        textureReader = vtk.vtkJPEGReader()
        textureReader.SetFileName(VTK_DATA_ROOT + "/Data/beach.jpg")
        texture = vtk.vtkTexture()
        texture.SetInputConnection(textureReader.GetOutputPort())

        # ------------------------------------------------------------
        # For each parametric surface:
        # 1) Create it
        # 2) Assign mappers and actors
        # 3) Position this object
        # 5) Add a label
        # ------------------------------------------------------------

        # ------------------------------------------------------------
        # Create a torus
        # ------------------------------------------------------------
        torus = vtk.vtkParametricTorus()
        torusSource = vtk.vtkParametricFunctionSource()
        torusSource.SetParametricFunction(torus)
        torusSource.SetScalarModeToPhase()

        torusMapper = vtk.vtkPolyDataMapper()
        torusMapper.SetInputConnection(torusSource.GetOutputPort())
        torusMapper.SetScalarRange(0, 360)

        torusActor = vtk.vtkActor()
        torusActor.SetMapper(torusMapper)
        torusActor.SetPosition(0, 12, 0)

        torusTextMapper = vtk.vtkTextMapper()
        torusTextMapper.SetInput("Torus")
        torusTextMapper.GetTextProperty().SetJustificationToCentered()
        torusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        torusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        torusTextMapper.GetTextProperty().SetFontSize(14)
        torusTextActor = vtk.vtkActor2D()
        torusTextActor.SetMapper(torusTextMapper)
        torusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        torusTextActor.GetPositionCoordinate().SetValue(0, 9.5, 0)

        # ------------------------------------------------------------
        # Create a klein bottle
        # ------------------------------------------------------------
        klein = vtk.vtkParametricKlein()
        kleinSource = vtk.vtkParametricFunctionSource()
        kleinSource.SetParametricFunction(klein)
        kleinSource.SetScalarModeToU0V0()

        kleinMapper = vtk.vtkPolyDataMapper()
        kleinMapper.SetInputConnection(kleinSource.GetOutputPort())
        kleinMapper.SetScalarRange(0, 3)

        kleinActor = vtk.vtkActor()
        kleinActor.SetMapper(kleinMapper)
        kleinActor.SetPosition(8, 10.5, 0)

        kleinTextMapper = vtk.vtkTextMapper()
        kleinTextMapper.SetInput("Klein")
        kleinTextMapper.GetTextProperty().SetJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        kleinTextMapper.GetTextProperty().SetFontSize(14)
        kleinTextActor = vtk.vtkActor2D()
        kleinTextActor.SetMapper(kleinTextMapper)
        kleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        kleinTextActor.GetPositionCoordinate().SetValue(8, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Figure-8 Klein
        # ------------------------------------------------------------
        klein2 = vtk.vtkParametricFigure8Klein()
        klein2Source = vtk.vtkParametricFunctionSource()
        klein2Source.SetParametricFunction(klein2)
        klein2Source.GenerateTextureCoordinatesOn()

        klein2Mapper = vtk.vtkPolyDataMapper()
        klein2Mapper.SetInputConnection(klein2Source.GetOutputPort())
        klein2Mapper.SetScalarRange(0, 3)

        klein2Actor = vtk.vtkActor()
        klein2Actor.SetMapper(klein2Mapper)
        klein2Actor.SetPosition(16, 12, 0)
        klein2Actor.SetTexture(texture)


        fig8KleinTextMapper = vtk.vtkTextMapper()
        fig8KleinTextMapper.SetInput("Fig-8.Klein")
        fig8KleinTextMapper.GetTextProperty().SetJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        fig8KleinTextMapper.GetTextProperty().SetFontSize(14)
        fig8KleinTextActor = vtk.vtkActor2D()
        fig8KleinTextActor.SetMapper(fig8KleinTextMapper)
        fig8KleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        fig8KleinTextActor.GetPositionCoordinate().SetValue(16, 9.5, 0)

        # ------------------------------------------------------------
        # Create a mobius strip
        # ------------------------------------------------------------
        mobius = vtk.vtkParametricMobius()
        mobiusSource = vtk.vtkParametricFunctionSource()
        mobiusSource.SetParametricFunction(mobius)
        mobiusSource.GenerateTextureCoordinatesOn()

        mobiusMapper = vtk.vtkPolyDataMapper()
        mobiusMapper.SetInputConnection(mobiusSource.GetOutputPort())

        mobiusActor = vtk.vtkActor()
        mobiusActor.SetMapper(mobiusMapper)
        mobiusActor.RotateX(45)
        mobiusActor.SetPosition(24, 12, 0)
        mobiusActor.SetTexture(texture)

        mobiusTextMapper = vtk.vtkTextMapper()
        mobiusTextMapper.SetInput("Mobius")
        mobiusTextMapper.GetTextProperty().SetJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        mobiusTextMapper.GetTextProperty().SetFontSize(14)
        mobiusTextActor = vtk.vtkActor2D()
        mobiusTextActor.SetMapper(mobiusTextMapper)
        mobiusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        mobiusTextActor.GetPositionCoordinate().SetValue(24, 9.5, 0)

        # ------------------------------------------------------------
        # Create a super toroid
        # ------------------------------------------------------------
        toroid = vtk.vtkParametricSuperToroid()
        toroid.SetN1(2)
        toroid.SetN2(3)
        toroidSource = vtk.vtkParametricFunctionSource()
        toroidSource.SetParametricFunction(toroid)
        toroidSource.SetScalarModeToU()

        toroidMapper = vtk.vtkPolyDataMapper()
        toroidMapper.SetInputConnection(toroidSource.GetOutputPort())
        toroidMapper.SetScalarRange(0, 6.28)

        toroidActor = vtk.vtkActor()
        toroidActor.SetMapper(toroidMapper)
        toroidActor.SetPosition(0, 4, 0)

        superToroidTextMapper = vtk.vtkTextMapper()
        superToroidTextMapper.SetInput("Super.Toroid")
        superToroidTextMapper.GetTextProperty().SetJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superToroidTextMapper.GetTextProperty().SetFontSize(14)
        superToroidTextActor = vtk.vtkActor2D()
        superToroidTextActor.SetMapper(superToroidTextMapper)
        superToroidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superToroidTextActor.GetPositionCoordinate().SetValue(0, 1.5, 0)

        # ------------------------------------------------------------
        # Create a super ellipsoid
        # ------------------------------------------------------------
        superEllipsoid = vtk.vtkParametricSuperEllipsoid()
        superEllipsoid.SetXRadius(1.25)
        superEllipsoid.SetYRadius(1.5)
        superEllipsoid.SetZRadius(1.0)
        superEllipsoid.SetN1(1.1)
        superEllipsoid.SetN2(1.75)
        superEllipsoidSource = vtk.vtkParametricFunctionSource()
        superEllipsoidSource.SetParametricFunction(superEllipsoid)
        superEllipsoidSource.SetScalarModeToV()

        superEllipsoidMapper = vtk.vtkPolyDataMapper()
        superEllipsoidMapper.SetInputConnection(superEllipsoidSource.GetOutputPort())
        superEllipsoidMapper.SetScalarRange(0, 3.14)

        superEllipsoidActor = vtk.vtkActor()
        superEllipsoidActor.SetMapper(superEllipsoidMapper)
        superEllipsoidActor.SetPosition(8, 4, 0)

        superEllipsoidTextMapper = vtk.vtkTextMapper()
        superEllipsoidTextMapper.SetInput("Super.Ellipsoid")
        superEllipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superEllipsoidTextMapper.GetTextProperty().SetFontSize(14)
        superEllipsoidTextActor = vtk.vtkActor2D()
        superEllipsoidTextActor.SetMapper(superEllipsoidTextMapper)
        superEllipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superEllipsoidTextActor.GetPositionCoordinate().SetValue(8, 1.5, 0)

        # ------------------------------------------------------------
        # Create an open 1D spline
        # ------------------------------------------------------------
        splinePoints = [[ -0.981576726763 , 0.639953289013 , -0.305071552892 ],
                        [ 0.6624105478 , -0.865923131754 , 0.429924616325 ],
                        [ -0.2569734311 , -0.952456491977 , 0.0637393393851 ],
                        [ -0.732922955292 , -0.236109588871 , -0.293860152035 ],
                        [ -0.907575251492 , 0.382748181644 , 0.848688894812 ],
                        [ -0.0857448890273 , 0.885650117828 , -0.878469658959 ],
                        [ -0.439558122977 , 0.346627118693 , -0.238016126323 ],
                        [ -0.337035103392 , -0.548982715024 , -0.752491410706 ],
                        [ 0.876860257181 , -0.609657562156 , -0.514647156705 ],
                        [ 0.325237251504 , 0.26248602721 , -0.397340677398 ]]
        inputPoints = vtk.vtkPoints()
        for i in range(0, 10):
            inputPoints.InsertPoint(i, splinePoints[i])

        spline = vtk.vtkParametricSpline()
        spline.SetPoints(inputPoints)
        spline.ClosedOff()
        splineSource = vtk.vtkParametricFunctionSource()
        splineSource.SetParametricFunction(spline)

        splineMapper = vtk.vtkPolyDataMapper()
        splineMapper.SetInputConnection(splineSource.GetOutputPort())

        splineActor = vtk.vtkActor()
        splineActor.SetMapper(splineMapper)
        splineActor.SetPosition(16, 4, 0)
        splineActor.GetProperty().SetColor(0, 0, 0)

        splineTextMapper = vtk.vtkTextMapper()
        splineTextMapper.SetInput("Open.Spline")
        splineTextMapper.GetTextProperty().SetJustificationToCentered()
        splineTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        splineTextMapper.GetTextProperty().SetColor(1, 0, 0)
        splineTextMapper.GetTextProperty().SetFontSize(14)
        splineTextActor = vtk.vtkActor2D()
        splineTextActor.SetMapper(splineTextMapper)
        splineTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        splineTextActor.GetPositionCoordinate().SetValue(16, 1.5, 0)

        # ------------------------------------------------------------
        # Create a closed 1D spline
        # ------------------------------------------------------------
        spline2 = vtk.vtkParametricSpline()
        spline2.SetPoints(inputPoints)
        spline2.ClosedOn()
        spline2Source = vtk.vtkParametricFunctionSource()
        spline2Source.SetParametricFunction(spline2)

        spline2Mapper = vtk.vtkPolyDataMapper()
        spline2Mapper.SetInputConnection(spline2Source.GetOutputPort())

        spline2Actor = vtk.vtkActor()
        spline2Actor.SetMapper(spline2Mapper)
        spline2Actor.SetPosition(24, 4, 0)
        spline2Actor.GetProperty().SetColor(0, 0, 0)

        spline2TextMapper = vtk.vtkTextMapper()
        spline2TextMapper.SetInput("Closed.Spline")
        spline2TextMapper.GetTextProperty().SetJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetColor(1, 0, 0)
        spline2TextMapper.GetTextProperty().SetFontSize(14)
        spline2TextActor = vtk.vtkActor2D()
        spline2TextActor.SetMapper(spline2TextMapper)
        spline2TextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        spline2TextActor.GetPositionCoordinate().SetValue(24, 1.5, 0)

        # ------------------------------------------------------------
        # Create a spiral conic
        # ------------------------------------------------------------
        sconic = vtk.vtkParametricConicSpiral()
        sconic.SetA(0.8)
        sconic.SetB(2.5)
        sconic.SetC(0.4)
        sconicSource = vtk.vtkParametricFunctionSource()
        sconicSource.SetParametricFunction(sconic)
        sconicSource.SetScalarModeToDistance()

        sconicMapper = vtk.vtkPolyDataMapper()
        sconicMapper.SetInputConnection(sconicSource.GetOutputPort())
        sconicActor = vtk.vtkActor()
        sconicActor.SetMapper(sconicMapper)
        sconicMapper.SetScalarRange(0, 9)
        sconicActor.SetPosition(0, -4, 0)
        sconicActor.SetScale(1.2, 1.2, 1.2)

        sconicTextMapper = vtk.vtkTextMapper()
        sconicTextMapper.SetInput("Spiral.Conic")
        sconicTextMapper.GetTextProperty().SetJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetColor(1, 0, 0)
        sconicTextMapper.GetTextProperty().SetFontSize(14)
        sconicTextActor = vtk.vtkActor2D()
        sconicTextActor.SetMapper(sconicTextMapper)
        sconicTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        sconicTextActor.GetPositionCoordinate().SetValue(0, -6.5, 0)

        # ------------------------------------------------------------
        # Create Boy's surface
        # ------------------------------------------------------------
        boy = vtk.vtkParametricBoy()
        boySource = vtk.vtkParametricFunctionSource()
        boySource.SetParametricFunction(boy)
        boySource.SetScalarModeToModulus()

        boyMapper = vtk.vtkPolyDataMapper()
        boyMapper.SetInputConnection(boySource.GetOutputPort())
        boyMapper.SetScalarRange(0, 2)
        boyActor = vtk.vtkActor()
        boyActor.SetMapper(boyMapper)
        boyActor.SetPosition(8, -4, 0)
        boyActor.SetScale(1.5, 1.5, 1.5)

        boyTextMapper = vtk.vtkTextMapper()
        boyTextMapper.SetInput("Boy")
        boyTextMapper.GetTextProperty().SetJustificationToCentered()
        boyTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        boyTextMapper.GetTextProperty().SetColor(1, 0, 0)
        boyTextMapper.GetTextProperty().SetFontSize(14)
        boyTextActor = vtk.vtkActor2D()
        boyTextActor.SetMapper(boyTextMapper)
        boyTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        boyTextActor.GetPositionCoordinate().SetValue(8, -6.5, 0)

        # ------------------------------------------------------------
        # Create a cross cap
        # ------------------------------------------------------------
        crossCap = vtk.vtkParametricCrossCap()
        crossCapSource = vtk.vtkParametricFunctionSource()
        crossCapSource.SetParametricFunction(crossCap)
        crossCapSource.SetScalarModeToY()

        crossCapMapper = vtk.vtkPolyDataMapper()
        crossCapMapper.SetInputConnection(crossCapSource.GetOutputPort())
        crossCapActor = vtk.vtkActor()
        crossCapActor.SetMapper(crossCapMapper)
        crossCapActor.RotateX(65)
        crossCapActor.SetPosition(16, -4, 0)
        crossCapActor.SetScale(1.5, 1.5, 1.5)

        crossCapTextMapper = vtk.vtkTextMapper()
        crossCapTextMapper.SetInput("Cross.Cap")
        crossCapTextMapper.GetTextProperty().SetJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetColor(1, 0, 0)
        crossCapTextMapper.GetTextProperty().SetFontSize(14)
        crossCapTextActor = vtk.vtkActor2D()
        crossCapTextActor.SetMapper(crossCapTextMapper)
        crossCapTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        crossCapTextActor.GetPositionCoordinate().SetValue(16, -6.5, 0)

        # ------------------------------------------------------------
        # Create Dini's surface
        # ------------------------------------------------------------
        dini = vtk.vtkParametricDini()
        diniSource = vtk.vtkParametricFunctionSource()
        diniSource.SetScalarModeToDistance()
        diniSource.SetParametricFunction(dini)

        diniMapper = vtk.vtkPolyDataMapper()
        diniMapper.SetInputConnection(diniSource.GetOutputPort())

        diniActor = vtk.vtkActor()
        diniActor.SetMapper(diniMapper)
        diniActor.RotateX(-90)
        diniActor.SetPosition(24, -3, 0)
        diniActor.SetScale(1.5, 1.5, 0.5)

        diniTextMapper = vtk.vtkTextMapper()
        diniTextMapper.SetInput("Dini")
        diniTextMapper.GetTextProperty().SetJustificationToCentered()
        diniTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        diniTextMapper.GetTextProperty().SetColor(1, 0, 0)
        diniTextMapper.GetTextProperty().SetFontSize(14)
        diniTextActor = vtk.vtkActor2D()
        diniTextActor.SetMapper(diniTextMapper)
        diniTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        diniTextActor.GetPositionCoordinate().SetValue(24, -6.5, 0)

        # ------------------------------------------------------------
        # Create Enneper's surface
        # ------------------------------------------------------------
        enneper = vtk.vtkParametricEnneper()
        enneperSource = vtk.vtkParametricFunctionSource()
        enneperSource.SetParametricFunction(enneper)
        enneperSource.SetScalarModeToQuadrant()

        enneperMapper = vtk.vtkPolyDataMapper()
        enneperMapper.SetInputConnection(enneperSource.GetOutputPort())
        enneperMapper.SetScalarRange(1, 4)

        enneperActor = vtk.vtkActor()
        enneperActor.SetMapper(enneperMapper)
        enneperActor.SetPosition(0, -12, 0)
        enneperActor.SetScale(0.25, 0.25, 0.25)

        enneperTextMapper = vtk.vtkTextMapper()
        enneperTextMapper.SetInput("Enneper")
        enneperTextMapper.GetTextProperty().SetJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetColor(1, 0, 0)
        enneperTextMapper.GetTextProperty().SetFontSize(14)
        enneperTextActor = vtk.vtkActor2D()
        enneperTextActor.SetMapper(enneperTextMapper)
        enneperTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        enneperTextActor.GetPositionCoordinate().SetValue(0, -14.5, 0)

        # ------------------------------------------------------------
        # Create an ellipsoidal surface
        # ------------------------------------------------------------
        ellipsoid = vtk.vtkParametricEllipsoid()
        ellipsoid.SetXRadius(1)
        ellipsoid.SetYRadius(0.75)
        ellipsoid.SetZRadius(0.5)
        ellipsoidSource = vtk.vtkParametricFunctionSource()
        ellipsoidSource.SetParametricFunction(ellipsoid)
        ellipsoidSource.SetScalarModeToZ()

        ellipsoidMapper = vtk.vtkPolyDataMapper()
        ellipsoidMapper.SetInputConnection(ellipsoidSource.GetOutputPort())
        ellipsoidMapper.SetScalarRange(-0.5, 0.5)

        ellipsoidActor = vtk.vtkActor()
        ellipsoidActor.SetMapper(ellipsoidMapper)
        ellipsoidActor.SetPosition(8, -12, 0)
        ellipsoidActor.SetScale(1.5, 1.5, 1.5)

        ellipsoidTextMapper = vtk.vtkTextMapper()
        ellipsoidTextMapper.SetInput("Ellipsoid")
        ellipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        ellipsoidTextMapper.GetTextProperty().SetFontSize(14)
        ellipsoidTextActor = vtk.vtkActor2D()
        ellipsoidTextActor.SetMapper(ellipsoidTextMapper)
        ellipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        ellipsoidTextActor.GetPositionCoordinate().SetValue(8, -14.5, 0)

        # ------------------------------------------------------------
        # Create an surface with random hills on it.
        # Note that for testing, we will disable the
        # random generation of the surfaces. This is
        # because random number generators do not
        # return the same result on different operating
        # systems.
        # ------------------------------------------------------------
        randomHills = vtk.vtkParametricRandomHills()
        randomHills.AllowRandomGenerationOff()
        randomHills.GenerateTheHills()
        randomHillsSource = vtk.vtkParametricFunctionSource()
        randomHillsSource.SetParametricFunction(randomHills)
        randomHillsSource.GenerateTextureCoordinatesOn()

        randomHillsMapper = vtk.vtkPolyDataMapper()
        randomHillsMapper.SetInputConnection(randomHillsSource.GetOutputPort())

        randomHillsActor = vtk.vtkActor()
        randomHillsActor.SetMapper(randomHillsMapper)
        randomHillsActor.SetPosition(16, -14, 0)
        randomHillsActor.SetScale(0.2, 0.2, 0.2)
        randomHillsActor.SetTexture(texture)

        randomHillsTextMapper = vtk.vtkTextMapper()
        randomHillsTextMapper.SetInput("Random.Hills")
        randomHillsTextMapper.GetTextProperty().SetJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetColor(1, 0, 0)
        randomHillsTextMapper.GetTextProperty().SetFontSize(14)
        randomHillsTextActor = vtk.vtkActor2D()
        randomHillsTextActor.SetMapper(randomHillsTextMapper)
        randomHillsTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        randomHillsTextActor.GetPositionCoordinate().SetValue(16, -14.5, 0)

        # ------------------------------------------------------------
        # Create an Steiner's Roman Surface.
        # ------------------------------------------------------------
        roman = vtk.vtkParametricRoman()
        roman.SetRadius(1.5)
        romanSource = vtk.vtkParametricFunctionSource()
        romanSource.SetParametricFunction(roman)
        romanSource.SetScalarModeToX()

        romanMapper = vtk.vtkPolyDataMapper()
        romanMapper.SetInputConnection(romanSource.GetOutputPort())

        romanActor = vtk.vtkActor()
        romanActor.SetMapper(romanMapper)
        romanActor.SetPosition(24, -12, 0)

        romanTextMapper = vtk.vtkTextMapper()
        romanTextMapper.SetInput("Roman")
        romanTextMapper.GetTextProperty().SetJustificationToCentered()
        romanTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        romanTextMapper.GetTextProperty().SetColor(1, 0, 0)
        romanTextMapper.GetTextProperty().SetFontSize(14)
        romanTextActor = vtk.vtkActor2D()
        romanTextActor.SetMapper(romanTextMapper)
        romanTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        romanTextActor.GetPositionCoordinate().SetValue(24, -14.5, 0)

        # ------------------------------------------------------------
        # Create the RenderWindow, Renderer and both Actors
        # ------------------------------------------------------------
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # add actors
        ren.AddViewProp(torusActor)
        ren.AddViewProp(kleinActor)
        ren.AddViewProp(klein2Actor)
        ren.AddViewProp(toroidActor)
        ren.AddViewProp(superEllipsoidActor)
        ren.AddViewProp(mobiusActor)
        ren.AddViewProp(splineActor)
        ren.AddViewProp(spline2Actor)
        ren.AddViewProp(sconicActor)
        ren.AddViewProp(boyActor)
        ren.AddViewProp(crossCapActor)
        ren.AddViewProp(diniActor)
        ren.AddViewProp(enneperActor)
        ren.AddViewProp(ellipsoidActor)
        ren.AddViewProp(randomHillsActor)
        ren.AddViewProp(romanActor)
        #add text actors
        ren.AddViewProp(torusTextActor)
        ren.AddViewProp(kleinTextActor)
        ren.AddViewProp(fig8KleinTextActor)
        ren.AddViewProp(mobiusTextActor)
        ren.AddViewProp(superToroidTextActor)
        ren.AddViewProp(superEllipsoidTextActor)
        ren.AddViewProp(splineTextActor)
        ren.AddViewProp(spline2TextActor)
        ren.AddViewProp(sconicTextActor)
        ren.AddViewProp(boyTextActor)
        ren.AddViewProp(crossCapTextActor)
        ren.AddViewProp(diniTextActor)
        ren.AddViewProp(enneperTextActor)
        ren.AddViewProp(ellipsoidTextActor)
        ren.AddViewProp(randomHillsTextActor)
        ren.AddViewProp(romanTextActor)

        ren.SetBackground(0.7, 0.8, 1)
        renWin.SetSize(500, 500)
        ren.ResetCamera()
        ren.GetActiveCamera().Zoom(1.3)

        iren.Initialize()
        renWin.Render()

        img_file = "TestParametricFunctions.png"
        vtk.test.Testing.compareImage(iren.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=35)
        vtk.test.Testing.interact()
Beispiel #42
0
    def setWidgetView(self, widget, color = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]):
        super(SurfaceView, self).setWidgetView(widget)
        
        if type(self.parent) is MdiChildRegistration:
            point_array_move = self.parent.getData('move').pointSet
            point_data_move = npy.array(point_array_move.getData('Contour'))
            point_data_result = npy.array(point_data_move)
            
            if point_data_result is None or not point_data_result.shape[0]:
                return
                
            self.spacing_mov = self.parent.getData('move').getResolution().tolist()
            self.spacing = self.parent.getData().getResolution().tolist()
            
            para = npy.array(self.parent.getData().getInfo().getData('transform'))
            R = ml.mat(para[:9].reshape(3, 3))
            T = ml.mat(para[9:12].reshape(3, 1))
            
            T = R.I * T
            T = -T
            point_data_result[:, :3] *= self.spacing_mov[:3]
            point_data_result[:, :3] = ml.mat(point_data_result[:, :3]) * R + ml.ones((point_data_result.shape[0], 1)) * T.T
            point_data_result[:, :3] /= self.spacing[:3]
        else:
            point_array_result = self.parent.getData().pointSet
            point_data_result = npy.array(point_array_result.getData('Contour'))
            point_array_move = point_array_result
            point_data_move = npy.array(point_array_move.getData('Contour'))

        
        zmin = int(npy.min(point_data_move[:, 2]) + 0.5)
        zmax = int(npy.max(point_data_move[:, 2]) + 0.5)
        self.spacing = self.parent.getData().getResolution().tolist()
        self.spacing = [float(x) / self.spacing[-1] for x in self.spacing]
        point_data_result[:, :2] *= self.spacing[:2]
        
        self.renderer = vtk.vtkRenderer()
        self.render_window = widget.GetRenderWindow()
        self.render_window.AddRenderer(self.renderer)
        self.window_interactor = vtk.vtkRenderWindowInteractor()
        self.render_window.SetInteractor(self.window_interactor)
        
        self.contours = []
        self.delaunay3D = []
        self.delaunayMapper = []
        self.surface_actor = []
        
        for cnt in range(3):
            self.contours.append(vtk.vtkPolyData())
            self.delaunay3D.append(vtk.vtkDelaunay3D())
            self.delaunayMapper.append(vtk.vtkDataSetMapper())
            self.surface_actor.append(vtk.vtkActor())
            
            point_result = point_data_result[npy.where(npy.round(point_data_result[:, -1]) == cnt)]
            point_move = point_data_move[npy.where(npy.round(point_data_move[:, -1]) == cnt)]
            if not point_result.shape[0]:
                continue
                
            self.cells = vtk.vtkCellArray()
            self.points = vtk.vtkPoints()
            l = 0
            for i in range(zmin, zmax + 1):
                data = point_result[npy.where(npy.round(point_move[:, 2]) == i)]
                if data is not None:
                    if data.shape[0] == 0:
                        continue
                    count = data.shape[0]
                    points = vtk.vtkPoints()
                    for j in range(count):
                        points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2])
                    
                    para_spline = vtk.vtkParametricSpline()
                    para_spline.SetPoints(points)
                    para_spline.ClosedOn()
                    
                    # The number of output points set to 10 times of input points
                    numberOfOutputPoints = count * 10
                    self.cells.InsertNextCell(numberOfOutputPoints)
                    for k in range(0, numberOfOutputPoints):
                        t = k * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[0] != pt[0]:
                            print pt
                            continue
                        self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                        self.cells.InsertCellPoint(l)
                        l += 1

            self.contours[cnt].SetPoints(self.points)
            self.contours[cnt].SetPolys(self.cells)
            
            self.delaunay3D[cnt].SetInput(self.contours[cnt])
            self.delaunay3D[cnt].SetAlpha(2)
            
            self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput())
            
            self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt])
            self.surface_actor[cnt].GetProperty().SetDiffuseColor(color[cnt][0], color[cnt][1], color[cnt][2])
            self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1)
            self.surface_actor[cnt].GetProperty().SetSpecular(0.4)
            self.surface_actor[cnt].GetProperty().SetSpecularPower(50)
            
            self.renderer.AddViewProp(self.surface_actor[cnt])
        
        self.renderer.ResetCamera()
        point = self.renderer.GetActiveCamera().GetFocalPoint()
        dis = self.renderer.GetActiveCamera().GetDistance()
        self.renderer.GetActiveCamera().SetViewUp(0, 0, 1)
        self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis, point[2])
        self.renderer.ResetCameraClippingRange()
        self.render_window.Render()
        
        # Manually set to trackball style
        self.window_interactor.SetKeyCode('t')
        self.window_interactor.CharEvent()
        self.window_interactor.GetInteractorStyle().AddObserver("KeyPressEvent", self.KeyPressCallback)
        self.window_interactor.GetInteractorStyle().AddObserver("CharEvent", self.KeyPressCallback)
 def analysis(self, data, point_data_fix = None):
     if point_data_fix is None:
         point_data_fix = self.gui.dataModel[data.getFixedIndex()].getPointSet('Centerline').copy()
     point_data_result = data.getPointSet('Centerline').copy()
     
     self.spacing = data.getResolution().tolist()
     point_data_fix = point_data_fix[point_data_fix[:, 0] >= 0]
     point_data_result = point_data_result[point_data_result[:, 0] >= 0]
     point_data_fix[:, :3] *= self.spacing[:3]
     point_data_result[:, :3] *= self.spacing[:3]
     
     ind = point_data_fix[:, 2].argsort()
     point_data_fix = point_data_fix[ind]
     
     Locator = [vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator()]
     targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()]
     targetVertices = [vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray()]
     target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()]
     
     for cnt in range(1, 3):
         resampled_points = point_data_fix[npy.where(npy.round(point_data_fix[:, -1]) != 3 - cnt)]
         
         count = resampled_points.shape[0]
         points = vtk.vtkPoints()
         for i in range(count):
             if i + 1 < count and resampled_points[i, 3] != resampled_points[i + 1, 3]: # bifurcation point
                 continue
             points.InsertPoint(i, resampled_points[i, 0], resampled_points[i, 1], resampled_points[i, 2])
 
         para_spline = vtk.vtkParametricSpline()
         para_spline.SetPoints(points)
         para_spline.ClosedOff()
         
         numberOfOutputPoints = count * 50
         
         for i in range(0, numberOfOutputPoints):
             t = i * 1.0 / numberOfOutputPoints
             pt = [0.0, 0.0, 0.0]
             para_spline.Evaluate([t, t, t], pt, [0] * 9)
             id = targetPoints[0].InsertNextPoint(pt[0], pt[1], pt[2])
             targetVertices[0].InsertNextCell(1)
             targetVertices[0].InsertCellPoint(id)
             id = targetPoints[cnt].InsertNextPoint(pt[0], pt[1], pt[2])
             targetVertices[cnt].InsertNextCell(1)
             targetVertices[cnt].InsertCellPoint(id)
     
     for i in range(3):
         target[i].SetPoints(targetPoints[i])
         target[i].SetVerts(targetVertices[i])
         
         Locator[i].SetDataSet(target[i])
         Locator[i].SetNumberOfCellsPerBucket(1)
         Locator[i].BuildLocator()
     
     id1 = id2 = vtk.mutable(0)
     dist = vtk.mutable(0.0)
     outPoint = [0.0, 0.0, 0.0]
     
     cnt_num = npy.array([0, 0, 0])
     mean_dis = npy.array([0.0, 0.0, 0.0])
     max_dis = npy.array([0.0, 0.0, 0.0])
     
     for pt in point_data_result:
         cnt = int(pt[-1] + 0.5)
         Locator[cnt].FindClosestPoint(pt[:3].tolist(), outPoint, id1, id2, dist)
         dis = npy.sqrt(npy.sum((npy.array(outPoint) - pt[:3]) ** 2))
         mean_dis[cnt] += dis
         max_dis[cnt] = npy.max([max_dis[cnt], dis])
         cnt_num[cnt] += 1
     
     cnt_total = npy.sum(cnt_num)
     mean_whole = npy.sum(mean_dis) / cnt_total
     mean_dis /= cnt_num
     mean_dis[mean_dis != mean_dis] = 0 # Replace the NAN in the mean distance
     max_whole = npy.max(max_dis)
     
     if self.gui is not None:
         message = "Error on Vessel 0: %0.2fmm (Total %d slices)\nError on Vessel 1: %0.2fmm (Total %d slices)\nError on Vessel 2: %0.2fmm (Total %d slices)\nWhole Error: %0.2fmm (Total %d slices)\n" \
             % (mean_dis[0], cnt_num[0], mean_dis[1], cnt_num[1], mean_dis[2], cnt_num[2], mean_whole, cnt_total) + \
             "-----------------------------------------------------------------------------\n" + \
             "Max Error on Vessel 0: %0.2fmm\nMax Error on Vessel 1: %0.2fmm\nMax Error on Vessel 2: %0.2fmm\nTotal Max Error: %0.2fmm" \
             % (max_dis[0], max_dis[1], max_dis[2], npy.max(max_dis));
         self.gui.showErrorMessage("Centerline Registration Error", message)
     return mean_dis, mean_whole, max_dis, max_whole
Beispiel #44
0
    def testParametricFunctions(self):
        # ------------------------------------------------------------
        # Get a texture
        # ------------------------------------------------------------
        textureReader = vtk.vtkJPEGReader()
        textureReader.SetFileName(VTK_DATA_ROOT + "/Data/beach.jpg")
        texture = vtk.vtkTexture()
        texture.SetInputConnection(textureReader.GetOutputPort())

        # ------------------------------------------------------------
        # For each parametric surface:
        # 1) Create it
        # 2) Assign mappers and actors
        # 3) Position the object
        # 5) Add a label
        # ------------------------------------------------------------

        # ------------------------------------------------------------
        # Create a torus
        # ------------------------------------------------------------
        torus = vtk.vtkParametricTorus()
        torusSource = vtk.vtkParametricFunctionSource()
        torusSource.SetParametricFunction(torus)
        torusSource.SetScalarModeToPhase()

        torusMapper = vtk.vtkPolyDataMapper()
        torusMapper.SetInputConnection(torusSource.GetOutputPort())
        torusMapper.SetScalarRange(0, 360)

        torusActor = vtk.vtkActor()
        torusActor.SetMapper(torusMapper)
        torusActor.SetPosition(0, 12, 0)

        torusTextMapper = vtk.vtkTextMapper()
        torusTextMapper.SetInput("Torus")
        torusTextMapper.GetTextProperty().SetJustificationToCentered()
        torusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        torusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        torusTextMapper.GetTextProperty().SetFontSize(14)
        torusTextActor = vtk.vtkActor2D()
        torusTextActor.SetMapper(torusTextMapper)
        torusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        torusTextActor.GetPositionCoordinate().SetValue(0, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Klein bottle
        # ------------------------------------------------------------
        klein = vtk.vtkParametricKlein()
        kleinSource = vtk.vtkParametricFunctionSource()
        kleinSource.SetParametricFunction(klein)
        kleinSource.SetScalarModeToU0V0()

        kleinMapper = vtk.vtkPolyDataMapper()
        kleinMapper.SetInputConnection(kleinSource.GetOutputPort())
        kleinMapper.SetScalarRange(0, 3)

        kleinActor = vtk.vtkActor()
        kleinActor.SetMapper(kleinMapper)
        kleinActor.SetPosition(8, 10.5, 0)

        kleinTextMapper = vtk.vtkTextMapper()
        kleinTextMapper.SetInput("Klein")
        kleinTextMapper.GetTextProperty().SetJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        kleinTextMapper.GetTextProperty().SetFontSize(14)
        kleinTextActor = vtk.vtkActor2D()
        kleinTextActor.SetMapper(kleinTextMapper)
        kleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        kleinTextActor.GetPositionCoordinate().SetValue(8, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Figure-8 Klein
        # ------------------------------------------------------------
        klein2 = vtk.vtkParametricFigure8Klein()
        klein2Source = vtk.vtkParametricFunctionSource()
        klein2Source.SetParametricFunction(klein2)
        klein2Source.GenerateTextureCoordinatesOn()

        klein2Mapper = vtk.vtkPolyDataMapper()
        klein2Mapper.SetInputConnection(klein2Source.GetOutputPort())
        klein2Mapper.SetScalarRange(0, 3)

        klein2Actor = vtk.vtkActor()
        klein2Actor.SetMapper(klein2Mapper)
        klein2Actor.SetPosition(16, 12, 0)
        klein2Actor.SetTexture(texture)


        fig8KleinTextMapper = vtk.vtkTextMapper()
        fig8KleinTextMapper.SetInput("Fig-8.Klein")
        fig8KleinTextMapper.GetTextProperty().SetJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        fig8KleinTextMapper.GetTextProperty().SetFontSize(14)
        fig8KleinTextActor = vtk.vtkActor2D()
        fig8KleinTextActor.SetMapper(fig8KleinTextMapper)
        fig8KleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        fig8KleinTextActor.GetPositionCoordinate().SetValue(16, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Mobius strip
        # ------------------------------------------------------------
        mobius = vtk.vtkParametricMobius()
        mobiusSource = vtk.vtkParametricFunctionSource()
        mobiusSource.SetParametricFunction(mobius)
        mobiusSource.GenerateTextureCoordinatesOn()

        mobiusMapper = vtk.vtkPolyDataMapper()
        mobiusMapper.SetInputConnection(mobiusSource.GetOutputPort())

        mobiusActor = vtk.vtkActor()
        mobiusActor.SetMapper(mobiusMapper)
        mobiusActor.RotateX(45)
        mobiusActor.SetPosition(24, 12, 0)
        mobiusActor.SetTexture(texture)

        mobiusTextMapper = vtk.vtkTextMapper()
        mobiusTextMapper.SetInput("Mobius")
        mobiusTextMapper.GetTextProperty().SetJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        mobiusTextMapper.GetTextProperty().SetFontSize(14)
        mobiusTextActor = vtk.vtkActor2D()
        mobiusTextActor.SetMapper(mobiusTextMapper)
        mobiusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        mobiusTextActor.GetPositionCoordinate().SetValue(24, 9.5, 0)

        # ------------------------------------------------------------
        # Create a super toroid
        # ------------------------------------------------------------
        toroid = vtk.vtkParametricSuperToroid()
        toroid.SetN1(2)
        toroid.SetN2(3)
        toroidSource = vtk.vtkParametricFunctionSource()
        toroidSource.SetParametricFunction(toroid)
        toroidSource.SetScalarModeToU()

        toroidMapper = vtk.vtkPolyDataMapper()
        toroidMapper.SetInputConnection(toroidSource.GetOutputPort())
        toroidMapper.SetScalarRange(0, 6.28)

        toroidActor = vtk.vtkActor()
        toroidActor.SetMapper(toroidMapper)
        toroidActor.SetPosition(0, 4, 0)

        superToroidTextMapper = vtk.vtkTextMapper()
        superToroidTextMapper.SetInput("Super.Toroid")
        superToroidTextMapper.GetTextProperty().SetJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superToroidTextMapper.GetTextProperty().SetFontSize(14)
        superToroidTextActor = vtk.vtkActor2D()
        superToroidTextActor.SetMapper(superToroidTextMapper)
        superToroidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superToroidTextActor.GetPositionCoordinate().SetValue(0, 1.5, 0)

        # ------------------------------------------------------------
        # Create a super ellipsoid
        # ------------------------------------------------------------
        superEllipsoid = vtk.vtkParametricSuperEllipsoid()
        superEllipsoid.SetXRadius(1.25)
        superEllipsoid.SetYRadius(1.5)
        superEllipsoid.SetZRadius(1.0)
        superEllipsoid.SetN1(1.1)
        superEllipsoid.SetN2(1.75)
        superEllipsoidSource = vtk.vtkParametricFunctionSource()
        superEllipsoidSource.SetParametricFunction(superEllipsoid)
        superEllipsoidSource.SetScalarModeToV()

        superEllipsoidMapper = vtk.vtkPolyDataMapper()
        superEllipsoidMapper.SetInputConnection(superEllipsoidSource.GetOutputPort())
        superEllipsoidMapper.SetScalarRange(0, 3.14)

        superEllipsoidActor = vtk.vtkActor()
        superEllipsoidActor.SetMapper(superEllipsoidMapper)
        superEllipsoidActor.SetPosition(8, 4, 0)

        superEllipsoidTextMapper = vtk.vtkTextMapper()
        superEllipsoidTextMapper.SetInput("Super.Ellipsoid")
        superEllipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superEllipsoidTextMapper.GetTextProperty().SetFontSize(14)
        superEllipsoidTextActor = vtk.vtkActor2D()
        superEllipsoidTextActor.SetMapper(superEllipsoidTextMapper)
        superEllipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superEllipsoidTextActor.GetPositionCoordinate().SetValue(8, 1.5, 0)

        # ------------------------------------------------------------
        # Create an open 1D spline
        # ------------------------------------------------------------
        splinePoints = [
          [0.50380158308139134, -0.60679315105396936, -0.37248976406291578],
          [-0.4354646054261665, -0.85362339758017258, -0.84844312996065385],
          [0.2163147512899315, -0.39797507012168643, -0.76700353518454523],
          [0.97158415334838644, -0.58513467367046257, -0.35846037946569753],
          [-0.64359767997804918, -0.94620739107309249, -0.90762176546623086],
          [-0.39901219094126117, -0.1978931497772658, 0.0098316934936828471],
          [-0.75872745167404765, 0.067719714281950116, 0.165237936733867],
          [-0.84599731389712418, -0.67685466896596114, 0.10357868909071133],
          [0.84702754758625654, -0.0080077177882230677, -0.58571286666473044],
          [-0.076150034124101484, 0.14637647622561856, 0.1494359239700418] ]
        inputPoints = vtk.vtkPoints()
        for i in range(0, 10):
            inputPoints.InsertPoint(i, splinePoints[i])

        spline = vtk.vtkParametricSpline()
        spline.SetPoints(inputPoints)
        spline.ClosedOff()
        splineSource = vtk.vtkParametricFunctionSource()
        splineSource.SetParametricFunction(spline)

        splineMapper = vtk.vtkPolyDataMapper()
        splineMapper.SetInputConnection(splineSource.GetOutputPort())

        splineActor = vtk.vtkActor()
        splineActor.SetMapper(splineMapper)
        splineActor.SetPosition(16, 4, 0)
        splineActor.GetProperty().SetColor(0, 0, 0)

        splineTextMapper = vtk.vtkTextMapper()
        splineTextMapper.SetInput("Open.Spline")
        splineTextMapper.GetTextProperty().SetJustificationToCentered()
        splineTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        splineTextMapper.GetTextProperty().SetColor(1, 0, 0)
        splineTextMapper.GetTextProperty().SetFontSize(14)
        splineTextActor = vtk.vtkActor2D()
        splineTextActor.SetMapper(splineTextMapper)
        splineTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        splineTextActor.GetPositionCoordinate().SetValue(16, 1.5, 0)

        # ------------------------------------------------------------
        # Create a closed 1D spline
        # ------------------------------------------------------------
        spline2 = vtk.vtkParametricSpline()
        spline2.SetPoints(inputPoints)
        spline2.ClosedOn()
        spline2Source = vtk.vtkParametricFunctionSource()
        spline2Source.SetParametricFunction(spline2)

        spline2Mapper = vtk.vtkPolyDataMapper()
        spline2Mapper.SetInputConnection(spline2Source.GetOutputPort())

        spline2Actor = vtk.vtkActor()
        spline2Actor.SetMapper(spline2Mapper)
        spline2Actor.SetPosition(24, 4, 0)
        spline2Actor.GetProperty().SetColor(0, 0, 0)

        spline2TextMapper = vtk.vtkTextMapper()
        spline2TextMapper.SetInput("Closed.Spline")
        spline2TextMapper.GetTextProperty().SetJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetColor(1, 0, 0)
        spline2TextMapper.GetTextProperty().SetFontSize(14)
        spline2TextActor = vtk.vtkActor2D()
        spline2TextActor.SetMapper(spline2TextMapper)
        spline2TextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        spline2TextActor.GetPositionCoordinate().SetValue(24, 1.5, 0)

        # ------------------------------------------------------------
        # Create a spiral conic
        # ------------------------------------------------------------
        sconic = vtk.vtkParametricConicSpiral()
        sconic.SetA(0.8)
        sconic.SetB(2.5)
        sconic.SetC(0.4)
        sconicSource = vtk.vtkParametricFunctionSource()
        sconicSource.SetParametricFunction(sconic)
        sconicSource.SetScalarModeToDistance()

        sconicMapper = vtk.vtkPolyDataMapper()
        sconicMapper.SetInputConnection(sconicSource.GetOutputPort())
        sconicActor = vtk.vtkActor()
        sconicActor.SetMapper(sconicMapper)
        sconicMapper.SetScalarRange(0, 9)
        sconicActor.SetPosition(0, -4, 0)
        sconicActor.SetScale(1.2, 1.2, 1.2)

        sconicTextMapper = vtk.vtkTextMapper()
        sconicTextMapper.SetInput("Spiral.Conic")
        sconicTextMapper.GetTextProperty().SetJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetColor(1, 0, 0)
        sconicTextMapper.GetTextProperty().SetFontSize(14)
        sconicTextActor = vtk.vtkActor2D()
        sconicTextActor.SetMapper(sconicTextMapper)
        sconicTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        sconicTextActor.GetPositionCoordinate().SetValue(0, -6.5, 0)

        # ------------------------------------------------------------
        # Create Boy's surface
        # ------------------------------------------------------------
        boy = vtk.vtkParametricBoy()
        boySource = vtk.vtkParametricFunctionSource()
        boySource.SetParametricFunction(boy)
        boySource.SetScalarModeToModulus()

        boyMapper = vtk.vtkPolyDataMapper()
        boyMapper.SetInputConnection(boySource.GetOutputPort())
        boyMapper.SetScalarRange(0, 2)
        boyActor = vtk.vtkActor()
        boyActor.SetMapper(boyMapper)
        boyActor.SetPosition(8, -4, 0)
        boyActor.SetScale(1.5, 1.5, 1.5)

        boyTextMapper = vtk.vtkTextMapper()
        boyTextMapper.SetInput("Boy")
        boyTextMapper.GetTextProperty().SetJustificationToCentered()
        boyTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        boyTextMapper.GetTextProperty().SetColor(1, 0, 0)
        boyTextMapper.GetTextProperty().SetFontSize(14)
        boyTextActor = vtk.vtkActor2D()
        boyTextActor.SetMapper(boyTextMapper)
        boyTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        boyTextActor.GetPositionCoordinate().SetValue(8, -6.5, 0)

        # ------------------------------------------------------------
        # Create a cross cap
        # ------------------------------------------------------------
        crossCap = vtk.vtkParametricCrossCap()
        crossCapSource = vtk.vtkParametricFunctionSource()
        crossCapSource.SetParametricFunction(crossCap)
        crossCapSource.SetScalarModeToY()

        crossCapMapper = vtk.vtkPolyDataMapper()
        crossCapMapper.SetInputConnection(crossCapSource.GetOutputPort())
        crossCapActor = vtk.vtkActor()
        crossCapActor.SetMapper(crossCapMapper)
        crossCapActor.RotateX(65)
        crossCapActor.SetPosition(16, -4, 0)
        crossCapActor.SetScale(1.5, 1.5, 1.5)

        crossCapTextMapper = vtk.vtkTextMapper()
        crossCapTextMapper.SetInput("Cross.Cap")
        crossCapTextMapper.GetTextProperty().SetJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetColor(1, 0, 0)
        crossCapTextMapper.GetTextProperty().SetFontSize(14)
        crossCapTextActor = vtk.vtkActor2D()
        crossCapTextActor.SetMapper(crossCapTextMapper)
        crossCapTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        crossCapTextActor.GetPositionCoordinate().SetValue(16, -6.5, 0)

        # ------------------------------------------------------------
        # Create Dini's surface
        # ------------------------------------------------------------
        dini = vtk.vtkParametricDini()
        diniSource = vtk.vtkParametricFunctionSource()
        diniSource.SetScalarModeToDistance()
        diniSource.SetParametricFunction(dini)

        diniMapper = vtk.vtkPolyDataMapper()
        diniMapper.SetInputConnection(diniSource.GetOutputPort())

        diniActor = vtk.vtkActor()
        diniActor.SetMapper(diniMapper)
        diniActor.RotateX(-90)
        diniActor.SetPosition(24, -3, 0)
        diniActor.SetScale(1.5, 1.5, 0.5)

        diniTextMapper = vtk.vtkTextMapper()
        diniTextMapper.SetInput("Dini")
        diniTextMapper.GetTextProperty().SetJustificationToCentered()
        diniTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        diniTextMapper.GetTextProperty().SetColor(1, 0, 0)
        diniTextMapper.GetTextProperty().SetFontSize(14)
        diniTextActor = vtk.vtkActor2D()
        diniTextActor.SetMapper(diniTextMapper)
        diniTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        diniTextActor.GetPositionCoordinate().SetValue(24, -6.5, 0)

        # ------------------------------------------------------------
        # Create Enneper's surface
        # ------------------------------------------------------------
        enneper = vtk.vtkParametricEnneper()
        enneperSource = vtk.vtkParametricFunctionSource()
        enneperSource.SetParametricFunction(enneper)
        enneperSource.SetScalarModeToQuadrant()

        enneperMapper = vtk.vtkPolyDataMapper()
        enneperMapper.SetInputConnection(enneperSource.GetOutputPort())
        enneperMapper.SetScalarRange(1, 4)

        enneperActor = vtk.vtkActor()
        enneperActor.SetMapper(enneperMapper)
        enneperActor.SetPosition(0, -12, 0)
        enneperActor.SetScale(0.25, 0.25, 0.25)

        enneperTextMapper = vtk.vtkTextMapper()
        enneperTextMapper.SetInput("Enneper")
        enneperTextMapper.GetTextProperty().SetJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetColor(1, 0, 0)
        enneperTextMapper.GetTextProperty().SetFontSize(14)
        enneperTextActor = vtk.vtkActor2D()
        enneperTextActor.SetMapper(enneperTextMapper)
        enneperTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        enneperTextActor.GetPositionCoordinate().SetValue(0, -14.5, 0)

        # ------------------------------------------------------------
        # Create an ellipsoidal surface
        # ------------------------------------------------------------
        ellipsoid = vtk.vtkParametricEllipsoid()
        ellipsoid.SetXRadius(1)
        ellipsoid.SetYRadius(0.75)
        ellipsoid.SetZRadius(0.5)
        ellipsoidSource = vtk.vtkParametricFunctionSource()
        ellipsoidSource.SetParametricFunction(ellipsoid)
        ellipsoidSource.SetScalarModeToZ()

        ellipsoidMapper = vtk.vtkPolyDataMapper()
        ellipsoidMapper.SetInputConnection(ellipsoidSource.GetOutputPort())
        ellipsoidMapper.SetScalarRange(-0.5, 0.5)

        ellipsoidActor = vtk.vtkActor()
        ellipsoidActor.SetMapper(ellipsoidMapper)
        ellipsoidActor.SetPosition(8, -12, 0)
        ellipsoidActor.SetScale(1.5, 1.5, 1.5)

        ellipsoidTextMapper = vtk.vtkTextMapper()
        ellipsoidTextMapper.SetInput("Ellipsoid")
        ellipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        ellipsoidTextMapper.GetTextProperty().SetFontSize(14)
        ellipsoidTextActor = vtk.vtkActor2D()
        ellipsoidTextActor.SetMapper(ellipsoidTextMapper)
        ellipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        ellipsoidTextActor.GetPositionCoordinate().SetValue(8, -14.5, 0)

        # ------------------------------------------------------------
        # Create a surface with random hills on it.
        # ------------------------------------------------------------
        randomHills = vtk.vtkParametricRandomHills()
        randomHills.AllowRandomGenerationOn()
        randomHillsSource = vtk.vtkParametricFunctionSource()
        randomHillsSource.SetParametricFunction(randomHills)
        randomHillsSource.GenerateTextureCoordinatesOn()

        randomHillsMapper = vtk.vtkPolyDataMapper()
        randomHillsMapper.SetInputConnection(randomHillsSource.GetOutputPort())

        randomHillsActor = vtk.vtkActor()
        randomHillsActor.SetMapper(randomHillsMapper)
        randomHillsActor.SetPosition(16, -14, 0)
        randomHillsActor.SetScale(0.2, 0.2, 0.2)
        randomHillsActor.SetTexture(texture)

        randomHillsTextMapper = vtk.vtkTextMapper()
        randomHillsTextMapper.SetInput("Random.Hills")
        randomHillsTextMapper.GetTextProperty().SetJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetColor(1, 0, 0)
        randomHillsTextMapper.GetTextProperty().SetFontSize(14)
        randomHillsTextActor = vtk.vtkActor2D()
        randomHillsTextActor.SetMapper(randomHillsTextMapper)
        randomHillsTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        randomHillsTextActor.GetPositionCoordinate().SetValue(16, -14.5, 0)

        # ------------------------------------------------------------
        # Create Steiner's Roman Surface.
        # ------------------------------------------------------------
        roman = vtk.vtkParametricRoman()
        roman.SetRadius(1.5)
        romanSource = vtk.vtkParametricFunctionSource()
        romanSource.SetParametricFunction(roman)
        romanSource.SetScalarModeToX()

        romanMapper = vtk.vtkPolyDataMapper()
        romanMapper.SetInputConnection(romanSource.GetOutputPort())

        romanActor = vtk.vtkActor()
        romanActor.SetMapper(romanMapper)
        romanActor.SetPosition(24, -12, 0)

        romanTextMapper = vtk.vtkTextMapper()
        romanTextMapper.SetInput("Roman")
        romanTextMapper.GetTextProperty().SetJustificationToCentered()
        romanTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        romanTextMapper.GetTextProperty().SetColor(1, 0, 0)
        romanTextMapper.GetTextProperty().SetFontSize(14)
        romanTextActor = vtk.vtkActor2D()
        romanTextActor.SetMapper(romanTextMapper)
        romanTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        romanTextActor.GetPositionCoordinate().SetValue(24, -14.5, 0)

        # ------------------------------------------------------------
        # Create the RenderWindow, Renderer and both Actors
        # ------------------------------------------------------------
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # add actors
        ren.AddViewProp(torusActor)
        ren.AddViewProp(kleinActor)
        ren.AddViewProp(klein2Actor)
        ren.AddViewProp(toroidActor)
        ren.AddViewProp(superEllipsoidActor)
        ren.AddViewProp(mobiusActor)
        ren.AddViewProp(splineActor)
        ren.AddViewProp(spline2Actor)
        ren.AddViewProp(sconicActor)
        ren.AddViewProp(boyActor)
        ren.AddViewProp(crossCapActor)
        ren.AddViewProp(diniActor)
        ren.AddViewProp(enneperActor)
        ren.AddViewProp(ellipsoidActor)
        ren.AddViewProp(randomHillsActor)
        ren.AddViewProp(romanActor)
        #add text actors
        ren.AddViewProp(torusTextActor)
        ren.AddViewProp(kleinTextActor)
        ren.AddViewProp(fig8KleinTextActor)
        ren.AddViewProp(mobiusTextActor)
        ren.AddViewProp(superToroidTextActor)
        ren.AddViewProp(superEllipsoidTextActor)
        ren.AddViewProp(splineTextActor)
        ren.AddViewProp(spline2TextActor)
        ren.AddViewProp(sconicTextActor)
        ren.AddViewProp(boyTextActor)
        ren.AddViewProp(crossCapTextActor)
        ren.AddViewProp(diniTextActor)
        ren.AddViewProp(enneperTextActor)
        ren.AddViewProp(ellipsoidTextActor)
        ren.AddViewProp(randomHillsTextActor)
        ren.AddViewProp(romanTextActor)

        ren.SetBackground(0.7, 0.8, 1)
        renWin.SetSize(500, 500)
        ren.ResetCamera()
        ren.GetActiveCamera().Zoom(1.3)

        iren.Initialize()
        renWin.Render()

        img_file = "TestParametricFunctions.png"
        # NOTE: this test has a companion .tcl test. The threshold set
        #  here should be the same as the threshold in the .tcl
        #  test. Both tests should produce exactly the same results.
        vtk.test.Testing.compareImage(iren.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=10)
        vtk.test.Testing.interact()
Beispiel #45
0
def augmentPointset(ori_points, multiple, opt_size, bif, nn = -1):
    if multiple <= 1:
        return ori_points
    if nn < 0:
        zmin = int(npy.min(ori_points[:, 2]) + 0.5)
        zmax = int(npy.max(ori_points[:, 2]) + 0.5)
        nn = int((opt_size - ori_points.shape[0]) / ((2 * zmax - zmin - bif)) / (multiple - 1) + 0.5) + 1
        #print nn
    
    new_points = npy.array([[-1, -1, -1, -1]], dtype = npy.float32)
    zmin = [0, 0, 0]
    zmax = [0, 0, 0]
    resampled_points = [None, None, None]
    for cnt in range(3):
        temp_result = ori_points[npy.where(npy.round(ori_points[:, -1]) == cnt)]
        if not temp_result.shape[0]:
            continue
        zmin[cnt] = int(npy.min(temp_result[:, 2]) + 0.5)
        zmax[cnt] = int(npy.max(temp_result[:, 2]) + 0.5)
        resampled_points[cnt] = npy.zeros([(zmax[cnt] - zmin[cnt] + 1) * nn, 4], dtype = npy.float32)
        resampled_index = 0
        
        for z in range(zmin[cnt], zmax[cnt] + 1):
            data_result = temp_result[npy.where(npy.round(temp_result[:, 2]) == z)]
            if data_result is not None:
                if data_result.shape[0] == 0:
                    continue
                
                #center_result = npy.mean(data_result[:, :2], axis = 0)
                center_result = calCentroidFromContour(data_result[:, :2])[0]
                points_result = getPointsOntheSpline(data_result, center_result, 900)
                
                i = 0
                for k in range(-nn / 2 + 1, nn / 2 + 1):
                    angle = k * 2 * npy.pi / nn 
                    
                    while i < 900 and points_result[i, 2] < angle:
                        i += 1
                    if i == 900 or (i > 0 and angle - points_result[i - 1, 2] < points_result[i, 2] - angle):
                        ind_result = i - 1
                    else:
                        ind_result = i
                    
                    resampled_points[cnt][resampled_index, :2] = points_result[ind_result, :2]
                    resampled_points[cnt][resampled_index, 2] = z
                    resampled_points[cnt][resampled_index, 3] = k + 4
                    resampled_index += 1
    trans_points = npy.array(ori_points)
    for cnt in range(3):
        for k in range(0, nn):
            data = resampled_points[cnt][npy.where(npy.round(resampled_points[cnt][:, -1]) == k)]
            count = data.shape[0]
            if count == 0:
                continue
            points = vtk.vtkPoints()
            for i in range(count):
                points.InsertPoint(i, data[i, 0], data[i, 1], data[i, 2])
    
            para_spline = vtk.vtkParametricSpline()
            para_spline.SetPoints(points)
            para_spline.ClosedOff()
            
            deltaz = 1.0 / multiple
            old_pt = [0.0, 0.0, 0.0]
            numberOfOutputPoints = int((zmax[cnt] - zmin[cnt] + 1) * 10)
            i = 0
            
            for z in range(zmin[cnt], zmax[cnt] + 1):
                znow = float(z)
                for dd in range(1, multiple):
                    znow += deltaz 
                    while i < numberOfOutputPoints:
                        t = i * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[2] >= znow:
                            if pt[2] - znow < znow - old_pt[2]:
                                new_point = pt
                            else:
                                new_point = old_pt
                            trans_points = npy.append(trans_points, [[new_point[0], new_point[1], znow, cnt]], axis = 0)
                            
                            old_pt = pt
                            break
                        i += 1
    return trans_points
    def ParametricObjects(self):

        parametricObjects = list()
        parametricObjects.append(vtk.vtkParametricBoy())
        parametricObjects.append(vtk.vtkParametricConicSpiral())
        parametricObjects.append(vtk.vtkParametricCrossCap())
        parametricObjects.append(vtk.vtkParametricDini())

        parametricObjects.append(vtk.vtkParametricEllipsoid())
        parametricObjects[-1].SetXRadius(0.5)
        parametricObjects[-1].SetYRadius(2.0)
        parametricObjects.append(vtk.vtkParametricEnneper())
        parametricObjects.append(vtk.vtkParametricFigure8Klein())
        parametricObjects.append(vtk.vtkParametricKlein())

        parametricObjects.append(vtk.vtkParametricMobius())
        parametricObjects[-1].SetRadius(2)
        parametricObjects[-1].SetMinimumV(-0.5)
        parametricObjects[-1].SetMaximumV(0.5)
        parametricObjects.append(vtk.vtkParametricRandomHills())
        parametricObjects[-1].AllowRandomGenerationOff()
        parametricObjects.append(vtk.vtkParametricRoman())
        parametricObjects.append(vtk.vtkParametricSuperEllipsoid())
        parametricObjects[-1].SetN1(0.5)
        parametricObjects[-1].SetN2(0.1)

        parametricObjects.append(vtk.vtkParametricSuperToroid())
        parametricObjects[-1].SetN1(0.2)
        parametricObjects[-1].SetN2(3.0)
        parametricObjects.append(vtk.vtkParametricTorus())
        parametricObjects.append(vtk.vtkParametricSpline())
        # Add some points to the parametric spline.
        inputPoints = vtk.vtkPoints()
        vtk.vtkMath.RandomSeed(8775070)
        for i in range(10):
            x = vtk.vtkMath.Random(0.0,1.0)
            y = vtk.vtkMath.Random(0.0,1.0)
            z = vtk.vtkMath.Random(0.0,1.0)
            inputPoints.InsertNextPoint(x, y, z)
        parametricObjects[-1].SetPoints(inputPoints)

        # There are only 15 objects.
        parametricFunctionSources = list()
        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()

        # Create a common text property.
        textProperty = vtk.vtkTextProperty()
        textProperty.SetFontSize(10)
        textProperty.SetJustificationToCentered()

        # Create a parametric function source, renderer, mapper
        # and actor for each object.
        for idx, item in enumerate(parametricObjects):
            parametricFunctionSources.append(vtk.vtkParametricFunctionSource())
            parametricFunctionSources[idx].SetParametricFunction(item)
            parametricFunctionSources[idx].Update()

            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(parametricFunctionSources[idx].GetOutputPort())

            actors.append(vtk.vtkActor())
            actors[idx].SetMapper(mappers[idx])

            textmappers.append(vtk.vtkTextMapper())
            textmappers[idx].SetInput(item.GetClassName())
            textmappers[idx].SetTextProperty(textProperty)

            textactors.append(vtk.vtkActor2D())
            textactors[idx].SetMapper(textmappers[idx])
            textactors[idx].SetPosition(100, 16)

            renderers.append(vtk.vtkRenderer())

        gridDimensions = 4

        for idx in range(len(parametricObjects)):
            if idx < gridDimensions * gridDimensions:
                renderers.append(vtk.vtkRenderer)

        rendererSize = 200

        # Create the RenderWindow
        #
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions)

        # Add and position the renders to the render window.
        viewport = list()
        for row in range(gridDimensions):
            for col in range(gridDimensions):
                idx = row * gridDimensions + col

                viewport[:] = []
                viewport.append(float(col) * rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(gridDimensions - (row+1)) * rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(col+1)*rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize))

                if idx > (len(parametricObjects) - 1):
                    continue

                renderers[idx].SetViewport(viewport)
                renderWindow.AddRenderer(renderers[idx])

                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.2,0.3,0.4)
                renderers[idx].ResetCamera()
                renderers[idx].GetActiveCamera().Azimuth(30)
                renderers[idx].GetActiveCamera().Elevation(-30)
                renderers[idx].GetActiveCamera().Zoom(0.9)
                renderers[idx].ResetCameraClippingRange()

        interactor = vtk.vtkRenderWindowInteractor()
        interactor.SetRenderWindow(renderWindow)

        renderWindow.Render()

        interactor.Start()
Beispiel #47
0
    # Outputs (we need only pos which is the x, y, z position
    # of the intersection)
    t = vtk.mutable(0)
    pos = [0.0, 0.0, 0.0]
    pcoords = [0.0, 0.0, 0.0]
    subId = vtk.mutable(0)
    locator.IntersectWithLine(p1, p2, tolerance, t, pos, pcoords, subId)

    # Add a slight offset in z
    pos[2] += 0.01
    # Add the x, y, z position of the intersection
    points.InsertNextPoint(pos)

# Create a spline and add the points
spline = vtk.vtkParametricSpline()
spline.SetPoints(points)
functionSource = vtk.vtkParametricFunctionSource()
functionSource.SetUResolution(maxloop)
functionSource.SetParametricFunction(spline)

# Map the spline
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(functionSource.GetOutputPort())

# Define the line actor
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor([1.0, 0.0, 0.0])
actor.GetProperty().SetLineWidth(3)
Beispiel #48
0
 def setWidgetView(self, widget):
     super(CenterLineView, self).setWidgetView(widget)
     point_array = self.parent.getData().pointSet
     point_data = npy.array(point_array.getData('Centerline'))
     if point_data is None or not point_data.shape[0]:
         return
     
     #self.spacing = [1, 1, 1]
     self.spacing = self.parent.getData().getResolution().tolist()
     self.spacing = [float(x) / self.spacing[-1] for x in self.spacing]
     point_data[:, :2] *= self.spacing[:2]
     
     self.renderer = vtk.vtkRenderer()
     self.render_window = widget.GetRenderWindow()
     self.render_window.AddRenderer(self.renderer)
     self.window_interactor = vtk.vtkRenderWindowInteractor()
     self.render_window.SetInteractor(self.window_interactor)
     
     self.center = []
     self.center_mapper = []
     self.center_actor = []
     self.points = []
     self.para_spline = []
     self.spline_source = []
     
     for cnt in range(3):
         self.center.append(vtk.vtkPolyData())
         self.center_mapper.append(vtk.vtkPolyDataMapper())
         self.center_actor.append(vtk.vtkActor())
         self.points.append(vtk.vtkPoints())
         self.para_spline.append(vtk.vtkParametricSpline())
         self.spline_source.append(vtk.vtkParametricFunctionSource())
         
         point = point_data[npy.where(npy.round(point_data[:, -1]) == cnt)]
         point = point[point[:, 2].argsort(), :]
         count = point.shape[0]
         if not count:
             continue
             
         self.points[cnt].SetNumberOfPoints(count)
         for i in range(count):
             self.points[cnt].SetPoint(i, point[i, 0], point[i, 1], point[i, 2])
             
         self.para_spline[cnt].SetPoints(self.points[cnt])
         
         self.spline_source[cnt].SetParametricFunction(self.para_spline[cnt])
         numberOfOutputPoints = count * 10
         self.spline_source[cnt].SetUResolution(numberOfOutputPoints)
         
         self.center_mapper[cnt].SetInput(self.spline_source[cnt].GetOutput())
         self.center_mapper[cnt].ScalarVisibilityOff()
         
         self.center_actor[cnt].SetMapper(self.center_mapper[cnt])
         color = [0, 0, 0]
         color[cnt] = 1
         self.center_actor[cnt].GetProperty().SetColor(color[0], color[1], color[2])
         self.renderer.AddViewProp(self.center_actor[cnt])
     
     bound = npy.array(self.parent.getData().getData().shape)[::-1] * self.spacing
     outline_source = vtk.vtkOutlineSource()
     outline_source.SetBounds(0, bound[0], 0, bound[1], 0, bound[2])
     
     mapOutline = vtk.vtkPolyDataMapper()
     mapOutline.SetInputConnection(outline_source.GetOutputPort())
     outlineActor = vtk.vtkActor()
     outlineActor.SetMapper(mapOutline)
     outlineActor.GetProperty().SetColor(1, 1, 1)
     self.renderer.AddViewProp(outlineActor)
     
     self.renderer.ResetCamera()
     point = self.renderer.GetActiveCamera().GetFocalPoint()
     dis = self.renderer.GetActiveCamera().GetDistance()
     self.renderer.GetActiveCamera().SetViewUp(0, 0, 1)
     self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis, point[2])
     self.renderer.ResetCameraClippingRange()
     self.render_window.Render()
     
     # Manually set to trackball style
     self.window_interactor.SetKeyCode('t')
     self.window_interactor.CharEvent()
     self.window_interactor.GetInteractorStyle().AddObserver("KeyPressEvent", self.KeyPressCallback)
     self.window_interactor.GetInteractorStyle().AddObserver("CharEvent", self.KeyPressCallback)
    def testParametricFunctions(self):
        # ------------------------------------------------------------
        # Get a texture
        # ------------------------------------------------------------
        textureReader = vtk.vtkJPEGReader()
        textureReader.SetFileName(VTK_DATA_ROOT + "/Data/beach.jpg")
        texture = vtk.vtkTexture()
        texture.SetInputConnection(textureReader.GetOutputPort())

        # ------------------------------------------------------------
        # For each parametric surface:
        # 1) Create it
        # 2) Assign mappers and actors
        # 3) Position this object
        # 5) Add a label
        # ------------------------------------------------------------

        # ------------------------------------------------------------
        # Create a torus
        # ------------------------------------------------------------
        torus = vtk.vtkParametricTorus()
        torusSource = vtk.vtkParametricFunctionSource()
        torusSource.SetParametricFunction(torus)
        torusSource.SetScalarModeToPhase()

        torusMapper = vtk.vtkPolyDataMapper()
        torusMapper.SetInputConnection(torusSource.GetOutputPort())
        torusMapper.SetScalarRange(0, 360)

        torusActor = vtk.vtkActor()
        torusActor.SetMapper(torusMapper)
        torusActor.SetPosition(0, 12, 0)

        torusTextMapper = vtk.vtkTextMapper()
        torusTextMapper.SetInput("Torus")
        torusTextMapper.GetTextProperty().SetJustificationToCentered()
        torusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        torusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        torusTextMapper.GetTextProperty().SetFontSize(14)
        torusTextActor = vtk.vtkActor2D()
        torusTextActor.SetMapper(torusTextMapper)
        torusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        torusTextActor.GetPositionCoordinate().SetValue(0, 9.5, 0)

        # ------------------------------------------------------------
        # Create a klein bottle
        # ------------------------------------------------------------
        klein = vtk.vtkParametricKlein()
        kleinSource = vtk.vtkParametricFunctionSource()
        kleinSource.SetParametricFunction(klein)
        kleinSource.SetScalarModeToU0V0()

        kleinMapper = vtk.vtkPolyDataMapper()
        kleinMapper.SetInputConnection(kleinSource.GetOutputPort())
        kleinMapper.SetScalarRange(0, 3)

        kleinActor = vtk.vtkActor()
        kleinActor.SetMapper(kleinMapper)
        kleinActor.SetPosition(8, 10.5, 0)

        kleinTextMapper = vtk.vtkTextMapper()
        kleinTextMapper.SetInput("Klein")
        kleinTextMapper.GetTextProperty().SetJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        kleinTextMapper.GetTextProperty().SetFontSize(14)
        kleinTextActor = vtk.vtkActor2D()
        kleinTextActor.SetMapper(kleinTextMapper)
        kleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        kleinTextActor.GetPositionCoordinate().SetValue(8, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Figure-8 Klein
        # ------------------------------------------------------------
        klein2 = vtk.vtkParametricFigure8Klein()
        klein2Source = vtk.vtkParametricFunctionSource()
        klein2Source.SetParametricFunction(klein2)
        klein2Source.GenerateTextureCoordinatesOn()

        klein2Mapper = vtk.vtkPolyDataMapper()
        klein2Mapper.SetInputConnection(klein2Source.GetOutputPort())
        klein2Mapper.SetScalarRange(0, 3)

        klein2Actor = vtk.vtkActor()
        klein2Actor.SetMapper(klein2Mapper)
        klein2Actor.SetPosition(16, 12, 0)
        klein2Actor.SetTexture(texture)

        fig8KleinTextMapper = vtk.vtkTextMapper()
        fig8KleinTextMapper.SetInput("Fig-8.Klein")
        fig8KleinTextMapper.GetTextProperty().SetJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty(
        ).SetVerticalJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        fig8KleinTextMapper.GetTextProperty().SetFontSize(14)
        fig8KleinTextActor = vtk.vtkActor2D()
        fig8KleinTextActor.SetMapper(fig8KleinTextMapper)
        fig8KleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        fig8KleinTextActor.GetPositionCoordinate().SetValue(16, 9.5, 0)

        # ------------------------------------------------------------
        # Create a mobius strip
        # ------------------------------------------------------------
        mobius = vtk.vtkParametricMobius()
        mobiusSource = vtk.vtkParametricFunctionSource()
        mobiusSource.SetParametricFunction(mobius)
        mobiusSource.GenerateTextureCoordinatesOn()

        mobiusMapper = vtk.vtkPolyDataMapper()
        mobiusMapper.SetInputConnection(mobiusSource.GetOutputPort())

        mobiusActor = vtk.vtkActor()
        mobiusActor.SetMapper(mobiusMapper)
        mobiusActor.RotateX(45)
        mobiusActor.SetPosition(24, 12, 0)
        mobiusActor.SetTexture(texture)

        mobiusTextMapper = vtk.vtkTextMapper()
        mobiusTextMapper.SetInput("Mobius")
        mobiusTextMapper.GetTextProperty().SetJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        mobiusTextMapper.GetTextProperty().SetFontSize(14)
        mobiusTextActor = vtk.vtkActor2D()
        mobiusTextActor.SetMapper(mobiusTextMapper)
        mobiusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        mobiusTextActor.GetPositionCoordinate().SetValue(24, 9.5, 0)

        # ------------------------------------------------------------
        # Create a super toroid
        # ------------------------------------------------------------
        toroid = vtk.vtkParametricSuperToroid()
        toroid.SetN1(2)
        toroid.SetN2(3)
        toroidSource = vtk.vtkParametricFunctionSource()
        toroidSource.SetParametricFunction(toroid)
        toroidSource.SetScalarModeToU()

        toroidMapper = vtk.vtkPolyDataMapper()
        toroidMapper.SetInputConnection(toroidSource.GetOutputPort())
        toroidMapper.SetScalarRange(0, 6.28)

        toroidActor = vtk.vtkActor()
        toroidActor.SetMapper(toroidMapper)
        toroidActor.SetPosition(0, 4, 0)

        superToroidTextMapper = vtk.vtkTextMapper()
        superToroidTextMapper.SetInput("Super.Toroid")
        superToroidTextMapper.GetTextProperty().SetJustificationToCentered()
        superToroidTextMapper.GetTextProperty(
        ).SetVerticalJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superToroidTextMapper.GetTextProperty().SetFontSize(14)
        superToroidTextActor = vtk.vtkActor2D()
        superToroidTextActor.SetMapper(superToroidTextMapper)
        superToroidTextActor.GetPositionCoordinate(
        ).SetCoordinateSystemToWorld()
        superToroidTextActor.GetPositionCoordinate().SetValue(0, 1.5, 0)

        # ------------------------------------------------------------
        # Create a super ellipsoid
        # ------------------------------------------------------------
        superEllipsoid = vtk.vtkParametricSuperEllipsoid()
        superEllipsoid.SetXRadius(1.25)
        superEllipsoid.SetYRadius(1.5)
        superEllipsoid.SetZRadius(1.0)
        superEllipsoid.SetN1(1.1)
        superEllipsoid.SetN2(1.75)
        superEllipsoidSource = vtk.vtkParametricFunctionSource()
        superEllipsoidSource.SetParametricFunction(superEllipsoid)
        superEllipsoidSource.SetScalarModeToV()

        superEllipsoidMapper = vtk.vtkPolyDataMapper()
        superEllipsoidMapper.SetInputConnection(
            superEllipsoidSource.GetOutputPort())
        superEllipsoidMapper.SetScalarRange(0, 3.14)

        superEllipsoidActor = vtk.vtkActor()
        superEllipsoidActor.SetMapper(superEllipsoidMapper)
        superEllipsoidActor.SetPosition(8, 4, 0)

        superEllipsoidTextMapper = vtk.vtkTextMapper()
        superEllipsoidTextMapper.SetInput("Super.Ellipsoid")
        superEllipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty(
        ).SetVerticalJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superEllipsoidTextMapper.GetTextProperty().SetFontSize(14)
        superEllipsoidTextActor = vtk.vtkActor2D()
        superEllipsoidTextActor.SetMapper(superEllipsoidTextMapper)
        superEllipsoidTextActor.GetPositionCoordinate(
        ).SetCoordinateSystemToWorld()
        superEllipsoidTextActor.GetPositionCoordinate().SetValue(8, 1.5, 0)

        # ------------------------------------------------------------
        # Create an open 1D spline
        # ------------------------------------------------------------
        math = vtk.vtkMath()
        inputPoints = vtk.vtkPoints()
        for i in range(0, 10):
            x = math.Random(-1, 1)
            y = math.Random(-1, 1)
            z = math.Random(-1, 1)
            inputPoints.InsertPoint(i, x, y, z)

        spline = vtk.vtkParametricSpline()
        spline.SetPoints(inputPoints)
        spline.ClosedOff()
        splineSource = vtk.vtkParametricFunctionSource()
        splineSource.SetParametricFunction(spline)

        splineMapper = vtk.vtkPolyDataMapper()
        splineMapper.SetInputConnection(splineSource.GetOutputPort())

        splineActor = vtk.vtkActor()
        splineActor.SetMapper(splineMapper)
        splineActor.SetPosition(16, 4, 0)
        splineActor.GetProperty().SetColor(0, 0, 0)

        splineTextMapper = vtk.vtkTextMapper()
        splineTextMapper.SetInput("Open.Spline")
        splineTextMapper.GetTextProperty().SetJustificationToCentered()
        splineTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        splineTextMapper.GetTextProperty().SetColor(1, 0, 0)
        splineTextMapper.GetTextProperty().SetFontSize(14)
        splineTextActor = vtk.vtkActor2D()
        splineTextActor.SetMapper(splineTextMapper)
        splineTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        splineTextActor.GetPositionCoordinate().SetValue(16, 1.5, 0)

        # ------------------------------------------------------------
        # Create a closed 1D spline
        # ------------------------------------------------------------
        spline2 = vtk.vtkParametricSpline()
        spline2.SetPoints(inputPoints)
        spline2.ClosedOn()
        spline2Source = vtk.vtkParametricFunctionSource()
        spline2Source.SetParametricFunction(spline2)

        spline2Mapper = vtk.vtkPolyDataMapper()
        spline2Mapper.SetInputConnection(spline2Source.GetOutputPort())

        spline2Actor = vtk.vtkActor()
        spline2Actor.SetMapper(spline2Mapper)
        spline2Actor.SetPosition(24, 4, 0)
        spline2Actor.GetProperty().SetColor(0, 0, 0)

        spline2TextMapper = vtk.vtkTextMapper()
        spline2TextMapper.SetInput("Closed.Spline")
        spline2TextMapper.GetTextProperty().SetJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetVerticalJustificationToCentered(
        )
        spline2TextMapper.GetTextProperty().SetColor(1, 0, 0)
        spline2TextMapper.GetTextProperty().SetFontSize(14)
        spline2TextActor = vtk.vtkActor2D()
        spline2TextActor.SetMapper(spline2TextMapper)
        spline2TextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        spline2TextActor.GetPositionCoordinate().SetValue(24, 1.5, 0)

        # ------------------------------------------------------------
        # Create a spiral conic
        # ------------------------------------------------------------
        sconic = vtk.vtkParametricConicSpiral()
        sconic.SetA(0.8)
        sconic.SetB(2.5)
        sconic.SetC(0.4)
        sconicSource = vtk.vtkParametricFunctionSource()
        sconicSource.SetParametricFunction(sconic)
        sconicSource.SetScalarModeToDistance()

        sconicMapper = vtk.vtkPolyDataMapper()
        sconicMapper.SetInputConnection(sconicSource.GetOutputPort())
        sconicActor = vtk.vtkActor()
        sconicActor.SetMapper(sconicMapper)
        sconicMapper.SetScalarRange(0, 9)
        sconicActor.SetPosition(0, -4, 0)
        sconicActor.SetScale(1.2, 1.2, 1.2)

        sconicTextMapper = vtk.vtkTextMapper()
        sconicTextMapper.SetInput("Spiral.Conic")
        sconicTextMapper.GetTextProperty().SetJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetColor(1, 0, 0)
        sconicTextMapper.GetTextProperty().SetFontSize(14)
        sconicTextActor = vtk.vtkActor2D()
        sconicTextActor.SetMapper(sconicTextMapper)
        sconicTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        sconicTextActor.GetPositionCoordinate().SetValue(0, -6.5, 0)

        # ------------------------------------------------------------
        # Create Boy's surface
        # ------------------------------------------------------------
        boy = vtk.vtkParametricBoy()
        boySource = vtk.vtkParametricFunctionSource()
        boySource.SetParametricFunction(boy)
        boySource.SetScalarModeToModulus()

        boyMapper = vtk.vtkPolyDataMapper()
        boyMapper.SetInputConnection(boySource.GetOutputPort())
        boyMapper.SetScalarRange(0, 2)
        boyActor = vtk.vtkActor()
        boyActor.SetMapper(boyMapper)
        boyActor.SetPosition(8, -4, 0)
        boyActor.SetScale(1.5, 1.5, 1.5)

        boyTextMapper = vtk.vtkTextMapper()
        boyTextMapper.SetInput("Boy")
        boyTextMapper.GetTextProperty().SetJustificationToCentered()
        boyTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        boyTextMapper.GetTextProperty().SetColor(1, 0, 0)
        boyTextMapper.GetTextProperty().SetFontSize(14)
        boyTextActor = vtk.vtkActor2D()
        boyTextActor.SetMapper(boyTextMapper)
        boyTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        boyTextActor.GetPositionCoordinate().SetValue(8, -6.5, 0)

        # ------------------------------------------------------------
        # Create a cross cap
        # ------------------------------------------------------------
        crossCap = vtk.vtkParametricCrossCap()
        crossCapSource = vtk.vtkParametricFunctionSource()
        crossCapSource.SetParametricFunction(crossCap)
        crossCapSource.SetScalarModeToY()

        crossCapMapper = vtk.vtkPolyDataMapper()
        crossCapMapper.SetInputConnection(crossCapSource.GetOutputPort())
        crossCapActor = vtk.vtkActor()
        crossCapActor.SetMapper(crossCapMapper)
        crossCapActor.RotateX(65)
        crossCapActor.SetPosition(16, -4, 0)
        crossCapActor.SetScale(1.5, 1.5, 1.5)

        crossCapTextMapper = vtk.vtkTextMapper()
        crossCapTextMapper.SetInput("Cross.Cap")
        crossCapTextMapper.GetTextProperty().SetJustificationToCentered()
        crossCapTextMapper.GetTextProperty(
        ).SetVerticalJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetColor(1, 0, 0)
        crossCapTextMapper.GetTextProperty().SetFontSize(14)
        crossCapTextActor = vtk.vtkActor2D()
        crossCapTextActor.SetMapper(crossCapTextMapper)
        crossCapTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        crossCapTextActor.GetPositionCoordinate().SetValue(16, -6.5, 0)

        # ------------------------------------------------------------
        # Create Dini's surface
        # ------------------------------------------------------------
        dini = vtk.vtkParametricDini()
        diniSource = vtk.vtkParametricFunctionSource()
        diniSource.SetScalarModeToDistance()
        diniSource.SetParametricFunction(dini)

        diniMapper = vtk.vtkPolyDataMapper()
        diniMapper.SetInputConnection(diniSource.GetOutputPort())

        diniActor = vtk.vtkActor()
        diniActor.SetMapper(diniMapper)
        diniActor.RotateX(-90)
        diniActor.SetPosition(24, -3, 0)
        diniActor.SetScale(1.5, 1.5, 0.5)

        diniTextMapper = vtk.vtkTextMapper()
        diniTextMapper.SetInput("Dini")
        diniTextMapper.GetTextProperty().SetJustificationToCentered()
        diniTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        diniTextMapper.GetTextProperty().SetColor(1, 0, 0)
        diniTextMapper.GetTextProperty().SetFontSize(14)
        diniTextActor = vtk.vtkActor2D()
        diniTextActor.SetMapper(diniTextMapper)
        diniTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        diniTextActor.GetPositionCoordinate().SetValue(24, -6.5, 0)

        # ------------------------------------------------------------
        # Create Enneper's surface
        # ------------------------------------------------------------
        enneper = vtk.vtkParametricEnneper()
        enneperSource = vtk.vtkParametricFunctionSource()
        enneperSource.SetParametricFunction(enneper)
        enneperSource.SetScalarModeToQuadrant()

        enneperMapper = vtk.vtkPolyDataMapper()
        enneperMapper.SetInputConnection(enneperSource.GetOutputPort())
        enneperMapper.SetScalarRange(1, 4)

        enneperActor = vtk.vtkActor()
        enneperActor.SetMapper(enneperMapper)
        enneperActor.SetPosition(0, -12, 0)
        enneperActor.SetScale(0.25, 0.25, 0.25)

        enneperTextMapper = vtk.vtkTextMapper()
        enneperTextMapper.SetInput("Enneper")
        enneperTextMapper.GetTextProperty().SetJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetVerticalJustificationToCentered(
        )
        enneperTextMapper.GetTextProperty().SetColor(1, 0, 0)
        enneperTextMapper.GetTextProperty().SetFontSize(14)
        enneperTextActor = vtk.vtkActor2D()
        enneperTextActor.SetMapper(enneperTextMapper)
        enneperTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        enneperTextActor.GetPositionCoordinate().SetValue(0, -14.5, 0)

        # ------------------------------------------------------------
        # Create an ellipsoidal surface
        # ------------------------------------------------------------
        ellipsoid = vtk.vtkParametricEllipsoid()
        ellipsoid.SetXRadius(1)
        ellipsoid.SetYRadius(0.75)
        ellipsoid.SetZRadius(0.5)
        ellipsoidSource = vtk.vtkParametricFunctionSource()
        ellipsoidSource.SetParametricFunction(ellipsoid)
        ellipsoidSource.SetScalarModeToZ()

        ellipsoidMapper = vtk.vtkPolyDataMapper()
        ellipsoidMapper.SetInputConnection(ellipsoidSource.GetOutputPort())
        ellipsoidMapper.SetScalarRange(-0.5, 0.5)

        ellipsoidActor = vtk.vtkActor()
        ellipsoidActor.SetMapper(ellipsoidMapper)
        ellipsoidActor.SetPosition(8, -12, 0)
        ellipsoidActor.SetScale(1.5, 1.5, 1.5)

        ellipsoidTextMapper = vtk.vtkTextMapper()
        ellipsoidTextMapper.SetInput("Ellipsoid")
        ellipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty(
        ).SetVerticalJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        ellipsoidTextMapper.GetTextProperty().SetFontSize(14)
        ellipsoidTextActor = vtk.vtkActor2D()
        ellipsoidTextActor.SetMapper(ellipsoidTextMapper)
        ellipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        ellipsoidTextActor.GetPositionCoordinate().SetValue(8, -14.5, 0)

        # ------------------------------------------------------------
        # Create an surface with random hills on it.
        # Note that for testing, we will disable the
        # random generation of the surfaces. This is
        # because random number generators do not
        # return the same result on different operating
        # systems.
        # ------------------------------------------------------------
        randomHills = vtk.vtkParametricRandomHills()
        randomHills.AllowRandomGenerationOff()
        randomHills.GenerateTheHills()
        randomHillsSource = vtk.vtkParametricFunctionSource()
        randomHillsSource.SetParametricFunction(randomHills)
        randomHillsSource.GenerateTextureCoordinatesOn()

        randomHillsMapper = vtk.vtkPolyDataMapper()
        randomHillsMapper.SetInputConnection(randomHillsSource.GetOutputPort())

        randomHillsActor = vtk.vtkActor()
        randomHillsActor.SetMapper(randomHillsMapper)
        randomHillsActor.SetPosition(16, -14, 0)
        randomHillsActor.SetScale(0.2, 0.2, 0.2)
        randomHillsActor.SetTexture(texture)

        randomHillsTextMapper = vtk.vtkTextMapper()
        randomHillsTextMapper.SetInput("Random.Hills")
        randomHillsTextMapper.GetTextProperty().SetJustificationToCentered()
        randomHillsTextMapper.GetTextProperty(
        ).SetVerticalJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetColor(1, 0, 0)
        randomHillsTextMapper.GetTextProperty().SetFontSize(14)
        randomHillsTextActor = vtk.vtkActor2D()
        randomHillsTextActor.SetMapper(randomHillsTextMapper)
        randomHillsTextActor.GetPositionCoordinate(
        ).SetCoordinateSystemToWorld()
        randomHillsTextActor.GetPositionCoordinate().SetValue(16, -14.5, 0)

        # ------------------------------------------------------------
        # Create an Steiner's Roman Surface.
        # ------------------------------------------------------------
        roman = vtk.vtkParametricRoman()
        roman.SetRadius(1.5)
        romanSource = vtk.vtkParametricFunctionSource()
        romanSource.SetParametricFunction(roman)
        romanSource.SetScalarModeToX()

        romanMapper = vtk.vtkPolyDataMapper()
        romanMapper.SetInputConnection(romanSource.GetOutputPort())

        romanActor = vtk.vtkActor()
        romanActor.SetMapper(romanMapper)
        romanActor.SetPosition(24, -12, 0)

        romanTextMapper = vtk.vtkTextMapper()
        romanTextMapper.SetInput("Roman")
        romanTextMapper.GetTextProperty().SetJustificationToCentered()
        romanTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        romanTextMapper.GetTextProperty().SetColor(1, 0, 0)
        romanTextMapper.GetTextProperty().SetFontSize(14)
        romanTextActor = vtk.vtkActor2D()
        romanTextActor.SetMapper(romanTextMapper)
        romanTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        romanTextActor.GetPositionCoordinate().SetValue(24, -14.5, 0)

        # ------------------------------------------------------------
        # Create the RenderWindow, Renderer and both Actors
        # ------------------------------------------------------------
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # add actors
        ren.AddViewProp(torusActor)
        ren.AddViewProp(kleinActor)
        ren.AddViewProp(klein2Actor)
        ren.AddViewProp(toroidActor)
        ren.AddViewProp(superEllipsoidActor)
        ren.AddViewProp(mobiusActor)
        ren.AddViewProp(splineActor)
        ren.AddViewProp(spline2Actor)
        ren.AddViewProp(sconicActor)
        ren.AddViewProp(boyActor)
        ren.AddViewProp(crossCapActor)
        ren.AddViewProp(diniActor)
        ren.AddViewProp(enneperActor)
        ren.AddViewProp(ellipsoidActor)
        ren.AddViewProp(randomHillsActor)
        ren.AddViewProp(romanActor)
        #add text actors
        ren.AddViewProp(torusTextActor)
        ren.AddViewProp(kleinTextActor)
        ren.AddViewProp(fig8KleinTextActor)
        ren.AddViewProp(mobiusTextActor)
        ren.AddViewProp(superToroidTextActor)
        ren.AddViewProp(superEllipsoidTextActor)
        ren.AddViewProp(splineTextActor)
        ren.AddViewProp(spline2TextActor)
        ren.AddViewProp(sconicTextActor)
        ren.AddViewProp(boyTextActor)
        ren.AddViewProp(crossCapTextActor)
        ren.AddViewProp(diniTextActor)
        ren.AddViewProp(enneperTextActor)
        ren.AddViewProp(ellipsoidTextActor)
        ren.AddViewProp(randomHillsTextActor)
        ren.AddViewProp(romanTextActor)

        ren.SetBackground(0.7, 0.8, 1)
        renWin.SetSize(500, 500)
        ren.ResetCamera()
        ren.GetActiveCamera().Zoom(1.3)

        iren.Initialize()
        renWin.Render()
        #iren.Start()
        img_file = "TestParametricFunctions.png"
        vtk.test.Testing.compareImage(
            iren.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()