Exemple #1
0
    def render_ground(self):
        self.ren.RemoveActor(self.ground_actor)
        if not self.config["GROUND"][0]:
            return
        ## Read the image
        png_reader = vtk.vtkPNGReader()
        png_reader.SetFileName(self.base_dir + self.data_folders["GROUND"])
        png_reader.Update()

        plane = vtk.vtkPlaneSource()
        plane.SetXResolution(500)
        plane.SetYResolution(500)
        plane.SetOrigin(0, 0, 0)
        plane.SetPoint1(1921, 0, 0)
        plane.SetPoint2(0, 2003.98, 0)

        atext = vtk.vtkTexture()
        atext.SetInputConnection(png_reader.GetOutputPort())
        atext.InterpolateOn()

        texturePlane = vtk.vtkTextureMapToPlane()
        texturePlane.SetInputConnection(plane.GetOutputPort())

        planeMapper = vtk.vtkPolyDataMapper()
        planeMapper.SetInputConnection(texturePlane.GetOutputPort())

        ## Position the primitives
        actor = vtk.vtkActor()
        actor.SetMapper(planeMapper)
        actor.SetTexture(atext)
        self.ground_actor = actor
        self.ren.AddActor(actor)
Exemple #2
0
def loadMesh(path, scale):
    # Read in STL
    meshPath = cleanResourcePath(path)
    extension = os.path.splitext(path)[1]
    if extension == ".stl" or extension == ".STL":
        meshInput = vtk.vtkSTLReader()
        meshInput.SetFileName(path)
        meshReader = vtk.vtkTextureMapToPlane()
        meshReader.SetInputConnection(meshInput.GetOutputPort())
    elif extension == ".obj" or extension == ".OBJ":
        meshReader = vtk.vtkOBJReader()
        meshReader.SetFileName(path)
    else:
        ROS_FATAL("Mesh file has invalid extension (" + extension + ")")

    # Scale STL
    transform = vtk.vtkTransform()
    transform.Scale(scale, scale, scale)
    # transform.RotateWXYZ(rot[1], rot[2], rot[3], rot[0])
    # transform.Translate(pos[0],pos[1], pos[2])
    transformFilter = vtk.vtkTransformFilter()
    transformFilter.SetTransform(transform)
    transformFilter.SetInputConnection(meshReader.GetOutputPort())
    transformFilter.Update()
    return transformFilter.GetOutput()
Exemple #3
0
 def TextureMapToPlane(self, currentElement):
     tmapper = vtk.vtkTextureMapToPlane()
     # Datatype(s) I need for input:  Algorithm
     AlgorithmElement = ''
     for childElement in currentElement.getchildren():
         if childElement.tag in vtkTypes['Algorithm']:
             AlgorithmElement = childElement
     if AlgorithmElement != '':
         dataset = self.namesToFunctions[AlgorithmElement.tag](AlgorithmElement)
         try:
             tmapper.SetInputConnection(dataset.GetOutputPort())
         except:
             self.logger.error('  .. <TextureMapToPlane> failed to SetInputConnection')
     else:
         self.logger.error('  .. <TextureMapToPlane> needs an Algorithm-type childElement')
     if 'SetOrigin' in currentElement.keys():
         try:
             tmapper.SetOrigin( coordsFromString(currentElement.get('SetOrigin')) )
         except:
             self.logger.error('  .. <TextureMapToPlane> failed to SetOrigin')
     if 'SetPoint1' in currentElement.keys():
         try:
             tmapper.SetPoint1( coordsFromString(currentElement.get('SetPoint1')) )
         except:
             self.logger.error('  .. <TextureMapToPlane> failed to SetPoint1')
     if 'SetPoint2' in currentElement.keys():
         try:
             tmapper.SetPoint2( coordsFromString(currentElement.get('SetPoint2')) )
         except:
             self.logger.error('  .. <TextureMapToPlane> failed to SetPoint2')
     return tmapper
Exemple #4
0
def insert_plane():
    img = 'floor.jpg'
    cube_source = vtk.vtkCubeSource()

    cube_source.SetCenter(0.49, 10, 10)
    cube_source.SetXLength(0.0010)
    cube_source.SetYLength(20)
    cube_source.SetZLength(20)
    cube_source.Update()

    reader = vtk.vtkJPEGReader()
    reader.SetFileName(img)

    # Create texture object
    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())

    # Map texture coordinates
    map_to_plane = vtk.vtkTextureMapToPlane()
    map_to_plane.SetInputConnection(cube_source.GetOutputPort())

    # Create mapper and set the mapped texture as input
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(map_to_plane.GetOutputPort())

    # Create actor and set the mapper and the texture . uncomment if no texture

    #  mapper = vtk.vtkPolyDataMapper()
    # mapper.SetInputConnection(cube_source.GetOutputPort())
    mapper.Update()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)
    return actor
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkTextureMapToPlane(), 'Processing.',
         ('vtkDataSet',), ('vtkDataSet',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemple #6
0
    def addCube(self,pos,tam,img=False):
        jpegfile = "struct.jpg"
        
        # Read the image data from a file
        reader = vtk.vtkJPEGReader()
        reader.SetFileName(jpegfile)
         
        (x,y,z) = pos
        (i,j,k) = tam

        cubito = vtk.vtkCubeSource()
        cubito.SetXLength(0.2*i)
        cubito.SetYLength(0.2*j)
        cubito.SetZLength(0.2*k)
        cubito.SetCenter((x,y,z)) 
        if img == True:
            
            # Create texture object
            texture = vtk.vtkTexture()
            if vtk.VTK_MAJOR_VERSION <= 5:
                texture.SetInput(reader.GetOutput())
            else:
                texture.SetInputConnection(reader.GetOutputPort())
            # Map texture coordinates
            map_to_sphere = vtk.vtkTextureMapToPlane()
            if vtk.VTK_MAJOR_VERSION <= 5:
                map_to_sphere.SetInput(cubito.GetOutput())
            else:
                map_to_sphere.SetInputConnection(cubito.GetOutputPort())
            #map_to_sphere.PreventSeamOn()
             
            # Create mapper and set the mapped texture as input
            mapper = vtk.vtkPolyDataMapper()
            if vtk.VTK_MAJOR_VERSION <= 5:
                mapper.SetInput(map_to_sphere.GetOutput())
            else:
                mapper.SetInputConnection(map_to_sphere.GetOutputPort())
            
        

        planeMapper = vtk.vtkPolyDataMapper()
        planeMapper.SetInputConnection(cubito.GetOutputPort())
        planeActor = (vtk.vtkActor())
        if (img == True):
            planeActor.SetMapper(mapper)
        else:
            planeActor.SetMapper(planeMapper)# mapper planeMapper
        planeActor.DragableOn()
        planeActor.SetDragable(1)
        if (img== True):
            planeActor.SetTexture(texture)
        else:
            planeActor.GetProperty().SetColor(.0,.3,.6)
            planeActor.GetProperty().SetOpacity(0.95)
        #planeActor.GetProperty().SetAmbient(0)
        #planeActor.GetProperty().SetDiffuse(0.9)
        #planeActor.GetProperty().SetSpecular(0.1)
        self.render.AddActor(planeActor)
        
        return planeActor
Exemple #7
0
def add_textures(output, textures, elname):
    """Add textures to a pyvista data object"""
    if not pyvista.is_pyvista_obj(output):
        output = pyvista.wrap(output)

    for i, tex in enumerate(textures):
        # Now map the coordinates for the texture
        m = vtk.vtkTextureMapToPlane()
        m.SetInputDataObject(output)
        m.SetOrigin(tex.origin)
        m.SetPoint1(tex.origin + tex.axis_u)
        m.SetPoint2(tex.origin + tex.axis_v)
        m.Update()
        # Grab the texture coordinates
        tmp = m.GetOutputDataObject(0)
        tcoord = tmp.GetPointData().GetTCoords()
        name = tex.name
        if name is None or name == '':
            name = '{}-texture-{}'.format(elname, i)
        tcoord.SetName(name)
        # Add these coordinates to the PointData of the output
        # NOTE: Let pyvista handle setting the TCoords because of how VTK cleans
        #       up old TCoords
        output.GetPointData().AddArray(tcoord)
        # Add the vtkTexture to the output
        img = np.array(Image.open(tex.image))
        tex.image.seek(0)  # Reset the image bytes in case it is accessed again
        if img.shape[2] > 3:
            img = img[:, :, 0:3]
        vtexture = pyvista.numpy_to_texture(img)
        output.textures[name] = vtexture
        output._activate_texture(name)

    return output
Exemple #8
0
 def __init__(self):
     # ODE initialization
     self.world = ode.World()
     self.world.setGravity(GRAVITY)
     self.world.setERP(ERP)
     self.world.setCFM(CFM)
     self.space = ode.Space()
     self.floor = ode.GeomPlane(self.space, (0.0,1.0,0.0), 0.0)
     self.jointGroup = ode.JointGroup()
     self.time = 0.0
     # VTK initialization
     self.renderer = vtk.vtkRenderer()
     self.renderer.SetBackground(102.0/255.0,204/255.0,1.0)
     self.window = vtk.vtkRenderWindow()
     self.window.SetSize(WINDOW_WIDTH,WINDOW_HEIGHT)
     self.window.AddRenderer(self.renderer)
     self.interactor = vtk.vtkRenderWindowInteractor()
     self.interactor.SetRenderWindow(self.window)
     self.axes = vtk.vtkAxesActor()
     self.axes.SetAxisLabels(0)
     transform = vtk.vtkTransform()
     transform.Scale(0.1,0.1,0.1)
     self.axes.SetUserTransform(transform)
     self.renderer.AddActor(self.axes)
     # Create ground plane visualization
     self.floorVisual = vtk.vtkPlaneSource()
     self.floorVisual.SetNormal((0.0,1.0,0.0))
     self.floorVisual.SetResolution(10,10)
     self.floorReader = vtk.vtkJPEGReader()
     self.floorReader.SetFileName(FLOOR_IMAGE)
     self.floorTexture = vtk.vtkTexture()
     transform = vtk.vtkTransform()
     transform.Scale(50.0,50.0,50.0)
     self.floorTexture.SetTransform(transform)
     self.floorTexture.SetInput(self.floorReader.GetOutput())
     self.floorMap = vtk.vtkTextureMapToPlane()
     self.floorMap.SetInput(self.floorVisual.GetOutput())
     self.floorMapper = vtk.vtkPolyDataMapper()
     self.floorMapper.SetInput(self.floorMap.GetOutput())
     self.floorActor = vtk.vtkActor()
     transform = vtk.vtkTransform()
     transform.Scale(100.0,100.0,100.0)
     self.floorActor.SetUserTransform(transform)
     self.floorActor.SetMapper(self.floorMapper)
     self.floorActor.SetTexture(self.floorTexture)
     self.renderer.AddActor(self.floorActor)
     # VTK camera setup
     self.camera = vtk.vtkCamera()
     self.renderer.SetActiveCamera(self.camera)
     self.cameraFocus = [0.0, 0.0, 0.0]
     self.cameraPos = [4.0, 2.5, 1.5]
     self.cameraOffset = [0.0,1.0,3.0]
     self.cameraRoll = 0.0
     # Keep track of the simulated bodies and robots
     self.bodies = []
     self.robots = []
     self.controllers = []
Exemple #9
0
def pointer(x, y, z, radius):
    # cast the positions to text so they can be added as labels
    labelX = str(x)
    labelY = str(y)
    labelZ = str(z)

    # Create sphere
    sphere_source = vtk.vtkSphereSource()
    sphere_source.SetCenter(x, y, z)
    sphere_source.SetRadius(radius)
    sphere_source.Update()

    # Create the caption to show the sphere position
    caption = vtk.vtkCaptionActor2D()
    caption.SetCaption("(" + labelX + ", " + labelY + ", " + labelZ + ")")

    # Set the size of the caption box. The box is measured from the lower left corner to the upper right corner.
    # SetWidth and SetHeight are defined as fraction of the viewport.  So SetWidth(0.1) sets the caption box
    # to 10% the width of the viewport.
    # The caption text will then fill the provided caption box as best possible
    caption.SetWidth(0.15)
    caption.SetHeight(0.02)

    caption.GetProperty().SetColor(colours['captionColour'])
    caption.SetAttachmentPoint(sphere_source.GetCenter())

    # Formatting of the text possible with vtkTextProperty
    # Disable the border box for the caption
    caption.BorderOff()

    # Map texture coordinates of the cube_source
    map_to_plane = vtk.vtkTextureMapToPlane()
    map_to_plane.SetInputConnection(sphere_source.GetOutputPort())

    # Create polydatamapper and set the mapped texture as input
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(map_to_plane.GetOutputPort())
    # Create actor and set the mapper and the texture . uncomment if no texture
    #  mapper = vtk.vtkPolyDataMapper()
    # mapper.SetInputConnection(cube_source.GetOutputPort())
    mapper.Update()

    # create the sphere actor with the mapper
    sphere = vtk.vtkActor()
    sphere.SetMapper(mapper)
    sphere.GetProperty().SetColor(colours['pointer'])

    # Assemble the cube and annotations into a complete prop actor.
    pointer = vtk.vtkPropAssembly()
    pointer.AddPart(sphere)
    pointer.AddPart(caption)

    # actor.SetTexture(texture)

    return pointer
Exemple #10
0
    def texture_map_to_plane(dataset, origin=None, point_u=None, point_v=None,
                             inplace=False, name='Texture Coordinates'):
        """Texture map this dataset to a user defined plane. This is often used
        to define a plane to texture map an image to this dataset. The plane
        defines the spatial reference and extent of that image.

        Parameters
        ----------
        origin : tuple(float)
            Length 3 iterable of floats defining the XYZ coordinates of the
            BOTTOM LEFT CORNER of the plane

        point_u : tuple(float)
            Length 3 iterable of floats defining the XYZ coordinates of the
            BOTTOM RIGHT CORNER of the plane

        point_v : tuple(float)
            Length 3 iterable of floats defining the XYZ coordinates of the
            TOP LEFT CORNER of the plane

        inplace : bool, optional
            If True, the new texture coordinates will be added to the dataset
            inplace. If False (default), a new dataset is returned with the
            textures coordinates

        name : str, optional
            The string name to give the new texture coordinates if applying
            the filter inplace.

        """
        alg = vtk.vtkTextureMapToPlane()
        if origin is None or point_u is None or point_v is None:
            alg.SetAutomaticPlaneGeneration(True)
        else:
            alg.SetOrigin(origin) # BOTTOM LEFT CORNER
            alg.SetPoint1(point_u) # BOTTOM RIGHT CORNER
            alg.SetPoint2(point_v) # TOP LEFT CORNER
        alg.SetInputDataObject(dataset)
        alg.Update()
        output = _get_output(alg)
        if not inplace:
            return output
        t_coords = output.GetPointData().GetTCoords()
        t_coords.SetName(name)
        otc = dataset.GetPointData().GetTCoords()
        dataset.GetPointData().SetTCoords(t_coords)
        dataset.GetPointData().AddArray(t_coords)
        # CRITICAL:
        dataset.GetPointData().AddArray(otc) # Add old ones back at the end
        return # No return type because it is inplace
Exemple #11
0
def floor():
    plane = vtk.vtkPlaneSource()
    reader = vtk.vtkJPEGReader()
    reader.SetFileName(pkg_resources.resource_filename("robopy", "media/imgs/floor.jpg"))
    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())
    map_to_plane = vtk.vtkTextureMapToPlane()
    map_to_plane.SetInputConnection(plane.GetOutputPort())
    mapper = vtk.vtkPolyDataMapper()

    mapper.SetInputConnection(map_to_plane.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)
    return actor
Exemple #12
0
def floor():
    plane = vtk.vtkPlaneSource()
    reader = vtk.vtkJPEGReader()
    reader.SetFileName(
        pkg_resources.resource_filename(
            __name__, '/'.join(('media', 'imgs', 'floor.jpg'))))
    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())
    map_to_plane = vtk.vtkTextureMapToPlane()
    map_to_plane.SetInputConnection(plane.GetOutputPort())
    mapper = vtk.vtkPolyDataMapper()

    mapper.SetInputConnection(map_to_plane.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)
    return actor
Exemple #13
0
def surface_to_vtk(surfel):
    """Convert the surface to a its appropriate VTK data object type.

    Args:
        surfel (:class:`omf.surface.SurfaceElement`): the surface element to
            convert
    """

    output = surface_geom_to_vtk(surfel.geometry)

    # Now add point data:
    for data in surfel.data:
        arr = data.array.array
        c = nps.numpy_to_vtk(num_array=arr)
        c.SetName(data.name)
        output.GetPointData().AddArray(c)

    output = vtki.wrap(output)
    for i, tex in enumerate(surfel.textures):
        # Now map the coordinates for the texture
        m = vtk.vtkTextureMapToPlane()
        m.SetInputDataObject(output)
        m.SetOrigin(tex.origin)
        m.SetPoint1(tex.origin + tex.axis_u)
        m.SetPoint2(tex.origin + tex.axis_v)
        m.Update()
        # Grab the texture coordinates
        tmp = m.GetOutputDataObject(0)
        tcoord = tmp.GetPointData().GetTCoords()
        name = tex.name
        if name is None or name == '':
            name = '{}-texture-{}'.format(surfel.name, i)
        tcoord.SetName(name)
        # Add these coordinates to the PointData of the output
        # NOTE: Let vtki handle setting the TCoords because of how VTK cleans
        #       up old TCoords
        output.GetPointData().AddArray(tcoord)
        # Add the vtkTexture to the output
        img = np.array(Image.open(tex.image))
        tex.image.seek(0)  # Reset the image bytes in case it is accessed again
        if img.shape[2] > 3:
            img = img[:, :, 0:3]
        vtexture = vtki.numpy_to_texture(img)
        output.textures[name] = vtexture

    return output
Exemple #14
0
def assignTexture(actor, name, scale=1, falsecolors=False, mapTo=1):
    '''Assign a texture to actor from file or name in /textures directory'''
    if mapTo == 1: tmapper = vtk.vtkTextureMapToCylinder()
    elif mapTo == 2: tmapper = vtk.vtkTextureMapToSphere()
    elif mapTo == 3: tmapper = vtk.vtkTextureMapToPlane()

    setInput(tmapper, polydata(actor))
    if mapTo == 1: tmapper.PreventSeamOn()

    xform = vtk.vtkTransformTextureCoords()
    xform.SetInputConnection(tmapper.GetOutputPort())
    xform.SetScale(scale, scale, scale)
    if mapTo == 1: xform.FlipSOn()
    xform.Update()

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(xform.GetOutputPort())
    mapper.ScalarVisibilityOff()

    cdir = os.path.dirname(__file__)
    if cdir == '': cdir = '.'
    fn = cdir + '/textures/' + name + ".jpg"
    if os.path.exists(name):
        fn = name
    elif not os.path.exists(fn):
        colors.printc(('Texture', name, 'not found in', cdir + '/textures'),
                      'r')
        colors.printc('Available textures:', c='m', end=' ')
        for ff in os.listdir(cdir + '/textures'):
            colors.printc(ff.split('.')[0], end=' ', c='m')
        print()
        return

    jpgReader = vtk.vtkJPEGReader()
    jpgReader.SetFileName(fn)
    atext = vtk.vtkTexture()
    atext.RepeatOn()
    atext.EdgeClampOff()
    atext.InterpolateOn()
    if falsecolors: atext.MapColorScalarsThroughLookupTableOn()
    atext.SetInputConnection(jpgReader.GetOutputPort())
    actor.GetProperty().SetColor(1, 1, 1)
    actor.SetMapper(mapper)
    actor.SetTexture(atext)
Exemple #15
0
    def __init__(self):

        self.sceneSources = list()
        self.sceneMappers = list()
        self.sceneActors = list()
        self.sceneLights = list()

        self.sceneSources.append(vtk.vtkCubeSource())
        self.sceneSources[-1].SetXLength(10000)
        self.sceneSources[-1].SetYLength(10000)
        self.sceneSources[-1].SetZLength(5)

        # self.sceneMappers.append(vtk.vtkPolyDataMapper())
        # self.sceneMappers[-1].SetInputConnection(self.sceneSources[-1].GetOutputPort())

        reader = vtk.vtkJPEGReader()
        reader.SetFileName("blackandwhite.jpg")
        #reader.SetFileName("white.jpg")

        # Create texture object
        texture = vtk.vtkTexture()
        texture.SetInputConnection(reader.GetOutputPort())
        texture.RepeatOn()

        #Map texture coordinates
        map_to_plane = vtk.vtkTextureMapToPlane()
        map_to_plane.SetInputConnection(self.sceneSources[-1].GetOutputPort())

        # Create mapper and set the mapped texture as input
        mapperplane = vtk.vtkPolyDataMapper()
        mapperplane.SetInputConnection(map_to_plane.GetOutputPort())

        self.sceneActors.append(vtk.vtkActor())
        self.sceneActors[-1].RotateX(90)
        self.sceneActors[-1].SetPosition(0, -800, 0)
        self.sceneActors[-1].SetMapper(mapperplane)
        self.sceneActors[-1].SetTexture(texture)
        # self.sceneActors[-1].GetProperty().SetColor(1,1,1)

        self.addLight(1.0, 1.0, 1.0, 1000, 1000, -1000, 0.75, 180, 0.75)
        self.addLight(1.0, 1.0, 1.0, -1000, 500, 1000, 0.5, 180, 0.0)
        self.addLight(1.0, 1.0, 1.0, -1000, 500, -1000, 0.5, 180, 0.0)
Exemple #16
0
def create_textured_plane(**kwargs):
    """
    create a plane with correct size and texture it with a map
    """
    image_reader = vtk.vtkPNGReader()
    image_reader.SetFileName(kwargs['map'])

    plane = vtk.vtkPlaneSource()
    size = kwargs['size']
    z_level = 0.0
    plane.SetOrigin(-0.5 * size[0], -0.5 * size[1], z_level)
    plane.SetPoint1(+0.5 * size[0], -0.5 * size[1], z_level)
    plane.SetPoint2(-0.5 * size[0], +0.5 * size[1], z_level)

    texture = vtk.vtkTexture()
    texture.SetInputConnection(image_reader.GetOutputPort())

    texture_plane = vtk.vtkTextureMapToPlane()
    texture_plane.SetInputConnection(plane.GetOutputPort())
    return texture_plane, texture
Exemple #17
0
def create_textured_plane(**kwargs):
    """
    create a plane with correct size and texture it with a map
    """
    image_reader = vtk.vtkPNGReader()
    image_reader.SetFileName(kwargs['map'])

    plane = vtk.vtkPlaneSource()
    size = kwargs['size']
    z_level = 0.0
    plane.SetOrigin(-0.5*size[0], -0.5*size[1], z_level)
    plane.SetPoint1(+0.5*size[0], -0.5*size[1], z_level)
    plane.SetPoint2(-0.5*size[0], +0.5*size[1], z_level)

    texture = vtk.vtkTexture()
    texture.SetInputConnection(image_reader.GetOutputPort())

    texture_plane = vtk.vtkTextureMapToPlane()
    texture_plane.SetInputConnection(plane.GetOutputPort())
    return texture_plane, texture
    def createActor(self):
        
        reader = vtk.vtkJPEGReader()
        reader.SetFileName("ice.jpg")

        # Create texture object
        texture = vtk.vtkTexture()
        texture.SetInputConnection(reader.GetOutputPort())

        #Map texture coordinates
        map_to_plane = vtk.vtkTextureMapToPlane()
        map_to_plane.SetInputConnection(self.source2.GetOutputPort())
        self.floor_actor.SetMapper(self.floor_mapper)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(map_to_plane.GetOutputPort())
        #self.floor_actor.GetProperty().SetColor(0, 1, 0.0)
        self.floor_actor.SetMapper(mapper)
        self.floor_actor.SetTexture(texture)
        self.floor_actor.GetProperty().SetOpacity(0.8)
        self.floor_actor.SetPosition(self.pos[0], self.pos[1], self.pos[2])
Exemple #19
0
    def _createOrthoPipelineForNewIPW(self, ipw):
        """This will create and append all the necessary constructs for a
        single new layer (ipw) to the self._orthoPipeline.

        Make sure you only call this method if the orthoView exists!
        After having done this, you still need to call _syncOrthoView() or
        _resetOrthoView() if you've added a new primary.
        """

        _ps = vtk.vtkPlaneSource()
        _pa = vtk.vtkActor()
        _tm2p = vtk.vtkTextureMapToPlane()
        self._orthoPipeline.append({
            'planeSource': _ps,
            'planeActor': _pa,
            'textureMapToPlane': _tm2p
        })

        _tm2p.AutomaticPlaneGenerationOff()
        _tm2p.SetInput(_ps.GetOutput())
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(_tm2p.GetOutput())
        _pa.SetMapper(mapper)

        otherTexture = ipw.GetTexture()

        # we don't just use the texture, else VTK goes mad re-uploading
        # the same texture unnecessarily... let's just make use of the
        # same input, we get much more effective use of the
        # host->GPU bus
        texture = vtk.vtkTexture()
        texture.SetInterpolate(otherTexture.GetInterpolate())
        texture.SetQuality(otherTexture.GetQuality())
        texture.MapColorScalarsThroughLookupTableOff()
        texture.RepeatOff()
        texture.SetInput(otherTexture.GetInput())

        _pa.SetTexture(texture)

        self._renderer.AddActor(_pa)
Exemple #20
0
    def _createOrthoPipelineForNewIPW(self, ipw):
        """This will create and append all the necessary constructs for a
        single new layer (ipw) to the self._orthoPipeline.

        Make sure you only call this method if the orthoView exists!
        After having done this, you still need to call _syncOrthoView() or
        _resetOrthoView() if you've added a new primary.
        """

        _ps = vtk.vtkPlaneSource()
        _pa = vtk.vtkActor()
        _tm2p = vtk.vtkTextureMapToPlane()
        self._orthoPipeline.append(
            {'planeSource' : _ps,
             'planeActor' : _pa,
             'textureMapToPlane': _tm2p})

        _tm2p.AutomaticPlaneGenerationOff()
        _tm2p.SetInput(_ps.GetOutput())
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(_tm2p.GetOutput())
        _pa.SetMapper(mapper)

        otherTexture = ipw.GetTexture()

        # we don't just use the texture, else VTK goes mad re-uploading
        # the same texture unnecessarily... let's just make use of the
        # same input, we get much more effective use of the
        # host->GPU bus
        texture = vtk.vtkTexture()
        texture.SetInterpolate(otherTexture.GetInterpolate())
        texture.SetQuality(otherTexture.GetQuality())
        texture.MapColorScalarsThroughLookupTableOff()
        texture.RepeatOff()
        texture.SetInput(otherTexture.GetInput())

        _pa.SetTexture(texture)

        self._renderer.AddActor(_pa)
Exemple #21
0
def make_patterned_polydata(inputContours,
                            fillareastyle=None,
                            fillareaindex=None,
                            fillareacolors=None,
                            fillareaopacity=None,
                            size=None):
    if inputContours is None or fillareastyle == 'solid':
        return None
    if inputContours.GetNumberOfCells() == 0:
        return None
    if fillareaindex is None:
        fillareaindex = 1
    if fillareaopacity is None:
        fillareaopacity = 100
    num_pixels = num_pixels_for_size(size)

    # Create the plane that will be textured with the pattern
    # The bounds of the plane match the bounds of the input polydata
    bounds = inputContours.GetBounds()

    patternPlane = vtk.vtkPlaneSource()
    patternPlane.SetOrigin(bounds[0], bounds[2], 0.0)
    patternPlane.SetPoint1(bounds[0], bounds[3], 0.0)
    patternPlane.SetPoint2(bounds[1], bounds[2], 0.0)
    # Generate texture coordinates for the plane
    textureMap = vtk.vtkTextureMapToPlane()
    textureMap.SetInputConnection(patternPlane.GetOutputPort())

    # Create the pattern image of the size of the input polydata
    # and type defined by fillareaindex
    xBounds = bounds[1] - bounds[0]
    yBounds = bounds[3] - bounds[2]

    if xBounds <= 1 and yBounds <= 1 and size is not None:
        xBounds *= size[0]
        yBounds *= size[1]
        xres, yres = int(xBounds), int(yBounds)

    xres = int(4.0 * xBounds)
    yres = int(4.0 * yBounds)

    # Handle the case when the bounds are less than 1 in physical dimensions

    patternImage = create_pattern(xres, yres, num_pixels, fillareastyle,
                                  fillareaindex, fillareacolors,
                                  fillareaopacity)
    if patternImage is None:
        return None

    # Extrude the contour since vtkPolyDataToImageStencil
    # requires 3D polydata
    extruder = vtk.vtkLinearExtrusionFilter()
    extruder.SetInputData(inputContours)
    extruder.SetScaleFactor(1.0)
    extruder.SetVector(0, 0, 1)
    extruder.SetExtrusionTypeToNormalExtrusion()

    # Create a binary image mask from the extruded polydata
    pol2stenc = vtk.vtkPolyDataToImageStencil()
    pol2stenc.SetTolerance(0)
    pol2stenc.SetInputConnection(extruder.GetOutputPort())
    pol2stenc.SetOutputOrigin(bounds[0], bounds[2], 0.0)
    pol2stenc.SetOutputSpacing((bounds[1] - bounds[0]) / xres,
                               (bounds[3] - bounds[2]) / yres, 0.0)
    pol2stenc.SetOutputWholeExtent(patternImage.GetExtent())

    # Stencil out the fillarea from the pattern image
    stenc = vtk.vtkImageStencil()
    stenc.SetInputData(patternImage)
    stenc.SetStencilConnection(pol2stenc.GetOutputPort())
    stenc.ReverseStencilOff()
    stenc.SetBackgroundColor(0, 0, 0, 0)
    stenc.Update()
    patternImage = stenc.GetOutput()

    # Create the texture using the stenciled pattern
    patternTexture = vtk.vtkTexture()
    patternTexture.SetInputData(patternImage)
    patternTexture.InterpolateOn()
    patternTexture.RepeatOn()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(textureMap.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(patternTexture)
    return actor
Exemple #22
0
    def __init__(self, parent = None):
        QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.date = 0
        
        self.default_infections_checked = True
        self.default_recovered_checked = True
        self.default_deaths_checked = True

        self.initial_date = date(2020, 1, 22) + timedelta(self.date)
        self.ui.setupUi(self)

        self.max_radius = 40

        self.infections_color = (1, 0, 0)
        self.recovered_color = (0, 1, 0)
        self.deaths_color = (0, 0, 0)

        self.infections_opacity = 0.9
        self.recovered_opacity = 0.75
        self.deaths_opacity = 0.5
        
        sat_path = sys.argv[1]
        global_infections_path = sys.argv[2]
        global_deaths_path = sys.argv[3]
        global_recovered_path = sys.argv[4]

        self.infections_data = []
        self.deaths_data = []
        self.recovered_data = []

        self.legend_circle_actors = []
        self.legend_text_actors = []

        # Read in data for global confirmed cases
        with open(global_infections_path) as csvDataFile:
            csv_reader = csv.reader(csvDataFile)
            for row in csv_reader:
                # We do not need country/province name, so we remove the first two columns
                if(row[2] != 0 or row[3] != 0):
                    self.infections_data.append(row[2:])
        self.infections_data = self.infections_data[1:]

        # Read in data for global deaths
        with open(global_deaths_path) as csvDataFile:
            csv_reader = csv.reader(csvDataFile)
            for row in csv_reader:
                if(row[2] != 0 or row[3] != 0):
                    self.deaths_data.append(row[2:])
        self.deaths_data = self.deaths_data[1:]

        # Read in data for global recovered cases
        with open(global_recovered_path) as csvDataFile:
            csv_reader = csv.reader(csvDataFile)
            for row in csv_reader:
                if(row[2] != 0 or row[3] != 0):    
                    self.recovered_data.append(row[2:])
        self.recovered_data = self.recovered_data[1:]

        self.numDates = len(self.infections_data[0]) - 3
        self.max_cases = self.compute_max(self.date)
        
        # Read in satellite image and determine size of the image
        sat_reader = vtk.vtkJPEGReader()
        sat_reader.SetFileName(sat_path)
        sat_reader.Update()
        sat_dimensions = sat_reader.GetOutput().GetDimensions()
        self.sat_x = sat_dimensions[0]
        self.sat_y = sat_dimensions[1]
        
        # Create a plane to map the satellite image onto
        plane = vtk.vtkPlaneSource()
        plane.SetCenter(0.0, 0.0, 0.0)
        plane.SetNormal(0.0, 0.0, 1.0)
        plane.SetPoint1(self.sat_x, 0, 0)
        plane.SetPoint2(0, self.sat_y, 0)
        
        # Create satellite image texture
        texture = vtk.vtkTexture()
        texture.SetInputConnection(sat_reader.GetOutputPort())

        # Map satellite texture to plane
        texturePlane = vtk.vtkTextureMapToPlane()
        texturePlane.SetInputConnection(plane.GetOutputPort())

        # Create mapper
        sat_mapper = vtk.vtkPolyDataMapper()
        sat_mapper.SetInputConnection(texturePlane.GetOutputPort())

        # Create actor
        sat_actor = vtk.vtkActor()
        sat_actor.SetMapper(sat_mapper)
        sat_actor.SetTexture(texture)
        sat_actor.GetProperty().SetOpacity(0.6)

        # Initialize renderer
        self.ren = vtk.vtkRenderer()

        # Add legend actors
        self.add_legend_actors()

        # Add infections actors for the initial date
        self.infections_actors = []
        if(self.ui.infections_check.isChecked()):
            self.add_case_actors(self.infections_data, self.infections_actors, self.infections_color, self.infections_opacity)

        # Add recoveries actors for the initial date
        self.recovered_actors = []
        if(self.ui.recovered_check.isChecked()):
            self.add_case_actors(self.recovered_data, self.recovered_actors, self.recovered_color, self.recovered_opacity)

        # Add death actors for the initial date
        self.deaths_actors = []
        if(self.ui.deaths_check.isChecked()):
            self.add_case_actors(self.deaths_data, self.deaths_actors, self.deaths_color, self.deaths_opacity)
        
        self.ren.AddActor(sat_actor)
        self.ren.ResetCamera()
        self.ren.GetActiveCamera().Zoom(2)
        self.ren.SetBackground(0.25, 0.25, 0.25)

        self.ren.ResetCameraClippingRange()

        self.ui.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.ui.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Setting up widgets
        def slider_setup(slider, val, bounds, interv):
            slider.setOrientation(QtCore.Qt.Horizontal)
            slider.setValue(float(val))
            slider.setTracking(False)
            slider.setTickInterval(interv)
            slider.setTickPosition(QSlider.TicksAbove)
            slider.setRange(bounds[0], bounds[1])

        slider_setup(self.ui.slider, self.date, [0, self.numDates], 1)
Exemple #23
0
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)

# create a renderwindowinteractor
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

createReader = vtk.vtkImageReader2Factory()
reader = createReader.CreateImageReader2(heightfile)
reader.SetFileName(heightfile)

geom = vtk.vtkImageDataGeometryFilter()
geom.SetInputConnection(reader.GetOutputPort())

#Compute texture coordinates for the geometry
toplane = vtk.vtkTextureMapToPlane()
toplane.SetInputConnection(geom.GetOutputPort())

#create a reader for the color image
colorreader = createReader.CreateImageReader2(colorfile)
colorreader.SetFileName(colorfile)

#create a texture from the color image
texture = vtk.vtkTexture()
texture.SetInputConnection(colorreader.GetOutputPort())

warp = vtk.vtkWarpScalar()
warp.SetInputConnection(toplane.GetOutputPort())
warp.SetScaleFactor(1.0)

mapper = vtk.vtkPolyDataMapper()
Exemple #24
0
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
aPlane = vtk.vtkPlaneSource()
aPlane.SetCenter(-100,-100,-100)
aPlane.SetOrigin(-100,-100,-100)
aPlane.SetPoint1(-90,-100,-100)
aPlane.SetPoint2(-100,-90,-100)
aPlane.SetNormal(0,-1,1)
imageIn = vtk.vtkPNMReader()
imageIn.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/earth.ppm")
texture = vtk.vtkTexture()
texture.SetInputConnection(imageIn.GetOutputPort())
texturePlane = vtk.vtkTextureMapToPlane()
texturePlane.SetInputConnection(aPlane.GetOutputPort())
texturePlane.AutomaticPlaneGenerationOn()
planeMapper = vtk.vtkPolyDataMapper()
planeMapper.SetInputConnection(texturePlane.GetOutputPort())
texturedPlane = vtk.vtkActor()
texturedPlane.SetMapper(planeMapper)
texturedPlane.SetTexture(texture)
# Add the actors to the renderer, set the background and size
#
ren1.AddActor(texturedPlane)
#ren1 SetBackground 1 1 1
renWin.SetSize(200,200)
renWin.Render()
renWin.Render()
# prevent the tk window from showing up then start the event loop
Exemple #25
0
import vtk

png = vtk.vtkPNGReader()
png.SetFileName("/git/uvcdat/Packages/vcs/Share/uvcdat_texture.png")
T=vtk.vtkTexture()
T.SetInputConnection(png.GetOutputPort())
p=vtk.vtkPlaneSource()
p.SetCenter(0,0,0)
p.SetNormal(0,0,1)

tmp = vtk.vtkTextureMapToPlane()
tmp.SetInputConnection(p.GetOutputPort())

pm = vtk.vtkPolyDataMapper()
pm.SetInputConnection(tmp.GetOutputPort())

ta = vtk.vtkActor()
ta.SetMapper(pm)
ta.SetTexture(T)

r = vtk.vtkRenderer()
r.AddActor(ta)

rw = vtk.vtkRenderWindow()
rw.AddRenderer(r)

rw.Render()

raw_input("PressENTER")

Exemple #26
0
  def plot3d(self, data, date):
    camera = vtk.vtkCamera()
    camera.SetPosition(1,0,0)
    camera.SetFocalPoint(0,0,0)
    camera.Roll(-90) 
    camera.Zoom(0.7) 
    self.renderer = vtk.vtkRenderer()
    self.vtkWidget.GetRenderWindow().AddRenderer(self.renderer)

    plane = vtk.vtkPlaneSource()
    plane.SetCenter(0.0, 0.0, 0.0)
    plane.SetNormal(1.0, 0.0, 0.0)

    reader = vtk.vtkJPEGReader()
    reader.SetFileName("poland_plane.jpg")

    map_to_plane = vtk.vtkTextureMapToPlane()
    map_to_plane.SetInputConnection(plane.GetOutputPort())

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

    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)
    self.renderer.AddActor(actor)
    points = vtk.vtkPoints()
    mat = []
    if (self.option != 5):
        for city,x,y in zip(data["city_name"], data["x"], data["y"]):
            df = self.dataframe_collection[city]
            val = 0
            if self.option == 1:
                val = df["humidity"].mean()
            elif self.option == 3:
                rain_max = df["rain"].max()
                val = (100 / (df["rain"].max() - df["rain"].min())) * (df["rain"].mean() - df["rain"].min())
                if math.isnan(val):
                    val = 0
            if(val != 0):
                cubeActor = vtk_bar((0,x/700-0.72,-y/700+0.72), val/500)
                cubeActor.GetMapper().ScalarVisibilityOff()
                cubeActor.GetProperty().SetColor((0, 0, 255))
                cubeActor.GetProperty().SetInterpolationToFlat()
                scale_transform = vtk.vtkTransform()
                scale_transform.Scale(0.5, 0.5, 0.5)
                cubeActor.SetUserTransform(scale_transform)
                self.renderer.AddActor(cubeActor)
            if self.option == 2:
                source = vtk.vtkSphereSource()
                source.SetCenter(0.1,x/1400-0.36,-y/1400+0.36)
                source.SetRadius(df["clouds"].mean()/1500)
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInputConnection(source.GetOutputPort())
                actor = vtk.vtkActor()
                actor.SetMapper(mapper)
                self.renderer.AddActor(actor)
            if self.option == 4:
                textActor = vtk.vtkTextActor()
                textActor.SetInput ("Hello world")
                textActor.SetPosition2 ( x/1400-0.36, -y/1400+0.36 )
                textActor.GetTextProperty().SetFontSize ( 1 )
                textActor.GetTextProperty().SetColor ( 1.0, 0.0, 0.0 )
                self.renderer.AddActor2D ( textActor )
                points.InsertNextPoint(df["temp"].mean(), x/1400-0.36, -y/1400+0.36)
                mat.append([x/1400-0.36, -y/1400+0.36, df["temp"].mean()])
    
    if self.option == 4:
        mat = np.array(mat)
        plane = vtk.vtkPlaneSource()
        plane.SetCenter(0.0, 0.0, 0.0)
        plane.SetNormal(1.0, 0.0, 0.0)

        inputPolyData = vtk.vtkPolyData()
        inputPolyData.SetPoints(points)
        delaunay = vtk.vtkDelaunay2D()
        delaunay.SetInputData(inputPolyData)
        delaunay.Update()
        outputPolyData = delaunay.GetOutput()
        bounds = [0 for i in range(6)]
        outputPolyData.GetBounds(bounds)
        xMin = bounds[2]
        xMax = bounds[3]
        yMin = bounds[4]
        yMax = bounds[5]

        x = np.linspace(xMin, xMax, 50)
        y = np.linspace(yMin, yMax, 50)
        x, y = np.meshgrid(x,y)
        x, y = x.flatten(), y.flatten()
        z = griddata((mat[:,0], mat[:,1]), mat[:,2], (x,y), method='nearest')
        z = z.flatten()

        plane.SetResolution(49,49)
        plane.SetOrigin([0.1, xMin, yMin])
        plane.SetPoint1([0.1, xMax, yMin])
        plane.SetPoint2([0.1, xMin, yMax])
        plane.Update()

        nPoints = plane.GetOutput().GetNumberOfPoints()
        scalars = vtk.vtkFloatArray()
        scalars.SetNumberOfValues(nPoints)
        for i in range(nPoints):
            scalars.SetValue(i, float(z[i]))
        plane.GetOutput().GetPointData().SetScalars(scalars)

        lookupTable = vtk.vtkLookupTable()
        lookupTable.SetTableRange (np.amin(z), np.amax(z))
        lookupTable.SetHueRange (0.5, 1);
        lookupTable.SetSaturationRange (1, 1);
        lookupTable.SetValueRange (1,1);
        lookupTable.Build()

        colorSeries = vtk.vtkColorSeries()
        colorSeries.SetColorScheme(vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_10)
        lut = vtk.vtkColorTransferFunction()
        lut.SetColorSpaceToHSV()
        nColors = colorSeries.GetNumberOfColors()
        zMin = np.min(z)
        zMax = np.max(z)
        for i in range(0, nColors):
            color = colorSeries.GetColor(i)
            color = [c/255.0 for c in color]
            t = zMin + float(zMax - zMin)/(nColors - 1) * i
            lut.AddRGBPoint(t, color[0], color[1], color[2])
 
        colorbar = vtk.vtkScalarBarActor()
        colorbar.SetMaximumNumberOfColors(400)
        colorbar.SetLookupTable (lut)
        colorbar.SetWidth(0.05)
        colorbar.SetPosition(0.95, 0.1)
        colorbar.SetLabelFormat("%.3g")
        colorbar.VisibilityOn()
        self.renderer.AddActor(colorbar)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(plane.GetOutputPort())
        mapper.ScalarVisibilityOn()
        mapper.SetScalarModeToUsePointData()
        mapper.SetLookupTable(lut)
        mapper.SetColorModeToMapScalars()

        actor = vtk.vtkActor()
        actor.GetProperty().SetOpacity(0.9)
        actor.SetMapper(mapper)
        self.renderer.AddActor(actor)
    self.renderer.SetActiveCamera(camera)
    self.vtkWidget.Initialize()
    self.vtkWidget.Start()
Exemple #27
0
connect.SetOutputUnconnectedValue(0)
connect.AddSeed(lindex(extent,0),lindex(extent,2))
connect.AddSeed(lindex(extent,1),lindex(extent,2))
connect.AddSeed(lindex(extent,1),lindex(extent,3))
connect.AddSeed(lindex(extent,0),lindex(extent,3))
smooth = vtk.vtkImageGaussianSmooth()
smooth.SetDimensionality(2)
smooth.SetStandardDeviation(1,1)
smooth.SetInputConnection(connect.GetOutputPort())
shrink = vtk.vtkImageShrink3D()
shrink.SetInputConnection(smooth.GetOutputPort())
shrink.SetShrinkFactors(2,2,1)
shrink.AveragingOn()
geometry = vtk.vtkImageDataGeometryFilter()
geometry.SetInputConnection(shrink.GetOutputPort())
geometryTexture = vtk.vtkTextureMapToPlane()
geometryTexture.SetInputConnection(geometry.GetOutputPort())
geometryTexture.SetOrigin(0,0,0)
geometryTexture.SetPoint1(expr.expr(globals(), locals(),["padX","-","1"]),0,0)
geometryTexture.SetPoint2(0,expr.expr(globals(), locals(),["padY","-","1"]),0)
geometryPD = vtk.vtkCastToConcrete()
geometryPD.SetInputConnection(geometryTexture.GetOutputPort())
geometryPD.Update()
clip = vtk.vtkClipPolyData()
clip.SetInputData(geometryPD.GetPolyDataOutput())
clip.SetValue(5.5)
clip.GenerateClipScalarsOff()
clip.InsideOutOff()
clip.InsideOutOn()
clip.GetOutput().GetPointData().CopyScalarsOff()
clip.Update()
Exemple #28
0
def main():
    # Initialize argument and constant variables
    parser = ArgumentParser("Create isosurfacing of object")
    parser.add_argument("infections")
    parser.add_argument("recovered")
    parser.add_argument("deaths")
    parser.add_argument("density")
    parser.add_argument("climate_max")
    parser.add_argument("climate_min")
    parser.add_argument("location")
    parser.add_argument("migration")
    parser.add_argument("sat")
    parser.add_argument("--camera",
                        type=str,
                        help="Optional camera settings file")

    args = parser.parse_args()

    global sat_x
    global sat_y
    global max_cases
    global max_radius

    global infections_color
    global recovered_color
    global deaths_color

    global infections_opacity
    global recovered_opacity
    global deaths_opacity

    global infections_data
    global recovered_data
    global deaths_data

    global legend_circle_actors
    global legend_text_actors

    global max_weight

    global ren

    app = QApplication([])
    window = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(window)

    # Read in data for global confirmed cases
    with open(args.infections) as csvDataFile:
        csv_reader = csv.reader(csvDataFile)
        for row in csv_reader:
            # We do not need country/province name, so we remove the first two columns
            if (row[2] != 0 or row[3] != 0):
                infections_data.append(row[2:])
    infections_data = infections_data[1:]

    # Read in data for global deaths
    with open(args.deaths) as csvDataFile:
        csv_reader = csv.reader(csvDataFile)
        for row in csv_reader:
            if (row[2] != 0 or row[3] != 0):
                deaths_data.append(row[2:])
    deaths_data = deaths_data[1:]

    # Read in data for global recovered cases
    with open(args.recovered) as csvDataFile:
        csv_reader = csv.reader(csvDataFile)
        for row in csv_reader:
            if (row[2] != 0 or row[3] != 0):
                recovered_data.append(row[2:])
    recovered_data = recovered_data[1:]

    numDates = len(infections_data[0]) - 3
    max_cases = compute_max(date)

    # Create reader for density file
    density_reader = vtk.vtkTIFFReader()
    density_reader.SetFileName(args.density)
    density_reader.Update()

    density_log = vtk.vtkImageLogarithmicScale()
    density_log.SetInputConnection(density_reader.GetOutputPort())
    density_log.SetConstant(0.435)
    density_log.Update()
    density_range = density_log.GetOutput().GetScalarRange()

    climate_max_reader = vtk.vtkTIFFReader()
    climate_max_reader.SetFileName(args.climate_max + "-" +
                                   str(initial_date.month.real).zfill(2) +
                                   ".tif")
    climate_max_reader.Update()
    climate_max_range = [-40, 45]

    climate_min_reader = vtk.vtkTIFFReader()
    climate_min_reader.SetFileName(args.climate_min + "-" +
                                   str(initial_date.month.real).zfill(2) +
                                   ".tif")
    climate_min_reader.Update()
    climate_min_range = [-50, 30]

    sat_reader = vtk.vtkJPEGReader()
    sat_reader.SetFileName(args.sat)
    sat_reader.Update()
    sat_dimensions = sat_reader.GetOutput().GetDimensions()
    sat_x = sat_dimensions[0]
    sat_y = sat_dimensions[1]

    # Read in data for migration
    location_map = create_long_lat(args.location)
    migrations = []
    for filename in os.listdir(args.migration):
        if filename.endswith(".csv"):
            with open(args.migration + "\\" + filename) as csvDataFile:
                country = filename.split(".")[0]
                if country not in location_map:
                    continue
                loc_dst = location_map[country]
                csv_reader = csv.reader(csvDataFile)
                for row in csv_reader:
                    if row[2] not in location_map:
                        continue
                    loc_src = location_map[row[2]]
                    try:
                        migrations.append(
                            add_migration_info(loc_src, loc_dst, int(row[9])))
                    except ValueError:
                        continue

    line_actors = process_migration_actors(migrations)

    # Create a plane to map the satellite image onto
    plane = vtk.vtkPlaneSource()
    plane.SetCenter(0.0, 0.0, 0.0)
    plane.SetNormal(0.0, 0.0, 1.0)
    plane.SetPoint1(sat_x, 0, 0)
    plane.SetPoint2(0, sat_y, 0)

    # Create satellite image texture
    texture = vtk.vtkTexture()
    texture.SetInputConnection(sat_reader.GetOutputPort())

    # Map satellite texture to plane
    texturePlane = vtk.vtkTextureMapToPlane()
    texturePlane.SetInputConnection(plane.GetOutputPort())

    max_val = 100
    color_count = 1000

    density_ctf = vtk.vtkColorTransferFunction()
    density_ctf.AddRGBPoint(0, 0, 0, 0)
    density_ctf.AddRGBPoint(10, 0, 0, 1)
    density_ctf.AddRGBPoint(30, 0, 1, 1)
    density_ctf.AddRGBPoint(50, 1, 1, 0)
    density_ctf.AddRGBPoint(65, 1, 0.5, 0)
    density_ctf.AddRGBPoint(80, 1, 0, 0)

    density_lut = vtk.vtkLookupTable()
    density_lut.SetNumberOfTableValues(color_count)
    density_lut.Build()

    rgb = list(density_ctf.GetColor(0)) + [0]
    density_lut.SetTableValue(0, rgb)
    for i in range(1, color_count):
        rgb = list(density_ctf.GetColor(
            max_val * float(i) / color_count)) + [1]
        density_lut.SetTableValue(i, rgb)

    climate_ctf = vtk.vtkColorTransferFunction()
    climate_ctf.AddRGBPoint(5, 0, 0, 1)
    climate_ctf.AddRGBPoint(35, 0, 1, 1)
    climate_ctf.AddRGBPoint(65, 1, 1, 0)
    climate_ctf.AddRGBPoint(95, 1, 0, 0)

    climate_lut = vtk.vtkLookupTable()
    climate_lut.SetNumberOfTableValues(color_count)
    climate_lut.Build()

    for i in range(0, color_count):
        rgb = list(climate_ctf.GetColor(
            max_val * float(i) / color_count)) + [1]
        climate_lut.SetTableValue(i, rgb)

    # Create mappers
    density_mapper = vtk.vtkDataSetMapper()
    density_mapper.SetInputConnection(density_log.GetOutputPort())
    density_mapper.SetLookupTable(density_lut)
    density_mapper.SetScalarRange([0, density_range[1]])
    density_mapper.Update()

    climate_max_mapper = vtk.vtkDataSetMapper()
    climate_max_mapper.SetInputConnection(climate_max_reader.GetOutputPort())
    climate_max_mapper.SetLookupTable(climate_lut)
    climate_max_mapper.SetScalarRange(climate_max_range)
    climate_max_mapper.Update()

    climate_min_mapper = vtk.vtkDataSetMapper()
    climate_min_mapper.SetInputConnection(climate_min_reader.GetOutputPort())
    climate_min_mapper.SetLookupTable(climate_lut)
    climate_min_mapper.SetScalarRange(climate_min_range)
    climate_min_mapper.Update()

    sat_mapper = vtk.vtkPolyDataMapper()
    sat_mapper.SetInputConnection(texturePlane.GetOutputPort())

    density_actor = vtk.vtkActor()
    density_actor.SetMapper(density_mapper)
    density_actor.GetProperty().SetOpacity(0.99)
    density_actor.VisibilityOn()

    climate_max_actor = vtk.vtkActor()
    climate_max_actor.SetMapper(climate_max_mapper)
    climate_max_actor.GetProperty().SetOpacity(0.6)
    climate_max_actor.VisibilityOff()

    climate_min_actor = vtk.vtkActor()
    climate_min_actor.SetMapper(climate_min_mapper)
    climate_min_actor.GetProperty().SetOpacity(0.6)
    climate_min_actor.VisibilityOff()

    sat_actor = vtk.vtkActor()
    sat_actor.SetMapper(sat_mapper)
    sat_actor.SetTexture(texture)
    sat_actor.GetProperty().SetOpacity(0.6)

    # Make satellite image same size as contour map
    crange = sat_actor.GetXRange()[0] - sat_actor.GetXRange()[1]
    mrange = density_actor.GetXRange()[0] - density_actor.GetXRange()[1]
    density_actor.SetScale(crange / mrange)

    crange = sat_actor.GetXRange()[0] - sat_actor.GetXRange()[1]
    mrange = climate_max_actor.GetXRange()[0] - climate_max_actor.GetXRange(
    )[1]
    climate_max_actor.SetScale(crange / mrange)
    climate_min_actor.SetScale(crange / mrange)

    # Initialize renderer and place actors
    ren = vtk.vtkRenderer()

    ren.AddActor(density_actor)
    ren.AddActor(climate_max_actor)
    ren.AddActor(climate_min_actor)

    # Add legend actors
    add_legend_actors()

    # Add infections, recovered, and deaths actors
    infections_actors = []
    if (ui.infections_check.isChecked()):
        add_case_actors(date, infections_data, infections_actors,
                        infections_color, infections_opacity)

    recovered_actors = []
    if (ui.recovered_check.isChecked()):
        add_case_actors(date, recovered_data, recovered_actors,
                        recovered_color, recovered_opacity)

    deaths_actors = []
    if (ui.deaths_check.isChecked()):
        add_case_actors(date, deaths_data, deaths_actors, deaths_color,
                        deaths_opacity)

    for line_actor in line_actors:
        line_actor.VisibilityOn()
        ren.AddActor(line_actor)

    ren.AddActor(sat_actor)
    ren.ResetCamera()
    ren.SetBackground(0, 0, 0)

    # Initialize camera settings
    cam1 = ren.GetActiveCamera()
    cam1.Azimuth(0)
    cam1.Elevation(0)
    cam1.Roll(360)
    cam1.Zoom(1.5)

    ren.ResetCameraClippingRange()

    if args.camera:
        reader = open(args.camera, "r")
        line = reader.readline().split(",")
        cam1.SetPosition(float(line[0]), float(line[1]), float(line[2]))
        line = reader.readline().split(",")
        cam1.SetFocalPoint(float(line[0]), float(line[1]), float(line[2]))
        line = reader.readline().split(",")
        cam1.SetViewUp(float(line[0]), float(line[1]), float(line[2]))
        line = reader.readline().split(",")
        cam1.SetClippingRange(float(line[0]), float(line[1]))
        line = reader.readline().split(",")
        cam1.SetViewAngle(float(line[0]))
        line = reader.readline().split(",")
        cam1.SetParallelScale(float(line[0]))

    # Initialize PyQT5 UI and link to renderer
    ui.vtkWidget.GetRenderWindow().AddRenderer(ren)
    ui.vtkWidget.GetRenderWindow().SetSize(1280, 720)

    ui.vtkWidget.GetRenderWindow().AddRenderer(ren)
    ui.vtkWidget.GetRenderWindow().SetAlphaBitPlanes(True)
    ui.vtkWidget.GetRenderWindow().SetMultiSamples(False)
    iren = ui.vtkWidget.GetRenderWindow().GetInteractor()

    # create the scalar_bar
    density_scalar_bar = vtk.vtkScalarBarActor()
    density_scalar_bar.SetOrientationToHorizontal()
    density_scalar_bar.SetMaximumNumberOfColors(color_count)
    density_scalar_bar.SetLookupTable(density_lut)
    density_scalar_bar.SetTitle("Density (Log 10)")

    # create the scalar_bar_widget
    density_scalar_bar_widget = vtk.vtkScalarBarWidget()
    density_scalar_bar_widget.SetInteractor(iren)
    density_scalar_bar_widget.SetScalarBarActor(density_scalar_bar)
    density_scalar_bar_widget.On()

    # create the scalar_bar
    climate_scalar_bar = vtk.vtkScalarBarActor()
    climate_scalar_bar.SetOrientationToHorizontal()
    climate_scalar_bar.SetMaximumNumberOfColors(color_count)
    climate_scalar_bar.SetLookupTable(climate_lut)
    climate_scalar_bar.SetTitle("Temparature (Celsius)")

    # create the scalar_bar_widget
    climate_scalar_bar_widget = vtk.vtkScalarBarWidget()
    climate_scalar_bar_widget.SetInteractor(iren)
    climate_scalar_bar_widget.SetScalarBarActor(climate_scalar_bar)
    climate_scalar_bar_widget.Off()

    # Function to initialize slider settings
    def slider_setup(slider, val, bounds, interv):
        slider.setOrientation(QtCore.Qt.Horizontal)
        slider.setValue(float(val))
        slider.setSliderPosition(val)
        slider.setTracking(False)
        slider.setTickInterval(interv)
        slider.setTickPosition(QSlider.TicksAbove)
        slider.setRange(bounds[0], bounds[1])

    slider_setup(ui.time_slider, 0, [0, numDates], 1)

    window.show()
    window.setWindowState(Qt.WindowMaximized)
    iren.Initialize()

    def time_slider_callback(val):
        global max_cases
        global date
        date = val
        new_date = initial_date + timedelta(val)
        if new_date.month.real != ui.curr_month:
            ui.curr_month = new_date.month.real
            climate_max_reader.SetFileName(args.climate_max + "-" +
                                           str(ui.curr_month).zfill(2) +
                                           ".tif")
            climate_max_reader.Update()
            climate_min_reader.SetFileName(args.climate_min + "-" +
                                           str(ui.curr_month).zfill(2) +
                                           ".tif")
            climate_min_reader.Update()
        ui.date_label.setText("Date (" + new_date.strftime('%m/%d/%Y') + "):")

        # Remove old infections, recovered, and deaths actors
        remove_case_actors(infections_actors)
        remove_case_actors(recovered_actors)
        remove_case_actors(deaths_actors)
        remove_legend_actors()

        # Recompute max cases
        max_cases = compute_max(date)

        # Add infections, recovered, and deaths actors
        if (ui.infections_check.isChecked()):
            add_case_actors(date, infections_data, infections_actors,
                            infections_color, infections_opacity)
        if (ui.recovered_check.isChecked()):
            add_case_actors(date, recovered_data, recovered_actors,
                            recovered_color, recovered_opacity)
        if (ui.deaths_check.isChecked()):
            add_case_actors(date, deaths_data, deaths_actors, deaths_color,
                            deaths_opacity)
        add_legend_actors()

        ui.vtkWidget.GetRenderWindow().Render()

    def infections_callback():
        if (ui.infections_check.isChecked()):
            add_case_actors(date, infections_data, infections_actors,
                            infections_color, infections_opacity)
        else:
            remove_case_actors(infections_actors)

        ui.vtkWidget.GetRenderWindow().Render()

    def recovered_callback():
        if (ui.recovered_check.isChecked()):
            add_case_actors(date, recovered_data, recovered_actors,
                            recovered_color, recovered_opacity)
        else:
            remove_case_actors(recovered_actors)

        ui.vtkWidget.GetRenderWindow().Render()

    def deaths_callback():
        if (ui.deaths_check.isChecked()):
            add_case_actors(date, deaths_data, deaths_actors, deaths_color,
                            deaths_opacity)
        else:
            remove_case_actors(deaths_actors)

        ui.vtkWidget.GetRenderWindow().Render()

    def density_callback():
        if ui.density_check.isChecked():
            ui.climate_max_check.setChecked(False)
            ui.climate_min_check.setChecked(False)
            density_actor.VisibilityOn()
            density_scalar_bar_widget.On()
            ui.vtkWidget.GetRenderWindow().Render()
        else:
            density_actor.VisibilityOff()
            density_scalar_bar_widget.Off()
            ui.vtkWidget.GetRenderWindow().Render()

    def climate_max_callback():
        if ui.climate_max_check.isChecked():
            ui.density_check.setChecked(False)
            ui.climate_min_check.setChecked(False)
            climate_max_actor.VisibilityOn()
            climate_scalar_bar_widget.On()
            ui.vtkWidget.GetRenderWindow().Render()
        else:
            climate_max_actor.VisibilityOff()
            climate_scalar_bar_widget.Off()
            ui.vtkWidget.GetRenderWindow().Render()

    def climate_min_callback():
        if ui.climate_min_check.isChecked():
            ui.density_check.setChecked(False)
            ui.climate_max_check.setChecked(False)
            climate_min_actor.VisibilityOn()
            climate_scalar_bar_widget.On()
            ui.vtkWidget.GetRenderWindow().Render()
        else:
            climate_min_actor.VisibilityOff()
            climate_scalar_bar_widget.Off()
            ui.vtkWidget.GetRenderWindow().Render()

    def migration_callback():
        if ui.migration_check.isChecked():
            for line_actor in line_actors:
                line_actor.VisibilityOn()
            ui.vtkWidget.GetRenderWindow().Render()
        else:
            for line_actor in line_actors:
                line_actor.VisibilityOff()
            ui.vtkWidget.GetRenderWindow().Render()

    # Handle screenshot button event
    def screenshot_callback():
        save_frame(ren.GetActiveCamera(), ui.vtkWidget.GetRenderWindow(),
                   ui.log)

    # Handle show camera settings button event
    def camera_callback():
        print_camera_settings(ren.GetActiveCamera(), ui.camera_info, ui.log)

    # Handle quit button event
    def quit_callback():
        sys.exit()

    # Register callbacks to UI
    ui.time_slider.valueChanged.connect(time_slider_callback)
    ui.push_screenshot.clicked.connect(screenshot_callback)
    ui.push_camera.clicked.connect(camera_callback)
    ui.push_quit.clicked.connect(quit_callback)

    ui.infections_check.stateChanged.connect(infections_callback)
    ui.recovered_check.stateChanged.connect(recovered_callback)
    ui.deaths_check.stateChanged.connect(deaths_callback)
    ui.density_check.stateChanged.connect(density_callback)
    ui.climate_max_check.stateChanged.connect(climate_max_callback)
    ui.climate_min_check.stateChanged.connect(climate_min_callback)
    ui.migration_check.stateChanged.connect(migration_callback)

    # Terminate setup for PyQT5 interface
    sys.exit(app.exec_())
	def __init__(self, data_source):
		"""Icicle view constructor needs a valid DataSource and will pull data
		from it immediately."""
		
		self.ds = data_source
		
		SHRINK = 0.1
		THICK = 1.0
		
		tree = self.ds.GetTree()
		
		# Build view
		self.view = vtk.vtkIcicleView()
		self.view.SetRepresentationFromInput(tree)
		self.view.SetAreaSizeArrayName("num_in_vertex")
		self.view.SetAreaColorArrayName("scale")
		self.view.SetAreaLabelArrayName("blank")
		self.view.SetLabelPriorityArrayName("VertexDegree")
		self.view.SetAreaLabelVisibility(True)
		self.view.SetAreaHoverArrayName("vertex_ids")
		self.view.SetDisplayHoverText(True)
		self.view.SetShrinkPercentage(SHRINK)
		self.view.SetLayerThickness(THICK)
		self.view.UseGradientColoringOff()
		
		self.style = vtk.vtkInteractorStyleImage()
		self.view.SetInteractorStyle(self.style)
		
		# Parallel pipeline with no shrinkage to get TCoords
		TreeLevels = vtk.vtkTreeLevelsFilter()
		TreeLevels.SetInput(tree)
		
		VertexDegree = vtk.vtkVertexDegree()
		VertexDegree.SetInputConnection(TreeLevels.GetOutputPort(0))
		
		TreeAggregation = vtk.vtkTreeFieldAggregator()
		TreeAggregation.LeafVertexUnitSizeOff()
		TreeAggregation.SetField('size')
		TreeAggregation.SetInputConnection(VertexDegree.GetOutputPort(0))
		
		# Layout with shrinkage for generating geometry
		strategy = vtk.vtkStackedTreeLayoutStrategy()
		strategy.UseRectangularCoordinatesOn()
		strategy.SetRootStartAngle(0.0)
		strategy.SetRootEndAngle(15.0)
		strategy.SetRingThickness(THICK)	# layer thickness
		strategy.ReverseOn()
		strategy.SetShrinkPercentage(0.0)
		layout = vtk.vtkAreaLayout()
		layout.SetLayoutStrategy(strategy)
		layout.SetInputConnection(TreeAggregation.GetOutputPort(0))
		layout.SetAreaArrayName("area")
		layout.SetSizeArrayName("num_in_vertex")
		areapoly = vtk.vtkTreeMapToPolyData()
		areapoly.SetInputConnection(layout.GetOutputPort(0))
		areapoly.SetAddNormals(0)
		areapoly.SetInputArrayToProcess( 0, 0, 0, 4, "area")  # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES
		texPlane = vtk.vtkTextureMapToPlane()
		texPlane.SetInputConnection(areapoly.GetOutputPort(0))
		texPlane.AutomaticPlaneGenerationOn()
		texPlane.Update()
		
		# Layout without shrinkage for generating texture coordinates
		strategy0 = vtk.vtkStackedTreeLayoutStrategy()
		strategy0.UseRectangularCoordinatesOn()
		strategy0.SetRootStartAngle(0.0)
		strategy0.SetRootEndAngle(15.0)
		strategy0.SetRingThickness(THICK)	# layer thickness
		strategy0.ReverseOn()
		strategy0.SetShrinkPercentage(SHRINK)
		layout0 = vtk.vtkAreaLayout()
		layout0.SetLayoutStrategy(strategy0)
		layout0.SetInputConnection(TreeAggregation.GetOutputPort(0))
		layout0.SetAreaArrayName("area")
		layout0.SetSizeArrayName("num_in_vertex")
		areapoly0 = vtk.vtkTreeMapToPolyData()
		areapoly0.SetAddNormals(0)
		areapoly0.SetInputConnection(layout0.GetOutputPort(0))
		areapoly0.SetInputArrayToProcess( 0, 0, 0, 4, "area")  # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES
		areapoly0.Update()
		
		# Copy over texture coordinates
		def transferTCoords():
			input = paf.GetInputDataObject(0,0)
			refin = paf.GetInputList().GetItem(0)
			output = paf.GetPolyDataOutput()
			
			TCorig = refin.GetPointData().GetTCoords()
			
			TC = vtk.vtkFloatArray()
			TC.SetNumberOfComponents(TCorig.GetNumberOfComponents())
			TC.SetNumberOfTuples(TCorig.GetNumberOfTuples())
			TC.SetName('Texture Coordinates')
			for ii in range(TCorig.GetNumberOfTuples()):
				ff = TCorig.GetTuple2(ii)
				TC.SetTuple2(ii,ff[0],ff[1])
			
			output.GetPointData().AddArray(TC)
			output.GetPointData().SetActiveTCoords('Texture Coordinates')
			
		paf = vtk.vtkProgrammableAttributeDataFilter()
		paf.SetInput(areapoly0.GetOutput())
		paf.AddInput(texPlane.GetOutput())
		paf.SetExecuteMethod(transferTCoords)
		
		# Need to find proper ordering of wavelet coeffs based on icicle layout
		# tree.GetVertexData().GetArray('area') is 4-component (Xmin,Xmax,Ymin,Ymax)
		print 'Reordering wavelet coeffs'
		out_polys = areapoly.GetOutputDataObject(0)
		isleaf = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('leaf'))
		poly_bounds = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('area'))
		vertex_ids = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('vertex_ids'))
		
		LeafIds = vertex_ids[isleaf>0]
		LeafXmins = poly_bounds[isleaf>0,0]
		XOrderedLeafIds = LeafIds[LeafXmins.argsort()]
					
		# And then grab the Wavelet Coefficients matrix sorted according to this
		WCimageData = self.ds.GetWaveletCoeffImage(XOrderedLeafIds)
		
		WCrange = N.array(WCimageData.GetPointData().GetScalars().GetRange())
		WCext = abs(WCrange.min()) if (abs(WCrange.min()) > abs(WCrange.max())) else abs(WCrange.max())
		# print WCext
		
		# Create blue to white to red lookup table
		lut = vtk.vtkLookupTable()
		lutNum = 256
		lut.SetNumberOfTableValues(lutNum)
		lut.Build()
		ctf = vtk.vtkColorTransferFunction()
		ctf.SetColorSpaceToDiverging()
		ctf.AddRGBPoint(0.0, 0, 0, 1.0)
		ctf.AddRGBPoint(1.0, 1.0, 0, 0)
		for ii,ss in enumerate([float(xx)/float(lutNum) for xx in range(lutNum)]):
			cc = ctf.GetColor(ss)
			lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0)
		lut.SetRange(-WCext,WCext)
		
		# Set up texture with lookup table for matrix polys
		tex = vtk.vtkTexture()
		tex.SetInput(WCimageData)
		tex.SetLookupTable(lut)
		
		# Separate mapper and actor for textured polys
		map2 = vtk.vtkPolyDataMapper()
		map2.SetInputConnection(paf.GetOutputPort(0))
		map2.ScalarVisibilityOff()
		act2 = vtk.vtkActor()
		act2.SetMapper(map2)
		act2.SetTexture(tex)
		act2.GetProperty().SetColor(1,1,1)
		act2.SetPickable(0)
		act2.SetPosition(0,0,0.1)
		
		# Add textured polys to the view
		ren = self.view.GetRenderer()
		ren.AddActor(act2)
		
		# NOTE: This is the one place I'm still hacking into the view -- to set the
		#   normal icicle view to wireframe and set the color...
		
		# Ren has an actor2d which is a scalar bar (edge)
		acts = ren.GetActors()
		# Acts has two actors -- graph blocks (0) and labels (1)
		act0 = acts.GetItemAsObject(0)
		
		act0.GetProperty().SetRepresentationToWireframe()
		act0.GetProperty().SetLineWidth(3.0)
		
		# Apply a theme to the views
		theme = vtk.vtkViewTheme.CreateMellowTheme()
		theme.SetPointHueRange(0,0)
		theme.SetPointSaturationRange(0.2,0.5)
		theme.SetPointValueRange(0.0,0.0)
		theme.SetPointAlphaRange(0.0,0.0)
		c = N.array([255,204,0])/255.0
		theme.SetSelectedPointColor(c[0],c[1],c[2])
		theme.SetBackgroundColor(0.1, 0.1, 0.06)
		theme.SetBackgroundColor2(0.25, 0.25, 0.2)
		self.view.ApplyViewTheme(theme)
		theme.FastDelete()
		
		# Connect the annotation link to the icicle representation
		rep = self.view.GetRepresentation(0)
		
		# Grab annotation link to monitor selection changes
		self.link = rep.GetAnnotationLink()
		# If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
		# See vtkSelectionNode doc for field and content type enum values
		# enum		SelectionContent { 
		#	SELECTIONS, GLOBALIDS, PEDIGREEIDS, VALUES, 
		#	INDICES, FRUSTUM, LOCATIONS, THRESHOLDS, 
		#	BLOCKS 
		# }
		# enum		SelectionField { 
		#	CELL, POINT, FIELD, VERTEX, 
		#	EDGE, ROW 
		# }
		
		# Note: This may be the defaults, anyway, for the IcicleView annotation link
		self.link.GetCurrentSelection().GetNode(0).SetFieldType(3)		# Vertex
		self.link.GetCurrentSelection().GetNode(0).SetContentType(2)	# Pedigree Ids
		
		# TEST: Set up callback to test icicle view selection IDs
		self.link.AddObserver("AnnotationChangedEvent", self.IcicleSelectionCallback)
		
		self.view.GetRenderer().GetActiveCamera().ParallelProjectionOn()		
		self.view.ResetCamera()
		self.view.Render()
Exemple #30
0
def make_patterned_polydata(
    inputContours, fillareastyle=None, fillareaindex=None, fillareacolors=None, fillareaopacity=None, size=None
):
    if inputContours is None or fillareastyle == "solid":
        return None
    if inputContours.GetNumberOfCells() == 0:
        return None
    if fillareaindex is None:
        fillareaindex = 1
    if fillareaopacity is None:
        fillareaopacity = 100
    num_pixels = num_pixels_for_size(size)

    # Create the plane that will be textured with the pattern
    # The bounds of the plane match the bounds of the input polydata
    bounds = inputContours.GetBounds()

    patternPlane = vtk.vtkPlaneSource()
    patternPlane.SetOrigin(bounds[0], bounds[2], 0.0)
    patternPlane.SetPoint1(bounds[0], bounds[3], 0.0)
    patternPlane.SetPoint2(bounds[1], bounds[2], 0.0)
    # Generate texture coordinates for the plane
    textureMap = vtk.vtkTextureMapToPlane()
    textureMap.SetInputConnection(patternPlane.GetOutputPort())

    # Create the pattern image of the size of the input polydata
    # and type defined by fillareaindex
    xBounds = bounds[1] - bounds[0]
    yBounds = bounds[3] - bounds[2]

    if xBounds <= 1 and yBounds <= 1 and size is not None:
        xBounds *= size[0]
        yBounds *= size[1]
        xres, yres = int(xBounds), int(yBounds)

    xres = int(4.0 * xBounds)
    yres = int(4.0 * yBounds)

    # Handle the case when the bounds are less than 1 in physical dimensions

    patternImage = create_pattern(xres, yres, num_pixels, fillareastyle, fillareaindex, fillareacolors, fillareaopacity)
    if patternImage is None:
        return None

    # Extrude the contour since vtkPolyDataToImageStencil
    # requires 3D polydata
    extruder = vtk.vtkLinearExtrusionFilter()
    extruder.SetInputData(inputContours)
    extruder.SetScaleFactor(1.0)
    extruder.SetVector(0, 0, 1)
    extruder.SetExtrusionTypeToNormalExtrusion()

    # Create a binary image mask from the extruded polydata
    pol2stenc = vtk.vtkPolyDataToImageStencil()
    pol2stenc.SetTolerance(0)
    pol2stenc.SetInputConnection(extruder.GetOutputPort())
    pol2stenc.SetOutputOrigin(bounds[0], bounds[2], 0.0)
    pol2stenc.SetOutputSpacing((bounds[1] - bounds[0]) / xres, (bounds[3] - bounds[2]) / yres, 0.0)
    pol2stenc.SetOutputWholeExtent(patternImage.GetExtent())

    # Stencil out the fillarea from the pattern image
    stenc = vtk.vtkImageStencil()
    stenc.SetInputData(patternImage)
    stenc.SetStencilConnection(pol2stenc.GetOutputPort())
    stenc.ReverseStencilOff()
    stenc.SetBackgroundColor(0, 0, 0, 0)
    stenc.Update()
    patternImage = stenc.GetOutput()

    # Create the texture using the stenciled pattern
    patternTexture = vtk.vtkTexture()
    patternTexture.SetInputData(patternImage)
    patternTexture.InterpolateOn()
    patternTexture.RepeatOn()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(textureMap.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(patternTexture)
    return actor
	def LoadData(self):
		
		# Remove all old actors from renderer
		self.renderer.RemoveAllViewProps()
		# Put back nav menu
		menu_actor_list = self.menu.GetActorList()
		for m_actor in menu_actor_list:
			self.renderer.AddActor(m_actor)
		
		tree = self.ds.GetTree()
		
		# Parallel pipeline with no shrinkage to get TCoords
		self.TreeLevels = vtk.vtkTreeLevelsFilter()
		self.TreeLevels.SetInput(tree)
		
		VertexDegree = vtk.vtkVertexDegree()
		VertexDegree.SetInputConnection(self.TreeLevels.GetOutputPort(0))
		
		TreeAggregation = vtk.vtkTreeFieldAggregator()
		TreeAggregation.LeafVertexUnitSizeOff()
		TreeAggregation.SetField('size')
		TreeAggregation.SetInputConnection(VertexDegree.GetOutputPort(0))
		
		# Layout without shrinkage for generating texture coordinates
		strategy = vtk.vtkStackedTreeLayoutStrategy()
		strategy.UseRectangularCoordinatesOn()
		strategy.SetRootStartAngle(0.0)
		strategy.SetRootEndAngle(15.0)
		strategy.SetRingThickness(self.THICK)	# layer thickness
		strategy.ReverseOn()
		strategy.SetShrinkPercentage(0.0)
		layout = vtk.vtkAreaLayout()
		layout.SetLayoutStrategy(strategy)
		layout.SetInputConnection(TreeAggregation.GetOutputPort(0))
		layout.SetAreaArrayName("area")
		layout.SetSizeArrayName("num_in_vertex")
		areapoly = vtk.vtkTreeMapToPolyData()
		areapoly.SetInputConnection(layout.GetOutputPort(0))
		areapoly.SetAddNormals(0)
		areapoly.SetInputArrayToProcess( 0, 0, 0, 4, "area")  # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES
		texPlane = vtk.vtkTextureMapToPlane()
		texPlane.SetInputConnection(areapoly.GetOutputPort(0))
		texPlane.AutomaticPlaneGenerationOn()
		texPlane.Update()
		
		# Layout with shrinkage for generating geometry
		strategy0 = vtk.vtkStackedTreeLayoutStrategy()
		strategy0.UseRectangularCoordinatesOn()
		strategy0.SetRootStartAngle(0.0)
		strategy0.SetRootEndAngle(15.0)
		strategy0.SetRingThickness(self.THICK)	# layer thickness
		strategy0.ReverseOn()
		strategy0.SetShrinkPercentage(self.SHRINK)
		layout0 = vtk.vtkAreaLayout()
		layout0.SetLayoutStrategy(strategy0)
		layout0.SetInputConnection(TreeAggregation.GetOutputPort(0))
		layout0.SetAreaArrayName("area")
		layout0.SetSizeArrayName("num_in_vertex")
		areapoly0 = vtk.vtkTreeMapToPolyData()
		areapoly0.SetAddNormals(0)
		areapoly0.SetInputConnection(layout0.GetOutputPort(0))
		areapoly0.SetInputArrayToProcess( 0, 0, 0, 4, "area")  # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES
		areapoly0.Update()
		
		# Copy over texture coordinates
		def transferTCoords():
			input = paf.GetInputDataObject(0,0)
			refin = paf.GetInputList().GetItem(0)
			output = paf.GetPolyDataOutput()
			
			TCorig = refin.GetPointData().GetTCoords()
			
			TC = vtk.vtkFloatArray()
			TC.SetNumberOfComponents(TCorig.GetNumberOfComponents())
			TC.SetNumberOfTuples(TCorig.GetNumberOfTuples())
			TC.SetName('Texture Coordinates')
			for ii in range(TCorig.GetNumberOfTuples()):
				ff = TCorig.GetTuple2(ii)
				TC.SetTuple2(ii,ff[0],ff[1])
			
			output.GetPointData().AddArray(TC)
			output.GetPointData().SetActiveTCoords('Texture Coordinates')
			
		paf = vtk.vtkProgrammableAttributeDataFilter()
		paf.SetInput(areapoly0.GetOutput())
		paf.AddInput(texPlane.GetOutput())
		paf.SetExecuteMethod(transferTCoords)
		
		# Need to find proper ordering of wavelet coeffs based on icicle layout
		# tree.GetVertexData().GetArray('area') is 4-component (Xmin,Xmax,Ymin,Ymax)
		print 'Reordering wavelet coeffs'
		out_polys = areapoly.GetOutputDataObject(0)
		isleaf = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('leaf'))
		poly_bounds = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('area'))
		vertex_ids = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('vertex_ids'))
		
		self.LeafIds = vertex_ids[isleaf>0]
		self.LeafXmins = poly_bounds[isleaf>0,0]
		self.XOrderedLeafIds = self.LeafIds[self.LeafXmins.argsort()]
					

		# Grab texture images and color map
		self.GrabTextureImagesAndLUT()
		

		# For each node and corresponding image data in self.WCimageDataList, need to create a texture,
		# then pull out the correct rectangle from areapoly0 (using vtkExtractSelectedPolyDataIds
		# and create a mapper and actor and apply the texture. 
		
		self.texture_list = []
		self.tex_mapper_list = []
		self.tex_actor_list = []
		
		for ii in range(len(self.WCimageDataList)):
			
			# Set up texture with lookup table for matrix polys
			tex = vtk.vtkTexture()
			tex.SetInput(self.WCimageDataList[ii])
			tex.SetLookupTable(self.lut)
			self.texture_list.append(tex)
			
			# Grab correct poly out of areapoly0
			sel = vtk.vtkSelection()
			node = vtk.vtkSelectionNode()
			node.SetContentType(4)	# 4 = indices
			node.SetFieldType(0)		# 0 = cell
			id_array = N.array([ii],dtype='int64')
			id_list = VN.numpy_to_vtkIdTypeArray(id_array)
			node.SetSelectionList(id_list)
			sel.AddNode(node)

			ext_id_poly = vtk.vtkExtractSelectedPolyDataIds()
			ext_id_poly.SetInput(1, sel)
			ext_id_poly.SetInputConnection(0, areapoly0.GetOutputPort(0))
			# ext_id_poly.Update()
			# print ext_id_poly.GetOutput()
			poly_tm = vtk.vtkTextureMapToPlane()
			poly_tm.SetInputConnection(ext_id_poly.GetOutputPort(0))
			poly_tm.AutomaticPlaneGenerationOn()
			poly_tm.Update()

			# Separate mapper and actor for textured polys
			map2 = vtk.vtkPolyDataMapper()
			map2.SetInputConnection(poly_tm.GetOutputPort(0))
			map2.ScalarVisibilityOff()
			self.tex_mapper_list.append(map2)
			
			act2 = vtk.vtkActor()
			act2.SetMapper(self.tex_mapper_list[ii])
			act2.SetTexture(self.texture_list[ii])
			act2.GetProperty().SetColor(1,1,1)
			act2.SetPickable(0)
			act2.SetPosition(0,0,0.1)	# ???
			self.tex_actor_list.append(act2)
			
			# Add textured polys to the view
			self.renderer.AddActor(self.tex_actor_list[ii])

				
		# Layout with shrinkage for generating outline geometry for showing selections
		self.applycolors1 = vtk.vtkApplyColors()
		self.applycolors1.SetInputConnection(0,layout0.GetOutputPort(0))
		self.applycolors1.AddInputConnection(1,self.output_link.GetOutputPort(0))
		self.applycolors1.SetDefaultPointColor(self.theme.GetPointColor())
		self.applycolors1.SetDefaultPointOpacity(self.theme.GetPointOpacity())
		self.applycolors1.SetSelectedPointColor(self.theme.GetSelectedPointColor())
		self.applycolors1.SetSelectedPointOpacity(self.theme.GetSelectedPointOpacity())

		self.areapoly1 = vtk.vtkTreeMapToPolyData()
		self.areapoly1.SetInputConnection(self.applycolors1.GetOutputPort(0))
		self.areapoly1.SetAddNormals(0)
		self.areapoly1.SetInputArrayToProcess( 0, 0, 0, 4, "area")  # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES
		
		# Separate mapper and actor for icicle polys outlines (pickable)
		map = vtk.vtkPolyDataMapper()
		map.SetInputConnection(self.areapoly1.GetOutputPort(0))
		map.SetScalarModeToUseCellFieldData()
		map.SelectColorArray("vtkApplyColors color")
		map.SetScalarVisibility(True)
		act = vtk.vtkActor()
		act.SetMapper(map)
		act.GetProperty().SetColor(1,1,1)
		act.SetPickable(True)
		act.SetPosition(0,0,0)
		act.GetProperty().SetRepresentationToWireframe()
		act.GetProperty().SetLineWidth(4.0)
		
		self.icicle_actor = act
		
		# Add actor for selection highlight outlines
		self.renderer.AddActor(act)
		
		
		# Now need to set up data for generating "selection lines" which come from 
		# xy or pcoords chart. Basic method is to create a new scalar array out of x-coord
		# of the texture coordinates, then do a Delaunay2D on the shrunken polys and contour
		# that at values obtained by finding what normalized distance along data set are
		# selected pedigree ids.

		self.calc = vtk.vtkArrayCalculator()
		self.calc.SetInputConnection(paf.GetOutputPort())
		self.calc.SetAttributeModeToUsePointData()
		self.calc.AddScalarVariable("tcoords_X", "Texture Coordinates", 0)
		self.calc.SetFunction("tcoords_X")
		self.calc.SetResultArrayName("tcx")
		# self.calc.Update()
		# print VN.vtk_to_numpy(self.calc.GetOutput().GetPointData().GetArray('tcx'))
		
		self.group_contour = vtk.vtkContourFilter()
		self.group_contour.SetInputConnection(self.calc.GetOutputPort(0))
		self.group_contour.SetInputArrayToProcess(0,0,0,0,'tcx')

		self.highlight_contour = vtk.vtkContourFilter()
		self.highlight_contour.SetInputConnection(self.calc.GetOutputPort(0))
		self.highlight_contour.SetInputArrayToProcess(0,0,0,0,'tcx')

		# Separate mapper and actor group selection (pcoords or xy) lines
		map3 = vtk.vtkPolyDataMapper()
		map3.SetInputConnection(self.group_contour.GetOutputPort(0))
		map3.SetScalarVisibility(0)
		act3 = vtk.vtkActor()
		act3.SetMapper(map3)
		act3.SetPickable(False)
		act3.SetPosition(0,0,0.2)
		act3.GetProperty().SetRepresentationToWireframe()
		act3.GetProperty().SetLineWidth(2.0)
		act3.GetProperty().SetColor(1,0,0)
		act3.GetProperty().SetOpacity(0.6)
		
		self.group_actor = act3
		# Add actor for selection highlight outlines
		self.renderer.AddActor(act3)
		
		# Separate mapper and actor for individual (image_flow) selection highlight
		map4 = vtk.vtkPolyDataMapper()
		map4.SetInputConnection(self.highlight_contour.GetOutputPort(0))
		map4.SetScalarVisibility(0)
		act4 = vtk.vtkActor()
		act4.SetMapper(map4)
		act4.SetPickable(False)
		act4.SetPosition(0,0,0.25)
		act4.GetProperty().SetRepresentationToWireframe()
		act4.GetProperty().SetLineWidth(3.0)
		act4.GetProperty().SetColor(0,0.5,1)
		act4.GetProperty().SetOpacity(0.6)
		
		self.highlight_actor = act4
		# Add actor for selection highlight outlines
		self.renderer.AddActor(act4)
		
		# Get Ordered fractional positions for pedigree ids (for setting contour values)
		self.ped_id_fracs = self.ds.GetIdsFractionalPosition(self.XOrderedLeafIds)
		
		# Clear out selections on data change
		self.output_link.GetCurrentSelection().RemoveAllNodes()
		self.output_link.InvokeEvent("AnnotationChangedEvent")

		self.renderer.ResetCamera(self.icicle_actor.GetBounds())
def vis_imgInit(ren):
    rdr = [None]*2
    txt = [None]*2
    plane = [None]*2
    tmap = [None]*2
    cast = [None]*2
    vmap = [None]*2
    actor = [None]*2
    lookupGrayscale = [None]*2
    lookupColor = [None]*2
    
    rdr[0] = 'vis_img_reader_' + ren[0]
    txt[0] = 'vis_img_texture_' + ren[0]
    plane[0] = 'vis_img_plane_' + ren[0]
    tmap[0] = 'vis_img_tmap_' + ren[0]
    vmap[0] = 'vis_img_map_' + ren[0]
    actor[0] = 'vis_img_actor_' + ren[0]
    lookupGrayscale[0] = 'vis_img_g8bitGrayscaleLUT_' + ren[0]
    lookupColor[0] = 'vis_img_gBlueToRedLUT_'+ ren[0]
    
    rdr[1] = vtk.vtkImageReader()
    rdr[1].SetDataScalarTypeToShort()
    rdr[1].SetFileDimensionality(2)
    rdr[1].SetDataByteOrderToBigEndian()
    
    txt[1] = vtk.vtkTexture()
    plane[1] = vtk.vtkPlaneSource()
    plane[1].SetResolution(1,1)
    plane[1].SetOrigin(0.,0.,0.)
    
    tmap[1] = vtk.vtkTextureMapToPlane()
    tmap[1].SetInputConnection(plane[1].GetOutputPort())
    
    cast[1] = vtk.vtkCastToConcrete()
    cast[1].SetInputConnection(tmap[1].GetOutputPort())
    
    vmap[1] = vtk.vtkPolyDataMapper()
    vmap[1].SetInputConnection(cast[1].GetOutputPort())
    
    actor[1] = vtk.vtkActor()
    actor[1].SetMapper(vmap[1])
    actor[1].SetTexture(txt[1])
    
    lookupGrayscale[1] = vtk.vtkLookupTable()
    lookupGrayscale[1].SetHueRange(0.,0.)
    lookupGrayscale[1].SetSaturationRange(0.,0.)
    lookupGrayscale[1].SetValueRange(0.,1.)
    lookupGrayscale[1].SetNumberOfColors(16384)
    lookupGrayscale[1].Build()
    
    lookupColor[1] = vtk.vtkLookupTable()
    lookupColor[1].SetHueRange(0.6667,0.)
    lookupColor[1].SetSaturationRange(1.,1.)
    lookupColor[1].SetValueRange(1.,1.)
    lookupColor[1].SetAlphaRange(1.,1.)
    lookupColor[1].SetNumberOfColors(16384)
    lookupColor[1].Build()
    
    setattr(vis,rdr[0], rdr)
    setattr(vis,txt[0], txt)
    setattr(vis,plane[0], plane)
    setattr(vis,tmap[0], tmap)
    setattr(vis,vmap[0], vmap)
    setattr(vis,actor[0], actor)
    setattr(vis,lookupGrayscale[0], lookupGrayscale)
    setattr(vis,lookupColor[0], lookupColor)
    return
Exemple #33
0
    def addPlanWithTexture(self,
                           name,
                           point1,
                           point2,
                           point3,
                           path,
                           opacity=1.0):
        self.removeActorByName(name)

        #png_file = vtk.vtkPNGReader()
        #print(png_file.CanReadFile(path))

        # Read the image which will be the texture
        #vtkSmartPointer<vtkJPEGReader> jPEGReader = vtkSmartPointer<vtkJPEGReader>::New();
        #jPEGReader->SetFileName ( inputFilename.c_str() );
        img = vtk.vtkJPEGReader()
        img.SetFileName(path)

        #print(img.CanReadFile(path))
        #print(path)

        # Create a plane
        #vtkSmartPointer<vtkPlaneSource> plane = vtkSmartPointer<vtkPlaneSource>::New();
        #plane->SetCenter(0.0, 0.0, 0.0);
        #plane->SetNormal(0.0, 0.0, 1.0);
        plane = vtk.vtkPlaneSource()
        # planeSource.SetOrigin(center_point[0], center_point[1], center_point[2])
        # #planeSource.SetNormal(normal_vector[0], normal_vector[1], normal_vector[2])
        # #print(dir(planeSource))
        # planeSource.SetPoint1(top_left_point[0], top_left_point[1], top_left_point[2])
        # planeSource.SetPoint2(bot_right_point[0], bot_right_point[1], bot_right_point[2])
        # planeSource.SetXResolution(10)
        # planeSource.SetYResolution(340)
        #plane.SetCenter(0.0,0.0,0.0)
        #plane.SetNormal(0.0,0.0,1.0)
        plane.SetOrigin(point1[0], point1[1], point1[2])
        plane.SetPoint1(point2[0], point2[1], point2[2])
        plane.SetPoint2(point3[0], point3[1], point3[2])
        plane.SetXResolution(1920)
        plane.SetYResolution(1080)

        # Apply the texture
        #vtkSmartPointer<vtkTexture> texture = vtkSmartPointer<vtkTexture>::New();
        #texture->SetInputConnection(jPEGReader->GetOutputPort());
        texture = vtk.vtkTexture()
        texture.SetInputConnection(img.GetOutputPort())

        #vtkSmartPointer<vtkTextureMapToPlane> texturePlane = vtkSmartPointer<vtkTextureMapToPlane>::New();
        #texturePlane->SetInputConnection(plane->GetOutputPort());
        texturePlane = vtk.vtkTextureMapToPlane()
        texturePlane.SetInputConnection(plane.GetOutputPort())

        #planeSource.Update()
        #plane = planeSource.GetOutput()

        #vtkSmartPointer<vtkPolyDataMapper> planeMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
        #planeMapper->SetInputConnection(texturePlane->GetOutputPort());
        planeMapper = vtk.vtkPolyDataMapper()
        planeMapper.SetInputConnection(texturePlane.GetOutputPort())

        #vtkSmartPointer<vtkActor> texturedPlane = vtkSmartPointer<vtkActor>::New();
        #texturedPlane->SetMapper(planeMapper);
        #texturedPlane->SetTexture(texture);
        texturedPlane = vtk.vtkActor()
        texturedPlane.SetMapper(planeMapper)
        texturedPlane.SetTexture(texture)

        # Create a mapper and actor
        #polygonMapper = vtk.vtkPolyDataMapper()
        #if vtk.VTK_MAJOR_VERSION <= 5:
        #    polygonMapper.SetInputConnection(texturePlane.GetProducePort())
        #else:
        #    polygonMapper.SetInputData(texturePlane.GetOutput())
        #    polygonMapper.Update()

        #polygonActor = vtk.vtkActor()
        #polygonActor.SetMapper(polygonMapper)
        #polygonActor.SetTexture(texture)
        #polygonActor.GetProperty().SetColor([color[0],color[1],color[2]])
        #polygonActor.GetProperty().SetOpacity(opacity)
        #actor.GetProperty().SetColor(colors->GetColor3d("Cyan").GetData());

        self.ren.AddActor(texturedPlane)
        self.actor_list[name] = texturedPlane
Exemple #34
0
connect.AddSeed(extent[0], extent[3])

smooth = vtk.vtkImageGaussianSmooth()
smooth.SetDimensionality(2)
smooth.SetStandardDeviation(1, 1)
smooth.SetInputConnection(connect.GetOutputPort())

shrink = vtk.vtkImageShrink3D()
shrink.SetInputConnection(smooth.GetOutputPort())
shrink.SetShrinkFactors(2, 2, 1)
shrink.AveragingOn()

geometry = vtk.vtkImageDataGeometryFilter()
geometry.SetInputConnection(shrink.GetOutputPort())

geometryTexture = vtk.vtkTextureMapToPlane()
geometryTexture.SetInputConnection(geometry.GetOutputPort())
geometryTexture.SetOrigin(0, 0, 0)
geometryTexture.SetPoint1(padX - 1, 0, 0)
geometryTexture.SetPoint2(0, padY - 1, 0)

geometryPD = vtk.vtkCastToConcrete()
geometryPD.SetInputConnection(geometryTexture.GetOutputPort())
geometryPD.Update()

clip = vtk.vtkClipPolyData()
clip.SetInputData(geometryPD.GetPolyDataOutput())
clip.SetValue(5.5)
clip.GenerateClipScalarsOff()
clip.InsideOutOff()
clip.InsideOutOn()
Exemple #35
0
# %%
from smalllib import generate_pixel_coordinates, transform_pixel_coorindates, show_raster

show_raster(dem_c[0], dmeta)

# %%
show_raster(cropped2[0], bmeta, cmap="gray")

# %%
T = dmeta["transform"]

T = np.array(T).reshape(3, 3)

asmesh = raster_to_pyvista_mesh(dem_c[0], T)

asmesh.points -= center_coords  # recenter the mesh
asmesh.points /= 1000

asmesh = asmesh.compute_normals(flip_normals=True)

# %%
mapper = vtk.vtkTextureMapToPlane()
mapper.SetInputData(asmesh)
mapper.Update()

# %%
save_mesh_and_texture_as_obj(of("crater_cropped_dem_textured.obj"),
                             mapper.GetOutput(), cropped2[0])

# %%
Exemple #36
0
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

# Generate a cube
cube = vtk.vtkCubeSource()

# Read the image data from a file
reader = vtk.vtkJPEGReader()
reader.SetFileName("yourimage.jpg")

# Create texture object
texture = vtk.vtkTexture()
texture.SetInputConnection(reader.GetOutputPort())

#Map texture coordinates
map_to_plane = vtk.vtkTextureMapToPlane()
map_to_plane.SetInputConnection(cube.GetOutputPort())

# Create mapper and set the mapped texture as input
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(map_to_plane.GetOutputPort())

# Create actor and set the mapper and the texture
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.SetTexture(texture)

ren.AddActor(actor)

iren.Initialize()
renWin.Render()
Exemple #37
0
    def createTexture(self, kernel=4):
        """
		Create the tiled Texture plane. This method is called in the constructor and should not be called directly

		:@param	kernel:	number of tiles per row. Will create kernel squared tiles
		"""
        # Step should be an integer, and tiles should be its square
        step = int(kernel)
        tiles = int(step * step)

        # Warning if the image size cannot be divided by the step
        if not (int(1.0 * self.w / step) - self.w / step
                == 0) or not (int(1.0 * self.h / step) - self.h / step == 0):
            print "Warning: image size not divisible by the number of tiles. May cause problems ..."

        # Generate each tile
        cur_x = 0
        cur_y = 0

        for i in range(tiles):

            # Update tile sub-coordinates
            if i == 0:
                cur_x = 0
                cur_y = 0
            elif i % step == 0:
                cur_x = 0
                cur_y += self.h / step
            else:
                cur_x += self.w / step

            # Compute the min-max coordinates of the tile
            xmin = np.max([0, cur_x])
            xmax = np.min([cur_x + self.w / step - 1, self.w - 1])
            ymin = np.max([0, cur_y])
            ymax = np.min([cur_y + self.h / step - 1, self.h - 1])
            xmid = (xmin + xmax) / 2
            ymid = (ymin + ymax) / 2

            # Generate a plane with the right dimensions
            source = vtk.vtkPlaneSource()
            source.SetNormal(self.direction[0], self.direction[1],
                             self.direction[2])
            source.SetCenter(xmin, ymin, 0)
            source.SetPoint2(
                xmax + 1, ymin - 1, 0
            )  #-1 and +1 to have minimal overlap between tiles. Suboptimal ...
            source.SetPoint1(xmin - 1, ymax + 1, 0)

            # Extract ROI from image to generate tile texture
            newVOI = [xmin, xmax, ymin, ymax, 0, 0]
            extractVOI = vtk.vtkExtractVOI()
            extractVOI.SetInputConnection(self.reader.GetOutputPort())
            extractVOI.SetVOI(newVOI)

            # Generate the texture
            texture = vtk.vtkTexture()
            texture.SetInputConnection(extractVOI.GetOutputPort())

            #Map texture coordinates
            map_to_plane = vtk.vtkTextureMapToPlane()
            map_to_plane.SetInputConnection(source.GetOutputPort())

            # Create mapper and set the mapped texture as input
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(map_to_plane.GetOutputPort())

            # Create actor and set the mapper and the texture
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            actor.SetTexture(texture)

            # Rotate the actor to set the plane in the right position/orientation
            actor.SetUserMatrix(self.transform.GetMatrix())

            # Save references to VTK objects in the class for later modifications, if needed
            self.sources.append(source)
            self.VOIs.append(extractVOI)
            self.textures.append(texture)
            self.textMappers.append(map_to_plane)
            self.mappers.append(mapper)
            self.actors.append(actor)
###############################################################################
# draw plane
#
plane = vtk.vtkPlaneSource()
plane.SetCenter(0,0,0)
plane.SetNormal(1.0, 0.0, 0.0)
#planeMapper = vtk.vtkPolyDataMapper()


# build texture for plane
reader = vtk.vtkPNGReader()
reader.SetFileName(png_filename)
texture = vtk.vtkTexture()
texture.SetInputConnection(reader.GetOutputPort())

map_to_plane = vtk.vtkTextureMapToPlane()
map_to_plane.SetInputConnection(plane.GetOutputPort())
#map_to_plane.PreventSeamOn() 
planeMapper = vtk.vtkPolyDataMapper()
planeMapper.SetInputConnection(map_to_plane.GetOutputPort()) 


# transform plane
transform = vtk.vtkTransform()
transform.Translate(5, 10, 5)
transform.Scale(1, plane_scale, plane_scale * plane_ratio)
#transform.RotateWXYZ(45,0,1,0)
transformFilter = vtk.vtkTransformPolyDataFilter()
transformFilter.SetTransform(transform)
transformFilter.SetInputConnection(plane.GetOutputPort())
transformFilter.Update()
Exemple #39
0
'''
## Floor

map_to_Floor = vtk.vtkTextureMapToPlane()
map_to_Floor.SetInputConnection(source2.GetOutputPort())
#map_to_Floor.PreventSeamOn()

# Create mapper and set the mapped texture as input
mapperFloor = vtk.vtkPolyDataMapper()
mapperFloor.SetInputConnection(map_to_Floor.GetOutputPort())
'''
## Walls

## 1

wallup_mapper = vtk.vtkTextureMapToPlane()
wallup_mapper.SetInputConnection(source3.GetOutputPort())
# Create mapper and set the mapped texture as input
mapperWall1 = vtk.vtkPolyDataMapper()
mapperWall1.SetInputConnection(wallup_mapper.GetOutputPort())


## 2

wallup_mapper2 = vtk.vtkTextureMapToPlane()
wallup_mapper2.SetInputConnection(source4.GetOutputPort())
# Create mapper and set the mapped texture as input
mapperWall2 = vtk.vtkPolyDataMapper()
mapperWall2.SetInputConnection(wallup_mapper2.GetOutputPort())