Ejemplo n.º 1
0
 def set_props(self, props):
     if props is None:
         self.props = None
     else:
         self.props = vtk.vtkPropCollection()
         for prop in props:
             self.props.AddItem(prop)
Ejemplo n.º 2
0
    def ColorByOrientation(self, colorScheme=None):
        if NoBacteria(): return
        
        bacilli, filaments, bdots, fdots, sRes = communityOrientationStats()
        bdots = [map(abs, bdots[i]) for i in range(3)]
        fdots = [map(abs, fdots[i]) for i in range(3)]
        
        if colorScheme is None:
            colorScheme = Vec3f(2,1,0)
        
        for i, a in enumerate(bacilli):
            aColl = vtk.vtkPropCollection()
            a.GetActors(aColl)
            aColl.InitTraversal()
            actors = [aColl.GetNextProp() for _ in range(aColl.GetNumberOfItems())]
            
            for actor in actors:
                actor.GetProperty().SetDiffuseColor(bdots[colorScheme.x][i], 
                                                    bdots[colorScheme.y][i], 
                                                    bdots[colorScheme.z][i])
        for j, fID in enumerate(filaments):
            fColl = vtk.vtkPropCollection()
            DataStore.BacteriaActors()[fID].GetActors(fColl)
            fColl.InitTraversal()
            factors = [fColl.GetNextProp() for _ in range(fColl.GetNumberOfItems())]
            
            # Set color LUT for filament spline based on marker positions
            colorTransferFunction = vtk.vtkColorTransferFunction()
            
            fdotIdx = sum(sRes[:j])
            for k in range(0, sRes[j]):
                colorTransferFunction.AddRGBPoint(k,fdots[colorScheme.x][fdotIdx+k],
                                                    fdots[colorScheme.y][fdotIdx+k],
                                                    fdots[colorScheme.z][fdotIdx+k])
#                print 'RGB:',fdots[colorScheme.x][fdotIdx+k],fdots[colorScheme.y][fdotIdx+k],fdots[colorScheme.z][fdotIdx+k]
            # filament spline
            factors[1].GetMapper().SetLookupTable(colorTransferFunction)
            factors[1].GetMapper().ScalarVisibilityOn()
            factors[1].GetMapper().SetColorModeToMapScalars()
            factors[1].GetMapper().InterpolateScalarsBeforeMappingOff()
            
            # sphere caps
            self.setColor(factors[0], fdotIdx, fdots, colorScheme)
            self.setColor(factors[-1], fdotIdx+k, fdots, colorScheme)
            

        self.iren.Render()
Ejemplo n.º 3
0
    def init(self):

        self.renderer = vtkRenderer()
        self.renderer.SetUseDepthPeeling(1); ####
        self.renderer.SetBackground(1,1,1)
        self.renderWindow = vtkGenericOpenGLRenderWindow()
        self.renderWindow.SetAlphaBitPlanes(True) ####
        self.renderWindow.AddRenderer(self.renderer)
        self.SetRenderWindow(self.renderWindow)
        
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        self.actors = vtkPropCollection()
Ejemplo n.º 4
0
    def init(self):

        self.renderer = vtkRenderer()
        self.renderer.SetUseDepthPeeling(1); ####
        self.renderer.SetBackground(1,1,1)
        self.renderWindow = vtkGenericOpenGLRenderWindow()
        self.renderWindow.SetAlphaBitPlanes(True) ####
        self.renderWindow.AddRenderer(self.renderer)
        self.SetRenderWindow(self.renderWindow)
        
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        self.actors = vtkPropCollection()
Ejemplo n.º 5
0
def get_wall_actors(renderers, blocks):
    # Returns a list of just the actor components from the wall cube props
    # Setup the list to collect the actors
    actorsList = []
    # A vtkPropCollection, populate it with the props from the blocks renderer
    propCollection = vtkPropCollection()
    propCollection = renderers[blocks].GetViewProps()
    # Get the number of props so we know how many items to iterate over
    numberProps = propCollection.GetNumberOfItems()
    # Initiate traversal over the collection
    propCollection.InitTraversal()
    # Now iterate over each of the props
    for prop in range(numberProps):
        # Move to the next prop in the collection and get the number of actors in that prop
        currentProp = propCollection.GetNextProp()
        # We're just interested in wall objects, not floor objects
        # So only scan this prop further if it is a prop and not an actor
        typeBool = currentProp.IsTypeOf("vtkPropAssembly")
        if typeBool == 1:
            # The prop doesn't list any positional attributes so we're going to need to loop over the component actors to find the cube actor which does have positional attributes
            # Get the number of actors in this prop so we know how many iterations to make
            numberOfActors = currentProp.GetNumberOfPaths()
            # Setup a vtkPropAssembly to store the assembly of parts that make up the current prop, and populate it
            actorCollection = vtkPropAssembly()
            actorCollection = currentProp.GetParts()
            # and initiate traversal over the collection of parts/actors
            actorCollection.InitTraversal()
            for actor in range(numberOfActors):
                # Now iterate over each actor.
                # Move to the next actor in the collection.
                currentActor = actorCollection.GetNextProp()
                # Check if the actor is an OpenGL type, which is used for the wall and floor objects, as opposed to a CaptionActor type which is the component used for the captioning
                # method returns a 1 if the type of the actor matches the argument, otherwise returns a 0
                typeBool = currentActor.IsTypeOf("vtkOpenGLActor")
                if typeBool == 1:
                    # This actor is a wall or floor actor
                    # check the height of the actor ... if it's less than 1 then this actor is floor
                    actorHeight = currentActor.GetBounds(
                    )[3] - currentActor.GetBounds()[2]
                    if actorHeight >= 1:
                        # This is a wall actor
                        actorsList.append(currentActor)
    return actorsList
Ejemplo n.º 6
0
def get_floor_actors(renderers, blocks):
    # Returns a list of just the floor panel actors
    # Setup the list to be returned
    actorsList = []
    # Setup a vtkPropCollection, get populate it with the props from the blocks renderer
    propCollection = vtkPropCollection()
    propCollection = renderers[blocks].GetViewProps()
    # Get the number of props so we know how many items to iterate over
    numberProps = propCollection.GetNumberOfItems()
    # Initiate traversal over the collection
    propCollection.InitTraversal()
    # now iterate over each of the props
    for prop in range(numberProps):
        # Move to the next prop in the collection and get the number of actors in that prop
        currentProp = propCollection.GetNextProp()
        # Check if this prop is an OpenGLActor
        typeBool = currentProp.IsTypeOf("vtkOpenGLActor")
        if typeBool == 1:
            # This is an actor, which means its part of the floor.
            actorsList.append(currentProp)
    return actorsList
Ejemplo n.º 7
0
def get_wall_props(renderers, blocks):
    # Returns a list of the vtkPropAssembly props which are wall and obstacle objects with embedded captions
    # Setup the list to collect the props
    propsList = []
    # A vtkPropCollection, populate it with the props from the blocks renderer
    propCollection = vtkPropCollection()
    propCollection = renderers[blocks].GetViewProps()
    # Get the number of props so we know how many items to iterate over
    numberProps = propCollection.GetNumberOfItems()
    # Initiate traversal over the collection
    propCollection.InitTraversal()
    # Now iterate over each of the props
    for prop in range(numberProps):
        # Move to the next prop in the collection and get the number of actors in that prop
        currentProp = propCollection.GetNextProp()
        # We're just interested in wall objects, not floor objects
        # So only scan this prop further if it is a prop and not an actor
        typeBool = currentProp.IsTypeOf("vtkPropAssembly")
        if typeBool == 1:
            # This is a wall object prop
            propsList.append(currentProp)
    return propsList
Ejemplo n.º 8
0
 def UpdateColor(self, color):
     """
     Set the color of all actors.
     
     :@type color: render.basic.Color
     :@param color: The new color to use.
     """
     self.color = color
     for marker in DataStore.Markers():
         marker.GetProperty().SetDiffuseColor(color.r, 
                                              color.g, 
                                              color.b)
     
     for bact in DataStore.BacteriaActors():
         aColl = vtk.vtkPropCollection()
         bact.GetActors(aColl)
         aColl.InitTraversal()
         actors = [aColl.GetNextProp() for _ in range(aColl.GetNumberOfItems())]
         
         for actor in actors:
             actor.GetProperty().SetDiffuseColor(color.r, 
                                                 color.g, 
                                                 color.b)
     self.renwin_update_callback()
Ejemplo n.º 9
0
def printInfo(obj):
    """Print information about a vtk object."""
    def printvtkactor(actor, tab=""):

        if not actor.GetPickable():
            return

        mapper = actor.GetMapper()
        if hasattr(actor, "polydata"):
            poly = actor.polydata()
        else:
            poly = mapper.GetInput()

        pro = actor.GetProperty()
        pos = actor.GetPosition()
        bnds = actor.GetBounds()
        col = pro.GetColor()
        colr = precision(col[0], 3)
        colg = precision(col[1], 3)
        colb = precision(col[2], 3)
        alpha = pro.GetOpacity()
        npt = poly.GetNumberOfPoints()
        ncl = poly.GetNumberOfCells()
        npl = poly.GetNumberOfPolys()

        print(tab, end="")
        colors.printc("vtkActor", c="g", bold=1, invert=1, dim=1, end=" ")

        if hasattr(actor, "_legend") and actor._legend:
            colors.printc("legend: ", c="g", bold=1, end="")
            colors.printc(actor._legend, c="g", bold=0)
        else:
            print()

        if hasattr(actor, "filename") and actor.filename:
            colors.printc(tab + "           file: ", c="g", bold=1, end="")
            colors.printc(actor.filename, c="g", bold=0)

        if not actor.GetMapper().GetScalarVisibility():
            colors.printc(tab + "          color: ", c="g", bold=1, end="")
            #colors.printc("defined by point or cell data", c="g", bold=0)
            #else:
            colors.printc(colors.getColorName(col) + ', rgb=(' + colr + ', ' +
                          colg + ', ' + colb + '), alpha=' + str(alpha),
                          c='g',
                          bold=0)

            if actor.GetBackfaceProperty():
                bcol = actor.GetBackfaceProperty().GetDiffuseColor()
                bcolr = precision(bcol[0], 3)
                bcolg = precision(bcol[1], 3)
                bcolb = precision(bcol[2], 3)
                colors.printc(tab + '     back color: ', c='g', bold=1, end='')
                colors.printc(colors.getColorName(bcol) + ', rgb=(' + bcolr +
                              ', ' + bcolg + ', ' + bcolb + ')',
                              c='g',
                              bold=0)

        colors.printc(tab + "         points: ", c="g", bold=1, end="")
        colors.printc(npt, c="g", bold=0)

        colors.printc(tab + "          cells: ", c="g", bold=1, end="")
        colors.printc(ncl, c="g", bold=0)

        colors.printc(tab + "       polygons: ", c="g", bold=1, end="")
        colors.printc(npl, c="g", bold=0)

        colors.printc(tab + "       position: ", c="g", bold=1, end="")
        colors.printc(pos, c="g", bold=0)

        if hasattr(actor, "polydata") and actor.N():
            colors.printc(tab + "     c. of mass: ", c="g", bold=1, end="")
            cm = tuple(actor.centerOfMass())
            colors.printc(precision(cm, 3), c="g", bold=0)

            colors.printc(tab + "      ave. size: ", c="g", bold=1, end="")
            colors.printc(precision(actor.averageSize(), 6), c="g", bold=0)

            colors.printc(tab + "     diag. size: ", c="g", bold=1, end="")
            colors.printc(precision(actor.diagonalSize(), 6), c="g", bold=0)

            _area = actor.area()
            if _area:
                colors.printc(tab + "           area: ", c="g", bold=1, end="")
                colors.printc(precision(_area, 6), c="g", bold=0)

            _vol = actor.volume()
            if _vol:
                colors.printc(tab + "         volume: ", c="g", bold=1, end="")
                colors.printc(precision(_vol, 6), c="g", bold=0)

        colors.printc(tab + "         bounds: ", c="g", bold=1, end="")
        bx1, bx2 = precision(bnds[0], 3), precision(bnds[1], 3)
        colors.printc("x=(" + bx1 + ", " + bx2 + ")", c="g", bold=0, end="")
        by1, by2 = precision(bnds[2], 3), precision(bnds[3], 3)
        colors.printc(" y=(" + by1 + ", " + by2 + ")", c="g", bold=0, end="")
        bz1, bz2 = precision(bnds[4], 3), precision(bnds[5], 3)
        colors.printc(" z=(" + bz1 + ", " + bz2 + ")", c="g", bold=0)

        arrtypes = dict()
        arrtypes[vtk.VTK_UNSIGNED_CHAR] = "UNSIGNED_CHAR"
        arrtypes[vtk.VTK_SIGNED_CHAR] = "SIGNED_CHAR"
        arrtypes[vtk.VTK_UNSIGNED_INT] = "UNSIGNED_INT"
        arrtypes[vtk.VTK_INT] = "INT"
        arrtypes[vtk.VTK_CHAR] = "CHAR"
        arrtypes[vtk.VTK_SHORT] = "SHORT"
        arrtypes[vtk.VTK_LONG] = "LONG"
        arrtypes[vtk.VTK_ID_TYPE] = "ID"
        arrtypes[vtk.VTK_FLOAT] = "FLOAT"
        arrtypes[vtk.VTK_DOUBLE] = "DOUBLE"

        ptdata = poly.GetPointData()
        cldata = poly.GetCellData()

        colors.printc(tab + "    scalar mode:", c="g", bold=1, end=" ")
        colors.printc(mapper.GetScalarModeAsString(),
                      '  coloring =',
                      mapper.GetColorModeAsString(),
                      c="g",
                      bold=0)

        if ptdata.GetNumberOfArrays() + cldata.GetNumberOfArrays():
            colors.printc(tab + " active scalars: ", c="g", bold=1, end="")
            if ptdata.GetScalars():
                colors.printc(ptdata.GetScalars().GetName(),
                              "(point data)  ",
                              c="g",
                              bold=0,
                              end="")
            if cldata.GetScalars():
                colors.printc(cldata.GetScalars().GetName(),
                              "(cell data)",
                              c="g",
                              bold=0,
                              end="")
            print()

        for i in range(ptdata.GetNumberOfArrays()):
            name = ptdata.GetArrayName(i)
            if name and ptdata.GetArray(i):
                colors.printc(tab + "     point data: ", c="g", bold=1, end="")
                try:
                    tt = arrtypes[ptdata.GetArray(i).GetDataType()]
                except:
                    tt = str(ptdata.GetArray(i).GetDataType())
                ncomp = str(ptdata.GetArray(i).GetNumberOfComponents())
                colors.printc("name=" + name,
                              "(" + ncomp + " " + tt + "),",
                              c="g",
                              bold=0,
                              end="")
                rng = ptdata.GetArray(i).GetRange()
                colors.printc(" range=(" + precision(rng[0], 4) + ',' +
                              precision(rng[1], 4) + ')',
                              c="g",
                              bold=0)

        for i in range(cldata.GetNumberOfArrays()):
            name = cldata.GetArrayName(i)
            if name and cldata.GetArray(i):
                colors.printc(tab + "      cell data: ", c="g", bold=1, end="")
                try:
                    tt = arrtypes[cldata.GetArray(i).GetDataType()]
                except:
                    tt = str(cldata.GetArray(i).GetDataType())
                ncomp = str(cldata.GetArray(i).GetNumberOfComponents())
                colors.printc("name=" + name,
                              "(" + ncomp + " " + tt + "),",
                              c="g",
                              bold=0,
                              end="")
                rng = cldata.GetArray(i).GetRange()
                colors.printc(" range=(" + precision(rng[0], 4) + ',' +
                              precision(rng[1], 4) + ')',
                              c="g",
                              bold=0)

    if not obj:
        return

    elif isinstance(obj, vtk.vtkActor):
        colors.printc("_" * 65, c="g", bold=0)
        printvtkactor(obj)

    elif isinstance(obj, vtk.vtkAssembly):
        colors.printc("_" * 65, c="g", bold=0)
        colors.printc("vtkAssembly", c="g", bold=1, invert=1, end=" ")
        if hasattr(obj, "_legend"):
            colors.printc("legend: ", c="g", bold=1, end="")
            colors.printc(obj._legend, c="g", bold=0)
        else:
            print()

        pos = obj.GetPosition()
        bnds = obj.GetBounds()
        colors.printc("          position: ", c="g", bold=1, end="")
        colors.printc(pos, c="g", bold=0)

        colors.printc("            bounds: ", c="g", bold=1, end="")
        bx1, bx2 = precision(bnds[0], 3), precision(bnds[1], 3)
        colors.printc("x=(" + bx1 + ", " + bx2 + ")", c="g", bold=0, end="")
        by1, by2 = precision(bnds[2], 3), precision(bnds[3], 3)
        colors.printc(" y=(" + by1 + ", " + by2 + ")", c="g", bold=0, end="")
        bz1, bz2 = precision(bnds[4], 3), precision(bnds[5], 3)
        colors.printc(" z=(" + bz1 + ", " + bz2 + ")", c="g", bold=0)

        cl = vtk.vtkPropCollection()
        obj.GetActors(cl)
        cl.InitTraversal()
        for i in range(obj.GetNumberOfPaths()):
            act = vtk.vtkActor.SafeDownCast(cl.GetNextProp())
            if isinstance(act, vtk.vtkActor):
                printvtkactor(act, tab="     ")

    elif isinstance(obj, vtk.vtkVolume):
        colors.printc("_" * 65, c="b", bold=0)
        colors.printc("vtkVolume", c="b", bold=1, invert=1, end=" ")
        if hasattr(obj, "_legend") and obj._legend:
            colors.printc("legend: ", c="b", bold=1, end="")
            colors.printc(obj._legend, c="b", bold=0)
        else:
            print()

        pos = obj.GetPosition()
        bnds = obj.GetBounds()
        img = obj.GetMapper().GetInput()
        colors.printc("         position: ", c="b", bold=1, end="")
        colors.printc(pos, c="b", bold=0)

        colors.printc("       dimensions: ", c="b", bold=1, end="")
        colors.printc(img.GetDimensions(), c="b", bold=0)
        colors.printc("          spacing: ", c="b", bold=1, end="")
        colors.printc(img.GetSpacing(), c="b", bold=0)
        colors.printc("   data dimension: ", c="b", bold=1, end="")
        colors.printc(img.GetDataDimension(), c="b", bold=0)

        colors.printc("      memory size: ", c="b", bold=1, end="")
        colors.printc(int(img.GetActualMemorySize() / 1024),
                      'Mb',
                      c="b",
                      bold=0)

        colors.printc("    scalar #bytes: ", c="b", bold=1, end="")
        colors.printc(img.GetScalarSize(), c="b", bold=0)

        colors.printc("           bounds: ", c="b", bold=1, end="")
        bx1, bx2 = precision(bnds[0], 3), precision(bnds[1], 3)
        colors.printc("x=(" + bx1 + ", " + bx2 + ")", c="b", bold=0, end="")
        by1, by2 = precision(bnds[2], 3), precision(bnds[3], 3)
        colors.printc(" y=(" + by1 + ", " + by2 + ")", c="b", bold=0, end="")
        bz1, bz2 = precision(bnds[4], 3), precision(bnds[5], 3)
        colors.printc(" z=(" + bz1 + ", " + bz2 + ")", c="b", bold=0)

        colors.printc("     scalar range: ", c="b", bold=1, end="")
        colors.printc(img.GetScalarRange(), c="b", bold=0)

        printHistogram(obj,
                       horizontal=True,
                       logscale=True,
                       bins=8,
                       height=15,
                       c='b',
                       bold=0)

    elif hasattr(obj, "interactor"):  # dumps Plotter info
        axtype = {
            0: "(no axes)",
            1: "(three customizable gray grid walls)",
            2: "(cartesian axes from origin",
            3: "(positive range of cartesian axes from origin",
            4: "(axes triad at bottom left)",
            5: "(oriented cube at bottom left)",
            6: "(mark the corners of the bounding box)",
            7: "(ruler at the bottom of the window)",
            8: "(the vtkCubeAxesActor object)",
            9: "(the bounding box outline)",
            10: "(circles of maximum bounding box range)",
        }
        bns, totpt = [], 0
        for a in obj.actors:
            b = a.GetBounds()
            if a.GetBounds() is not None:
                if isinstance(a, vtk.vtkActor):
                    totpt += a.GetMapper().GetInput().GetNumberOfPoints()
                bns.append(b)
        if len(bns) == 0:
            return
        acts = obj.getActors()
        colors.printc("_" * 65, c="c", bold=0)
        colors.printc("Plotter", invert=1, dim=1, c="c", end=" ")
        otit = obj.title
        if not otit:
            otit = None
        colors.printc("   title:", otit, bold=0, c="c")
        colors.printc(" active renderer:",
                      obj.renderers.index(obj.renderer),
                      bold=0,
                      c="c")
        colors.printc("   nr. of actors:", len(acts), bold=0, c="c", end="")
        colors.printc(" (" + str(totpt), "vertices)", bold=0, c="c")
        max_bns = np.max(bns, axis=0)
        min_bns = np.min(bns, axis=0)
        colors.printc("      max bounds: ", c="c", bold=0, end="")
        bx1, bx2 = precision(min_bns[0], 3), precision(max_bns[1], 3)
        colors.printc("x=(" + bx1 + ", " + bx2 + ")", c="c", bold=0, end="")
        by1, by2 = precision(min_bns[2], 3), precision(max_bns[3], 3)
        colors.printc(" y=(" + by1 + ", " + by2 + ")", c="c", bold=0, end="")
        bz1, bz2 = precision(min_bns[4], 3), precision(max_bns[5], 3)
        colors.printc(" z=(" + bz1 + ", " + bz2 + ")", c="c", bold=0)
        if isinstance(obj.axes, dict): obj.axes = 1
        colors.printc("       axes type:",
                      obj.axes,
                      axtype[obj.axes],
                      bold=0,
                      c="c")

        for a in obj.getVolumes():
            if a.GetBounds() is not None:
                img = a.GetMapper().GetDataSetInput()
                colors.printc('_' * 65, c='b', bold=0)
                colors.printc('Volume', invert=1, dim=1, c='b')
                colors.printc('      scalar range:',
                              np.round(img.GetScalarRange(), 4),
                              c='b',
                              bold=0)
                bnds = a.GetBounds()
                colors.printc("            bounds: ", c="b", bold=0, end="")
                bx1, bx2 = precision(bnds[0], 3), precision(bnds[1], 3)
                colors.printc("x=(" + bx1 + ", " + bx2 + ")",
                              c="b",
                              bold=0,
                              end="")
                by1, by2 = precision(bnds[2], 3), precision(bnds[3], 3)
                colors.printc(" y=(" + by1 + ", " + by2 + ")",
                              c="b",
                              bold=0,
                              end="")
                bz1, bz2 = precision(bnds[4], 3), precision(bnds[5], 3)
                colors.printc(" z=(" + bz1 + ", " + bz2 + ")", c="b", bold=0)

        colors.printc(" Click actor and press i for Actor info.", c="c")

    else:
        colors.printc("_" * 65, c="g", bold=0)
        colors.printc(type(obj), c="g", invert=1)
Ejemplo n.º 10
0
from pymicro.crystal.lattice import Lattice, HklDirection

s3d = Scene3D(display=False, ren_size=(600, 600))
s3d.name = 'euler_angles_and_orientation_matrix'
euler_angles = np.array([142.8, 32.0, 214.4])
(phi1, Phi, phi2) = euler_angles
orientation = Orientation.from_euler(euler_angles)
g = orientation.orientation_matrix()

lab_frame = axes_actor(1, fontSize=50)
lab_frame.SetCylinderRadius(0.02)
s3d.add(lab_frame)

crystal_frame = axes_actor(0.6, fontSize=50, axisLabels=None)
crystal_frame.SetCylinderRadius(0.05)
collection = vtk.vtkPropCollection()
crystal_frame.GetActors(collection)
for i in range(collection.GetNumberOfItems()):
    collection.GetItemAsObject(i).GetProperty().SetColor(0.0, 0.0, 0.0)
apply_orientation_to_actor(crystal_frame, orientation)
s3d.add(crystal_frame)

a = 1.0
l = Lattice.face_centered_cubic(a)
fcc_lattice = lattice_3d(l, crystal_orientation=orientation)
set_opacity(fcc_lattice, 0.3)
s3d.add(fcc_lattice)

# arrow to show 111 lattice vector
Vc = np.array([a, a, a])
Vs = np.dot(g.T, Vc)
Ejemplo n.º 11
0
    def reset_camera(self):
        self.ren.ResetCamera()
        self.ren.ResetCameraClippingRange()

        if self.experiment is not None:
            calib = self.experiment.calibration_points
            focal_point = self.experiment.sphere_center
            view_up = calib["vertex"]-focal_point
            mid_point = (calib["nasion"]*0.7+calib["vertex"]*0.3)
            pos_vec = mid_point - focal_point
            pos = focal_point+pos_vec*15

            cam = self.ren.GetActiveCamera()
            cam.SetFocalPoint(focal_point)
            cam.SetPosition(pos)
            cam.SetViewUp(view_up)
            self.light.SetFocalPoint(focal_point)
            self.light2.SetFocalPoint(focal_point)
            self.light3.SetFocalPoint(focal_point)

            left_mid_point= (calib["vertex"]+calib["left"])/2
            right_mid_point= (calib["vertex"]+calib["right"])/2

            #top_left_pos = focal_point + (left_mid_point-focal_point)*5
            #top_right_pos = focal_point + (right_mid_point-focal_point)*5
            right_pos = focal_point + (calib["right"]-focal_point)*15

            top_pos = focal_point+(calib["vertex"]-focal_point)*15
            top_front_pos = focal_point+((calib["nasion"]+calib["vertex"])/2-focal_point)*15

            #self.light.SetPosition(top_left_pos)
            #self.light2.SetPosition(top_right_pos)

            trans = vtk.vtkTransform()
            view_up_uni = view_up/np.linalg.norm(view_up)

            n1 = calib["nasion"]-focal_point
            n1 = n1 - (np.dot(n1, view_up_uni) * view_up_uni)
            n1 /= np.linalg.norm(n1)
            n2 = np.array((0,0,1))
            n2 = n2 - (np.dot(n2, view_up_uni) * view_up_uni)
            n2 /= np.linalg.norm(n2)
            v2 = np.cross(n2,n1)
            angle2 = np.arcsin(np.linalg.norm(v2))
            angle2_deg = 180*angle2/np.pi

            v1 = np.cross((0,1,0),view_up_uni)
            angle1 = np.arcsin(np.linalg.norm(v1))
            angle1_deg = 180*angle1/np.pi

            trans.RotateWXYZ(angle2_deg,view_up_uni)
            trans.RotateWXYZ(angle1_deg,*v1)

            acs = vtk.vtkPropCollection()
            self.axes_actor.GetActors(acs)
            for i in xrange(acs.GetNumberOfItems()):
                ac = acs.GetItemAsObject(i)
                mapper = ac.GetMapper()
                source_con = mapper.GetInputConnection(0,0)
                source = source_con.GetProducer()
                if not isinstance(source,vtk.vtkTransformFilter):
                    trans_filter = vtk.vtkTransformFilter()
                    trans_filter.SetInputConnection(source.GetOutputPort())
                    trans_filter.SetTransform(trans)
                    mapper.SetInputConnection(trans_filter.GetOutputPort())
                else:
                    source.SetTransform(trans)

            #self.axes_actor.RotateY(180)

            self.light.SetPosition(top_pos)
            self.light2.SetPosition(top_front_pos)
            self.light3.SetPosition(right_pos)
            self.light3.SetIntensity(0.5)
            self.ren.ResetCameraClippingRange()
Ejemplo n.º 12
0
m1.SetInput(s1.GetOutput())

s2 = vtk.vtkConeSource()
m2 = vtk.vtkPolyDataMapper()
a2 = vtk.vtkActor()
a2.SetMapper(m2)
m2.SetInput(s2.GetOutput())

as1 = vtk.vtkAssembly()
as1.AddPart(a1)
as1.AddPart(a2)

t1 = vtk.vtkTransform()
t1.PostMultiply()
t1.Translate(5.0, 0.0, 0.0)

pc1 = vtk.vtkPropCollection()
as1.GetActors(pc1)
pc1.InitTraversal()
for i in xrange(pc1.GetNumberOfItems()):
    pc1.GetNextProp().GetProperty().SetColor(255.0, 0.0, 0.0)

ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
iren = vtk.vtkRenderWindowInteractor()
ren.AddActor(as1)
renWin.AddRenderer(ren)
iren.SetRenderWindow(renWin)

iren.Initialize()
iren.Start()
Ejemplo n.º 13
0
def printInfo(obj):
    '''Print information about a vtkActor or vtkAssembly.'''
    print([obj])

    def printvtkactor(actor, tab=''):
        poly = actor.polydata()
        pro = actor.GetProperty()
        pos = actor.GetPosition()
        bnds = actor.GetBounds()
        col = pro.GetColor()
        colr = to_precision(col[0], 3)
        colg = to_precision(col[1], 3)
        colb = to_precision(col[2], 3)
        alpha = pro.GetOpacity()
        npt = poly.GetNumberOfPoints()
        ncl = poly.GetNumberOfCells()

        print(tab, end='')
        colors.printc('vtkActor', c='g', bold=1, invert=1, dim=1, end=' ')

        if hasattr(actor, 'legend') and actor.legend:
            colors.printc('legend: ', c='g', bold=1, end='')
            colors.printc(actor.legend, c='g', bold=0)
        else:
            print()

        if hasattr(actor, 'filename'):
            colors.printc(tab+'           file: ', c='g', bold=1, end='')
            colors.printc(actor.filename, c='g', bold=0)

        colors.printc(tab+'          color: ', c='g', bold=1, end='')
        if actor.GetMapper().GetScalarVisibility():
            colors.printc('defined by point or cell data', c='g', bold=0)
        else:
            colors.printc(colors.getColorName(col) + ', rgb=('+colr+', '
                          + colg+', '+colb+'), alpha='+str(alpha), c='g', bold=0)

            if actor.GetBackfaceProperty():
                bcol = actor.GetBackfaceProperty().GetDiffuseColor()
                bcolr = to_precision(bcol[0], 3)
                bcolg = to_precision(bcol[1], 3)
                bcolb = to_precision(bcol[2], 3)
                colors.printc(tab+'     back color: ', c='g', bold=1, end='')
                colors.printc(colors.getColorName(bcol) + ', rgb=('+bcolr+', '
                              + bcolg+', ' + bcolb+')', c='g', bold=0)

        colors.printc(tab+'         points: ', c='g', bold=1, end='')
        colors.printc(npt, c='g', bold=0)

        colors.printc(tab+'          cells: ', c='g', bold=1, end='')
        colors.printc(ncl, c='g', bold=0)

        colors.printc(tab+'       position: ', c='g', bold=1, end='')
        colors.printc(pos, c='g', bold=0)

        colors.printc(tab+'     c. of mass: ', c='g', bold=1, end='')
        colors.printc(actor.centerOfMass(), c='g', bold=0)

        colors.printc(tab+'      ave. size: ', c='g', bold=1, end='')
        colors.printc(to_precision(actor.averageSize(), 4), c='g', bold=0)

        colors.printc(tab+'     diag. size: ', c='g', bold=1, end='')
        colors.printc(actor.diagonalSize(), c='g', bold=0)

        #colors.printc('      clicked point:', obj.picked3d, bold=0, c='c')
        colors.printc(tab+'         bounds: ', c='g', bold=1, end='')
        bx1, bx2 = to_precision(bnds[0], 3), to_precision(bnds[1], 3)
        colors.printc('x=('+bx1+', '+bx2+')', c='g', bold=0, end='')
        by1, by2 = to_precision(bnds[2], 3), to_precision(bnds[3], 3)
        colors.printc(' y=('+by1+', '+by2+')', c='g', bold=0, end='')
        bz1, bz2 = to_precision(bnds[4], 3), to_precision(bnds[5], 3)
        colors.printc(' z=('+bz1+', '+bz2+')', c='g', bold=0)

        colors.printc(tab+'           area: ', c='g', bold=1, end='')
        colors.printc(to_precision(actor.area(), 8), c='g', bold=0)

        colors.printc(tab+'         volume: ', c='g', bold=1, end='')
        colors.printc(to_precision(actor.volume(), 8), c='g', bold=0)

        arrtypes = dict()
        arrtypes[vtk.VTK_UNSIGNED_CHAR] = 'VTK_UNSIGNED_CHAR'
        arrtypes[vtk.VTK_UNSIGNED_INT] = 'VTK_UNSIGNED_INT'
        arrtypes[vtk.VTK_FLOAT] = 'VTK_FLOAT'
        arrtypes[vtk.VTK_DOUBLE] = 'VTK_DOUBLE'

        if poly.GetPointData():
            ptdata = poly.GetPointData()
            for i in range(ptdata.GetNumberOfArrays()):
                name = ptdata.GetArrayName(i)
                if name:
                    colors.printc(tab+'     point data: ',
                                  c='g', bold=1, end='')
                    try:
                        tt = arrtypes[ptdata.GetArray(i).GetDataType()]
                        colors.printc('name='+name, 'type='+tt, c='g', bold=0)
                    except:
                        tt = ptdata.GetArray(i).GetDataType()
                        colors.printc('name='+name, 'type=', tt, c='g', bold=0)

        if poly.GetCellData():
            cldata = poly.GetCellData()
            for i in range(cldata.GetNumberOfArrays()):
                name = cldata.GetArrayName(i)
                if name:
                    colors.printc(tab+'      cell data: ',
                                  c='g', bold=1, end='')
                    try:
                        tt = arrtypes[cldata.GetArray(i).GetDataType()]
                        colors.printc('name='+name, 'type='+tt, c='g', bold=0)
                    except:
                        tt = cldata.GetArray(i).GetDataType()
                        colors.printc('name='+name, 'type=', tt, c='g', bold=0)

    if not obj:
        return

    elif isinstance(obj, vtk.vtkActor):
        colors.printc('_'*60, c='g', bold=0)
        printvtkactor(obj)

    elif isinstance(obj, vtk.vtkAssembly):
        colors.printc('_'*60, c='g', bold=0)
        colors.printc('vtkAssembly', c='g', bold=1, invert=1, end=' ')
        if hasattr(obj, 'legend'):
            colors.printc('legend: ', c='g', bold=1, end='')
            colors.printc(obj.legend, c='g', bold=0)
        else:
            print()

        pos = obj.GetPosition()
        bnds = obj.GetBounds()
        colors.printc('          position: ', c='g', bold=1, end='')
        colors.printc(pos, c='g', bold=0)

        colors.printc('            bounds: ', c='g', bold=1, end='')
        bx1, bx2 = to_precision(bnds[0], 3), to_precision(bnds[1], 3)
        colors.printc('x=('+bx1+', '+bx2+')', c='g', bold=0, end='')
        by1, by2 = to_precision(bnds[2], 3), to_precision(bnds[3], 3)
        colors.printc(' y=('+by1+', '+by2+')', c='g', bold=0, end='')
        bz1, bz2 = to_precision(bnds[4], 3), to_precision(bnds[5], 3)
        colors.printc(' z=('+bz1+', '+bz2+')', c='g', bold=0)

        cl = vtk.vtkPropCollection()
        obj.GetActors(cl)
        cl.InitTraversal()
        for i in range(obj.GetNumberOfPaths()):
            act = vtk.vtkActor.SafeDownCast(cl.GetNextProp())
            if isinstance(act, vtk.vtkActor):
                printvtkactor(act, tab='     ')
    
    elif hasattr(obj, 'interactor'): # dumps Plotter info
        axtype = {0 : '(no axes)',                   
                  1 : '(three gray grid walls)',
                  2 : '(cartesian axes from origin',
                  3 : '(positive range of cartesian axes from origin',
                  4 : '(axes triad at bottom left)',
                  5 : '(oriented cube at bottom left)',
                  6 : '(mark the corners of the bounding box)',
                  7 : '(ruler at the bottom of the window)',
                  8 : '(the vtkCubeAxesActor object)', 
                  9 : '(the bounding box outline)'}
        bns, totpt = [], 0
        for a in obj.actors:
            b = a.GetBounds()
            if b is not None: 
                if isinstance(obj, vtk.vtkVolume): # dumps Volume info
                    colors.printc('Volume', invert=1, dim=1, c='b')
                    colors.printc('      scalar range:', 
                                  np.round(obj.GetScalarRange(),4), c='b', bold=0)
                    bnds = obj.GetBounds()  
                    colors.printc('            bounds: ', c='g', bold=1, end='')
                    bx1, bx2 = to_precision(bnds[0], 3), to_precision(bnds[1], 3)
                    colors.printc('x=('+bx1+', '+bx2+')', c='g', bold=0, end='')
                    by1, by2 = to_precision(bnds[2], 3), to_precision(bnds[3], 3)
                    colors.printc(' y=('+by1+', '+by2+')', c='g', bold=0, end='')
                    bz1, bz2 = to_precision(bnds[4], 3), to_precision(bnds[5], 3)
                    colors.printc(' z=('+bz1+', '+bz2+')', c='g', bold=0)
                elif isinstance(obj, vtk.vtkActor):
                    totpt += a.GetMapper().GetInput().GetNumberOfPoints()
                bns.append(b)
        if len(bns) == 0: 
            return
        acts = obj.getActors()
        colors.printc('_'*60, c='c', bold=0)
        colors.printc('Plotter', invert=1, dim=1, c='c', end=' ')
        otit = obj.title
        if not otit:
            otit = None
        colors.printc('   title:', otit, bold=0, c='c')
        colors.printc(' active renderer:', obj.renderers.index(obj.renderer), bold=0, c='c')
        colors.printc('   nr. of actors:', len(acts), bold=0, c='c', end='')
        colors.printc(' ('+str(totpt), 'vertices)', bold=0, c='c')
        max_bns = np.max(bns, axis=0)
        min_bns = np.min(bns, axis=0)
        colors.printc('      max bounds: ', c='c', bold=0, end='')
        bx1, bx2 = to_precision(min_bns[0], 3), to_precision(max_bns[1], 3)
        colors.printc('x=('+bx1+', '+bx2+')', c='c', bold=0, end='')
        by1, by2 = to_precision(min_bns[2], 3), to_precision(max_bns[3], 3)
        colors.printc(' y=('+by1+', '+by2+')', c='c', bold=0, end='')
        bz1, bz2 = to_precision(min_bns[4], 3), to_precision(max_bns[5], 3)
        colors.printc(' z=('+bz1+', '+bz2+')', c='c', bold=0)
        colors.printc('       axes type:', obj.axes, axtype[obj.axes], bold=0, c='c')
        colors.printc(' click actor and press i for more info.', c='c')

    else:
        colors.printc('_'*60, c='g', bold=0)
        colors.printc(obj, c='g')
        colors.printc(type(obj), c='g', invert=1)
Ejemplo n.º 14
0
def polydata(obj, rebuild=True, index=0):
    '''
    Returns the vtkPolyData of a vtkActor or vtkAssembly.
        If rebuild=True returns a copy of polydata
        that corresponds to the current actor's position in space.
        If a vtkAssembly is passed, return the polydata of component index.
    '''

    if isinstance(obj, vtk.vtkActor):
        if not rebuild:
            if hasattr(obj, 'poly'):
                if obj.poly: return obj.poly
            else:
                setattr(obj, 'poly', None)
            obj.poly = obj.GetMapper().GetInput()  #cache it for speed
            return obj.poly
        M = obj.GetMatrix()
        if isIdentity(M):
            if hasattr(obj, 'poly'):
                if obj.poly: return obj.poly
            else:
                setattr(obj, 'poly', None)
            obj.poly = obj.GetMapper().GetInput()  #cache it for speed
            return obj.poly
        # if identity return the original polydata
        # otherwise make a copy that corresponds to
        # the actual position in space of the actor
        transform = vtk.vtkTransform()
        transform.SetMatrix(M)
        tp = vtk.vtkTransformPolyDataFilter()
        tp.SetTransform(transform)
        if vtkMV: tp.SetInputData(obj.GetMapper().GetInput())
        else: tp.SetInput(obj.GetMapper().GetInput())
        tp.Update()
        return tp.GetOutput()

    elif isinstance(obj, vtk.vtkAssembly):
        cl = vtk.vtkPropCollection()
        obj.GetActors(cl)
        cl.InitTraversal()
        for i in range(index + 1):
            act = vtk.vtkActor.SafeDownCast(cl.GetNextProp())
        pd = act.GetMapper().GetInput()  #not optimized
        if not rebuild: return pd
        M = act.GetMatrix()
        if isIdentity(M): return pd
        # if identity return the original polydata
        # otherwise make a copy that corresponds to
        # the actual position in space of the actor
        transform = vtk.vtkTransform()
        transform.SetMatrix(M)
        tp = vtk.vtkTransformPolyDataFilter()
        tp.SetTransform(transform)
        if vtkMV: tp.SetInputData(pd)
        else: tp.SetInput(pd)
        tp.Update()
        return tp.GetOutput()

    elif isinstance(obj, vtk.vtkPolyData):
        return obj
    elif isinstance(obj, vtk.vtkActor2D):
        return obj.GetMapper().GetInput()
    elif isinstance(obj, vtk.vtkImageActor):
        return obj.GetMapper().GetInput()
    elif obj is None:
        return None

    colors.printc("Fatal Error in polydata(): ", 'r', end='')
    colors.printc(("input is neither a vtkActor nor vtkAssembly.", [obj]), 'r')
    exit(1)
Ejemplo n.º 15
0
def view(image=None,  # noqa: C901
         label_image=None,  # noqa: C901
         label_image_names=None,  # noqa: C901
         label_image_weights=None,  # noqa: C901
         label_image_blend=0.5,
         cmap=None,
         lut='glasbey',
         select_roi=False,
         interpolation=True,
         gradient_opacity=0.22, opacity_gaussians=None, channels=None,
         slicing_planes=False, shadow=True, blend_mode='composite',
         point_sets=[],
         point_set_colors=[], point_set_opacities=[],
         point_set_representations=[], point_set_sizes=[],
         geometries=[],
         geometry_colors=[], geometry_opacities=[],
         ui_collapsed=False, rotate=False, annotations=True, mode='v',
         **kwargs):
    """View the image and/or point sets and/or geometries.

    Creates and returns an ipywidget to visualize an image, and/or point sets
    and/or geometries .

    The image can be 2D or 3D. A label map that corresponds to the image can
    also be provided. The image and label map must have the same size.

    The type of the image can be an numpy.array, itk.Image,
    vtk.vtkImageData, pyvista.UniformGrid, imglyb.ReferenceGuardingRandomAccessibleInterval,
    or a NumPy array-like, e.g. a Dask array.

    A point set or a sequence of points sets can be visualized. The type of the
    point set can be an numpy.array (Nx3 array of point positions).

    A geometry or a sequence of geometries can be visualized. The type of the
    geometry can be an itk.Mesh.

    Parameters
    ----------

    General Interface
    ^^^^^^^^^^^^^^^^^

    ui_collapsed : bool, default: False
        Collapse the native widget user interface.

    rotate : bool, default: False
        Continuously rotate the camera around the scene in volume rendering
        mode.

    annotations : bool, default: True
        Display annotations describing orientation and the value of a
        mouse-position-based data probe.

    mode: 'x', 'y', 'z', or 'v', default: 'v'
        Only relevant for 3D scenes.
        Viewing mode:
            'x': x-plane
            'y': y-plane
            'z': z-plane
            'v': volume rendering

    camera: 3x3 numpy float32 array
        Camera parameters:
            [[position_x,    position_y,    position_z],
             [focal_point_x, focal_point_y, focal_point_z],
             [view_up_x,     view_up_y,     view_up_z]]

    background: (red, green, blue) tuple, components from 0.0 to 1.0
        Background color. Default is based on the current Jupyter theme.


    Images
    ^^^^^^

    image : array_like, itk.Image, or vtk.vtkImageData
        The 2D or 3D image to visualize.

    label_image : array_like, itk.Image, or vtk.vtkImageData
        The 2D or 3D label map to visualize. If an image is also provided, the
        label map must have the same size.

    label_image_names : OrderedDict of (label_value, label_name)
        String names associated with the integer label values.

    label_image_weights : 1D numpy float32 array, default: None
        Rendering weights, from 0.0 to 1.0, associated labels in the label map.

    label_image_blend : float, default: 0.5
        Label map blend with intensity image, from 0.0 to 1.0.

    vmin: list of floats, default: Minimum of the image pixel buffer
        Value that maps to the minimum of image colormap. A single value
        can be provided or a list for multi-component images.

    vmax: list of floats, default: Maximum of the image pixel buffer
        Value that maps to the minimum of image colormap.  A single value can
        be provided or a list for multi-component images.

    cmap: list of colormaps
            default:
                - single component: 'viridis', 'grayscale' with a label map,
                - two components: 'BkCy', 'BkMa'
                - three components: 'BkRd', 'BkGn', 'BkBu'
        Colormap for each image component. Some valid values available at
        itkwidgets.cm.*
        Colormaps can also be Nx3 float NumPy arrays from 0.0 to 1.0 for the
        red, green, blue points on the map or a
        matplotlib.colors.LinearSegmentedColormap.

    lut: lookup table, default: 'glasbey'
        Lookup table for the label map. Some valid values available at
        itkwidgets.lut.*

    select_roi: bool, default: False
        Enable an interactive region of interest widget for the image.

    slicing_planes: bool, default: False
        Enable slicing planes on the volume rendering.

    x_slice: float, default: None
        World-space position of the X slicing plane.

    y_slice: float, default: None
        World-space position of the Y slicing plane.

    z_slice: float, default: None
        World-space position of the Z slicing plane.

    interpolation: bool, default: True
        Linear as opposed to nearest neighbor interpolation for image slices.
        Note: Interpolation is not currently supported with label maps.

    gradient_opacity: float, default: 0.22
        Gradient opacity for composite volume rendering, in the range (0.0, 1.0].

    opacity_gaussians: list of list of dict
        Volume rendering opacity transfer function Gaussian parameters. For each
        image component, multiple Gaussians can be specified.
        Default Gaussian parameters:
          {'position': 0.5, 'height': 1, 'width': 0.5, 'xBias': 0.51, 'yBias': 0.4}

    channels: list of booleans
        For multi-component images, the components or channels that are enabled.

    shadow: bool, default: True
        Use shadowing with composite volume rendering.

    blend_mode: 'composite', 'max', 'min', or 'average', default: 'composite'
        Volume rendering blend mode.

    Point Sets
    ^^^^^^^^^^

    point_sets: point set, or sequence of point sets
        The point sets to visualize.

    point_set_colors: list of (r, g, b) colors
        Colors for the N points. See help(matplotlib.colors) for
        specification. Defaults to the Glasbey series of categorical colors.

    point_set_opacities: array of floats, default: [1.0,]*n
        Opacity for the point sets, in the range (0.0, 1.0].

    point_set_sizes: array of unsigned integers, default: [3,]*n
        Sizes for the point sets, in pixel size units.

    point_set_representations: list of strings, default: ['points',]*n
        How to represent the point set. One of 'hidden', 'points', or 'spheres'.

    Geometries
    ^^^^^^^^^^

    geometries: geometries, or sequence of geometries
        The geometries to visualize.

    geometry_colors: list of RGB colors
        Colors for the N geometries. See help(matplotlib.colors) for
        specification. Defaults to the Glasbey series of categorical colors.

    geometry_opacities: list of floats, default: [1.0,]*n
        Opacity for the point sets, in the range (0.0, 1.0].


    Other Parameters
    ----------------

    units: string, default: ''
        Units to display in the scale bar.

    actors: vtkActor, vtkAssembly, vtkVolume, default: None
        List of standard vtk objects, colors are extracted from their properties

    size_limit_2d: 2x1 numpy int64 array, default: [1024, 1024]
        Size limit for 2D image visualization. If the roi is larger than this
        size, it will be downsampled for visualization

    size_limit_3d: 3x1 numpy int64 array, default: [192, 192, 192]
        Size limit for 3D image visualization. If the roi is larger than this
        size, it will be downsampled for visualization.

    sample_distance: float, default: 0.25
        Sampling distance for volume rendering, normalized from 0.0 to 1.0.
        Lower values result in a higher quality rendering. High values improve
        the framerate.

    Returns
    -------
    viewer : ipywidget
        Display by placing at the end of a Jupyter cell or calling
        IPython.display.display. Query or set properties on the object to change
        the visualization or retrieve values created by interacting with the
        widget.
    """

    # this block allows the user to pass already formed vtkActor vtkVolume
    # objects
    actors = kwargs.pop("actors", None)
    if have_vtk and actors is not None:
        if not isinstance(actors, (list, tuple)
                          ):  # passing the object directly, so make it a list
            actors = [actors]

        images = []

        for a in actors:
            if have_mayavi:
                from mayavi.modules import surface
                from mayavi.modules import iso_surface
                from tvtk.api import tvtk
                if isinstance(a, surface.Surface):
                    a = tvtk.to_vtk(a.actor.actor)
                elif isinstance(a, iso_surface.IsoSurface):
                    a = tvtk.to_vtk(a.actor.actor)

            if isinstance(a, vtk.vtkAssembly):  # unpack assemblies
                cl = vtk.vtkPropCollection()
                a.GetActors(cl)
                cl.InitTraversal()
                for i in range(a.GetNumberOfPaths()):
                    ac = vtk.vtkActor.SafeDownCast(cl.GetNextProp())
                    apoly = ac.GetMapper().GetInput()
                    prop = ac.GetProperty()
                    transform = vtk.vtkTransform()
                    transform.SetMatrix(ac.GetMatrix())
                    tp = vtk.vtkTransformPolyDataFilter()
                    tp.SetTransform(transform)
                    tp.SetInputData(apoly)
                    tp.Update()
                    poly = tp.GetOutput()
                    if poly.GetNumberOfPolys():
                        geometries.insert(0, poly)
                        geometry_colors.insert(0, prop.GetColor())
                        geometry_opacities.insert(0, prop.GetOpacity())
                    else:
                        point_sets.insert(0, poly)
                        point_set_colors.insert(0, prop.GetColor())
                        point_set_opacities.insert(0, prop.GetOpacity())

            elif isinstance(a, vtk.vtkActor):
                apoly = a.GetMapper().GetInput()
                transform = vtk.vtkTransform()
                transform.SetMatrix(a.GetMatrix())
                tp = vtk.vtkTransformPolyDataFilter()
                tp.SetTransform(transform)
                tp.SetInputData(apoly)
                tp.Update()
                poly = tp.GetOutput()
                prop = a.GetProperty()
                if poly.GetNumberOfPolys() or poly.GetNumberOfStrips() or poly.GetNumberOfLines():
                    geometries.insert(0, poly)
                    geometry_colors.insert(0, prop.GetColor())
                    geometry_opacities.insert(0, prop.GetOpacity())
                else:
                    point_sets.insert(0, poly)
                    point_set_colors.insert(0, prop.GetColor())
                    point_set_opacities.insert(0, prop.GetOpacity())

            elif isinstance(a, vtk.vtkVolume):
                images.append(a.GetMapper().GetInput())

        if image is None and len(images):  # only one image is rendered
            image = images[0]

    viewer = Viewer(image=image,
                    label_image=label_image,
                    label_image_names=label_image_names,
                    label_image_blend=label_image_blend,
                    label_image_weights=label_image_weights,
                    cmap=cmap,
                    lut=lut,
                    select_roi=select_roi,
                    interpolation=interpolation,
                    gradient_opacity=gradient_opacity,
                    opacity_gaussians=opacity_gaussians,
                    slicing_planes=slicing_planes,
                    shadow=shadow, blend_mode=blend_mode,
                    point_sets=point_sets,
                    point_set_colors=point_set_colors,
                    point_set_opacities=point_set_opacities,
                    point_set_representations=point_set_representations,
                    point_set_sizes=point_set_sizes,
                    geometries=geometries, geometry_colors=geometry_colors, geometry_opacities=geometry_opacities,
                    rotate=rotate, ui_collapsed=ui_collapsed, annotations=annotations, mode=mode,
                    **kwargs)
    return viewer
Ejemplo n.º 16
0
def view(image=None,  # noqa: C901
         cmap=cm.viridis,
         select_roi=False,
         interpolation=True,
         gradient_opacity=0.22, slicing_planes=False, shadow=True, blend='composite',
         point_sets=[],
         point_set_colors=[], point_set_opacities=[], point_set_representations=[],
         # point_set_sizes=[],
         geometries=[],
         geometry_colors=[], geometry_opacities=[],
         ui_collapsed=False, rotate=False, annotations=True, mode='v',
         **kwargs):
    """View the image and/or point sets and/or geometries.

    Creates and returns an ipywidget to visualize an image, and/or point sets
    and/or geometries .

    The image can be 2D or 3D.

    The type of the image can be an numpy.array, itk.Image,
    vtk.vtkImageData, pyvista.UniformGrid, imglyb.ReferenceGuardingRandomAccessibleInterval,
    or a NumPy array-like, e.g. a Dask array.

    A point set or a sequence of points sets can be visualized. The type of the
    point set can be an numpy.array (Nx3 array of point positions).

    A geometry or a sequence of geometries can be visualized. The type of the
    geometry can be an itk.Mesh.

    Parameters
    ----------

    General Interface
    ^^^^^^^^^^^^^^^^^

    ui_collapsed : bool, optional, default: False
        Collapse the native widget user interface.

    rotate : bool, optional, default: False
        Continuously rotate the camera around the scene in volume rendering
        mode.

    annotations : bool, optional, default: True
        Display annotations describing orientation and the value of a
        mouse-position-based data probe.

    mode: 'x', 'y', 'z', or 'v', optional, default: 'v'
        Only relevant for 3D scenes.
        Viewing mode:
            'x': x-plane
            'y': y-plane
            'z': z-plane
            'v': volume rendering

    camera: 3x3 numpy float32 array, optional
        Camera parameters:
            [[position_x,    position_y,    position_z],
             [focal_point_x, focal_point_y, focal_point_z],
             [view_up_x,     view_up_y,     view_up_z]]


    Images
    ^^^^^^

    image : array_like, itk.Image, or vtk.vtkImageData
        The 2D or 3D image to visualize.

    vmin: float, optional, default: None
        Value that maps to the minimum of image colormap. Defaults to minimum of
        the image pixel buffer.

    vmax: float, optional, default: None
        Value that maps to the minimum of image colormap. Defaults to maximum of
        the image pixel buffer.

    cmap: string, optional, default: 'Viridis (matplotlib)'
        Colormap. Some valid values available at itkwidgets.cm.*

    select_roi: bool, optional, default: False
        Enable an interactive region of interest widget for the image.

    slicing_planes: bool, optional, default: False
        Enable slicing planes on the volume rendering.

    x_slice: float, optional, default: None
        World-space position of the X slicing plane.

    y_slice: float, optional, default: None
        World-space position of the Y slicing plane.

    z_slice: float, optional, default: None
        World-space position of the Z slicing plane.

    interpolation: bool, optional, default: True
        Linear as opposed to nearest neighbor interpolation for image slices.

    gradient_opacity: float, optional, default: 0.22
        Gradient opacity for composite volume rendering, in the range (0.0, 1.0].

    shadow: bool, optional, default: True
        Use shadowing with composite volume rendering.

    blend: 'composite', 'max', 'min', or 'average', optional, default: 'composite'
        Volume rendering blend mode.

    Point Sets
    ^^^^^^^^^^

    point_sets: point set, or sequence of point sets, optional
        The point sets to visualize.

    point_set_colors: list of RGB colors, optional
        Colors for the N geometries. See help(matplotlib.colors) for
        specification. Defaults to the Glasbey series of categorical colors.

    point_set_opacities: list of floats, optional, default: [0.5,]*n
        Opacity for the point sets, in the range (0.0, 1.0].

    point_set_representations: list of strings, optional, default: ['points',]*n
        How to represent the point set. One of 'hidden', 'points', or 'spheres'.

    Geometries
    ^^^^^^^^^^

    geometries: geometries, or sequence of geometries, optional
        The geometries to visualize.

    geometry_colors: list of RGB colors, optional
        Colors for the N geometries. See help(matplotlib.colors) for
        specification. Defaults to the Glasbey series of categorical colors.

    geometry_opacities: list of floats, optional, default: [1.0,]*n
        Opacity for the point sets, in the range (0.0, 1.0].


    Other Parameters
    ----------------

    units: string, optional, default: ''
        Units to display in the scale bar.

    actors: vtkActor, vtkAssembly, vtkVolume, optional, default: None
        List of standard vtk objects, colors are extracted from their properties

    size_limit_2d: 2x1 numpy int64 array, optional, default: [1024, 1024]
        Size limit for 2D image visualization. If the roi is larger than this
        size, it will be downsampled for visualization

    size_limit_3d: 3x1 numpy int64 array, optional, default: [192, 192, 192]
        Size limit for 3D image visualization. If the roi is larger than this
        size, it will be downsampled for visualization.

    Returns
    -------
    viewer : ipywidget
        Display by placing at the end of a Jupyter cell or calling
        IPython.display.display. Query or set properties on the object to change
        the visualization or retrieve values created by interacting with the
        widget.
    """

    # this block allows the user to pass already formed vtkActor vtkVolume
    # objects
    actors = kwargs.pop("actors", None)
    if have_vtk and actors is not None:
        if not isinstance(actors, (list, tuple)
                          ):  # passing the object directly, so make it a list
            actors = [actors]

        images = []

        for a in actors:
            if have_mayavi:
                from mayavi.modules import surface
                from mayavi.modules import iso_surface
                from tvtk.api import tvtk
                if isinstance(a, surface.Surface):
                    a = tvtk.to_vtk(a.actor.actor)
                elif isinstance(a, iso_surface.IsoSurface):
                    a = tvtk.to_vtk(a.actor.actor)

            if isinstance(a, vtk.vtkAssembly):  # unpack assemblies
                cl = vtk.vtkPropCollection()
                a.GetActors(cl)
                cl.InitTraversal()
                for i in range(a.GetNumberOfPaths()):
                    ac = vtk.vtkActor.SafeDownCast(cl.GetNextProp())
                    apoly = ac.GetMapper().GetInput()
                    prop = ac.GetProperty()
                    transform = vtk.vtkTransform()
                    transform.SetMatrix(ac.GetMatrix())
                    tp = vtk.vtkTransformPolyDataFilter()
                    tp.SetTransform(transform)
                    tp.SetInputData(apoly)
                    tp.Update()
                    poly = tp.GetOutput()
                    if poly.GetNumberOfPolys():
                        geometries.insert(0, poly)
                        geometry_colors.insert(0, prop.GetColor())
                        geometry_opacities.insert(0, prop.GetOpacity())
                    else:
                        point_sets.insert(0, poly)
                        point_set_colors.insert(0, prop.GetColor())
                        point_set_opacities.insert(0, prop.GetOpacity())

            elif isinstance(a, vtk.vtkActor):
                apoly = a.GetMapper().GetInput()
                transform = vtk.vtkTransform()
                transform.SetMatrix(a.GetMatrix())
                tp = vtk.vtkTransformPolyDataFilter()
                tp.SetTransform(transform)
                tp.SetInputData(apoly)
                tp.Update()
                poly = tp.GetOutput()
                prop = a.GetProperty()
                if poly.GetNumberOfPolys() or poly.GetNumberOfStrips() or poly.GetNumberOfLines():
                    geometries.insert(0, poly)
                    geometry_colors.insert(0, prop.GetColor())
                    geometry_opacities.insert(0, prop.GetOpacity())
                else:
                    point_sets.insert(0, poly)
                    point_set_colors.insert(0, prop.GetColor())
                    point_set_opacities.insert(0, prop.GetOpacity())

            elif isinstance(a, vtk.vtkVolume):
                images.append(a.GetMapper().GetInput())

        if image is None and len(images):  # only one image is rendered
            image = images[0]

    viewer = Viewer(image=image,
                    cmap=cmap,
                    select_roi=select_roi,
                    interpolation=interpolation,
                    gradient_opacity=gradient_opacity, slicing_planes=slicing_planes,
                    shadow=shadow, blend=blend,
                    point_sets=point_sets,
                    point_set_colors=point_set_colors,
                    point_set_opacities=point_set_opacities,
                    point_set_representations=point_set_representations,
                    geometries=geometries, geometry_colors=geometry_colors, geometry_opacities=geometry_opacities,
                    rotate=rotate, ui_collapsed=ui_collapsed, annotations=annotations, mode=mode,
                    **kwargs)
    return viewer
Ejemplo n.º 17
0
    def getActors(self, obj=None, renderer=None):
        """
        Return an actors list.

        If ``obj`` is:
            ``None``, return actors of current renderer

            ``int``, return actors in given renderer number

            ``vtkAssembly`` return the contained actors

            ``string``, return actors matching legend name

        :param int,vtkRenderer renderer: specify which renederer to look into.
        """
        if renderer is None:
            renderer = self.renderer
        elif isinstance(renderer, int):
            renderer = self.renderers.index(renderer)
        else:
            return []

        if obj is None or isinstance(obj, int):
            if obj is None:
                acs = renderer.GetActors()
            elif obj >= len(self.renderers):
                colors.printc(
                    "~timesError in getActors: non existing renderer",
                    obj,
                    c=1)
                return []
            else:
                acs = self.renderers[obj].GetActors()
            actors = []
            acs.InitTraversal()
            for i in range(acs.GetNumberOfItems()):
                a = acs.GetNextItem()
                if a.GetPickable():
                    r = self.renderers.index(renderer)
                    if a == self.axes_exist[r]:
                        continue
                    actors.append(a)
            return actors

        elif isinstance(obj, vtk.vtkAssembly):
            cl = vtk.vtkPropCollection()
            obj.GetActors(cl)
            actors = []
            cl.InitTraversal()
            for i in range(obj.GetNumberOfPaths()):
                act = vtk.vtkActor.SafeDownCast(cl.GetNextProp())
                if act.GetPickable():
                    actors.append(act)
            return actors

        elif isinstance(obj, str):  # search the actor by the legend name
            actors = []
            for a in self.actors:
                if hasattr(a, "_legend") and obj in a._legend:
                    actors.append(a)
            return actors

        elif isinstance(obj, vtk.vtkActor):
            return [obj]

        if self.verbose:
            colors.printc(
                "~lightning Warning in getActors: unexpected input type",
                obj,
                c=1)
        return []
Ejemplo n.º 18
0
 def set_props(self, props):
     self.props = vtk.vtkPropCollection()
     for prop in props:
         self.props.AddItem(prop)
Ejemplo n.º 19
0
def printInfo(obj):
    """Print information about a vtk object."""
    def printvtkactor(actor, tab=""):

        if not actor.GetPickable():
            return

        if hasattr(actor, "polydata"):
            poly = actor.polydata()
        else:
            poly = actor.GetMapper().GetInput()
        pro = actor.GetProperty()
        pos = actor.GetPosition()
        bnds = actor.GetBounds()
        col = pro.GetColor()
        colr = precision(col[0], 3)
        colg = precision(col[1], 3)
        colb = precision(col[2], 3)
        alpha = pro.GetOpacity()
        npt = poly.GetNumberOfPoints()
        ncl = poly.GetNumberOfCells()

        print(tab, end="")
        colors.printc("vtkActor", c="g", bold=1, invert=1, dim=1, end=" ")

        if hasattr(actor, "_legend") and actor._legend:
            colors.printc("legend: ", c="g", bold=1, end="")
            colors.printc(actor._legend, c="g", bold=0)
        else:
            print()

        if hasattr(actor, "filename") and actor.filename:
            colors.printc(tab + "           file: ", c="g", bold=1, end="")
            colors.printc(actor.filename, c="g", bold=0)

        colors.printc(tab + "          color: ", c="g", bold=1, end="")
        if actor.GetMapper().GetScalarVisibility():
            colors.printc("defined by point or cell data", c="g", bold=0)
        else:
            colors.printc(colors.getColorName(col) + ', rgb=(' + colr + ', ' +
                          colg + ', ' + colb + '), alpha=' + str(alpha),
                          c='g',
                          bold=0)

            if actor.GetBackfaceProperty():
                bcol = actor.GetBackfaceProperty().GetDiffuseColor()
                bcolr = precision(bcol[0], 3)
                bcolg = precision(bcol[1], 3)
                bcolb = precision(bcol[2], 3)
                colors.printc(tab + '     back color: ', c='g', bold=1, end='')
                colors.printc(colors.getColorName(bcol) + ', rgb=(' + bcolr +
                              ', ' + bcolg + ', ' + bcolb + ')',
                              c='g',
                              bold=0)

        colors.printc(tab + "         points: ", c="g", bold=1, end="")
        colors.printc(npt, c="g", bold=0)

        colors.printc(tab + "          cells: ", c="g", bold=1, end="")
        colors.printc(ncl, c="g", bold=0)

        colors.printc(tab + "       position: ", c="g", bold=1, end="")
        colors.printc(pos, c="g", bold=0)

        if hasattr(actor, "polydata"):
            colors.printc(tab + "     c. of mass: ", c="g", bold=1, end="")
            colors.printc(actor.centerOfMass(), c="g", bold=0)

            colors.printc(tab + "      ave. size: ", c="g", bold=1, end="")
            colors.printc(precision(actor.averageSize(), 4), c="g", bold=0)

            colors.printc(tab + "     diag. size: ", c="g", bold=1, end="")
            colors.printc(actor.diagonalSize(), c="g", bold=0)

            colors.printc(tab + "           area: ", c="g", bold=1, end="")
            colors.printc(precision(actor.area(), 8), c="g", bold=0)

            colors.printc(tab + "         volume: ", c="g", bold=1, end="")
            colors.printc(precision(actor.volume(), 8), c="g", bold=0)

        colors.printc(tab + "         bounds: ", c="g", bold=1, end="")
        bx1, bx2 = precision(bnds[0], 3), precision(bnds[1], 3)
        colors.printc("x=(" + bx1 + ", " + bx2 + ")", c="g", bold=0, end="")
        by1, by2 = precision(bnds[2], 3), precision(bnds[3], 3)
        colors.printc(" y=(" + by1 + ", " + by2 + ")", c="g", bold=0, end="")
        bz1, bz2 = precision(bnds[4], 3), precision(bnds[5], 3)
        colors.printc(" z=(" + bz1 + ", " + bz2 + ")", c="g", bold=0)

        arrtypes = dict()
        arrtypes[vtk.VTK_UNSIGNED_CHAR] = "VTK_UNSIGNED_CHAR"
        arrtypes[vtk.VTK_UNSIGNED_INT] = "VTK_UNSIGNED_INT"
        arrtypes[vtk.VTK_FLOAT] = "VTK_FLOAT"
        arrtypes[vtk.VTK_DOUBLE] = "VTK_DOUBLE"

        if poly.GetPointData():
            ptdata = poly.GetPointData()
            for i in range(ptdata.GetNumberOfArrays()):
                name = ptdata.GetArrayName(i)
                if name:
                    colors.printc(tab + "     point data: ",
                                  c="g",
                                  bold=1,
                                  end="")
                    try:
                        tt = arrtypes[ptdata.GetArray(i).GetDataType()]
                        colors.printc("name=" + name,
                                      "type=" + tt,
                                      c="g",
                                      bold=0)
                    except:
                        tt = ptdata.GetArray(i).GetDataType()
                        colors.printc("name=" + name,
                                      "type=",
                                      tt,
                                      c="g",
                                      bold=0)

        if poly.GetCellData():
            cldata = poly.GetCellData()
            for i in range(cldata.GetNumberOfArrays()):
                name = cldata.GetArrayName(i)
                if name:
                    colors.printc(tab + "      cell data: ",
                                  c="g",
                                  bold=1,
                                  end="")
                    try:
                        tt = arrtypes[cldata.GetArray(i).GetDataType()]
                        colors.printc("name=" + name,
                                      "type=" + tt,
                                      c="g",
                                      bold=0)
                    except:
                        tt = cldata.GetArray(i).GetDataType()
                        colors.printc("name=" + name,
                                      "type=",
                                      tt,
                                      c="g",
                                      bold=0)

    if not obj:
        return

    elif isinstance(obj, vtk.vtkActor):
        colors.printc("_" * 60, c="g", bold=0)
        printvtkactor(obj)

    elif isinstance(obj, vtk.vtkAssembly):
        colors.printc("_" * 60, c="g", bold=0)
        colors.printc("vtkAssembly", c="g", bold=1, invert=1, end=" ")
        if hasattr(obj, "_legend"):
            colors.printc("legend: ", c="g", bold=1, end="")
            colors.printc(obj._legend, c="g", bold=0)
        else:
            print()

        pos = obj.GetPosition()
        bnds = obj.GetBounds()
        colors.printc("          position: ", c="g", bold=1, end="")
        colors.printc(pos, c="g", bold=0)

        colors.printc("            bounds: ", c="g", bold=1, end="")
        bx1, bx2 = precision(bnds[0], 3), precision(bnds[1], 3)
        colors.printc("x=(" + bx1 + ", " + bx2 + ")", c="g", bold=0, end="")
        by1, by2 = precision(bnds[2], 3), precision(bnds[3], 3)
        colors.printc(" y=(" + by1 + ", " + by2 + ")", c="g", bold=0, end="")
        bz1, bz2 = precision(bnds[4], 3), precision(bnds[5], 3)
        colors.printc(" z=(" + bz1 + ", " + bz2 + ")", c="g", bold=0)

        cl = vtk.vtkPropCollection()
        obj.GetActors(cl)
        cl.InitTraversal()
        for i in range(obj.GetNumberOfPaths()):
            act = vtk.vtkActor.SafeDownCast(cl.GetNextProp())
            if isinstance(act, vtk.vtkActor):
                printvtkactor(act, tab="     ")

    elif hasattr(obj, "interactor"):  # dumps Plotter info
        axtype = {
            0: "(no axes)",
            1: "(three gray grid walls)",
            2: "(cartesian axes from origin",
            3: "(positive range of cartesian axes from origin",
            4: "(axes triad at bottom left)",
            5: "(oriented cube at bottom left)",
            6: "(mark the corners of the bounding box)",
            7: "(ruler at the bottom of the window)",
            8: "(the vtkCubeAxesActor object)",
            9: "(the bounding box outline)",
        }
        bns, totpt = [], 0
        for a in obj.actors:
            b = a.GetBounds()
            if a.GetBounds() is not None:
                if isinstance(a, vtk.vtkActor):
                    totpt += a.GetMapper().GetInput().GetNumberOfPoints()
                bns.append(b)
        if len(bns) == 0:
            return
        acts = obj.getActors()
        colors.printc("_" * 60, c="c", bold=0)
        colors.printc("Plotter", invert=1, dim=1, c="c", end=" ")
        otit = obj.title
        if not otit:
            otit = None
        colors.printc("   title:", otit, bold=0, c="c")
        colors.printc(" active renderer:",
                      obj.renderers.index(obj.renderer),
                      bold=0,
                      c="c")
        colors.printc("   nr. of actors:", len(acts), bold=0, c="c", end="")
        colors.printc(" (" + str(totpt), "vertices)", bold=0, c="c")
        max_bns = np.max(bns, axis=0)
        min_bns = np.min(bns, axis=0)
        colors.printc("      max bounds: ", c="c", bold=0, end="")
        bx1, bx2 = precision(min_bns[0], 3), precision(max_bns[1], 3)
        colors.printc("x=(" + bx1 + ", " + bx2 + ")", c="c", bold=0, end="")
        by1, by2 = precision(min_bns[2], 3), precision(max_bns[3], 3)
        colors.printc(" y=(" + by1 + ", " + by2 + ")", c="c", bold=0, end="")
        bz1, bz2 = precision(min_bns[4], 3), precision(max_bns[5], 3)
        colors.printc(" z=(" + bz1 + ", " + bz2 + ")", c="c", bold=0)
        colors.printc("       axes type:",
                      obj.axes,
                      axtype[obj.axes],
                      bold=0,
                      c="c")

        for a in obj.actors:
            if a.GetBounds() is not None:
                if isinstance(a, vtk.vtkVolume):  # dumps Volume info
                    img = a.GetMapper().GetDataSetInput()
                    colors.printc('_' * 60, c='b', bold=0)
                    colors.printc('Volume', invert=1, dim=1, c='b')
                    colors.printc('      scalar range:',
                                  np.round(img.GetScalarRange(), 4),
                                  c='b',
                                  bold=0)
                    bnds = a.GetBounds()
                    colors.printc("            bounds: ",
                                  c="b",
                                  bold=0,
                                  end="")
                    bx1, bx2 = precision(bnds[0], 3), precision(bnds[1], 3)
                    colors.printc("x=(" + bx1 + ", " + bx2 + ")",
                                  c="b",
                                  bold=0,
                                  end="")
                    by1, by2 = precision(bnds[2], 3), precision(bnds[3], 3)
                    colors.printc(" y=(" + by1 + ", " + by2 + ")",
                                  c="b",
                                  bold=0,
                                  end="")
                    bz1, bz2 = precision(bnds[4], 3), precision(bnds[5], 3)
                    colors.printc(" z=(" + bz1 + ", " + bz2 + ")",
                                  c="b",
                                  bold=0)

        colors.printc(" Click actor and press i for Actor info.", c="c")

    else:
        colors.printc("_" * 60, c="g", bold=0)
        colors.printc(obj, c="g")
        colors.printc(type(obj), c="g", invert=1)