Esempio n. 1
1
def exportWindow(fileoutput, binary=False, speed=None, html=True):
    '''
    Exporter which writes out the renderered scene into an OBJ or X3D file.
    X3D is an XML-based format for representation 3D scenes (similar to VRML).
    Check out http://www.web3d.org/x3d for more details.

    :param float speed: set speed for x3d files.
    :param bool html: generate a test html page for x3d files.

    |export_x3d| |export_x3d.py|_

        `generated webpage <https://vtkplotter.embl.es/examples/embryo.html>`_

        See also: FEniCS test `webpage <https://vtkplotter.embl.es/examples/fenics_elasticity.html>`_.
    '''
    fr = fileoutput.lower()
    if ".obj" in fr:
        w = vtk.vtkOBJExporter()
        w.SetInputData(settings.plotter_instance.window)
        w.Update()
        colors.printc("~save Saved file:", fileoutput, c="g")
    elif ".x3d" in fr:
        exporter = vtk.vtkX3DExporter()
        exporter.SetBinary(binary)
        exporter.FastestOff()
        if speed:
            exporter.SetSpeed(speed)
        exporter.SetInput(settings.plotter_instance.window)
        exporter.SetFileName(fileoutput)
        exporter.Update()
        exporter.Write()
        if not html:
            return
        from vtkplotter.docs import x3d_html
        x3d_html = x3d_html.replace("~fileoutput", fileoutput)
        wsize = settings.plotter_instance.window.GetSize()
        x3d_html = x3d_html.replace("~width", str(wsize[0]))
        x3d_html = x3d_html.replace("~height", str(wsize[1]))
        #b = settings.plotter_instance.renderer.ComputeVisiblePropBounds()
        #s = max(b[1] - b[0], b[3] - b[2], b[5] - b[4])
        #c = (b[1] + b[0])/2, (b[3] + b[2])/2, (b[5] + b[4])/2
        #x3d_html = x3d_html.replace("~size", str(s*2))
        #x3d_html = x3d_html.replace("~center", str(c[0])+" "+str(c[1])+" "+str(c[2]))
        outF = open(fileoutput.replace('.x3d', '.html'), "w")
        outF.write(x3d_html)
        outF.close()
        colors.printc("~save Saved files:",
                      fileoutput,
                      fileoutput.replace('.x3d', '.html'),
                      c="g")
    return
Esempio n. 2
0
    def OnExportSurface(self, pubsub_evt):
        filename, filetype = pubsub_evt.data
        fileprefix = filename.split(".")[-2]
        renwin = self.interactor.GetRenderWindow()

        if filetype == const.FILETYPE_RIB:
            writer = vtk.vtkRIBExporter()
            writer.SetFilePrefix(fileprefix)
            writer.SetTexturePrefix(fileprefix)
            writer.SetInput(renwin)
            writer.Write()
        elif filetype == const.FILETYPE_VRML:
            writer = vtk.vtkVRMLExporter()
            writer.SetFileName(filename)
            writer.SetInput(renwin)
            writer.Write()
        elif filetype == const.FILETYPE_X3D:
            writer = vtk.vtkX3DExporter()
            writer.SetInput(renwin)
            writer.SetFileName(filename)
            writer.Update()
            writer.Write()
        elif filetype == const.FILETYPE_OBJ:
            writer = vtk.vtkOBJExporter()
            writer.SetFilePrefix(fileprefix)
            writer.SetInput(renwin)
            writer.Write()
        elif filetype == const.FILETYPE_IV:
            writer = vtk.vtkIVExporter()
            writer.SetFileName(filename)
            writer.SetInput(renwin)
            writer.Write()
Esempio n. 3
0
 def plot3d(self, x3d=False):
     """
     Returns an interactive 3D representation of all boreholes in the project
     
     Parameters
     -----------
     x3d : bool
         if True, generates a 3xd file of the 3D (default=False)
     """
     pl = pv.Plotter()
     for bh in self.boreholes_3d:
         bh.plot3d(plotter=pl)
     if not x3d:
         pl.show()
     else:
         writer = vtkX3DExporter()
         writer.SetInput(pl.renderer.GetRenderWindow())
         filename = f'project_{self.name:s}.x3d'
         writer.SetFileName(filename)
         writer.Update()
         writer.Write()
         x3d_html = f'<html>\n<head>\n    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>\n' \
                    '<title>X3D scene</title>\n <p>' \
                    '<script type=\'text/javascript\' src=\'http://www.x3dom.org/download/x3dom.js\'> </script>\n' \
                    '<link rel=\'stylesheet\' type=\'text/css\' href=\'http://www.x3dom.org/download/x3dom.css\'/>\n' \
                    '</head>\n<body>\n<p>\n For interaction, click in the view and press "a" to see the whole scene. For more info on interaction,' \
                    ' please read  <a href="https://doc.x3dom.org/tutorials/animationInteraction/navigation/index.html">the docs</a>  \n</p>\n' \
                    '<x3d width=\'968px\' height=\'600px\'>\n <scene>\n' \
                    '<viewpoint position="-1.94639 1.79771 -2.89271" orientation="0.03886 0.99185 0.12133 3.75685">' \
                    '</viewpoint>\n <Inline nameSpaceName="Borehole" mapDEFToID="true" url="' + filename + '" />\n' \
                    '</scene>\n</x3d>\n</body>\n</html>\n'
         return HTML(x3d_html)
Esempio n. 4
0
    def OnExportSurface(self, pubsub_evt):
        filename, filetype = pubsub_evt.data
        fileprefix = filename.split(".")[-2]
        renwin = self.interactor.GetRenderWindow()

        if filetype == const.FILETYPE_RIB:
            writer = vtk.vtkRIBExporter()
            writer.SetFilePrefix(fileprefix)
            writer.SetTexturePrefix(fileprefix)
            writer.SetInput(renwin)
            writer.Write()
        elif filetype == const.FILETYPE_VRML:
            writer = vtk.vtkVRMLExporter()
            writer.SetFileName(filename)
            writer.SetInput(renwin)
            writer.Write()
        elif filetype == const.FILETYPE_X3D:
            writer = vtk.vtkX3DExporter()
            writer.SetInput(renwin)
            writer.SetFileName(filename)
            writer.Update()
            writer.Write()
        elif filetype == const.FILETYPE_OBJ:
            writer = vtk.vtkOBJExporter()
            writer.SetFilePrefix(fileprefix)
            writer.SetInput(renwin)
            writer.Write()
        elif filetype == const.FILETYPE_IV:
            writer = vtk.vtkIVExporter()
            writer.SetFileName(filename)
            writer.SetInput(renwin)
            writer.Write()
Esempio n. 5
0
def exportScene(scene, filePrefix, ext='x3d', names=[]):
    renWin = scene['window']
    ren = scene['renderer']
    if ext == 'x3d':
        writer = vtk.vtkX3DExporter()
        writer.SetInput(renWin)
        writer.SetFileName(filePrefix + '.x3d')
        writer.Update()
        writer.Write()
    elif ext == 'obj':
        writer = vtk.vtkOBJExporter()
        writer.SetFilePrefix(filePrefix)
        writer.SetInput(renWin)
        writer.Write()
    elif ext == 'vtm':
        actors = ren.GetActors()
        actors.InitTraversal()
        mb = vtk.vtkMultiBlockDataSet()
        mb.SetNumberOfBlocks(actors.GetNumberOfItems())
        for i in range(actors.GetNumberOfItems()):
            actor = actors.GetNextItem()
            block = actor.GetMapper().GetInput()
            mb.GetMetaData(i).Set(vtk.vtkCompositeDataSet.NAME(), names[i])
            mb.SetBlock(i, block)
        writer = vtk.vtkXMLMultiBlockDataWriter()
        if vtk.VTK_MAJOR_VERSION <= 5:
            writer.SetInput(mb)
        else:
            writer.SetInputData(mb)
        writer.SetFileName(filePrefix + '.vtm')
        writer.Write()
Esempio n. 6
0
    def exportToX3d(self, filename):
        """
        Export the rendered scene to an X3D file.

        @param filename: the name of the file
        @type filename: str
        """
        self.__exportToVtkExporter(vtk.vtkX3DExporter(), filename)
Esempio n. 7
0
    def exportToX3d(self, filename):
        """
        Export the rendered scene to an X3D file.

        @param filename: the name of the file
        @type filename: str
        """
        self.__exportToVtkExporter(vtk.vtkX3DExporter(), filename)
def export_image(renderer, step):
    dir = "./rendered_objects/"
    if not os.path.exists(dir):
        os.makedirs(dir)
    renWin = vtk.vtkRenderWindow()

    exporter = vtk.vtkX3DExporter()
    exporter.SetFileName("testX3DExporter.x3d")
    exporter.SetInput(renWin)
    exporter.Update()
    exporter.Write()
Esempio n. 9
0
    def export_scene_to_x3d(self, file_prefix):

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

        exporter = vtk.vtkX3DExporter()
        exporter.SetInput(render_window)
        exporter.SetFileName(file_prefix + '.x3d')
        exporter.Write()

        del render_window
Esempio n. 10
0
    def plot3d(self, plotter=None, x3d=False):
        """
        Returns an interactive 3D representation of all boreholes in the project
        
        Parameters
        -----------
        plotter : pyvista.plotter object
            Plotting object to display vtk meshes or numpy arrays (default=None)
            
        x3d : bool
            if True, generates a 3xd file of the 3D (default=False)
        """

        omf_legend, _ = striplog_legend_to_omf_legend(self.legend)

        if plotter is None:
            plotter = pv.Plotter()
            show = True
        else:
            show = False

        seg = ov.line_set_to_vtk(self.geometry)
        seg.set_active_scalars('component')
        ov.lineset.add_data(seg, self.geometry.data)
        plotter.add_mesh(seg.tube(radius=3), cmap=self.omf_cmap)

        if show and not x3d:
            plotter.show()
        else:
            writer = vtkX3DExporter()
            writer.SetInput(plotter.renderer.GetRenderWindow())
            filename = f'BH_{self.name:s}.x3d'
            writer.SetFileName(filename)
            writer.Update()
            writer.Write()
            x3d_html = f'<html>\n<head>\n    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>\n' \
                       '<title>X3D scene</title>\n <p>' \
                       '<script type=\'text/javascript\' src=\'http://www.x3dom.org/download/x3dom.js\'> </script>\n' \
                       '<link rel=\'stylesheet\' type=\'text/css\' href=\'http://www.x3dom.org/download/x3dom.css\'/>\n' \
                       '</head>\n<body>\n<p>\n For interaction, click in the view and press "a" to see the whole scene. For more info on interaction,' \
                       ' please read  <a href="https://doc.x3dom.org/tutorials/animationInteraction/navigation/index.html">the docs</a>  \n</p>\n' \
                       '<x3d width=\'968px\' height=\'600px\'>\n <scene>\n' \
                       '<viewpoint position="-1.94639 1.79771 -2.89271" orientation="0.03886 0.99185 0.12133 3.75685">' \
                       '</viewpoint>\n <Inline nameSpaceName="Borehole" mapDEFToID="true" url="' + filename + '" />\n' \
                                                                                                              '</scene>\n</x3d>\n</body>\n</html>\n'
            return HTML(x3d_html)
Esempio n. 11
0
def stl2x3d(inname, outname):

    reader = vtk.vtkSTLReader()
    reader.SetFileName(inname)

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

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # Create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

    # Assign actor to the renderer
    ren.AddActor(actor)

    writer = vtk.vtkX3DExporter()
    writer.SetFileName(outname)
    #writer.BinaryOn()
    writer.SetRenderWindow(renWin)
    writer.Write()
Esempio n. 12
0
def exportWindow(fileoutput, binary=False, speed=None, html=True):
    '''
    Exporter which writes out the renderered scene into an OBJ, X3D or Numpy file.
    X3D is an XML-based format for representation 3D scenes (similar to VRML).
    Check out http://www.web3d.org/x3d for more details.

    :param float speed: set speed for x3d files.
    :param bool html: generate a test html page for x3d files.

    |export_x3d| |export_x3d.py|_

        `generated webpage <https://vtkplotter.embl.es/examples/embryo.html>`_

        See also: FEniCS test `webpage <https://vtkplotter.embl.es/examples/fenics_elasticity.html>`_.

    .. note:: the rendering window can also be exported to `numpy` file `scene.npy`
        by pressing ``E`` keyboard at any moment during visualization.
    '''
    fr = fileoutput.lower()

    if ".obj" in fr:
        w = vtk.vtkOBJExporter()
        w.SetInputData(settings.plotter_instance.window)
        w.Update()
        colors.printc("~save Saved file:", fileoutput, c="g")

    elif ".x3d" in fr:
        exporter = vtk.vtkX3DExporter()
        exporter.SetBinary(binary)
        exporter.FastestOff()
        if speed:
            exporter.SetSpeed(speed)
        exporter.SetInput(settings.plotter_instance.window)
        exporter.SetFileName(fileoutput)
        exporter.Update()
        exporter.Write()
        if not html:
            return
        from vtkplotter.docs import x3d_html
        x3d_html = x3d_html.replace("~fileoutput", fileoutput)
        wsize = settings.plotter_instance.window.GetSize()
        x3d_html = x3d_html.replace("~width", str(wsize[0]))
        x3d_html = x3d_html.replace("~height", str(wsize[1]))
        #b = settings.plotter_instance.renderer.ComputeVisiblePropBounds()
        #s = max(b[1] - b[0], b[3] - b[2], b[5] - b[4])
        #c = (b[1] + b[0])/2, (b[3] + b[2])/2, (b[5] + b[4])/2
        #x3d_html = x3d_html.replace("~size", str(s*2))
        #x3d_html = x3d_html.replace("~center", str(c[0])+" "+str(c[1])+" "+str(c[2]))
        outF = open(fileoutput.replace('.x3d', '.html'), "w")
        outF.write(x3d_html)
        outF.close()
        colors.printc("~save Saved files:", fileoutput,
                      fileoutput.replace('.x3d', '.html'), c="g")
    elif ".npy" in fr:
        sdict = dict()
        vp = settings.plotter_instance
        sdict['shape'] = vp.shape #todo
        sdict['sharecam'] = vp.sharecam #todo
        sdict['camera'] = None #todo
        sdict['position'] = vp.pos
        sdict['size'] = vp.size
        sdict['axes'] = vp.axes
        sdict['title'] = vp.title
        sdict['xtitle'] = vp.xtitle
        sdict['ytitle'] = vp.ytitle
        sdict['ztitle'] = vp.ztitle
        sdict['backgrcol'] = colors.getColor(vp.backgrcol)
        sdict['useDepthPeeling'] = settings.useDepthPeeling
        sdict['renderPointsAsSpheres'] = settings.renderPointsAsSpheres
        sdict['renderLinesAsTubes'] = settings.renderLinesAsTubes
        sdict['hiddenLineRemoval'] = settings.hiddenLineRemoval
        sdict['visibleGridEdges'] = settings.visibleGridEdges
        sdict['interactorStyle'] = settings.interactorStyle
        sdict['useParallelProjection'] = settings.useParallelProjection
        sdict['objects'] = []
        for a in vp.getActors() + vp.getVolumes():
            sdict['objects'].append(_np_dump(a))
        np.save(fileoutput, [sdict])

    return
Esempio n. 13
0
def run(args):
    try:
        # inspired by /my/github/3dbar/lib/pymodules/python2.6/bar/rec/default_pipeline.xml

        if op.exists(args.out):
            if not args.replace:
                print('Skipping creation of image "{}", it already exists.'.
                      format(args.out))
                result = {'Status': 'Skipped'}
                report.success(result)
                return

        nii = nibabel.load(args.inp)

        # Nifti data is supposed to be in RAS orientation.
        # For Nifti files that violate the standard, the reorient string can be used to correct the orientation.
        if isinstance(args.reorient, str):
            nii = nit.reorient(nii, args.reorient)

        nii = nibabel.as_closest_canonical(nii)
        # numpy.array() will copy image to 'clean' data buffer
        img = numpy.squeeze(nii.get_data())

        if (args.bg_color == "auto"):
            bgColor = img[0, 0, 0]
        else:
            bgColor = int(args.bg_color)

        mask = nit.imageMask(img, [bgColor])
        img[mask] = 8
        if img.dtype != numpy.uint8:
            img = img.astype(numpy.uint8)

        #if numpy.prod(img.shape) > 512*512*512:
        hdr = nii.get_header()
        q = hdr.get_best_affine()
        scalef = [1 + v / 512 for v in img.shape]
        if any(numpy.array(scalef) > 1):
            print('Downsampling by a factor {} to reduce memory load'.format(
                scalef))
            print 'Best affine before downsampling: {}'.format(q)
            (img, q) = nit.downsample3d(img, q.tolist(), scalef)
            print 'Best affine after downsampling: {}'.format(q)

        # image zero-padding
        bb = nit.get_boundingbox(img, 2)
        w = 2
        padded = numpy.zeros((bb[3] + 2 * w, bb[4] + 2 * w, bb[5] + 2 * w),
                             numpy.uint8,
                             order='F')
        padded[w:-w, w:-w,
               w:-w] = img[bb[0]:bb[0] + bb[3], bb[1]:bb[1] + bb[4],
                           bb[2]:bb[2] + bb[5]]
        img = padded
        dims = img.shape
        spacing = q.diagonal()[0:3]
        print('Origin before {}'.format(q[0:3, 3]))
        # origin adjusted for zero-padding
        q[0:3, 3] = apply_affine(q, [bb[0] - w, bb[1] - w, bb[2] - w])
        origin = q[0:3, 3]
        print('Origin after {}'.format(origin))

        doRender = args.render

        # create a rendering window and renderer
        ren = vtk.vtkRenderer()
        if doRender:
            renWin = vtk.vtkRenderWindow()
            iren = vtk.vtkRenderWindowInteractor()
            iren.SetRenderWindow(renWin)
        else:
            renWin = vtk.vtkRenderWindow()
            renWin.SetOffScreenRendering(1)

        renWin.AddRenderer(ren)
        WIDTH = 800
        HEIGHT = 600
        renWin.SetSize(WIDTH, HEIGHT)

        # import data
        dataImporter = vtk.vtkImageImport()
        dataImporter.SetImportVoidPointer(img)
        dataImporter.SetDataScalarTypeToUnsignedChar()
        dataImporter.SetNumberOfScalarComponents(1)
        dataImporter.SetDataExtent(0, dims[0] - 1, 0, dims[1] - 1, 0,
                                   dims[2] - 1)
        dataImporter.SetWholeExtent(0, dims[0] - 1, 0, dims[1] - 1, 0,
                                    dims[2] - 1)
        # new since October 2015
        dataImporter.SetDataSpacing(spacing)
        dataImporter.SetDataOrigin(origin)
        print 'ORIGIN: {}'.format(dataImporter.GetDataOrigin())

        print 'Dimensions {}'.format(dims)

        # create iso surface
        iso = vtk.vtkMarchingCubes()
        iso.SetInputConnection(dataImporter.GetOutputPort())
        iso.ComputeNormalsOff()
        iso.SetValue(0, 3)

        iso.Update()

        #DEBUG
        #from vtk.util.numpy_support import vtk_to_numpy
        #iso.Update()
        #output = iso.GetOutput()
        #A = vtk_to_numpy(output.GetPoints().GetData())
        #print 'iso Output {}'.format(A)

        tf = vtk.vtkTriangleFilter()
        tf.SetInput(iso.GetOutput())

        # apply smoothing
        smth = vtk.vtkSmoothPolyDataFilter()
        smth.SetRelaxationFactor(0.5)
        smth.SetInput(tf.GetOutput())

        # reduce triangles
        qc = vtk.vtkQuadricClustering()
        qc.SetNumberOfXDivisions(90)
        qc.SetNumberOfYDivisions(90)
        qc.SetNumberOfZDivisions(90)
        qc.SetInput(smth.GetOutput())

        # map data
        volumeMapper = vtk.vtkPolyDataMapper()
        volumeMapper.SetInput(qc.GetOutput())
        volumeMapper.ScalarVisibilityOff()

        # actor
        act = vtk.vtkActor()
        act.SetMapper(volumeMapper)

        # assign actor to the renderer
        ren.AddActor(act)
        bgColor = [0, 0, 0]
        ren.SetBackground(bgColor)

        camera = ren.GetActiveCamera()
        camera.SetViewUp(0, 0, 1)
        camera.SetFocalPoint(dims[0] / 2, dims[1] / 2, dims[2] / 2)
        camera.SetPosition(dims[0], dims[1] / 2, dims[2] / 2)
        camera.ParallelProjectionOn()
        camera.Yaw(180)
        ren.SetActiveCamera(camera)
        ren.ResetCamera()
        ren.ResetCameraClippingRange()
        ren.GetActiveCamera().Zoom(1.5)

        if args.out:
            take_screenshot(args.out, ren)
            im = Image.open(args.out)
            A = numpy.array(im)
            mask = nit.imageMask(A, [bgColor])
            bgColor = [238, 221, 170]
            A[numpy.invert(mask)] = bgColor
            nonzero = numpy.argwhere(mask)
            if nonzero.size > 0:
                lefttop = [v if v > 0 else 0 for v in (nonzero.min(0) - 4)]
                rightbottom = [
                    v if v < A.shape[i] else A.shape[i]
                    for i, v in enumerate(nonzero.max(0) + 4)
                ]
                A = A[lefttop[0]:rightbottom[0] + 1,
                      lefttop[1]:rightbottom[1] + 1]
            im = Image.fromarray(A)
            sz = numpy.array(im.size, 'double')
            sz = numpy.ceil((128.0 / sz[1]) * sz)
            print 'sz {}'.format(sz)
            im.thumbnail(sz.astype(int), Image.ANTIALIAS)
            im = im.convert('P', palette=Image.ADAPTIVE, colors=256)
            palette = numpy.array(im.getpalette()).reshape(256, 3)
            match = numpy.where(numpy.all(palette == bgColor, axis=1))
            im.save(args.out, transparency=match[0])
            print('Created image "{}"'.format(args.out))

        if args.x3d:
            vtkX3DExporter = vtk.vtkX3DExporter()
            vtkX3DExporter.SetInput(renWin)
            vtkX3DExporter.SetFileName(args.x3d)
            vtkX3DExporter.Write()

        if args.stl:
            stlWriter = vtk.vtkSTLWriter()
            stlWriter.SetInputConnection(qc.GetOutputPort())
            stlWriter.SetFileTypeToBinary()
            stlWriter.SetFileName(args.stl)
            stlWriter.Write()

        # enable user interface interactor
        if doRender:
            iren.Initialize()
            renWin.Render()
            pos = camera.GetPosition()
            ornt = camera.GetOrientation()

            print 'Camera position; orientation {};{}'.format(pos, ornt)
            iren.Start()

        result = {'Status': 'Done'}
        report.success(result)
    except:
        report.fail(__file__)
cylinderActor = vtk.vtkActor()
cylinderActor.SetMapper(cylinderMapper)
cylinderActor.GetProperty().SetColor(colors.GetColor3d("Beige"))
cylinderActor.RotateX(30.0)
cylinderActor.RotateY(-45.0)

# Add the actors to the renderer, set the background and size
ren.AddActor(cylinderActor)
renWin.SetSize(300, 300)
ren.SetBackground(colors.GetColor3d("SlateGray"))
renWin.SetWindowName('Cylinder')

# This allows the interactor to initalize itself. It has to be
# called before an event loop.
iren.Initialize()

# We'll zoom in a little by accessing the camera and invoking a "Zoom"
# method on it.
ren.ResetCamera()
ren.GetActiveCamera().Zoom(1.5)
renWin.Render()

# Start the event loop.
iren.Start()

exporter = vtk.vtkX3DExporter()
exporter.SetRenderWindow(renWin)
exporter.SetFileName("small_lattice.x3d")
exporter.Write()
exporter.Update()