コード例 #1
2
ファイル: spine_view.py プロジェクト: crispamares/indyva
def read_vrml(rw, input_filename):    
    importer = vtk.vtkVRMLImporter()
    importer.SetFileName(input_filename)
    importer.Read()
    importer.SetRenderWindow(rw)
    importer.Update()

    rw.Render()
    
    ren = importer.GetRenderer()
    actors = ren.GetActors()
    actors.InitTraversal()
    actors_list = [actors.GetNextActor() 
        for _x in range(ren.GetNumberOfPropsRendered())]
    return actors_list, ren
コード例 #2
0
    def getPolyData(self):
        # VRML importer
        importer = vtk.vtkVRMLImporter()
        # WRL file to upload
        importer.SetFileName(self.filepath)
        # Read data
        importer.Read()

        self.polydata = vtk.vtkPolyData()
        append = vtk.vtkAppendPolyData()
        renActors = importer.GetRenderer().GetActors()
        renActors.InitTraversal()
        actor = renActors.GetNextActor()

        i = 0
        while (actor != None):
            actor.GetProperty().SetAmbientColor(i, 1 - i, 0.0)
            actor.GetProperty().SetAmbient(1)
            append.AddInputData(actor.GetMapper().GetInput())
            actor = renActors.GetNextActor()
            i += 0.05

        append.Update()
        self.polydata.DeepCopy(append.GetOutput())

        return self.polydata
コード例 #3
0
def main():
    filename = get_program_parameters()

    colors = vtk.vtkNamedColors()

    renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)

    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    # VRML Import
    importer = vtk.vtkVRMLImporter()
    importer.SetFileName(filename)
    importer.SetRenderWindow(render_window)
    importer.Update()

    actors = vtk.vtkActorCollection()
    actors = renderer.GetActors()
    print("There are", actors.GetNumberOfItems(), "actors")

    renderer.SetBackground(colors.GetColor3d("Burlywood"))
    render_window.SetSize(512, 512)
    render_window.Render()
    render_window_interactor.Start()
コード例 #4
0
def main():
    filename, actorname = get_program_parameters()
    print("Showing", actorname, "from", filename)

    renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)

    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    # VRML Import
    importer = vtk.vtkVRMLImporter()
    importer.SetFileName(filename)
    importer.Read()
    importer.SetRenderWindow(render_window)
    importer.Update()

    # ----------------------------------------------------------
    def_actor = importer.GetVRMLDEFObject(actorname)
    if def_actor is None:
        print("Cannot locate actor", actorname, "in", filename)
        # importer.Print()

    actor = vtk.vtkActor(actorname)
    color = {0.89, 0.81, 0.34}
    actor.GetProperty().SetColor(color)
    actor.GetProperty().SetRepresentationToWireframe()

    transform = vtk.vtkTransform()

    transform.Translate(actor.GetCenter()[0],
                        actor.GetCenter()[1],
                        actor.GetCenter()[2])
    # axes
    axes = vtk.vtkAxesActor()

    l = [0.0, 0.0, 0.0]
    l[0] = (actor.GetBounds()[1] - actor.GetBounds()[0]) * 1.5
    l[1] = (actor.GetBounds()[3] - actor.GetBounds()[2]) * 1.5
    l[2] = (actor.GetBounds()[5] - actor.GetBounds()[4]) * 1.5

    axes.SetTotalLength(l)
    axes.SetUserTransform(transform)
    renderer.AddActor(axes)

    named_colors = vtk.vtkNamedColors()
    renderer.SetBackground(named_colors.GetColor3d("Azure"))

    render_window.Render()
    render_window_interactor.Start()
コード例 #5
0
 def showVRML(self, fileName):
     vtk = self.vtk
     importer = vtk.vtkVRMLImporter()
     importer.SetFileName(fileName)
     importer.Read()
     ren = importer.GetRenderer()
     ren.SetBackground(0.1, 0.2, 0.4)
     ren.ResetCamera()
     w = self.winManager.newWindow(fileName)
     importer.SetRenderWindow(w.vtkWidget.GetRenderWindow())
     w.vtkWidget.GetRenderWindow().AddRenderer(ren)
     w.show()
     w.vtkWidget.Initialize()
     w.vtkWidget.Start()
     return w
コード例 #6
0
 def readVRML(self, filename=None):
     if filename is not None:
         self.filename = filename
     r = vtk.vtkVRMLImporter()
     r.SetFileName( self.filename )
     r.Update()
     actors = r.GetRenderer().GetActors()
     actors.InitTraversal()
     self.polydata = actors.GetNextActor().GetMapper().GetInput()
     
     if self.polydata.GetPoints()==None:
         raise IOError, 'file not loaded'
     else:
         self._loadPoints()
         self._loadTriangles()
コード例 #7
0
ファイル: utils3d.py プロジェクト: RasmusRPaulsen/Deep-MVLM
 def multi_read_surface(file_name):
     clean_name, file_extension = os.path.splitext(file_name)
     if file_extension == ".obj":
         obj_in = vtk.vtkOBJReader()
         obj_in.SetFileName(file_name)
         obj_in.Update()
         pd = obj_in.GetOutput()
         return pd
     elif file_extension == ".wrl":
         vrmlin = vtk.vtkVRMLImporter()
         vrmlin.SetFileName(file_name)
         vrmlin.Update()
         pd = vrmlin.GetRenderer().GetActors().GetLastActor().GetMapper(
         ).GetInput()
         return pd
     elif file_extension == ".vtk":
         pd_in = vtk.vtkPolyDataReader()
         pd_in.SetFileName(file_name)
         pd_in.Update()
         pd = pd_in.GetOutput()
         return pd
     elif file_extension == ".vtp":
         pd_in = vtk.vtkXMLPolyDataReader()
         pd_in.SetFileName(file_name)
         pd_in.Update()
         pd = pd_in.GetOutput()
         return pd
     elif file_extension == ".stl":
         pd_in = vtk.vtkSTLReader()
         pd_in.SetFileName(file_name)
         pd_in.Update()
         pd = pd_in.GetOutput()
         return pd
     elif file_extension == ".ply":
         pd_in = vtk.vtkPLYReader()
         pd_in.SetFileName(file_name)
         pd_in.Update()
         pd = pd_in.GetOutput()
         return pd
     else:
         print("Can not read files with extenstion", file_extension)
         return None
コード例 #8
0
    def load_object_3d(self, path, viewer_3d):
        generic_reader = vtkDataReader()
        generic_reader.SetFileName(path)

        if generic_reader.OpenVTKFile() and generic_reader.ReadHeader():
            if generic_reader.IsFileStructuredPoints():
                raise Exception("Cannot read VTK structured points")
            elif generic_reader.IsFilePolyData():
                reader = vtkPolyDataReader()
                reader.SetFileName(path)
                object_3d = Object3D(reader.GetOutput(), path)
            elif generic_reader.IsFileStructuredGrid():
                reader = vtkStructuredGridReader()
                reader.SetFileName(path)
                object_3d = Object3D(reader.GetOutput(), path)
            elif generic_reader.IsFileUnstructuredGrid():
                reader = vtkUnstructuredGridReader()
                reader.SetFileName(path)
                object_3d = Object3D(reader.GetOutput(), path)
            elif generic_reader.IsFileRectilinearGrid():
                reader = vtkRectilinearGridReader()
                reader.SetFileName(path)
                object_3d = Object3D(reader.GetOutput(), path)
            else:
                raise Exception("Cannot read VTK file containing type %i" %
                                generic_reader.GetFileType())
            viewer_3d.objects_3d.append(object_3d)
        else:
            importer = vtkVRMLImporter()
            importer.SetFileName(path)
            importer.Update()
            actors = importer.GetRenderer().GetActors()
            number_of_actors = actors.GetNumberOfItems()
            actors.InitTraversal()
            for i in range(number_of_actors):
                actor = actors.GetNextItem()
                object_3d = Object3D(path + ", %i" % i)
                object_3d.actor.SetProperty(actor.GetProperty())
                object_3d.actor.SetMapper(actor.GetMapper())
                viewer_3d.objects_3d.append(object_3d)
コード例 #9
0
ファイル: mmio.py プロジェクト: rickyspaceguy/meshmagick
def load_WRL(filename):
    """Loads VRML 2.0 mesh files.

    Parameters
    ----------
    filename: str
        name of the meh file on disk

    Returns
    -------
    vertices: ndarray
        numpy array of the coordinates of the mesh's nodes
    faces: ndarray
        numpy array of the faces' nodes connectivities
    """

    from vtk import vtkVRMLImporter
    import re

    _check_file(filename)

    # Checking version
    with open(filename, 'r') as f:
        line = f.readline()
        ver = re.search(r'#VRML\s+V(\d.\d)', line).group(1)
        if not ver == '2.0':
            raise NotImplementedError(
                'VRML loader only supports VRML 2.0 format (version %s given)'
                % ver)

    importer = vtkVRMLImporter()
    importer.SetFileName(filename)
    importer.Update()

    actors = importer.GetRenderer().GetActors()
    actors.InitTraversal()
    dataset = actors.GetNextActor().GetMapper().GetInput()

    return _dump_vtk(dataset)
コード例 #10
0
ファイル: wrml_read.py プロジェクト: Chen41284/Python
def vrml_read(filename):
    '''
    读取并显示vrml格式的文件
    filename:文件的路径
    '''
    colors = vtk.vtkNamedColors()
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()

    importer = vtk.vtkVRMLImporter()
    importer.SetFileName(filename)
    importer.SetRenderWindow(renderWindow)
    importer.Update()

    actors = renderer.GetActors()
    print("There are %d actors" % actors.GetNumberOfItems())

    renderer.SetBackground(colors.GetColor3d("Burlwood"))
    renderWindow.SetSize(512, 512)
    renderWindow.Render()
    renderWindowInteractor.Start()
コード例 #11
0
ファイル: VRMLImporter.py プロジェクト: sldion/DNACC
    def __init__ (self, renwin, file_name):        
        """Initializes the class given a vtkRenderWindow and a
        file_name."""
        debug ("In VRMLImporter::__init__ ()")
        self.file_name = file_name
        self.renwin = renwin
        orig_actors = self._get_actors (self.renwin)
        
        self.vrml_imp = vtk.vtkVRMLImporter ()
        self.vrml_imp.SetFileName (file_name)
        self.vrml_imp.SetRenderWindow (self.renwin)
        try:
            self.vrml_imp.ComputeNormalsOn ()
        except AttributeError:
            pass
        self.vrml_imp.Read ()
        self.renwin.Render ()
        final_actors = self._get_actors (self.renwin)

        self.actors = []
        for act in final_actors:
            if act not in orig_actors:
                self.actors.append (act)        
コード例 #12
0
ファイル: vtkio.py プロジェクト: hhy5277/vtkplotter
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

            if fod.endswith("wrl"):
                importer = vtk.vtkVRMLImporter()
                importer.SetFileName(fod)
                importer.Read()
                importer.Update()
                actors = importer.GetRenderer().GetActors(
                )  #vtkActorCollection
                actors.InitTraversal()
                for i in range(actors.GetNumberOfItems()):
                    act = actors.GetNextActor()
                    acts.append(act)
            else:
                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 = isosurface(image, 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)
        return acts[0]
    elif len(acts) == 0:
        colors.printc("~times Error in load(): cannot load", inputobj, c=1)
        return None
    else:
        return acts
コード例 #13
0
ファイル: base.py プロジェクト: HaoyangWang/menpo3d
def wrl_importer(filepath, asset=None, texture_resolver=None, **kwargs):
    """Allows importing VRML 2.0 meshes.

    Uses VTK and assumes that the first actor in the scene is the one
    that we want.

    Parameters
    ----------
    asset : `object`, optional
        An optional asset that may help with loading. This is unused for this
        implementation.
    texture_resolver : `callable`, optional
        A callable that recieves the mesh filepath and returns a single
        path to the texture to load.
    \**kwargs : `dict`, optional
        Any other keyword arguments.

    Returns
    -------
    shape : :map:`PointCloud` or subclass
        The correct shape for the given inputs.
    """
    import vtk
    from vtk.util.numpy_support import vtk_to_numpy

    vrml_importer = vtk.vtkVRMLImporter()
    vrml_importer.SetFileName(str(filepath))
    vrml_importer.Update()

    # Get the first actor.
    actors = vrml_importer.GetRenderer().GetActors()
    actors.InitTraversal()
    mapper = actors.GetNextActor().GetMapper()
    mapper_dataset = mapper.GetInput()

    if actors.GetNextActor():
        # There was more than one actor!
        warnings.warn('More than one actor was detected in the scene. Only '
                      'single scene actors are currently supported.')

    # Get the Data
    polydata = vtk.vtkPolyData.SafeDownCast(mapper_dataset)

    # We must have point data!
    points = vtk_to_numpy(polydata.GetPoints().GetData()).astype(np.float)

    trilist = vtk_ensure_trilist(polydata)

    texture = None
    if texture_resolver is not None:
        texture_path = texture_resolver(filepath)
        if texture_path is not None and texture_path.exists():
            texture = mio.import_image(texture_path)

    # Three different outcomes - either we have a textured mesh, a coloured
    # mesh or just a plain mesh. Let's try each in turn.

    # Textured
    tcoords = None
    try:
        tcoords = vtk_to_numpy(polydata.GetPointData().GetTCoords())
    except Exception:
        pass

    if isinstance(tcoords, np.ndarray) and tcoords.size == 0:
        tcoords = None

    # Colour-per-vertex
    try:
        colour_per_vertex = vtk_to_numpy(mapper.GetLookupTable().GetTable()) / 255.
    except Exception:
        pass

    if isinstance(colour_per_vertex, np.ndarray) and colour_per_vertex.size == 0:
        colour_per_vertex = None

    return _construct_shape_type(points, trilist, tcoords, texture,
                                 colour_per_vertex)
コード例 #14
0
ファイル: VRMLImporter.py プロジェクト: 0004c/VTK
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
importer = vtk.vtkVRMLImporter()
importer.SetRenderWindow(renWin)
importer.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/bot2.wrl")
importer.Read()
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
importer.GetRenderer().SetBackground(0.1,0.2,0.4)
importer.GetRenderWindow().SetSize(300,300)
#
# the importer created the renderer
renCollection = renWin.GetRenderers()
renCollection.InitTraversal()
ren = renCollection.GetNextItem()
#
# change view up to +z
#
ren.GetActiveCamera().SetPosition(-3.25303,3.46205,3.15906)
ren.GetActiveCamera().SetFocalPoint(0,0,0)
ren.GetActiveCamera().SetViewUp(0.564063,0.825024,-0.0341876)
#
# let the renderer compute good position and focal point
#
コード例 #15
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot

VTK_DATA_ROOT = vtkGetDataRoot()

ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
importer = vtk.vtkVRMLImporter()
importer.SetRenderWindow(renWin)
importer.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/bot2.wrl")
importer.Read()
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
importer.GetRenderer().SetBackground(0.1, 0.2, 0.4)
importer.GetRenderWindow().SetSize(300, 300)
#
# the importer created the renderer
renCollection = renWin.GetRenderers()
renCollection.InitTraversal()
ren = renCollection.GetNextItem()
#
# change view up to +z
#
ren.GetActiveCamera().SetPosition(-3.25303, 3.46205, 3.15906)
ren.GetActiveCamera().SetFocalPoint(0, 0, 0)
ren.GetActiveCamera().SetViewUp(0.564063, 0.825024, -0.0341876)
#
# let the renderer compute good position and focal point
コード例 #16
0
def process_file_bu_3dfe(config, file_name, output_dir):
    bu_3dfe_dir = config['preparedata']['raw_data_dir']
    base_name = os.path.basename(file_name)
    name_pd = bu_3dfe_dir + file_name + '_RAW.wrl'
    name_bmp = bu_3dfe_dir + file_name + '_F3D.bmp'
    name_lm = bu_3dfe_dir + file_name + '_RAW_84_LMS.txt'

    name_path = os.path.dirname(file_name)
    o_dir_image = output_dir + '/images/' + name_path + '/'
    o_dir_lm = output_dir + '/2D LM/' + name_path + '/'
    if not os.path.exists(o_dir_image):
        os.makedirs(o_dir_image)
    if not os.path.exists(o_dir_lm):
        os.makedirs(o_dir_lm)

    lock_file = o_dir_image + base_name + '.lock'

    if not os.path.isfile(name_pd):
        print(name_pd, ' could not read')
        return False
    if not os.path.isfile(name_bmp):
        print(name_bmp, ' could not read')
        return False
    if not os.path.isfile(name_lm):
        print(name_lm, ' could not read')
        return False
    if os.path.isfile(lock_file):
        print(file_name, ' is locked - skipping')
        return True
    create_lock_file(lock_file)
    print('Rendering ', file_name)

    win_size = config['data_loader']['args']['image_size']
    off_screen_rendering = config['preparedata']['off_screen_rendering']
    n_views = config['data_loader']['args']['n_views']
    slack = 5

    # Load Landmarks
    points = vtk.vtkPoints()
    lms = vtk.vtkPolyData()

    with open(name_lm) as f:
        for line in f:
            line = line.strip("/n")
            x, y, z = np.double(line.split(" "))
            points.InsertNextPoint(x, y, z)
    lms.SetPoints(points)
    del points

    vrmlin = vtk.vtkVRMLImporter()
    vrmlin.SetFileName(name_pd)
    vrmlin.Update()

    pd = vrmlin.GetRenderer().GetActors().GetLastActor().GetMapper().GetInput()
    pd.GetPointData().SetScalars(None)

    # Load texture
    texture_image = vtk.vtkBMPReader()
    texture_image.SetFileName(name_bmp)
    texture_image.Update()

    texture = vtk.vtkTexture()
    texture.SetInterpolate(1)
    texture.SetQualityTo32Bit()
    texture.SetInputConnection(texture_image.GetOutputPort())

    # Initialize Camera
    ren = vtk.vtkRenderer()
    ren.SetBackground(1, 1, 1)
    ren.GetActiveCamera().SetPosition(0, 0, 1)
    ren.GetActiveCamera().SetFocalPoint(0, 0, 0)
    ren.GetActiveCamera().SetViewUp(0, 1, 0)
    ren.GetActiveCamera().SetParallelProjection(1)

    # Initialize RenderWindow
    ren_win = vtk.vtkRenderWindow()
    ren_win.AddRenderer(ren)
    ren_win.SetSize(win_size, win_size)
    ren_win.SetOffScreenRendering(off_screen_rendering)

    # Initialize Transform
    t = vtk.vtkTransform()
    t.Identity()
    t.Update()

    # Transform (assuming only one mesh)
    trans = vtk.vtkTransformPolyDataFilter()
    trans.SetInputData(pd)
    trans.SetTransform(t)
    trans.Update()

    trans_lm = vtk.vtkTransformPolyDataFilter()
    trans_lm.SetInputData(lms)
    trans_lm.SetTransform(t)
    trans_lm.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(trans.GetOutput())

    actor_text = vtk.vtkActor()
    actor_text.SetMapper(mapper)
    actor_text.SetTexture(texture)
    actor_text.GetProperty().SetColor(1, 1, 1)
    actor_text.GetProperty().SetAmbient(1.0)
    actor_text.GetProperty().SetSpecular(0)
    actor_text.GetProperty().SetDiffuse(0)
    ren.AddActor(actor_text)

    actor_geometry = vtk.vtkActor()
    actor_geometry.SetMapper(mapper)
    ren.AddActor(actor_geometry)

    w2if = vtk.vtkWindowToImageFilter()
    w2if.SetInput(ren_win)
    writer_png = vtk.vtkPNGWriter()
    writer_png.SetInputConnection(w2if.GetOutputPort())

    scale = vtk.vtkImageShiftScale()
    scale.SetOutputScalarTypeToUnsignedChar()
    scale.SetInputConnection(w2if.GetOutputPort())
    scale.SetShift(0)
    scale.SetScale(-255)

    writer_png_2 = vtk.vtkPNGWriter()
    writer_png_2.SetInputConnection(scale.GetOutputPort())

    for view in range(n_views):
        name_rgb = o_dir_image + base_name + '_' + str(view) + '.png'
        name_geometry = o_dir_image + base_name + '_' + str(
            view) + '_geometry.png'
        name_depth = o_dir_image + base_name + '_' + str(view) + '_zbuffer.png'
        name_2dlm = o_dir_lm + base_name + '_' + str(view) + '.txt'

        if not os.path.isfile(name_rgb):
            # print('Rendering ', name_rgb)
            rx, ry, rz, s, tx, ty = random_transform(config)

            t.Identity()
            t.RotateY(ry)
            t.RotateX(rx)
            t.RotateZ(rz)
            t.Update()
            trans.Update()
            trans_lm.Update()

            xmin = -150
            xmax = 150
            ymin = -150
            ymax = 150
            zmin = trans.GetOutput().GetBounds()[4]
            zmax = trans.GetOutput().GetBounds()[5]
            xlen = xmax - xmin
            ylen = ymax - ymin

            cx = 0
            cy = 0
            extend_factor = 1.0
            side_length = max([xlen, ylen]) * extend_factor
            zoom_fac = win_size / side_length

            ren.GetActiveCamera().SetParallelScale(side_length / 2)
            ren.GetActiveCamera().SetPosition(cx, cy, 500)
            ren.GetActiveCamera().SetFocalPoint(cx, cy, 0)
            ren.GetActiveCamera().SetClippingRange(500 - zmax - slack,
                                                   500 - zmin + slack)

            # Save textured image
            w2if.SetInputBufferTypeToRGB()

            actor_geometry.SetVisibility(False)
            actor_text.SetVisibility(True)
            mapper.Modified()
            ren.Modified()  # force actors to have the correct visibility
            ren_win.Render()

            w2if.Modified(
            )  # Needed here else only first rendering is put to file
            writer_png.SetFileName(name_rgb)
            writer_png.Write()

            actor_text.SetVisibility(False)
            actor_geometry.SetVisibility(True)
            mapper.Modified()
            ren.Modified()  # force actors to have the correct visibility
            ren_win.Render()

            w2if.Modified(
            )  # Needed here else only first rendering is put to file
            writer_png.SetFileName(name_geometry)
            writer_png.Write()

            ren.Modified()  # force actors to have the correct visibility
            ren_win.Render()
            w2if.SetInputBufferTypeToZBuffer()
            w2if.Modified()

            writer_png_2.SetFileName(name_depth)
            writer_png_2.Write()
            actor_geometry.SetVisibility(False)
            actor_text.SetVisibility(True)
            ren.Modified()

            # Write transformed landmarks
            f = open(name_2dlm, 'w')

            t_lm = trans_lm.GetOutput()
            for i in range(t_lm.GetNumberOfPoints()):
                x_pos = t_lm.GetPoint(i)[0]
                y_pos = t_lm.GetPoint(i)[1]

                x_pos_screen = (x_pos - cx) * zoom_fac + win_size / 2
                y_pos_screen = -(y_pos - cy) * zoom_fac + win_size / 2

                line = str(x_pos_screen) + ' ' + str(y_pos_screen) + '\n'
                f.write(line)
            f.close()

    del writer_png_2, writer_png, ren_win, actor_geometry, actor_text, mapper, w2if, t, trans, vrmlin, texture
    del texture_image
    del lms, trans_lm

    delete_lock_file(lock_file)
コード例 #17
0
def main():
    filename = get_program_parameters()
    colors = vtk.vtkNamedColors()

    print("Reading " + filename)

    renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)

    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    # VRML Import
    importer = vtk.vtkVRMLImporter()
    importer.SetFileName(filename)
    importer.SetRenderWindow(render_window)
    importer.Update()

    actors = vtk.vtkActorCollection()
    actors = renderer.GetActors()
    print("There are", actors.GetNumberOfItems(), "actors")
    actors.InitTraversal()

    for a in range(0, actors.GetNumberOfItems()):
        actor = actors.GetNextActor()

        # The importer shininess parameter is between 0 and 1. VTK specular power is usually 10 - 100.
        # Also, the default for the specular factor for VRML is 1, while VTK's
        # is 0
        specular_power = actor.GetProperty().GetSpecularPower()
        if specular_power <= 1.0:
            actor.GetProperty().SetSpecularPower(specular_power * 128.0)
        specular = actor.GetProperty().GetSpecular()
        if specular == 0.0:
            actor.GetProperty().SetSpecular(1.0)
            # if 0
            # The VRML default ambient intensity is .2
        ambient_intensity = actor.GetProperty().GetAmbient()
        if ambient_intensity == 0.0:
            actor.GetProperty().SetAmbient(.2)
            # endif
        mapper = actor.GetMapper()
        if (mapper):
            data_set = mapper.GetInput()
            if not data_set.GetPointData().GetNormals():
                normals = vtk.vtkPolyDataNormals()
                normals.SetInputData(data_set)
                normals.SplittingOff()
                normals.Update()
                mapper.SetInputData(normals.GetOutput())

                # If there is a lookup table, convert it to point data
                lut = mapper.GetLookupTable()
                if lut and mapper.GetScalarVisibility():
                    pc = vtk.vtkUnsignedCharArray()
                    pc.SetNumberOfComponents(4)
                    pc.SetNumberOfTuples(lut.GetNumberOfColors())
                    for t in range(0, lut.GetNumberOfColors()):
                        lutc = lut.GetTableValue(t)
                        lutuc = ['', '', '', '']
                        lut.GetColorAsUnsignedChars(lutc, lutuc)
                        pc.SetTypedTuple(t, lutuc)
                    mapper.SetLookupTable(None)
                    mapper.GetInput().GetPointData().SetScalars(pc)

        renderer.ResetCamera()
        renderer.GetActiveCamera().Azimuth(30)
        renderer.GetActiveCamera().Elevation(30)
        renderer.GetActiveCamera().Dolly(1.4)
        renderer.ResetCameraClippingRange()

        renderer.SetBackground(colors.GetColor3d("PaleGreen"))
        render_window.SetSize(640, 480)
        render_window.Render()
        render_window_interactor.Start()
コード例 #18
0
def main(input_filename,
         areas_filename,
         scale,
         is_imx,
         exportPath=None,
         exportType=False,
         reduction=70,
         radius=RADIUS,
         combine=False):
    # TODO: The following doesn't hide the RenderWindow :/
    # factGraphics = vtk.vtkGraphicsFactory()
    # factGraphics.SetUseMesaClasses(1)
    # factImage = vtk.vtkImagingFactory()
    # factImage.SetUseMesaClasses(1)

    if exportPath is None:
        pos = areas_filename.rfind("/")
        filename = os.path.splitext(input_filename)[0]
        posFilename = filename.rfind("/")
        exportPath = areas_filename[:pos] + "/Meshes" + filename[posFilename:]
    else:
        filename = os.path.splitext(input_filename)[0]
        pos = filename.rfind("/")
        if pos == -1:
            exportPath += "/"

        exportPath += filename[pos:]

    print(exportPath)
    if is_imx:
        vrml_filename = os.path.splitext(input_filename)[0] + ".vrml"
        names_filename = os.path.splitext(input_filename)[0] + ".names"
        args = [
            "{}".format(input_filename), "{}".format(vrml_filename),
            "{}".format(names_filename)
        ]
        p = Process(target=parse_imx.main, args=[args])
        p.start()
        p.join()

        names_list = []
        with open(names_filename) as f:
            for line in f:
                line = re.sub(r'\n', '', line)
                names_list.append(line)
    else:
        vrml_filename = input_filename
        names_list = None

    rw = vtk.vtkRenderWindow()
    rwi = vtk.vtkRenderWindowInteractor()
    rwi.SetRenderWindow(rw)
    # rw.OffScreenRenderingOn()

    importer = vtk.vtkVRMLImporter()
    importer.SetFileName(vrml_filename)
    # importer = vtk.vtk3DSImporter()
    # importer.SetFileName("cube.3ds")
    importer.Read()
    importer.SetRenderWindow(rw)
    importer.Update()

    rw.Render()

    ren = importer.GetRenderer()
    actors = ren.GetActors()
    actors.InitTraversal()

    rwExport = vtk.vtkRenderWindow()
    # rwExport.OffScreenRenderingOn()
    renExport = vtk.vtkRenderer()
    rwExport.AddRenderer(renExport)

    rwExport.Render()

    if is_imx:
        csv = "Object,Pre_Area,Post_Area,Post/Pre,X,Y,Z,Name\n"
    else:
        csv = "Object,Pre_Area,Post_Area,Post/Pre,X,Y,Z\n"

    print(
        "-------- Repairing original mesh and Calculating areas (This process might take a long time, please wait) -----------"
    )
    for i in range(ren.GetNumberOfPropsRendered()):
        sys.stdout.write("%d _" % i)
        actor = actors.GetNextActor()
        polydata = actor.GetMapper().GetInput()
        polydataCopy = vtk.vtkPolyData()
        polydataCopy.DeepCopy(polydata)
        area_pre = compute_area(actor)
        centroid = actor.GetCenter()
        rescaled = False
        try:
            rw.Render()
            (center, rotation) = axisAligment(actor)
            rw.Render()
            open_actor(actor, i, scale, radius)

        except ValueError as e:
            # [KNOWN BUG] The sizes are corrected, but not the position
            scale = scale * 2
            open_actor(actor, i, scale, radius)
            rescaled = True
        area_post = compute_area(actor) / scale**2

        if is_imx:
            data = []
            data.extend([i, area_pre, area_post, area_post / area_pre])
            data.extend(centroid)
            data.append(names_list[i])
            csv += "%d,%f,%f,%f,%f,%f,%f,%s\n" % tuple(data)

        else:
            data = []
            data.extend([i, area_pre, area_post, area_post / area_pre])
            data.extend(centroid)
            csv += "%d,%f,%f,%f,%f,%f,%f\n" % tuple(data)

        if exportType != "None":
            initActorForExport(actor, rwExport, scale, reduction)
            toOriginalPos(actor, center, rotation)
            if names_list is not None:
                name = names_list[i]
            else:
                name = i

            if exportType == "Stl":
                save_stl(actor.GetMapper().GetInput(), exportPath,
                         str(name) + "_R")
                save_stl(polydataCopy, exportPath, str(name) + "_O")
                renExport.RemoveActor(actor)
            elif exportType == "Vrml":
                save_vrml(str(name) + "_R", exportPath, rwExport)
                renExport.RemoveActor(actor)
                actorOld = vtk.vtkActor()
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInputData(polydataCopy)
                actorOld.SetMapper(mapper)
                renExport.AddActor(actorOld)
                save_vrml(str(name) + "_O", exportPath, rwExport)
                renExport.RemoveActor(actorOld)
            elif exportType == "Obj":
                save_obj(rwExport, exportPath, str(name) + "_R")
                renExport.RemoveActor(actor)
                actorOld = vtk.vtkActor()
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInputData(polydataCopy)
                actorOld.SetMapper(mapper)
                renExport.AddActor(actorOld)
                save_obj(rwExport, exportPath, str(name) + "_O")
                renExport.RemoveActor(actorOld)

        ren.RemoveActor(actor)
        if rescaled:
            scale /= 2

    with open(areas_filename, 'w') as f:
        f.write(csv)
    if is_imx:
        os.remove(vrml_filename)
        os.remove(names_filename)

    rw.Finalize()
    print("")
コード例 #19
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)
    elif fl.endswith(".wrl"):
        importer = vtk.vtkVRMLImporter()
        importer.SetFileName(filename)
        importer.Read()
        importer.Update()
        actors = importer.GetRenderer().GetActors() #vtkActorCollection
        actors.InitTraversal()
        wacts = []
        for i in range(actors.GetNumberOfItems()):
            act = actors.GetNextActor()
            wacts.append(act)
        actor = Assembly(wacts)

        ################################################################# 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") \
        or fl.endswith(".dem"):
        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 = Volume(img).isosurface(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 = Picture()  # 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

        ################################################################# numpy:
    elif fl.endswith(".npy"):
        acts = loadNumpy(filename)
        if unpack == False:
            return Assembly(acts)
        return acts

    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
コード例 #20
0
ファイル: base.py プロジェクト: redstorm-fyy/menpo3d
def wrl_importer(filepath, asset=None, texture_resolver=None, **kwargs):
    """Allows importing VRML 2.0 meshes.

    Uses VTK and assumes that the first actor in the scene is the one
    that we want.

    Parameters
    ----------
    asset : `object`, optional
        An optional asset that may help with loading. This is unused for this
        implementation.
    texture_resolver : `callable`, optional
        A callable that recieves the mesh filepath and returns a single
        path to the texture to load.
    \**kwargs : `dict`, optional
        Any other keyword arguments.

    Returns
    -------
    shape : :map:`PointCloud` or subclass
        The correct shape for the given inputs.
    """
    import vtk
    from vtk.util.numpy_support import vtk_to_numpy

    vrml_importer = vtk.vtkVRMLImporter()
    vrml_importer.SetFileName(str(filepath))
    vrml_importer.Update()

    # Get the first actor.
    actors = vrml_importer.GetRenderer().GetActors()
    actors.InitTraversal()
    mapper = actors.GetNextActor().GetMapper()
    mapper_dataset = mapper.GetInput()

    if actors.GetNextActor():
        # There was more than one actor!
        warnings.warn('More than one actor was detected in the scene. Only '
                      'single scene actors are currently supported.')

    # Get the Data
    polydata = vtk.vtkPolyData.SafeDownCast(mapper_dataset)

    # We must have point data!
    points = vtk_to_numpy(polydata.GetPoints().GetData()).astype(np.float)

    trilist = vtk_ensure_trilist(polydata)

    texture = None
    if texture_resolver is not None:
        texture_path = texture_resolver(filepath)
        if texture_path is not None and texture_path.exists():
            texture = mio.import_image(texture_path)

    # Three different outcomes - either we have a textured mesh, a coloured
    # mesh or just a plain mesh. Let's try each in turn.

    # Textured
    tcoords = None
    try:
        tcoords = vtk_to_numpy(polydata.GetPointData().GetTCoords())
    except Exception:
        pass

    if isinstance(tcoords, np.ndarray) and tcoords.size == 0:
        tcoords = None

    # Colour-per-vertex
    try:
        colour_per_vertex = vtk_to_numpy(
            mapper.GetLookupTable().GetTable()) / 255.
    except Exception:
        pass

    if isinstance(colour_per_vertex,
                  np.ndarray) and colour_per_vertex.size == 0:
        colour_per_vertex = None

    return _construct_shape_type(points, trilist, tcoords, texture,
                                 colour_per_vertex)