Beispiel #1
0
def load(inputobj, c=None, alpha=1, threshold=False, spacing=(), unpack=True):
    """
    Load ``Actor`` and ``Volume`` from file.

    The output will depend on the file extension. See examples below.

    :param c: color in RGB format, hex, symbol or name
    :param alpha: transparency/opacity of the polygonal data.

    For volumetric data `(tiff, slc, vti etc..)`:

    :param list c: can be a list of any length of colors. This list represents the color
        transfer function values equally spaced along the range of the volumetric scalar.
    :param list alpha: can be a list of any length of tranparencies. This list represents the
        transparency transfer function values equally spaced along the range of the volumetric scalar.
    :param float threshold: value to draw the isosurface, False by default to return a ``Volume``.
        If set to True will return an ``Actor`` with automatic choice of the isosurfacing threshold.
    :param list spacing: specify the voxel spacing in the three dimensions
    :param bool unpack: only for multiblock data, if True returns a flat list of objects.

    :Examples:
        .. code-block:: python

            from vtkplotter import datadir, load, show

            # Return an Actor
            g = load(datadir+'250.vtk')
            show(g)

            # Return a list of 2 Actors
            g = load([datadir+'250.vtk', datadir+'270.vtk'])
            show(g)

            # Return a list of actors by reading all files in a directory
            # (if directory contains DICOM files then a Volume is returned)
            g = load(datadir+'timecourse1d/')
            show(g)

            # Return a Volume. Color/Opacity transfer functions can be specified too.
            g = load(datadir+'embryo.slc')
            g.c(['y','lb','w']).alpha((0.0, 0.4, 0.9, 1))
            show(g)

            # Return an Actor from a SLC volume with automatic thresholding
            g = load(datadir+'embryo.slc', threshold=True)
            show(g)
    """
    acts = []
    if utils.isSequence(inputobj):
        flist = inputobj
    else:
        import glob
        flist = sorted(glob.glob(inputobj))

    for fod in flist:

        if os.path.isfile(fod): ### it's a file

            a = _load_file(fod, c, alpha, threshold, spacing, unpack)
            acts.append(a)

        elif os.path.isdir(fod):### it's a directory or DICOM
            flist = os.listdir(fod)
            if '.dcm' in flist[0]: ### it's DICOM
                reader = vtk.vtkDICOMImageReader()
                reader.SetDirectoryName(fod)
                reader.Update()
                image = reader.GetOutput()
                if len(spacing) == 3:
                    image.SetSpacing(spacing[0], spacing[1], spacing[2])
                if threshold is False:
                    if c is None and alpha == 1:
                        c = ['b','lb','lg','y','r'] # good for blackboard background
                        alpha = (0.0, 0.0, 0.2, 0.4, 0.8, 1)
                        #c = ['lb','db','dg','dr']  # good for white backgr
                        #alpha = (0.0, 0.0, 0.2, 0.6, 0.8, 1)
                    actor = Volume(image, c, alpha)
                else:
                    actor = Volume(image).isosurface(threshold=threshold)
                    actor.color(c).alpha(alpha)
                acts.append(actor)
            else: ### it's a normal directory
                utils.humansort(flist)
                for ifile in flist:
                    a = _load_file(fod+'/'+ifile, c, alpha, threshold, spacing, unpack)
                    acts.append(a)
        else:
            colors.printc("~times Error in load(): cannot find", fod, c=1)

    if len(acts) == 1:
        if not acts[0]:
            colors.printc("~times Error in load(): cannot load", inputobj, c=1)
        settings.collectable_actors.append(acts[0])
        return acts[0]
    elif len(acts) == 0:
        colors.printc("~times Error in load(): cannot load", inputobj, c=1)
        return None
    else:
        settings.collectable_actors += acts
        return acts
Beispiel #2
0
def loadNumpy(inobj):
    import numpy as np

    if isinstance(inobj, str):
        data = np.load(inobj, allow_pickle=True, encoding='latin1').flatten()[0]
    else:
        data = inobj

    def loadcommon(obj, d):
        keys = d.keys()
        if 'time' in keys: obj.time(d['time'])
        if 'transform' in keys and len(d['transform']) == 4:
            vm = vtk.vtkMatrix4x4()
            for i in [0, 1, 2, 3]:
               for j in [0, 1, 2, 3]:
                   vm.SetElement(i, j, d['transform'][i,j])
            obj.setTransform(vm)
        elif 'position' in keys:
            obj.pos(d['position'])
        if hasattr(obj, 'GetProperty'):
            prp = obj.GetProperty()
            if 'ambient' in keys: prp.SetAmbient(d['ambient'])
            if 'diffuse' in keys: prp.SetDiffuse(d['diffuse'])

    ##################
    def _buildactor(d):
        vertices = d['points']
        cells = None
        lines = None
        keys = d.keys()
        if 'cells' in keys:
            cells = d['cells']
        if 'lines' in keys:
            lines = d['lines']

        poly = utils.buildPolyData(vertices, cells, lines)
        act = Actor(poly)
        loadcommon(act, d)

        act.mapper.ScalarVisibilityOff()
        if 'celldata' in keys:
            for csc, cscname in d['celldata']:
                act.addCellScalars(csc, cscname)
                if not 'normal' in cscname.lower():
                    act.scalars(cscname) # activate
        if 'pointdata' in keys:
            for psc, pscname in d['pointdata']:
                act.addPointScalars(psc, pscname)
                if not 'normal' in pscname.lower():
                    act.scalars(pscname) # activate

        prp = act.GetProperty()
        if 'specular' in keys:      prp.SetSpecular(d['specular'])
        if 'specularpower' in keys: prp.SetSpecularPower(d['specularpower'])
        if 'specularcolor' in keys: prp.SetSpecularColor(d['specularcolor'])
        if 'shading' in keys:       prp.SetInterpolation(d['shading'])
        if 'alpha' in keys:         prp.SetOpacity(d['alpha'])
        if 'opacity' in keys:       prp.SetOpacity(d['opacity']) # synomym
        if 'pointsize' in keys and d['pointsize']: prp.SetPointSize(d['pointsize'])
        if 'texture' in keys and d['texture']:     act.texture(d['texture'])
        if 'linewidth' in keys and d['linewidth']: act.lineWidth(d['linewidth'])
        if 'linecolor' in keys and d['linecolor']: act.lineColor(d['linecolor'])
        if 'representation' in keys: prp.SetRepresentation(d['representation'])
        if 'color' in keys and d['color']: act.color(d['color'])
        if 'backColor' in keys and d['backColor']: act.backColor(d['backColor'])

        if 'activedata' in keys and d['activedata'] is not None:
            act.mapper.ScalarVisibilityOn()
            if d['activedata'][0] == 'celldata':
                poly.GetCellData().SetActiveScalars(d['activedata'][1])
            if d['activedata'][0] == 'pointdata':
                poly.GetPointData().SetActiveScalars(d['activedata'][1])

        return act
        ##################

    objs = []
    for d in data:
        #print('loadNumpy type is:', d['type'])

        if 'mesh' == d['type']:
            objs.append(_buildactor(d))

        elif 'assembly' == d['type']:
            assacts = []
            for ad in d['actors']:
                assacts.append(_buildactor(ad))
            asse = Assembly(assacts)
            loadcommon(asse, d)
            objs.append(asse)

        elif 'image' == d['type']:
            shp = d['shape'][1], d['shape'][0]
            arr0 = d['array']
            rcv =   arr0[:,0].reshape(shp)
            gcv =   arr0[:,1].reshape(shp)
            bcv =   arr0[:,2].reshape(shp)
            arr = np.array([rcv, gcv, bcv])
            arr = np.swapaxes(arr, 0, 2)
            vimg = Picture(arr)
            loadcommon(vimg, d)
            objs.append(vimg)

        elif 'volume' == d['type']:
            vol = Volume(d['array'])
            loadcommon(vol, d)
            vol.jittering(d['jittering'])
            vol.mode(d['mode'])
            vol.color(d['color'])
            vol.alpha(d['alpha'])
            vol.alphaGradient(d['alphagrad'])
            objs.append(vol)

    if len(objs) == 1:
        return objs[0]
    elif len(objs) == 0:
        return None
    else:
        return objs
Beispiel #3
0
def _load_file(filename, c, alpha, threshold, spacing, unpack):
    fl = filename.lower()

    ################################################################# other formats:
    if fl.endswith(".xml") or fl.endswith(".xml.gz") or fl.endswith(".xdmf"):
        # Fenics tetrahedral file
        actor = loadDolfin(filename)
    elif fl.endswith(".neutral") or fl.endswith(
            ".neu"):  # neutral tetrahedral file
        actor = loadNeutral(filename)
    elif fl.endswith(".gmsh"):  # gmesh file
        actor = loadGmesh(filename)
    elif fl.endswith(".pcd"):  # PCL point-cloud format
        actor = loadPCD(filename)
        actor.GetProperty().SetPointSize(2)
    elif fl.endswith(".off"):
        actor = loadOFF(filename)
    elif fl.endswith(".3ds"):  # 3ds format
        actor = load3DS(filename)

        ################################################################# volumetric:
    elif fl.endswith(".tif") or fl.endswith(".slc") or fl.endswith(".vti") \
        or fl.endswith(".mhd") or fl.endswith(".nrrd") or fl.endswith(".nii"):
        img = loadImageData(filename, spacing)
        if threshold is False:
            if c is None and alpha == 1:
                c = ['b', 'lb', 'lg', 'y',
                     'r']  # good for blackboard background
                alpha = (0.0, 0.0, 0.2, 0.4, 0.8, 1)
            actor = Volume(img, c, alpha)
        else:
            actor = isosurface(img, threshold=threshold)
            actor.color(c).alpha(alpha)

        ################################################################# 2D images:
    elif fl.endswith(".png") or fl.endswith(".jpg") or fl.endswith(
            ".bmp") or fl.endswith(".jpeg"):
        if ".png" in fl:
            picr = vtk.vtkPNGReader()
        elif ".jpg" in fl or ".jpeg" in fl:
            picr = vtk.vtkJPEGReader()
        elif ".bmp" in fl:
            picr = vtk.vtkBMPReader()
        picr.SetFileName(filename)
        picr.Update()
        actor = Image()  # object derived from vtk.vtkImageActor()
        actor.SetInputData(picr.GetOutput())
        if alpha is None:
            alpha = 1
        actor.SetOpacity(alpha)

        ################################################################# multiblock:
    elif fl.endswith(".vtm") or fl.endswith(".vtmb"):
        read = vtk.vtkXMLMultiBlockDataReader()
        read.SetFileName(filename)
        read.Update()
        mb = read.GetOutput()
        if unpack:
            acts = []
            for i in range(mb.GetNumberOfBlocks()):
                b = mb.GetBlock(i)
                if isinstance(b,
                              (vtk.vtkPolyData, vtk.vtkImageData,
                               vtk.vtkUnstructuredGrid, vtk.vtkStructuredGrid,
                               vtk.vtkRectilinearGrid)):
                    acts.append(b)
            return acts
        else:
            return mb

    elif fl.endswith(".geojson") or fl.endswith(".geojson.gz"):
        return loadGeoJSON(fl)

        ################################################################# polygonal mesh:
    else:
        if fl.endswith(".vtk"):  # read all legacy vtk types

            #output can be:
            # PolyData, StructuredGrid, StructuredPoints, UnstructuredGrid, RectilinearGrid
            reader = vtk.vtkDataSetReader()
            reader.ReadAllScalarsOn()
            reader.ReadAllVectorsOn()
            reader.ReadAllTensorsOn()
            reader.ReadAllFieldsOn()
            reader.ReadAllNormalsOn()
            reader.ReadAllColorScalarsOn()

        elif fl.endswith(".ply"):
            reader = vtk.vtkPLYReader()
        elif fl.endswith(".obj"):
            reader = vtk.vtkOBJReader()
        elif fl.endswith(".stl"):
            reader = vtk.vtkSTLReader()
        elif fl.endswith(".byu") or fl.endswith(".g"):
            reader = vtk.vtkBYUReader()
        elif fl.endswith(".foam"):  # OpenFoam
            reader = vtk.vtkOpenFOAMReader()
        elif fl.endswith(".pvd"):
            reader = vtk.vtkXMLGenericDataObjectReader()
        elif fl.endswith(".vtp"):
            reader = vtk.vtkXMLPolyDataReader()
        elif fl.endswith(".vts"):
            reader = vtk.vtkXMLStructuredGridReader()
        elif fl.endswith(".vtu"):
            reader = vtk.vtkXMLUnstructuredGridReader()
        elif fl.endswith(".vtr"):
            reader = vtk.vtkXMLRectilinearGridReader()
        elif fl.endswith(".pvtk"):
            reader = vtk.vtkPDataSetReader()
        elif fl.endswith(".pvtr"):
            reader = vtk.vtkXMLPRectilinearGridReader()
        elif fl.endswith("pvtu"):
            reader = vtk.vtkXMLPUnstructuredGridReader()
        elif fl.endswith(".txt") or fl.endswith(".xyz"):
            reader = vtk.vtkParticleReader()  # (format is x, y, z, scalar)
        elif fl.endswith(".facet"):
            reader = vtk.vtkFacetReader()
        else:
            return None

        reader.SetFileName(filename)
        reader.Update()
        routput = reader.GetOutput()

        if not routput:
            colors.printc("~noentry Unable to load", filename, c=1)
            return None

        actor = Actor(routput, c, alpha)
        if fl.endswith(".txt") or fl.endswith(".xyz"):
            actor.GetProperty().SetPointSize(4)

    actor.filename = filename
    return actor