Example #1
0
def show_predict(predict1, predict2, pts):
    """
    显示预测结果
    @predict1: 牙齿部分
    @predict2: 牙龈部分
    @pts: 牙龈线点
    return: None
    """
    a = load(predict1).c(('blue'))
    b = load(predict2).c(('magenta'))
    c = load(pts).pointSize(10).c(('green'))

    show(a, b, c)
Example #2
0
def exe_convert(args):

    allowedexts = [
        'vtk', 'vtp', 'vtu', 'vts', 'npy', 'ply', 'stl', 'obj', 'byu', 'xml',
        'vti', 'tif', 'mhd', 'xml'
    ]

    humansort(args.convert)
    nfiles = len(args.convert)
    if nfiles == 0:
        sys.exit()

    target_ext = args.to.lower()

    if target_ext not in allowedexts:
        printc('Sorry target cannot be',
               target_ext,
               '\nMust be',
               allowedexts,
               c=1)
        sys.exit()

    for f in args.convert:
        source_ext = f.split('.')[-1]

        if target_ext == source_ext:
            continue

        a = load(f)
        newf = f.replace("." + source_ext, "") + "." + target_ext
        a.write(newf, binary=True)
Example #3
0
    def load_cached_neuron(self, neuron_name, _params):
        if not self._check_neuron_mesh_cached(neuron_name):
            return None

        # Check if params are the same as when cached
        cached_params = load_yaml(self.get_cache_params_filename(neuron_name))
        if len(cached_params) != len(_params):
            changed = cached_params.values()
        else:
            changed = {v for k, v in _params.items() if v != cached_params[k]}
        if changed:
            return None

        # Load neurites
        neurites = [
            "soma",
            "axon",
            "apical_dendrites",
            "basal_dendrites",
            "whole_neuron",
        ]
        loaded = {
            nn: load(fp)
            for nn, fp in zip(neurites, self.get_cache_filenames(neuron_name))
        }

        for nn, act in loaded.items():
            if len(act.points()) == 0:
                loaded[nn] = None

        return loaded
Example #4
0
def stl_2_obj_by_vedo(stl_path, file_out_path):
    """
    stl model convert to obj model
    @objct: stl model path
    @file_out_path: obj保存地址
    """
    from vedo import load
    objct = load(stl_path)
    fr = file_out_path.lower()

    assert fr.endswith(".obj"), "fileoutput 需以obj为后缀"
    outF = open(file_out_path, "w")
    outF.write('# OBJ file format with ext .obj\n')
    outF.write('# File generated by vedo\n')

    for p in objct.points():
        # outF.write("v {:.5g} {:.5g} {:.5g}\n".format(*p))
        outF.write("v {:.10f} {:.10f} {:.10f}\n".format(*p))

    for i, f in enumerate(objct.faces()):
        fs = ''
        for fi in f:
            fs += " {:d}".format(fi + 1)
        outF.write('f' + fs + '\n')

    for l in objct.lines():
        ls = ''
        for li in l:
            ls += str(li + 1) + " "
        outF.write('l ' + ls + '\n')

    outF.close()
    return objct
Example #5
0
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.setupUi(self)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.vtkLayout.addWidget(self.vtkWidget)

        self.plt = Plotter(qtWidget=self.vtkWidget, axes=1)

        self.plt += load(datadir + 'shark.ply').c('cyan')

        self.plt.show(interactorStyle=0)
    def FinalizeSolutionStep(self):
        super().FinalizeSolutionStep()
        if self.timestep > 1.5:
            if self.timestep == 2:
                self.a_mesh = vedo.load(
                    f'./vtk_output/VISUALIZE_HROM_0_{self.timestep}.vtk'
                ).tomesh(fill=True, shrink=1)
                displs = self.a_mesh.getPointArray("DISPLACEMENT")

            if self.timestep > 2:
                b_mesh = vedo.load(
                    f'./vtk_output/VISUALIZE_HROM_0_{self.timestep}.vtk'
                ).tomesh(fill=True, shrink=1)
                newpoints = b_mesh.points()
                displs = b_mesh.getPointArray("DISPLACEMENT")
                self.a_mesh.points(newpoints + displs)

            self.a_mesh.pointColors(vedo.mag(displs),
                                    cmap='jet',
                                    vmin=0,
                                    vmax=0.009).addScalarBar()
            self.a_mesh.show(axes=1, viewup='z')
        self.timestep += 1
Example #7
0
    def download_and_write_mesh(self, acronym, obj_path):
        print(f"Downloading mesh data for {acronym}")
        path = self.structures.loc[self.structures.acronym ==
                                   acronym].obj_path.values[0]
        url = f"{self._url_paths['data']}/{path}"

        # download and write .obj
        mesh_data = request(url).content.decode("utf-8").split("\n")
        with open(obj_path, "w") as f:
            for md in mesh_data:
                f.write(f"{md}\n")
            f.close()

        # return the vtk actor
        return load(obj_path)
Example #8
0
def exe_info(args):
    for i in range(2, len(sys.argv)):
        file = sys.argv[i]
        try:
            A = load(file)
            if isinstance(A, np.ndarray):
                printInfo(A)
            elif isSequence(A):
                for a in A:
                    printInfo(a)
            else:
                printInfo(A)
        except:
            printc("Could not load:", file, "skip.", c="r")

    printc("_" * 65, bold=0)
    printc("vedo version      :", __version__, invert=1, end='   ')
    printc("https://vedo.embl.es", underline=1, italic=1)
    printc("vtk version       :", vtk.vtkVersion().GetVTKVersion())
    printc("python version    :", sys.version.replace("\n", ""))
    printc("python interpreter:", sys.executable)
    printc("vedo installation :", settings.installdir)
    try:
        import platform
        printc("system            :", platform.system(), platform.release(),
               os.name, platform.machine())
    except:
        pass
    try:
        import k3d
        printc("k3d version       :", k3d.__version__, bold=0, dim=1)
    except:
        pass
    try:
        import ipyvtk_simple
        printc("ipyvtk version    :", ipyvtk_simple.__version__, bold=0, dim=1)
    except:
        pass
    try:
        import itkwidgets
        printc("itkwidgets version:", itkwidgets.__version__, bold=0, dim=1)
    except:
        pass
    try:
        import panel
        printc("panel version     :", panel.__version__, bold=0, dim=1)
    except:
        pass
Example #9
0
def load_mesh_from_file(filepath, *args, **kwargs):
    """	
    Load a a mesh or volume from files like .obj, .stl, ...

    :param filepath: path to file
    :param **kwargs: 

    """
    actor = load(str(filepath))
    color = kwargs.pop("color", None)
    alpha = kwargs.pop("alpha", None)

    if color is not None:
        actor.c(color)
    if alpha is not None:
        actor.alpha(alpha)

    return actor
Example #10
0
    def _get_structure_mesh(self, acronym, **kwargs):
        """
            Get's the mesh for a brainregion, for this atlas it's just for
            getting/making the root mesh

        """
        if acronym != "root":
            raise ValueError(
                f"The atlas {self.atlas_name} only has one structure mesh: root. Argument {acronym} is not valid"
            )

        objpath = os.path.join(self.data_folder, "objs_smoothed", "root2.obj")
        if not os.path.isfile(objpath):
            root = self._make_root(objpath)
        else:
            root = load(objpath)

        root.c(ROOT_COLOR).alpha(ROOT_ALPHA)

        return root
def create_atlas(level):

    if level == 'high':
        MESH_PATH = os.path.join(DATA_PATH, 'atlas_data', atlas_name, 'mesh',
                                 '0.9')
    else:
        MESH_PATH = os.path.join(DATA_PATH, 'atlas_data', atlas_name, 'mesh',
                                 '0.1')

    sqlController = SqlController('MD589')
    structures = sqlController.get_structures_list()

    acts = []
    for structure in tqdm(structures):
        filepath = os.path.join(MESH_PATH, f'{structure}.stl')
        if os.path.exists(filepath):
            act = load(filepath)
            color = sqlController.get_structure_color_rgb(structure)
            act.color(color)
            acts.append(act)

    show(acts)
Example #12
0
"""Create slicers for multiple datasets"""
from vedo import Plotter, Text2D, load, printc, datadir

volumes = load(
    [datadir + 'vase.vti', datadir + 'embryo.slc', datadir + 'head.vti'])

cmaps = ['hot_r', 'gist_ncar_r', 'bone_r']
alphas = [0, 0, 0.15, 0, 0]  # transparency of the grey volume
sliderstart, sliderstop = [0.025, 0.04], [0.025, 0.4]  # slider positioning


######################################################################
def slicerfunc(index, data):
    vol = data.mode(1).c('k').alpha(alphas)
    dims = vol.dimensions()
    box = vol.box().alpha(0.5)
    vmin, vmax = vol.scalarRange()
    msh = vol.zSlice(0).pointColors(cmap=cmaps[index], vmin=vmin, vmax=vmax)
    sb = msh.lighting('off').addScalarBar3D()
    zb = vol.zbounds()
    visibles = [msh]
    txt = Text2D('..' + data.filename[-30:], font='MonospaceTypewriter')
    plt.show(vol, msh, sb, box, txt, at=index, interactorStyle=6)

    def func(widget, event):
        i = int(widget.GetRepresentation().GetValue())
        plt.renderer = widget.GetCurrentRenderer()
        plt.resetcam = False
        msh = vol.zSlice(i).lighting('off')
        msh.pointColors(cmap=cmaps[index], vmin=vmin, vmax=vmax)
        plt.remove(visibles[0], render=False)
Example #13
0
def exe_eog(args):
    # print("EOG emulator")
    settings.immediateRendering = False
    settings.useParallelProjection = True
    settings.enableDefaultMouseCallbacks = False
    settings.enableDefaultKeyboardCallbacks = False

    if args.background == "":
        args.background = "white"

    if args.background_grad:
        args.background_grad = getColor(args.background_grad)

    files = []
    for s in sys.argv:
        if '--' in s or s.endswith('.py') or s.endswith('vedo'):
            continue
        if s.endswith('.gif'):
            continue
        files.append(s)

    def vfunc(event):
        # print(event.keyPressed)
        for p in pics:
            if event.keyPressed == "r":
                p.window(win).level(lev)
            elif event.keyPressed == "Up":
                p.level(p.level() + 10)
            elif event.keyPressed == "Down":
                p.level(p.level() - 10)
            if event.keyPressed == "Right":
                p.window(p.window() + 10)
            elif event.keyPressed == "Down":
                p.window(p.window() - 10)
            elif event.keyPressed == "m":
                p.mirror()
            elif event.keyPressed == "t":
                p.rotate(90)
            elif event.keyPressed == "k":
                p.enhance()
            elif event.keyPressed == "s":
                p.smooth(sigma=1)
            elif event.keyPressed == "S":
                ahl = plt.hoverLegends[-1]
                plt.remove(ahl)
                plt.screenshot()  # writer
                printc("Picture saved as screenshot.png")
                plt.add(ahl, render=False)
                return
            elif event.keyPressed == "h":
                printc('---------------------------------------------')
                printc('Press:')
                printc('  up/down     to modify level (or drag mouse)')
                printc('  left/right  to modify window')
                printc('  m           to mirror image')
                printc('  t           to rotate image by 90 deg')
                printc('  k           to enhance b&w image')
                printc('  s           to apply gaussian smoothing')
                printc('  S           to save image as png')
                printc('---------------------------------------------')

            plt.render()

    pics = load(files)
    if isinstance(pics, Picture):
        pics = [pics]
    if pics is None:
        return
    n = len(pics)
    pic = pics[0]
    if pic is None:
        printc("Could not load image.", c='r')
        return
    lev, win = pic.level(), pic.window()

    if n > 1:

        plt = Plotter(N=n,
                      sharecam=True,
                      bg=args.background,
                      bg2=args.background_grad)
        plt.addCallback('key press', vfunc)
        for i in range(n):
            p = pics[i].pickable(True)
            pos = [-p.shape[0] / 2, -p.shape[1] / 2, 0]
            p.pos(pos)
            plt.addHoverLegend(at=i, c='k8', bg='k2', alpha=0.4)
            plt.show(p, axes=0, at=i, mode='image')
        plt.show(interactive=False)
        plt.resetCamera(xypad=0.05)
        plt.interactor.Start()

    else:

        shape = pic.shape
        if shape[0] > 1500:
            shape[1] = shape[1] / shape[0] * 1500
            shape[0] = 1500

        if shape[1] > 1200:
            shape[0] = shape[0] / shape[1] * 1200
            shape[1] = 1200

        plt = Plotter(title=files[0],
                      size=shape,
                      bg=args.background,
                      bg2=args.background_grad)
        plt.addCallback('key press', vfunc)
        plt.addHoverLegend(c='k8', bg='k2', alpha=0.4)
        plt.show(pic, mode='image', interactive=False)
        plt.resetCamera(xypad=0.0)
        plt.interactor.Start()

    plt.close()
Example #14
0
"""Use sliders to slice volume
Click button to change colormap"""
from vedo import dataurl, load, show, Text2D
from vedo.applications import SlicerPlotter

filename = dataurl + 'embryo.slc'
#filename = dataurl+'embryo.tif'
#filename = dataurl+'vase.vti'

vol = load(filename)  #.printInfo()

plt = SlicerPlotter(
    vol,
    bg='white',
    bg2='lightblue',
    cmaps=("gist_ncar_r", "jet", "Spectral_r", "hot_r", "bone_r"),
    useSlider3D=False,
)

#Can now add any other object to the Plotter scene:
#plt += Text2D('some message', font='arial')

plt.show().close()
Example #15
0
"""Read structured grid data and show
the associated vector and scalar fields
"""
from vedo import load, datadir, Arrows, show

g = load(datadir+'structgrid.vts').printInfo()

coords = g.points()
vects  = g.getPointArray('Momentum')/600 # printInfo gives the list
print('numpy array shapes are:', coords.shape, vects.shape)

# build arrows from starting points to endpoints, with colormap
arrows = Arrows(coords-vects, coords+vects, c='hot_r')

g.pointColors('Density').lineWidth(0.1).alpha(0.3)
#g.color('grey').alpha(0.3)

show(g, arrows, __doc__, axes=9) # axes type 9 is a simple box
Example #16
0
"""Insert 2D and 3D scalarbars
in the rendering scene"""
from vedo import load, dataurl, show

shape = load(dataurl + "lamp.vtk")

ms = []
cmaps = ("jet", "PuOr", "viridis")
for i in range(3):
    s = shape.clone(deep=False).pos(0, i * 2.2, 0)

    # colorize mesh
    scals = s.points()[:, 2]
    s.cmap(cmaps[i], scals)

    ms.append(s)

# add 2D scalar bar to first mesh
ms[0].addScalarBar(title="my scalarbar\nnumber #0")  #2D

# add 3D scalar bars
ms[1].addScalarBar3D(c="k", title="scalarbar #1", sy=3)

sc = ms[2].addScalarBar3D(
    pos=(1, 0, -5),
    c="k",
    sy=2.8,  # change y-size
    title="A viridis 3D\nscalarbar to play with",
    titleFont='Quikhand',
    titleXOffset=-2,  # offset of labels
    titleSize=1.5)
Example #17
0
# Please install pyshtools to run this example
# Follow instructions at https://shtools.oca.eu/shtools
import pyshtools

from scipy.interpolate import griddata
from vedo import Points, load, mag, show, spher2cart, datadir
print(__doc__)

#############################################################
lmax = 10  # maximum degree of the spherical harm. expansion
N = 50  # number of grid intervals on the unit sphere
rmax = 1.5  # line length
x0 = [0, 0, 0]  # set object at this position
#############################################################

shape = load(datadir + 'apple.ply').normalize().pos(x0).lineWidth(0.1)

show(shape, at=0, N=2, axes=dict(zxGrid=False))

############################################################
# cast rays from the center and find intersections
agrid, pts = [], []
for th in np.linspace(0, np.pi, N, endpoint=False):
    lats = []
    for ph in np.linspace(0, 2 * np.pi, N, endpoint=False):
        p = spher2cart(rmax, th, ph)
        intersections = shape.intersectWithLine([0, 0, 0], p)
        if len(intersections):
            value = mag(intersections[0])
            lats.append(value)
            pts.append(intersections[0])
Example #18
0
"""Make a static 2D copy of a mesh
and place it in the rendering window"""
from vedo import load, dataurl, show

s = load(dataurl + 'man.vtk').rotateZ(20).rotateX(-70).scale(0.2).c(
    'darkgreen', 0.3)

# Make a 2D snapshot of a 3D mesh
# The coordinate system options are
#     0. Displays
#     1. Normalized Display
#     2. Viewport (origin is the bottom-left corner of the window)
#     3. Normalized Viewport
#     4. View (origin is the center of the window)
#     5. World (anchor the 2d image to mesh)
# (returns a vtkActor2D)

s2d = s.clone2D(pos=[0.4, 0.4], coordsys=4, c='r', alpha=1)

show(s, s2d, __doc__, axes=1)
Example #19
0
"""Read structured grid data and show
the associated vector and scalar fields
"""
from vedo import load, dataurl, Arrows, show

g = load(dataurl + 'structgrid.vts')  #.printInfo()

coords = g.points()
vects = g.getPointArray('Momentum') / 600  # printInfo gives the list
print('numpy array shapes are:', coords.shape, vects.shape)

# build arrows from starting points to endpoints, with colormap
arrows = Arrows(coords - vects, coords + vects, c='hot_r')

g.cmap('jet', input_array='Density').lineWidth(0.1).alpha(0.3)

show(g, arrows, __doc__, axes=7, viewup='z')
Example #20
0
"""Custom color and transparency maps for Volumes"""
from vedo import load, dataurl, show
from vedo.pyplot import cornerHistogram

# Build a Volume object.
# A set of color/transparency values - of any length - can be passed
# to define the transfer function in the range of the scalar.
#  E.g.: setting alpha=[0, 0, 0, 1, 0, 0, 0] would make visible
#  only voxels with value close to center of the range (see histogram).
vol = load(dataurl+'embryo.slc') # returns a Volume
vol.color([(0,"green"), (49,"green"),
           (50,"blue"), (109,"blue"),
           (110,"red"), (180,"red"),
          ])
# vol.mode('max-projection')
vol.alpha([0., 1.])
vol.alphaUnit(8) # absorption unit, higher factors = higher transparency
vol.addScalarBar3D(title='color~\dot~alpha transfer function', c='k')

ch = cornerHistogram(vol, logscale=True, pos='bottom-left')

# show both Volume and Mesh
show(vol, ch, __doc__, axes=1, zoom=1.2)
Example #21
0
"""Make a 2D copy of a Mesh and place it in the 3D scene"""
from vedo import load, datadir, show

s = load(datadir + 'man.vtk').rotateZ(20).rotateX(-70).scale(0.2)
s.c('darkgreen').alpha(0.3)

# Make a sort of 2D snapshot of the mesh (return vtkActor2D)
# The coordinate system options are
#     0. Displays
#     1. Normalized Display
#     2. Viewport (origin is the bottom-left corner of the window)
#     3. Normalized Viewport
#     4. View (origin is the center of the window)
#     5. World (anchor the 2d image to mesh)
s2d = s.clone2D(pos=[0.4, 0.4], coordsys=4, c='r', alpha=1)

show(s, s2d, __doc__, axes=1)
Example #22
0
"""Elliptic Fourier Descriptors
parametrizing a closed countour (in red)"""
import vedo, pyefd

shapes = vedo.load(vedo.dataurl+'timecourse1d.npy')

sh = shapes[55]
sr = vedo.Line(sh).mirror('x').reverse()
sm = vedo.merge(sh, sr).c('red5').lw(3)
pts = sm.points()[:,(0,1)]

rlines = []
for order in range(5,30, 5):
    coeffs = pyefd.elliptic_fourier_descriptors(pts, order=order, normalize=False)
    a0, c0 = pyefd.calculate_dc_coefficients(pts)
    rpts = pyefd.reconstruct_contour(coeffs, locus=(a0,c0), num_points=400)
    color = vedo.colorMap(order, "Blues", 5,30)
    rline = vedo.Line(rpts).lw(3).c(color)
    rlines.append(rline)

sm.z(0.1) # move it on top so it's visible
vedo.show(sm, *rlines, __doc__, axes=1, bg='k', size=(1190, 630), zoom=1.8)
Example #23
0
def draw_scene(args):

    nfiles = len(args.files)
    if nfiles == 0:
        printc("No input files.", c='r')
        return
    humansort(args.files)

    wsize = "auto"
    if args.full_screen:
        wsize = "full"

    if args.ray_cast_mode:
        if args.background == "":
            args.background = "bb"

    if args.background == "":
        args.background = "white"

    if args.background_grad:
        args.background_grad = getColor(args.background_grad)

    if nfiles == 1 and args.files[0].endswith(".gif"):  ###can be improved
        frames = load(args.files[0])
        applications.Browser(frames).show(bg=args.background,
                                          bg2=args.background_grad)
        return  ##########################################################

    if args.scrolling_mode:
        args.multirenderer_mode = False

    N = None
    if args.multirenderer_mode:
        if nfiles < 201:
            N = nfiles
        if nfiles > 200:
            printc("Warning: option '-n' allows a maximum of 200 files", c=1)
            printc("         you are trying to load ",
                   nfiles,
                   " files.\n",
                   c=1)
            N = 200
        vp = Plotter(size=wsize,
                     N=N,
                     bg=args.background,
                     bg2=args.background_grad)
        settings.immediateRendering = False
        vp.axes = args.axes_type
        for i in range(N):
            vp.addHoverLegend(at=i)
        if args.axes_type == 4 or args.axes_type == 5:
            vp.axes = 0
    else:
        N = nfiles
        vp = Plotter(size=wsize, bg=args.background, bg2=args.background_grad)
        vp.axes = args.axes_type
        vp.addHoverLegend()

    vp.sharecam = not args.no_camera_share

    wire = False
    if args.wireframe:
        wire = True

    ##########################################################
    # special case of SLC/TIFF volumes with -g option
    if args.ray_cast_mode:
        # print('DEBUG special case of SLC/TIFF volumes with -g option')

        vol = io.load(args.files[0], force=args.reload)

        if not isinstance(vol, Volume):
            printc("Type Error: expected a Volume but loaded",
                   type(vol),
                   'object.',
                   c=1)
            return

        sp = vol.spacing()
        vol.spacing([
            sp[0] * args.x_spacing, sp[1] * args.y_spacing,
            sp[2] * args.z_spacing
        ])
        vol.mode(int(args.mode)).color(args.cmap).jittering(True)
        # if args.lighting !='default':
        vol.lighting(args.lighting).jittering(True)
        vp = applications.RayCastPlotter(vol)
        vp.show(viewup="z", interactive=True)
        vp.sliders[0][0].SetEnabled(False)
        vp.sliders[1][0].SetEnabled(False)
        vp.sliders[2][0].SetEnabled(False)
        return

    ##########################################################
    # special case of SLC/TIFF/DICOM volumes with --slicer option
    elif args.slicer:
        # print('DEBUG special case of SLC/TIFF/DICOM volumes with --slicer option')

        useSlider3D = False
        if args.axes_type == 4:
            args.axes_type = 1
        elif args.axes_type == 3:
            args.axes_type = 1
            useSlider3D = True

        vol = io.load(args.files[0], force=args.reload)

        sp = vol.spacing()
        vol.spacing([
            sp[0] * args.x_spacing, sp[1] * args.y_spacing,
            sp[2] * args.z_spacing
        ])

        settings.plotter_instance = None  # reset

        plt = applications.SlicerPlotter(
            vol,
            bg='white',
            bg2='lb',
            useSlider3D=useSlider3D,
            cmaps=[args.cmap, "Spectral_r", "hot_r", "bone_r", "gist_ncar_r"],
            alpha=args.alpha,
            axes=args.axes_type,
            clamp=True,
            size=(1000, 800),
        )
        plt.show()
        return

    ########################################################################
    elif args.edit:
        # print('edit mode for meshes and pointclouds')
        settings.plotter_instance = None  # reset
        settings.useParallelProjection = True

        try:
            m = Mesh(args.files[0], alpha=args.alpha / 2, c=args.color)
        except AttributeError:
            printc(
                "In edit mode, input file must be a point cloud or polygonal mesh. Exit.",
                c='r')
            return

        vp = applications.FreeHandCutPlotter(m, splined=True)
        vp.addHoverLegend()
        if not args.background_grad:
            args.background_grad = None
        vp.start(axes=1, bg=args.background, bg2=args.background_grad)

    ########################################################################
    elif args.slicer2d:
        # print('DEBUG special case of SLC/TIFF/DICOM volumes with --slicer2d option')
        vol = io.load(args.files[0], force=args.reload)
        if not vol:
            return
        vol.cmap('bone_r')
        sp = vol.spacing()
        vol.spacing([
            sp[0] * args.x_spacing, sp[1] * args.y_spacing,
            sp[2] * args.z_spacing
        ])
        settings.plotter_instance = None  # reset
        plt = applications.Slicer2d(vol)
        plt.interactor.Start()
        return

    ########################################################################
    # normal mode for single VOXEL file with Isosurface Slider or LEGO mode
    elif nfiles == 1 and (".slc" in args.files[0].lower()
                          or ".vti" in args.files[0].lower()
                          or ".tif" in args.files[0].lower()
                          or ".mhd" in args.files[0].lower()
                          or ".nrrd" in args.files[0].lower()
                          or ".dem" in args.files[0].lower()):
        # print('DEBUG normal mode for single VOXEL file with Isosurface Slider or LEGO mode')
        vol = io.load(args.files[0], force=args.reload)
        sp = vol.spacing()
        vol.spacing([
            sp[0] * args.x_spacing, sp[1] * args.y_spacing,
            sp[2] * args.z_spacing
        ])
        if not args.color:
            args.color = 'gold'
        vp = applications.IsosurfaceBrowser(vol,
                                            lego=args.lego,
                                            c=args.color,
                                            cmap=args.cmap,
                                            delayed=args.lego)
        vp.show(zoom=args.zoom, viewup="z")
        return

    ########################################################################
    # NORMAL mode for single or multiple files, or multiren mode, or numpy scene
    elif nfiles == 1 or (not args.scrolling_mode):
        # print('DEBUG NORMAL mode for single or multiple files, or multiren mode')

        interactor_mode = 0
        if args.image:
            interactor_mode = 'image'

        ##########################################################
        # loading a full scene
        if ".npy" in args.files[0] or ".npz" in args.files[0] and nfiles == 1:

            objct = io.load(args.files[0], force=args.reload)

            if "Plotter" in str(type(objct)):  # loading a full scene
                objct.show(mode=interactor_mode)
                return
            else:  # loading a set of meshes
                vp.show(objct, mode=interactor_mode)
                return
        #########################################################

        ds = 0
        actors = []
        for i in range(N):
            f = args.files[i]

            colb = args.color
            if args.color is None and N > 1:
                colb = i

            actor = load(f, force=args.reload)

            if isinstance(actor, (TetMesh, UGrid)):
                actor = actor.tomesh().shrink(0.975).c(colb).alpha(args.alpha)

            if isinstance(actor, Mesh):
                actors.append(actor)
                actor.c(colb).alpha(args.alpha).wireframe(wire).lighting(
                    args.lighting)
                if args.flat:
                    actor.flat()
                else:
                    actor.phong()

                if i == 0 and args.texture_file:
                    actor.texture(args.texture_file)

                if args.point_size > 0:
                    try:
                        actor.GetProperty().SetPointSize(args.point_size)
                        actor.GetProperty().SetRepresentationToPoints()
                    except AttributeError:
                        pass

                if args.showedges:
                    try:
                        actor.GetProperty().SetEdgeVisibility(1)
                        actor.GetProperty().SetLineWidth(0.1)
                        actor.GetProperty().SetRepresentationToSurface()
                    except AttributeError:
                        pass
            else:
                actors.append(actor)

            if args.multirenderer_mode:
                try:
                    ds = actor.diagonalSize() * 3
                    vp.camera.SetClippingRange(0, ds)
                    vp.show(actor,
                            at=i,
                            interactive=False,
                            zoom=args.zoom,
                            mode=interactor_mode)
                    vp.actors = actors
                except AttributeError:
                    # wildcards in quotes make glob return actor as a list :(
                    printc(
                        "Please do not use wildcards within single or double quotes!",
                        c='r')

        if args.multirenderer_mode:
            vp.interactor.Start()

        else:

            # scene is empty
            if all(a is None for a in actors):
                printc("..could not load file(s). Quit.", c='r')
                return

            vp.show(actors,
                    interactive=True,
                    zoom=args.zoom,
                    mode=interactor_mode)
        return

    ########################################################################
    # scrolling mode  -s
    else:
        #print("DEBUG simple browser mode  -s")
        if vp.axes == 4:
            vp.axes = 1

        acts = vp.load(args.files, force=args.reload)
        for a in acts:
            if hasattr(a, 'c'):  #Picture doesnt have it
                a.c(args.color)
            a.alpha(args.alpha)

        applications.Browser(acts)
        vp.show(interactive=True, zoom=args.zoom)
Example #24
0
"""Load and render a 3D Volume

mode=0, composite rendering
mode=1, maximum-projection rendering"""
from vedo import datadir, load, show

vol1 = load(datadir + "vase.vti")

# can set colors and transparencies along the scalar range
# from minimum to maximum value. In this example voxels with
# the smallest value will be completely transparent (and white)
# while voxels with highest value of the scalar will get alpha=0.8
# and color will be=(0,0,1)
vol1.color(["white", "fuchsia", "dg", (0, 0, 1)])
#vol1.color('jet') # a matplotlib colormap name is also accepted
vol1.alpha([0.0, 0.2, 0.3, 0.8])

# a transparency for the GRADIENT of the scalar can also be set:
# in this case when the scalar is ~constant the gradient is ~zero
# and the voxel are made transparent:
vol1.alphaGradient([0.0, 0.5, 0.9])
vol1.addScalarBar3D(title='composite rendering', c='k').scale(0.8).x(20)

# mode = 1 is maximum-projection volume rendering
vol2 = load(datadir + "vase.vti").mode(1).addPos(60, 0, 0)
vol2.addScalarBar3D(title='maximum-projection', c='k').scale(0.8).x(160)

# show command creates and returns an instance of class Plotter
show(vol1, vol2, __doc__, axes=1)
Example #25
0
"""Read structured grid data and show
the associated vector and scalar fields
"""
from vedo import load, dataurl, Arrows, show

g = load(dataurl + 'structgrid.vts')

coords = g.points()
vects = g.getPointArray('Momentum') / 600  # printInfo gives the list
print('numpy array shapes are:', coords.shape, vects.shape)

# build arrows from starting points to endpoints, with colormap
arrows = Arrows(coords - vects, coords + vects, c='hot_r')

g.cmap('jet', input_array='Density').lineWidth(0.1).alpha(0.3)

show(g, arrows, __doc__, axes=7, viewup='z').close()
Example #26
0
from vedo import load, datadir, show

vol = load(datadir + 'embryo.slc').alpha([0, 0, 1]).c('hot_r')
#vol.addScalarBar(title='Volume', pos=(0.8,0.55))
vol.addScalarBar3D(title='Voxel intensity', c='k')

sl = vol.slicePlane(origin=vol.center(), normal=(0, 1, 1))

sl.pointColors(cmap='viridis') \
  .lighting('ambient') \
  .addScalarBar(title='Slice')

show(
    vol,
    sl,
    "Slice a Volume with an arbitrary plane",
    axes=1,
)