Example #1
0
    def on_selected_index(change):
        if change.new == 1 and isinstance(change.owner.children[1], widgets.HTML):
            slider = widgets.IntSlider(value=0, min=0, max=lfp.data.shape[1] - 1, description='Channel',
                                       orientation='horizontal')

            def create_spectrogram(channel=0):
                f, t, Zxx = stft(lfp.data[:, channel], lfp.rate, nperseg=128)
                spect = np.log(np.abs(Zxx))
                image = itk.GetImageFromArray(spect)
                image.SetSpacing([(f[1] - f[0]), (t[1] - t[0]) * 1e-1])
                direction = image.GetDirection()
                vnl_matrix = direction.GetVnlMatrix()
                vnl_matrix.set(0, 0, 0.0)
                vnl_matrix.set(0, 1, -1.0)
                vnl_matrix.set(1, 0, 1.0)
                vnl_matrix.set(1, 1, 0.0)
                return image

            spectrogram = create_spectrogram(0)

            viewer = itkwidgets.view(spectrogram, ui_collapsed=True, select_roi=True, annotations=False)
            spect_vbox = widgets.VBox([slider, viewer])
            children[1] = spect_vbox
            change.owner.children = children
            channel_to_spectrogram = {0: spectrogram}

            def on_change_channel(change):
                channel = change.new
                if channel not in channel_to_spectrogram:
                    channel_to_spectrogram[channel] = create_spectrogram(channel)
                viewer.image = channel_to_spectrogram[channel]

            slider.observe(on_change_channel, names='value')
Example #2
0
 def __init__(self):
     super().__init__()
     self.addInputPort("array")
     self.addInputPort("dataset")
     self.view = view()
     self.view.ui_collapsed = True
     self._bounds = None
     self.view.observe(self.camera_changed, ['camera'])
Example #3
0
 def gui(self, **kwargs ):
     if self._gui is None:
         self.init_data()
         bin_colors = self.get_bin_colors("gist_rainbow") # self.get_bin_colors("jet",True)
         ptcolors = [ [1.0, 1.0, 1.0, 1.0], ] + bin_colors + LabelsManager.instance().colors[::-1]
         ptsizes = [1]*(self._n_point_bins+1) + [8]*LabelsManager.instance().nLabels
         self._gui = view( point_sets = self.point_sets, point_set_sizes=ptsizes, point_set_colors=ptcolors, background=[0,0,0] )
         self._gui.layout = { 'width': 'auto', 'flex': '1 1 auto' }
     return self._gui
Example #4
0
    def mesh(self, **kwargs):

        x = kwargs.get("x", self._obj.SCHISM_hgrid_node_x[:].values)
        y = kwargs.get("y", self._obj.SCHISM_hgrid_node_y[:].values)
        try:
            t = kwargs.get("t", self._obj.time.values)
        except:
            pass

        tri3 = kwargs.get("tes", self._obj.SCHISM_hgrid_face_nodes.values[:, :3].astype(int))

        dim = kwargs.get("dim", "2D")

        R = kwargs.get("R", 1.0)

        if dim == "3D":
            px, py, pz = to_3d(x, y, R=R)
        else:
            px = x
            py = y
            pz = np.zeros(x.shape[0])

        mlab.figure(1, size=(3840 / 2, 2160 / 2), bgcolor=(0, 0, 0), fgcolor=(1.0, 1.0, 1.0))
        mlab.clf()
        bcolor = kwargs.get("bcolor", (0.0, 0.0, 0.0))
        if dim == "3D":
            self.globe(R - 0.002, bcolor=bcolor)

        # 3D triangular mesh surface (like trisurf)
        grd = mlab.triangular_mesh(px, py, pz, tri3, representation="wireframe", opacity=1.0)
        #       grd.scalar.name = 'depth'

        coast = kwargs.get("coastlines", None)

        if coast is not None:
            try:
                del kwargs["coastlines"]
            except:
                pass
            try:
                del kwargs["R"]
            except:
                pass
            src, lines = self.c3d(coast, R=R, **kwargs)
            mlab.pipeline.surface(src, color=(1, 0, 0), line_width=10, opacity=0.8)

        engine = mlab.get_engine()
        scene = engine.scenes[0]
        scene.scene.z_plus_view()

        v = view(actors=grd, rotate=False, ui_collapsed=True)
        v.geometries = [v.geometries[0]]

        #        mlab.show()
        return v
Example #5
0
def show_cad(mesh, emax=1, show_log=False):
    global mgeoCounter
    temp_file_name = "tmp_step_" + str(stepCounter) + ".step"
    val = mesh.val()
    val.exportStep(temp_file_name)
    time.sleep(1)
    stl_file = step2stl(temp_file_name, emax=emax)
    time.sleep(1)
    vol = pyvista.read(stl_file)
    v = view(geometries=[vol])
    return v
Example #6
0
def Viewer_3D(imgs):
    '''
    :param imgs: array:[D, H, W]
    :return: the 3D player
    '''
    itk_img = itk.image_view_from_array(imgs)
    viewer = view(itk_img,
                  rotate=True,
                  axes=True,
                  vmin=0,
                  vmax=255,
                  gradient_opacity=0.9)
    return viewer
Example #7
0
    def show_volume(self, renderer: str = 'itkwidgets', **kwargs) -> None:
        """Show volume using `itkwidgets` or `ipyvolume`.

        Extra keyword arguments (`kwargs`) are passed to
        `itkwidgets.view` or `ipyvolume.quickvolshow`.
        """
        if renderer in ('ipyvolume', 'ipv'):
            import ipyvolume as ipv
            return ipv.quickvolshow(self.image, **kwargs)
        elif renderer in ('itkwidgets', 'itk', 'itkw'):
            import itkwidgets as itkw
            return itkw.view(self.image)
        else:
            raise ValueError(f'No such renderer: {renderer!r}')
Example #8
0
def figure_9():
    """

    Notes
    -----
    You should run this code inside a Jupyter Notebook.
    """

    # reading all images from the sample.
    pattern = 'unet/rec20160318_191511_232p3_2cm_cont__4097im_1500ms_ML17keV_6.h5/predict/*.png'
    images = io.ImageCollection(pattern)
    images = images.concatenate()[:, ::2, ::2]

    # slicing the outer part to show inside fibers.
    images = images[:, :1000, :]
    images = itk.GetImageFromArray(images)

    view(images,
         label_image_blend=0,
         gradient_opacity=0,
         shadow=False,
         interpolation=False)

    return None
Example #9
0
    def plot(self, stance, unit='rad', itkwidget=False):
        """
        Plots the SerialLink object in a desired stance.
        :param stance: list of joint angles for SerialLink object.
        :param unit: unit of input angles.
        :return: null.
        """

        assert type(stance) is np.matrix

        if unit == 'deg':
            stance = stance * (pi / 180)

        self.pipeline = VtkPipeline()
        self.pipeline.reader_list, self.pipeline.actor_list, self.pipeline.mapper_list = self.__setup_pipeline_objs(
        )
        self.fkine(stance,
                   apply_stance=True,
                   actor_list=self.pipeline.actor_list)

        if itkwidget:
            from itkwidgets import view

            viewer = view(axes=False,
                          ui_collapsed=True,
                          actors=self.pipeline.actor_list,
                          geometries=[],
                          geometry_colors=[],
                          geometry_opacities=[])
            return viewer
        else:
            cube_axes = axesCubeFloor(self.pipeline.ren,
                                      self.param.get("cube_axes_x_bounds"),
                                      self.param.get("cube_axes_y_bounds"),
                                      self.param.get("cube_axes_z_bounds"),
                                      self.param.get("floor_position"))

            self.pipeline.add_actor(cube_axes)

            # for each in self.pipeline.actor_list:
            #     each.SetScale(self.scale)

            self.pipeline.render()
Example #10
0
def getNotebookBackend(actors2show, zoom, viewup):

    vp = settings.plotter_instance

    if isinstance(vp.shape, str) or sum(vp.shape) > 2:
        colors.printc("Multirendering is not supported in jupyter.", c=1)
        return

    ####################################################################################
    # https://github.com/InsightSoftwareConsortium/itkwidgets
    #  /blob/master/itkwidgets/widget_viewer.py
    if 'itk' in settings.notebookBackend:
        from itkwidgets import view

        settings.notebook_plotter = view(actors=actors2show,
                                         cmap='jet', ui_collapsed=True,
                                         gradient_opacity=False)


    ####################################################################################
    elif settings.notebookBackend == 'k3d':
        try:
            import k3d # https://github.com/K3D-tools/K3D-jupyter
        except:
            print("Cannot find k3d, install with:  pip install k3d")
            return

        actors2show2 = []
        for ia in actors2show:
            if not ia:
                continue
            if isinstance(ia, vtk.vtkAssembly): #unpack assemblies
                acass = ia.unpack()
                actors2show2 += acass
            else:
                actors2show2.append(ia)

        # vbb, sizes, _, _ = addons.computeVisibleBounds()
        # kgrid = vbb[0], vbb[2], vbb[4], vbb[1], vbb[3], vbb[5]

        settings.notebook_plotter = k3d.plot(axes=[vp.xtitle, vp.ytitle, vp.ztitle],
                                             menu_visibility=True,
                                             # height=int(vp.size[1]/2),
                                             )
        # settings.notebook_plotter.grid = kgrid
        settings.notebook_plotter.lighting = 1.2

        # set k3d camera
        settings.notebook_plotter.camera_auto_fit = True

        if settings.plotter_instance and settings.plotter_instance.camera:
            k3dc =  utils.vtkCameraToK3D(settings.plotter_instance.camera)
            if zoom:
                k3dc[0] /= zoom
                k3dc[1] /= zoom
                k3dc[2] /= zoom
            settings.notebook_plotter.camera = k3dc
        # else:
        #     vsx, vsy, vsz = vbb[0]-vbb[1], vbb[2]-vbb[3], vbb[4]-vbb[5]
        #     vss = numpy.linalg.norm([vsx, vsy, vsz])
        #     if zoom:
        #         vss /= zoom
        #     vfp = (vbb[0]+vbb[1])/2, (vbb[2]+vbb[3])/2, (vbb[4]+vbb[5])/2 # camera target
        #     if viewup == 'z':
        #         vup = (0,0,1) # camera up vector
        #         vpos= vfp[0] + vss/1.9, vfp[1] + vss/1.9, vfp[2]+vss*0.01  # camera position
        #     elif viewup == 'x':
        #         vup = (1,0,0)
        #         vpos= vfp[0]+vss*0.01, vfp[1] + vss/1.5, vfp[2]  # camera position
        #     else:
        #         vup = (0,1,0)
        #         vpos= vfp[0]+vss*0.01, vfp[1]+vss*0.01, vfp[2] + vss/1.5  # camera position
        #     settings.notebook_plotter.camera = [vpos[0], vpos[1], vpos[2],
        #                                           vfp[0],  vfp[1],  vfp[2],
        #                                           vup[0],  vup[1],  vup[2] ]
        if not vp.axes:
            settings.notebook_plotter.grid_visible = False

        for ia in actors2show2:

            if isinstance(ia, (vtk.vtkCornerAnnotation, vtk.vtkAssembly)):
                continue

            kobj = None
            kcmap= None
            name = None
            if hasattr(ia, 'filename'):
                if ia.filename:
                    name = os.path.basename(ia.filename)
                if ia.name:
                    name = os.path.basename(ia.name)

            #####################################################################scalars
            # work out scalars first, Points Lines are also Mesh objs
            if isinstance(ia, (Mesh, shapes.Line, Points)):
#                print('scalars', ia.name, ia.N())
                iap = ia.GetProperty()

                if isinstance(ia, (shapes.Line, Points)):
                    iapoly = ia.polydata()
                else:
                    iapoly = ia.clone().clean().triangulate().computeNormals().polydata()

                vtkscals = None
                color_attribute = None
                if ia.mapper().GetScalarVisibility():
                    vtkdata = iapoly.GetPointData()
                    vtkscals = vtkdata.GetScalars()

                    if vtkscals is None:
                        vtkdata = iapoly.GetCellData()
                        vtkscals = vtkdata.GetScalars()
                        if vtkscals is not None:
                            c2p = vtk.vtkCellDataToPointData()
                            c2p.SetInputData(iapoly)
                            c2p.Update()
                            iapoly = c2p.GetOutput()
                            vtkdata = iapoly.GetPointData()
                            vtkscals = vtkdata.GetScalars()

                    if vtkscals is not None:
                        if not vtkscals.GetName():
                            vtkscals.SetName('scalars')
                        scals_min, scals_max = ia.mapper().GetScalarRange()
                        color_attribute = (vtkscals.GetName(), scals_min, scals_max)
                        lut = ia.mapper().GetLookupTable()
                        lut.Build()
                        kcmap=[]
                        nlut = lut.GetNumberOfTableValues()
                        for i in range(nlut):
                            r,g,b,a = lut.GetTableValue(i)
                            kcmap += [i/(nlut-1), r,g,b]


            #####################################################################Volume
            if isinstance(ia, Volume):
#                print('Volume', ia.name, ia.dimensions())
                kx, ky, kz = ia.dimensions()
                arr = ia.getPointArray()
                kimage = arr.reshape(-1, ky, kx)

                colorTransferFunction = ia.GetProperty().GetRGBTransferFunction()
                kcmap=[]
                for i in range(128):
                    r,g,b = colorTransferFunction.GetColor(i/127)
                    kcmap += [i/127, r,g,b]

                kbounds = numpy.array(ia.imagedata().GetBounds()) \
                    + numpy.repeat(numpy.array(ia.imagedata().GetSpacing()) / 2.0, 2)\
                    * numpy.array([-1,1] * 3)

                kobj = k3d.volume(kimage.astype(numpy.float32),
                                  color_map=kcmap,
                                  #color_range=ia.imagedata().GetScalarRange(),
                                  alpha_coef=10,
                                  bounds=kbounds,
                                  name=name,
                                  )
                settings.notebook_plotter += kobj

            #####################################################################text
            elif hasattr(ia, 'info') and 'formula' in ia.info.keys():
                pos = (ia.GetPosition()[0],ia.GetPosition()[1])
                kobj = k3d.text2d(ia.info['formula'], position=pos)
                settings.notebook_plotter += kobj


            #####################################################################Mesh
            elif isinstance(ia, Mesh) and ia.N() and len(ia.faces()):
                # print('Mesh', ia.name, ia.N(), len(ia.faces()))
                kobj = k3d.vtk_poly_data(iapoly,
                                         name=name,
                                         # color=_rgb2int(iap.GetColor()),
                                         color_attribute=color_attribute,
                                         color_map=kcmap,
                                         opacity=iap.GetOpacity(),
                                         wireframe=(iap.GetRepresentation()==1))

                if iap.GetInterpolation() == 0:
                    kobj.flat_shading = True
                settings.notebook_plotter += kobj

            #####################################################################Points
            elif isinstance(ia, Points) or ia.NPoints() == ia.NCells():
                # print('Points', ia.name, ia.N())
                kcols=[]
                if color_attribute is not None:
                    scals = utils.vtk2numpy(vtkscals)
                    kcols = k3d.helpers.map_colors(scals, kcmap,
                                                   [scals_min,scals_max]).astype(numpy.uint32)
                # sqsize = numpy.sqrt(numpy.dot(sizes, sizes))

                kobj = k3d.points(ia.points().astype(numpy.float32),
                                  color=_rgb2int(iap.GetColor()),
                                  colors=kcols,
                                  opacity=iap.GetOpacity(),
                                  shader="dot",
                                  point_size=3, # point_size=iap.GetPointSize()*sqsize/800,
                                  name=name,
                                  )
                settings.notebook_plotter += kobj


            #####################################################################Line
            elif ia.polydata(False).GetNumberOfLines():
                # print('Line', ia.name, ia.N(), len(ia.faces()),
                #       ia.polydata(False).GetNumberOfLines(), len(ia.lines()),
                #       color_attribute, [vtkscals])

                # kcols=[]
                # if color_attribute is not None:
                #     scals = utils.vtk2numpy(vtkscals)
                #     kcols = k3d.helpers.map_colors(scals, kcmap,
                #                                    [scals_min,scals_max]).astype(numpy.uint32)

                # sqsize = numpy.sqrt(numpy.dot(sizes, sizes))

                for i, ln_idx in enumerate(ia.lines()):
                    if i>200:
                        print('WARNING: K3D nr of line segments is limited to 200.')
                        break
                    pts = ia.points()[ln_idx]
                    kobj = k3d.line(pts.astype(numpy.float32),
                                    color=_rgb2int(iap.GetColor()),
#                                    colors=kcols,
                                    opacity=iap.GetOpacity(),
                                    shader="thick",
                                    # width=iap.GetLineWidth()*sqsize/1000,
                                    name=name,
                                    )

                    settings.notebook_plotter += kobj


    ####################################################################################
    elif settings.notebookBackend == 'panel' and hasattr(vp, 'window') and vp.window:

        import panel # https://panel.pyviz.org/reference/panes/VTK.html
        vp.renderer.ResetCamera()
        settings.notebook_plotter = panel.pane.VTK(vp.window,
                                                   width=int(vp.size[0]/1.5),
                                                   height=int(vp.size[1]/2))


    ####################################################################################
    elif 'ipyvtk' in settings.notebookBackend and hasattr(vp, 'window') and vp.window:

        from ipyvtklink.viewer import ViewInteractiveWidget
        vp.renderer.ResetCamera()
        settings.notebook_plotter = ViewInteractiveWidget(vp.window)


    ####################################################################################
    elif '2d' in settings.notebookBackend.lower() and hasattr(vp, 'window') and vp.window:
        import PIL.Image
        try:
            import IPython
        except ImportError:
            raise Exception('IPython not available.')

        from vedo.io import screenshot
        settings.screeshotLargeImage = True
        nn = screenshot(returnNumpy=True, scale=settings.screeshotScale+2)
        pil_img = PIL.Image.fromarray(nn)
        settings.notebook_plotter = IPython.display.display(pil_img)

    return settings.notebook_plotter
Example #11
0
    index_matrix = ss_airway_modeling(index_matrix, ssl8)
    index_matrix = ss_airway_modeling(index_matrix, ssl9)
    index_matrix = ss_airway_modeling(index_matrix, ssl10)
    print("swaping axes")
    index_matrix = np.array(index_matrix, dtype="f")
    index_matrix = np.swapaxes(index_matrix, 0, 2).copy()
    end = time.time()
    print(end - start, 's')
    return index_matrix


# In[19]:


def image_generation(index_matrix):
    index_matrix = generating_test_image(index_matrix)
    print("generating Image")
    image = itk.GetImageFromArray(index_matrix)
    return image


# In[20]:

image = image_generation(index_matrix)

# In[21]:

view(image)

# In[ ]:
Example #12
0
def getNotebookBackend(actors2show, zoom, viewup):

    vp = settings.plotter_instance

    ####################################################################################
    # https://github.com/InsightSoftwareConsortium/itkwidgets
    #  /blob/master/itkwidgets/widget_viewer.py
    if 'itk' in settings.notebookBackend:
        from itkwidgets import view

        if sum(vp.shape) != 2:
            colors.printc("Warning: multirendering is not supported in jupyter.", c=1)

        settings.notebook_plotter = view(actors=actors2show,
                                         cmap='jet', ui_collapsed=True,
                                         gradient_opacity=False)


    ####################################################################################
    elif settings.notebookBackend == 'k3d':
        import k3d # https://github.com/K3D-tools/K3D-jupyter

        if vp.shape[0] != 1 or vp.shape[1] != 1:
            colors.printc("Warning: multirendering is not supported in jupyter.", c=1)

        actors2show2 = []
        for ia in actors2show:
            if isinstance(ia, vtk.vtkAssembly): #unpack assemblies
                acass = ia.unpack()
                #for a in acass:
                #    a.SetScale(ia.GetScale())
                actors2show2 += acass
            else:
                actors2show2.append(ia)

        vbb, sizes, min_bns, max_bns = addons.computeVisibleBounds()
        kgrid = vbb[0], vbb[2], vbb[4], vbb[1], vbb[3], vbb[5]

        settings.notebook_plotter = k3d.plot(axes=[vp.xtitle, vp.ytitle, vp.ztitle],
                                             menu_visibility=True,
                                             height=int(vp.size[1]/2) )
        settings.notebook_plotter.grid = kgrid
        settings.notebook_plotter.lighting = 1.2

        # set k3d camera
        settings.notebook_plotter.camera_auto_fit = False

        eps = 1 + numpy.random.random()*1.0e-04 # workaround to bug in k3d
        # https://github.com/K3D-tools/K3D-jupyter/issues/180

        if settings.plotter_instance and settings.plotter_instance.camera:
            k3dc =  utils.vtkCameraToK3D(settings.plotter_instance.camera)
            k3dc[2] = k3dc[2]*eps
            settings.notebook_plotter.camera = k3dc
        else:
            vsx, vsy, vsz = vbb[0]-vbb[1], vbb[2]-vbb[3], vbb[4]-vbb[5]
            vss = numpy.linalg.norm([vsx, vsy, vsz])
            if zoom:
                vss /= zoom
            vfp = (vbb[0]+vbb[1])/2, (vbb[2]+vbb[3])/2, (vbb[4]+vbb[5])/2 # camera target
            if viewup == 'z':
                vup = (0,0,1) # camera up vector
                vpos= vfp[0] + vss/1.9, vfp[1] + vss/1.9, vfp[2]+vss*0.01  # camera position
            elif viewup == 'x':
                vup = (1,0,0)
                vpos= vfp[0]+vss*0.01, vfp[1] + vss/1.5, vfp[2]  # camera position
            else:
                vup = (0,1,0)
                vpos= vfp[0]+vss*0.01, vfp[1]+vss*0.01, vfp[2] + vss/1.5  # camera position
            settings.notebook_plotter.camera = [vpos[0], vpos[1], vpos[2]*eps,
                                                 vfp[0],  vfp[1],  vfp[2],
                                                 vup[0],  vup[1],  vup[2] ]
        if not vp.axes:
            settings.notebook_plotter.grid_visible = False

        for ia in actors2show2:
            kobj = None
            kcmap= None

            if isinstance(ia, Mesh) and ia.N():

                iap = ia.GetProperty()
                #ia.clean().triangulate().computeNormals()
                #ia.triangulate())
                iapoly = ia.clone().clean().triangulate().computeNormals().polydata()

                vtkscals = None
                color_attribute = None
                if ia.mapper().GetScalarVisibility():
                    vtkdata = iapoly.GetPointData()
                    vtkscals = vtkdata.GetScalars()

                    if vtkscals is None:
                        vtkdata = iapoly.GetCellData()
                        vtkscals = vtkdata.GetScalars()
                        if vtkscals is not None:
                            c2p = vtk.vtkCellDataToPointData()
                            c2p.SetInputData(iapoly)
                            c2p.Update()
                            iapoly = c2p.GetOutput()
                            vtkdata = iapoly.GetPointData()
                            vtkscals = vtkdata.GetScalars()

                    if vtkscals is not None:
                        if not vtkscals.GetName():
                            vtkscals.SetName('scalars')
                        scals_min, scals_max = ia.mapper().GetScalarRange()
                        color_attribute = (vtkscals.GetName(), scals_min, scals_max)
                        lut = ia.mapper().GetLookupTable()
                        lut.Build()
                        kcmap=[]
                        nlut = lut.GetNumberOfTableValues()
                        for i in range(nlut):
                            r,g,b,a = lut.GetTableValue(i)
                            kcmap += [i/(nlut-1), r,g,b]

                if iapoly.GetNumberOfPolys() > 0:
                    name = None
                    if ia.filename:
                        name = os.path.basename(ia.filename)
                    kobj = k3d.vtk_poly_data(iapoly,
                                             name=name,
                                             color=colors.rgb2int(iap.GetColor()),
                                             color_attribute=color_attribute,
                                             color_map=kcmap,
                                             opacity=iap.GetOpacity(),
                                             wireframe=(iap.GetRepresentation()==1))

                    if iap.GetInterpolation() == 0:
                        kobj.flat_shading = True

                else:
                    kcols=[]
                    if color_attribute is not None:
                        scals = vtk_to_numpy(vtkscals)
                        kcols = k3d.helpers.map_colors(scals, kcmap,
                                                       [scals_min,scals_max]).astype(numpy.uint32)
                    sqsize = numpy.sqrt(numpy.dot(sizes, sizes))

                    if ia.NPoints() == ia.NCells():
                        kobj = k3d.points(ia.points().astype(numpy.float32),
                                          color=colors.rgb2int(iap.GetColor()),
                                          colors=kcols,
                                          opacity=iap.GetOpacity(),
                                          shader="3d",
                                          point_size=iap.GetPointSize()*sqsize/400,
                                          #compression_level=9,
                                          )
                    else:
                        kobj = k3d.line(ia.points().astype(numpy.float32),
                                        color=colors.rgb2int(iap.GetColor()),
                                        colors=kcols,
                                        opacity=iap.GetOpacity(),
                                        shader="thick",
                                        width=iap.GetLineWidth()*sqsize/1000,
                                        )

                settings.notebook_plotter += kobj

            elif isinstance(ia, Volume):
                kx, ky, kz = ia.dimensions()
                arr = ia.getPointArray()
                kimage = arr.reshape(-1, ky, kx)

                colorTransferFunction = ia.GetProperty().GetRGBTransferFunction()
                kcmap=[]
                for i in range(128):
                    r,g,b = colorTransferFunction.GetColor(i/127)
                    kcmap += [i/127, r,g,b]

                #print('vol scal range', ia.imagedata().GetScalarRange())
                #print(numpy.min(kimage), numpy.max(kimage))

                kbounds = numpy.array(ia.imagedata().GetBounds()) \
                    + numpy.repeat(numpy.array(ia.imagedata().GetSpacing()) / 2.0, 2)\
                    * numpy.array([-1,1] * 3)

                kobj = k3d.volume(kimage.astype(numpy.float32),
                                  color_map=kcmap,
                                  #color_range=ia.imagedata().GetScalarRange(),
                                  alpha_coef=10,
                                  bounds=kbounds,
                                  )
                settings.notebook_plotter += kobj

            elif hasattr(ia, 'info') and 'formula' in ia.info.keys():
                pos = (ia.GetPosition()[0],ia.GetPosition()[1])
                kobj = k3d.text2d(ia.info['formula'], position=pos)
                settings.notebook_plotter += kobj


    ####################################################################################
    elif settings.notebookBackend == 'panel' and hasattr(vp, 'window') and vp.window:

        import panel # https://panel.pyviz.org/reference/panes/VTK.html

        vp.renderer.ResetCamera()

        settings.notebook_plotter = panel.pane.VTK(vp.window,
                                                   width=int(vp.size[0]/1.5),
                                                   height=int(vp.size[1]/2))


    ####################################################################################
    elif '2d' in settings.notebookBackend.lower() and hasattr(vp, 'window') and vp.window:
        import PIL.Image
        try:
            import IPython
        except ImportError:
            raise Exception('IPython not available.')
            return

        from vtkplotter.vtkio import screenshot
        settings.screeshotLargeImage = True
        nn = screenshot(returnNumpy=True, scale=settings.screeshotScale+2)
        pil_img = PIL.Image.fromarray(nn)
        settings.notebook_plotter = IPython.display.display(pil_img)

    return settings.notebook_plotter
Example #13
0
import math
import numpy as np
import itk
import itkwidgets
from itkwidgets import view
from ipywidgets import interactive
import ipywidgets as widgets

# 加载原始体数据并显示
input_name = '/home/hja/Projects/3D2DRegister/ASOCA/Train_Masks/0.nrrd'
volume_lung = itk.imread(input_name, itk.ctype('float'))  # 读取影像文件,并将数据格式转换为float
print(volume_lung.GetLargestPossibleRegion().GetSize())
print(volume_lung.GetBufferedRegion().GetSize())
print(volume_lung.GetSpacing())
print(volume_lung.GetOrigin())
view(volume_lung, gradient_opacity=0.5, cmp=itkwidgets.cm.bone)

output_image_pixel_spacing = [0.37, 0.37, 1]
output_image_size = [512, 512, 1]  # [501, 501, 1]

InputImageType = type(volume_lung)
FilterType = itk.ResampleImageFilter[InputImageType, InputImageType]
filter = FilterType.New()
filter.SetInput(volume_lung)
filter.SetDefaultPixelValue(0)
filter.SetSize(output_image_size)
filter.SetOutputSpacing(output_image_pixel_spacing)

TransformType = itk.CenteredEuler3DTransform[itk.D]
transform = TransformType.New()
transform.SetComputeZYX(True)
Example #14
0
from skimage.util import montage as montage2d

# for showing results
import dask.diagnostics as diag

foam_stack = imread("../common/data/plateau_border.tif")[:-54, 52:-52, 52:-52]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))
ax1.imshow(np.sum(foam_stack, 0), cmap="bone_r")
ax2.imshow(montage2d(foam_stack[::10]), cmap="bone_r")

# In[18]:

from itkwidgets import view
import itk

view(itk.GetImageFromArray(foam_stack.copy()))

# In[19]:

da_foam = da.from_array(foam_stack / 255.0,
                        chunks=(20, 400, 400),
                        name="FoamImage")
dot_graph(da_foam.dask)

# In[20]:

import dask_ndfilters as da_ndfilt

image_filt = da_ndfilt.gaussian_filter(1 - da_foam, (3, 6, 6))
dot_graph(image_filt.dask)
Example #15
0
def DigitallyReconstructedRadiograph(
        ray_source_distance=100,
        camera_tx=0.,
        camera_ty=0.,
        camera_tz=0.,
        rotation_x=0.,
        rotation_y=0.,
        rotation_z=0.,
        projection_normal_p_x=0.,
        projection_normal_p_y=0.,
        rotation_center_rt_volume_center_x=0.,
        rotation_center_rt_volume_center_y=0.,
        rotation_center_rt_volume_center_z=0.,
        threshold=0.,
):
    """
    Parameters description:

    ray_source_distance = 400                              # <-sid float>            Distance of ray source (focal point) focal point 400mm
    camera_translation_parameter = [0., 0., 0.]            # <-t float float float>  Translation parameter of the camera
    rotation_around_xyz = [0., 0., 0.]                     # <-rx float>             Rotation around x,y,z axis in degrees
    projection_normal_position = [0, 0]                    # <-normal float float>   The 2D projection normal position [default: 0x0mm]
    rotation_center_relative_to_volume_center = [0, 0, 0]  # <-cor float float float> The centre of rotation relative to centre of volume
    threshold = 10                                          # <-threshold float>      Threshold [default: 0]
    """

    dgree_to_radius_coef = 1. / 180. * math.pi
    camera_translation_parameter = [camera_tx, camera_ty, camera_tz]
    rotation_around_xyz = [rotation_x * dgree_to_radius_coef, rotation_y * dgree_to_radius_coef,
                           rotation_z * dgree_to_radius_coef]
    projection_normal_position = [projection_normal_p_x, projection_normal_p_y]
    rotation_center_relative_to_volume_center = [
        rotation_center_rt_volume_center_x,
        rotation_center_rt_volume_center_y,
        rotation_center_rt_volume_center_z
    ]

    imageOrigin = volume_lung.GetOrigin()
    imageSpacing = volume_lung.GetSpacing()
    imageRegion = volume_lung.GetBufferedRegion()
    imageSize = imageRegion.GetSize()
    imageCenter = [imageOrigin[i] + imageSpacing[i] * imageSize[i] / 2.0 for i in range(3)]

    transform.SetTranslation(camera_translation_parameter)
    transform.SetRotation(rotation_around_xyz[0], rotation_around_xyz[1], rotation_around_xyz[2])

    center = [c + imageCenter[i] for i, c in enumerate(rotation_center_relative_to_volume_center)]
    transform.SetCenter(center)

    interpolator.SetTransform(transform)
    interpolator.SetThreshold(threshold)
    focalPoint = [imageCenter[0], imageCenter[1], imageCenter[2] - ray_source_distance / 2.0]
    interpolator.SetFocalPoint(focalPoint)

    filter.SetInterpolator(interpolator)
    filter.SetTransform(transform)

    origin = [
        imageCenter[0] + projection_normal_position[0] - output_image_pixel_spacing[0] * (
                    output_image_size[0] - 1) / 2.,
        imageCenter[1] + projection_normal_position[1] - output_image_pixel_spacing[1] * (
                    output_image_size[1] - 1) / 2.,
        imageCenter[2] + imageSpacing[2] * imageSize[2]
    ]

    filter.SetOutputOrigin(origin)
    filter.Update()

    global viewer
    if viewer is None:
        viewer = view(filter.GetOutput(), mode='z')
    else:
        print("Update viewer image")
        viewer.image = filter.GetOutput()

    # print informations
    print("Volume image informations:")
    print("tvolume image origin : ", imageOrigin)
    print("tvolume image size   : ", imageSize)
    print("tvolume image spacing: ", imageSpacing)
    print("tvolume image center : ", imageCenter)
    print("Transform informations:")
    print("ttranslation         : ", camera_translation_parameter)
    print("trotation            : ", rotation_around_xyz)
    print("tcenter               : ", center)
    print("Interpolator informations: ")
    print("tthreshold           : ", threshold)
    print("tfocalPoint          : ", focalPoint)
    print("Filter informations:")
    print("toutput origin        : ", origin)
Example #16
0
def getNotebookBackend(actors2show, zoom, viewup):

    vp = settings.plotter_instance

    if zoom == 'tight':
        zoom=1 # disable it

    if isinstance(vp.shape, str) or sum(vp.shape) > 2:
        colors.printc("Multirendering is not supported in jupyter.", c=1)
        return

    ####################################################################################
    # https://github.com/InsightSoftwareConsortium/itkwidgets
    #  /blob/master/itkwidgets/widget_viewer.py
    if 'itk' in settings.notebookBackend:
        from itkwidgets import view

        settings.notebook_plotter = view(actors=actors2show,
                                         cmap='jet', ui_collapsed=True,
                                         gradient_opacity=False)


    ####################################################################################
    elif settings.notebookBackend == 'k3d':
        try:
            import k3d # https://github.com/K3D-tools/K3D-jupyter
        except:
            print("Cannot find k3d, install with:  pip install k3d")
            return

        actors2show2 = []
        for ia in actors2show:
            if not ia:
                continue
            if isinstance(ia, vtk.vtkAssembly): #unpack assemblies
                acass = ia.unpack()
                actors2show2 += acass
            else:
                actors2show2.append(ia)

        # vbb, sizes, _, _ = addons.computeVisibleBounds()
        # kgrid = vbb[0], vbb[2], vbb[4], vbb[1], vbb[3], vbb[5]

        settings.notebook_plotter = k3d.plot(axes=[vp.xtitle, vp.ytitle, vp.ztitle],
                                             menu_visibility=settings.k3dMenuVisibility,
                                             height=settings.k3dPlotHeight,
                                             antialias=settings.k3dAntialias,
                                             )
        # settings.notebook_plotter.grid = kgrid
        settings.notebook_plotter.lighting = settings.k3dLighting

        # set k3d camera
        settings.notebook_plotter.camera_auto_fit = settings.k3dCameraAutoFit
        settings.notebook_plotter.grid_auto_fit = settings.k3dGridAutoFit

        settings.notebook_plotter.axes_helper = settings.k3dAxesHelper

        if settings.plotter_instance and settings.plotter_instance.camera:
            k3dc =  utils.vtkCameraToK3D(settings.plotter_instance.camera)
            if zoom:
                k3dc[0] /= zoom
                k3dc[1] /= zoom
                k3dc[2] /= zoom
            settings.notebook_plotter.camera = k3dc
        # else:
        #     vsx, vsy, vsz = vbb[0]-vbb[1], vbb[2]-vbb[3], vbb[4]-vbb[5]
        #     vss = numpy.linalg.norm([vsx, vsy, vsz])
        #     if zoom:
        #         vss /= zoom
        #     vfp = (vbb[0]+vbb[1])/2, (vbb[2]+vbb[3])/2, (vbb[4]+vbb[5])/2 # camera target
        #     if viewup == 'z':
        #         vup = (0,0,1) # camera up vector
        #         vpos= vfp[0] + vss/1.9, vfp[1] + vss/1.9, vfp[2]+vss*0.01  # camera position
        #     elif viewup == 'x':
        #         vup = (1,0,0)
        #         vpos= vfp[0]+vss*0.01, vfp[1] + vss/1.5, vfp[2]  # camera position
        #     else:
        #         vup = (0,1,0)
        #         vpos= vfp[0]+vss*0.01, vfp[1]+vss*0.01, vfp[2] + vss/1.5  # camera position
        #     settings.notebook_plotter.camera = [vpos[0], vpos[1], vpos[2],
        #                                           vfp[0],  vfp[1],  vfp[2],
        #                                           vup[0],  vup[1],  vup[2] ]
        if not vp.axes:
            settings.notebook_plotter.grid_visible = False

        for ia in actors2show2:

            if isinstance(ia, (vtk.vtkCornerAnnotation, vtk.vtkAssembly)):
                continue

            kobj = None
            kcmap= None
            name = None
            if hasattr(ia, 'filename'):
                if ia.filename:
                    name = os.path.basename(ia.filename)
                if ia.name:
                    name = os.path.basename(ia.name)

            #####################################################################scalars
            # work out scalars first, Points Lines are also Mesh objs
            if isinstance(ia, (Mesh, shapes.Line, Points)):
#                print('scalars', ia.name, ia.N())
                iap = ia.GetProperty()

                if isinstance(ia, (shapes.Line, Points)):
                    iapoly = ia.polydata()
                else:
                    iapoly = ia.clone().clean().triangulate().computeNormals().polydata()

                vtkscals = None
                color_attribute = None
                if ia.mapper().GetScalarVisibility():
                    vtkdata = iapoly.GetPointData()
                    vtkscals = vtkdata.GetScalars()

                    if vtkscals is None:
                        vtkdata = iapoly.GetCellData()
                        vtkscals = vtkdata.GetScalars()
                        if vtkscals is not None:
                            c2p = vtk.vtkCellDataToPointData()
                            c2p.SetInputData(iapoly)
                            c2p.Update()
                            iapoly = c2p.GetOutput()
                            vtkdata = iapoly.GetPointData()
                            vtkscals = vtkdata.GetScalars()

                    if vtkscals is not None:
                        if not vtkscals.GetName():
                            vtkscals.SetName('scalars')
                        scals_min, scals_max = ia.mapper().GetScalarRange()
                        color_attribute = (vtkscals.GetName(), scals_min, scals_max)
                        lut = ia.mapper().GetLookupTable()
                        lut.Build()
                        kcmap=[]
                        nlut = lut.GetNumberOfTableValues()
                        for i in range(nlut):
                            r,g,b,a = lut.GetTableValue(i)
                            kcmap += [i/(nlut-1), r,g,b]


            #####################################################################Volume
            if isinstance(ia, Volume):
#                print('Volume', ia.name, ia.dimensions())
                kx, ky, kz = ia.dimensions()
                arr = ia.pointdata[0]
                kimage = arr.reshape(-1, ky, kx)

                colorTransferFunction = ia.GetProperty().GetRGBTransferFunction()
                kcmap=[]
                for i in range(128):
                    r,g,b = colorTransferFunction.GetColor(i/127)
                    kcmap += [i/127, r,g,b]

                kbounds = numpy.array(ia.imagedata().GetBounds()) \
                    + numpy.repeat(numpy.array(ia.imagedata().GetSpacing()) / 2.0, 2)\
                    * numpy.array([-1,1] * 3)

                kobj = k3d.volume(kimage.astype(numpy.float32),
                                  color_map=kcmap,
                                  #color_range=ia.imagedata().GetScalarRange(),
                                  alpha_coef=10,
                                  bounds=kbounds,
                                  name=name,
                                  )
                settings.notebook_plotter += kobj

            #####################################################################text
            elif hasattr(ia, 'info') and 'formula' in ia.info.keys():
                pos = (ia.GetPosition()[0],ia.GetPosition()[1])
                kobj = k3d.text2d(ia.info['formula'], position=pos)
                settings.notebook_plotter += kobj


            #####################################################################Mesh
            elif isinstance(ia, Mesh) and ia.N() and len(ia.faces()):
                # print('Mesh', ia.name, ia.N(), len(ia.faces()))
                kobj = k3d.vtk_poly_data(iapoly,
                                         name=name,
                                         # color=_rgb2int(iap.GetColor()),
                                         color_attribute=color_attribute,
                                         color_map=kcmap,
                                         opacity=iap.GetOpacity(),
                                         wireframe=(iap.GetRepresentation()==1))

                if iap.GetInterpolation() == 0:
                    kobj.flat_shading = True
                settings.notebook_plotter += kobj

            #####################################################################Points
            elif isinstance(ia, Points):
                # print('Points', ia.name, ia.N())
                kcols=[]
                if color_attribute is not None:
                    scals = utils.vtk2numpy(vtkscals)
                    kcols = k3d.helpers.map_colors(scals, kcmap,
                                                   [scals_min,scals_max]).astype(numpy.uint32)
                # sqsize = numpy.sqrt(numpy.dot(sizes, sizes))

                kobj = k3d.points(ia.points().astype(numpy.float32),
                                  color=_rgb2int(iap.GetColor()),
                                  colors=kcols,
                                  opacity=iap.GetOpacity(),
                                  shader=settings.k3dPointShader,
                                  point_size=iap.GetPointSize(),
                                  name=name,
                                  )
                settings.notebook_plotter += kobj


            #####################################################################Lines
            elif ia.polydata(False).GetNumberOfLines():
                # print('Line', ia.name, ia.N(), len(ia.faces()),
                #       ia.polydata(False).GetNumberOfLines(), len(ia.lines()),
                #       color_attribute, [vtkscals])

                # kcols=[]
                # if color_attribute is not None:
                #     scals = utils.vtk2numpy(vtkscals)
                #     kcols = k3d.helpers.map_colors(scals, kcmap,
                #                                    [scals_min,scals_max]).astype(numpy.uint32)

                # sqsize = numpy.sqrt(numpy.dot(sizes, sizes))

                for i, ln_idx in enumerate(ia.lines()):
                    if i>200:
                        print('WARNING: K3D nr of line segments is limited to 200.')
                        break
                    pts = ia.points()[ln_idx]
                    kobj = k3d.line(pts.astype(numpy.float32),
                                    color=_rgb2int(iap.GetColor()),
                                    opacity=iap.GetOpacity(),
                                    shader=settings.k3dLineShader,
                                    # width=iap.GetLineWidth()*sqsize/1000,
                                    name=name,
                                    )

                    settings.notebook_plotter += kobj


    ####################################################################################
    elif settings.notebookBackend == 'panel' and hasattr(vp, 'window') and vp.window:

        import panel # https://panel.pyviz.org/reference/panes/VTK.html
        vp.renderer.ResetCamera()
        settings.notebook_plotter = panel.pane.VTK(vp.window,
                                                   width=int(vp.size[0]/1.5),
                                                   height=int(vp.size[1]/2))


    ####################################################################################
    elif 'ipyvtk' in settings.notebookBackend and hasattr(vp, 'window') and vp.window:

        from ipyvtklink.viewer import ViewInteractiveWidget
        vp.renderer.ResetCamera()
        settings.notebook_plotter = ViewInteractiveWidget(vp.window)

    ####################################################################################
    elif 'ipygany' in settings.notebookBackend:

        from ipygany import PolyMesh, Scene, IsoColor, RGB, Component
        from ipygany import Alpha, ColorBar, colormaps, PointCloud
        from ipywidgets import FloatRangeSlider, Dropdown, VBox, AppLayout, jslink

        bgcol = colors.rgb2hex(colors.getColor(vp.backgrcol))

        actors2show2 = []
        for ia in actors2show:
            if not ia:
                continue
            if isinstance(ia, vedo.Assembly): #unpack assemblies
                assacts = ia.unpack()
                for ja in assacts:
                    if isinstance(ja, vedo.Assembly):
                        actors2show2 += ja.unpack()
                    else:
                        actors2show2.append(ja)
            else:
                actors2show2.append(ia)

        pmeshes = []
        colorbar = None
        for obj in actors2show2:
#            print("ipygany processing:", [obj], obj.name)

            if isinstance(obj, vedo.shapes.Line):
                lg = obj.diagonalSize()/1000 * obj.GetProperty().GetLineWidth()
                vmesh = vedo.shapes.Tube(obj.points(), r=lg, res=4).triangulate()
                vmesh.c(obj.c())
                faces = vmesh.faces()
                # todo: Lines
            elif isinstance(obj, Mesh):
                vmesh = obj.triangulate()
                faces = vmesh.faces()
            elif isinstance(obj, Points):
                vmesh = obj
                faces = []
            elif isinstance(obj, Volume):
                vmesh = obj.isosurface()
                faces = vmesh.faces()
            elif isinstance(obj, vedo.TetMesh):
                vmesh = obj.tomesh(fill=False)
                faces = vmesh.faces()
            else:
                print("ipygany backend: cannot process object type", [obj])
                continue

            vertices = vmesh.points()
            scals = vmesh.inputdata().GetPointData().GetScalars()
            if scals and not colorbar: # there is an active array, only pick the first
                aname = scals.GetName()
                arr = vmesh.pointdata[aname]
                parr = Component(name=aname, array=arr)
                if len(faces):
                    pmesh = PolyMesh(vertices=vertices, triangle_indices=faces, data={aname: [parr]})
                else:
                    pmesh = PointCloud(vertices=vertices, data={aname: [parr]})
                rng = scals.GetRange()
                colored_pmesh = IsoColor(pmesh, input=aname, min=rng[0], max=rng[1])
                if obj.scalarbar:
                    colorbar = ColorBar(colored_pmesh)
                    colormap_slider_range = FloatRangeSlider(value=rng,
                                                             min=rng[0], max=rng[1],
                                                             step=(rng[1] - rng[0]) / 100.)
                    jslink((colored_pmesh, 'range'), (colormap_slider_range, 'value'))
                    colormap = Dropdown(
                        options=colormaps,
                        description='Colormap:'
                    )
                    jslink((colored_pmesh, 'colormap'), (colormap, 'index'))

            else:
                if len(faces):
                    pmesh = PolyMesh(vertices=vertices, triangle_indices=faces)
                else:
                    pmesh = PointCloud(vertices=vertices)
                if vmesh.alpha() < 1:
                    colored_pmesh = Alpha(RGB(pmesh, input=tuple(vmesh.color())), input=vmesh.alpha())
                else:
                    colored_pmesh = RGB(pmesh, input=tuple(vmesh.color()))

            pmeshes.append(colored_pmesh)

        if colorbar:
            scene = AppLayout(
                    left_sidebar=Scene(pmeshes, background_color=bgcol),
                    right_sidebar=VBox((colormap_slider_range, #not working
                                        colorbar,
                                        colormap)),
                    pane_widths=[2, 0, 1],
            )
        else:
            scene = Scene(pmeshes, background_color=bgcol)

        settings.notebook_plotter = scene



    ####################################################################################
    elif '2d' in settings.notebookBackend.lower() and hasattr(vp, 'window') and vp.window:
        import PIL.Image
        try:
            import IPython
        except ImportError:
            raise Exception('IPython not available.')

        from vedo.io import screenshot
        settings.screeshotLargeImage = True
        nn = screenshot(returnNumpy=True, scale=settings.screeshotScale+2)
        pil_img = PIL.Image.fromarray(nn)
        settings.notebook_plotter = IPython.display.display(pil_img)

    return settings.notebook_plotter
Example #17
0
    def contourf(self, **kwargs):

        x = kwargs.get("x", self._obj.SCHISM_hgrid_node_x[:].values)
        y = kwargs.get("y", self._obj.SCHISM_hgrid_node_y[:].values)
        try:
            t = kwargs.get("t", self._obj.time.values)
        except:
            pass

        tri3 = kwargs.get("tes", self._obj.SCHISM_hgrid_face_nodes.values[:, :3].astype(int))

        it = kwargs.get("it", None)

        var = kwargs.get("var", "depth")
        z = kwargs.get("z", self._obj[var].values[it, :].flatten())
        name = kwargs.get("name", self._obj[var].name)

        vmin = kwargs.get("vmin", z.min())
        vmax = kwargs.get("vmax", z.max())

        R = kwargs.get("R", 1.0)

        dim = kwargs.get("dim", "2D")

        if dim == "3D":
            px, py, pz = to_3d(x, y, R=R)
        else:
            px = x
            py = y
            pz = np.zeros(x.shape[0])

        rep = kwargs.get("representation", "surface")

        cmap = kwargs.get("cmap", "gist_earth")

        mlab.figure(1, size=(3840, 2160), bgcolor=(0, 0, 0), fgcolor=(1.0, 1.0, 1.0))
        mlab.clf()

        bcolor = kwargs.get("bcolor", (0.0, 0.0, 0.0))
        #        self.globe(R - 0.002, bcolor=bcolor)
        # 3D triangular mesh surface (like trisurf)
        grd = mlab.triangular_mesh(
            px,
            py,
            pz,
            tri3,
            representation=rep,
            opacity=1.0,
            scalars=z,
            colormap=cmap,
            vmin=vmin,
            vmax=vmax,
        )

        grd.actor.mapper.scalar_visibility = True
        mlab.view(azimuth=0, distance=4)

        title = kwargs.get("title", "{}".format(var))

        mlab.colorbar(grd, title=name, orientation="vertical")

        coast = kwargs.get("coastlines", None)

        if coast is not None:
            src, lines = self.c3d(coast, R=R)
            mlab.pipeline.surface(src, color=(1, 0, 0), line_width=10, opacity=0.8)

        v = view(actors=grd, rotate=False, ui_collapsed=True)
        v.geometries = [v.geometries[0]]
        #        print(v.geometries)
        #        print(v.geometries[0].keys())
        #        print(v.geometries[0]['points'])
        #        v.geometries[0]['pointData']['arrays'][1]['data']['name'] = 'elevation'
        #        v.geometries[0]['metadata'] = {"name":"earth"}
        #        print(v.geometries)
        return v
    def __init__(self,
                 tree=None,
                 swc_morphologies=[],
                 markers=[],
                 marker_sizes=[],
                 marker_opacities=[],
                 marker_colors=[],
                 selected_allen_ids=None,
                 selected_acronyms=None,
                 rotate=False,
                 **kwargs):
        """Create a 3D CCF visualization ipywidget.

        Parameters
        ----------
        tree: None or 'ipytree', optional, default: None
            Structure tree visualization to include.

        swc_morphologies: List, optional, default: []
            List of Allen SWC morphologies to render.

        markers: List of Nx3 arrays, optional, default: []
            Points locations to visualize in the CCF. Each element in the list
            corresponds to a different set of markers. Each marker set has N points,
            with point locations in CCF coordinates:
                [anterior_posterior, dorsal_ventral, left_right]

        marker_sizes: List of integers in [1, 10], optional, default: []
            Size of the markers.

        marker_opacities: array of floats, default: [1.0,]*n
            Opacity for the markers, in the range (0.0, 1.0].

        marker_colors: list of (r, g, b) colors
            Colors for the N markers. See help(matplotlib.colors) for
            specification. Defaults to the Glasbey series of categorical colors.

        selected_allen_ids: List of Allen ids to highlight, optional, default: None
            List of integer Allen Structure Graph ids to highlight. Specify
            selected_allen_ids or selected_acronyms.

        selected_acronyms: List of Allen acronyms to highlight, optional, default: None
            List of string Allen Structure Graph acronyms to highlight. Specify
            selected_allen_ids or selected_acronyms.

        rotate: bool, optional, default: False
            Make the CCF continuously rotate.
        """
        self._image = itk.image_from_xarray(_image_da)
        self._label_image = itk.image_from_xarray(_label_image_da)
        self.swc_point_sets = []
        self.swc_geometries = []
        opacity_gaussians = [[{
            'position': 0.28094135802469133,
            'height': 0.3909090909090909,
            'width': 0.44048611111111113,
            'xBias': 0.21240499194846996,
            'yBias': 0.5416908212560397
        }, {
            'position': 0.2787808641975309,
            'height': 1,
            'width': 0.1,
            'xBias': 0,
            'yBias': 0
        }]]
        opacity_gaussians = [[{
            'position': 0.32816358024691356,
            'height': 0.5,
            'width': 0.29048611111111106,
            'xBias': 0.20684943639291442,
            'yBias': 1.1235090030742216
        }]]
        camera = np.array([[1.3441567e+03, -2.1723846e+04, 1.7496496e+04],
                           [6.5500000e+03, 3.9750000e+03, 5.6750000e+03],
                           [3.6606243e-01, -4.4908229e-01, -8.1506038e-01]],
                          dtype=np.float32)
        size_limit_3d = [256, 256, 256]
        self.itk_viewer = view(image=self._image,
                               label_image=self._label_image,
                               opacity_gaussians=opacity_gaussians,
                               label_image_blend=0.65,
                               point_sets=markers.copy(),
                               camera=camera,
                               ui_collapsed=True,
                               shadow=False,
                               size_limit_3d=size_limit_3d,
                               background=(0.85, ) * 3,
                               units="μm",
                               gradient_opacity=0.1)
        # Todo: initialization should work
        self.itk_viewer.opacity_gaussians = opacity_gaussians
        self.itk_viewer.rotate = rotate
        self.itk_viewer.label_image_blend = 0.65

        mode_buttons = RadioButtons(options=['x', 'y', 'z', 'v'],
                                    value='v',
                                    description='View mode:')
        link((mode_buttons, 'value'), (self.itk_viewer, 'mode'))

        rotate_checkbox = Checkbox(value=rotate, description='Rotate')
        link((rotate_checkbox, 'value'), (self.itk_viewer, 'rotate'))
        viewer_controls = HBox([mode_buttons, rotate_checkbox])

        viewer = VBox([self.itk_viewer, viewer_controls])

        children = [viewer]

        self._validating_allen_ids = False
        self._validating_acronyms = False
        self._validating_tree = False

        self.tree_widget = None
        if tree is not None:
            if tree == 'ipytree':
                from .ipytree_widget import IPyTreeWidget
                self.tree_widget = IPyTreeWidget(structure_graph)
                children.append(self.tree_widget)
                self.tree_widget.observe(self._ipytree_on_selected_change,
                                         names=['selected_nodes'])

                def open_parent(node):
                    if hasattr(node, 'parent_structure_id') and \
                            node.parent_structure_id in self.tree_widget.allen_id_to_node:
                        parent = self.tree_widget.allen_id_to_node[
                            node.parent_structure_id]
                        open_parent(parent)
                    else:
                        node.opened = True

                self.last_selected_tree_nodes = []

                def ipytree_on_allen_ids_changed(change):
                    self._validating_tree = True
                    with self.tree_widget.hold_sync():
                        for node in self.last_selected_tree_nodes:
                            node.selected = False
                        tree_nodes = [
                            self.tree_widget.allen_id_to_node[allen_id]
                            for allen_id in change.new
                        ]
                        for node in tree_nodes:
                            open_parent(node)
                            node.selected = True
                            node.opened = True
                    self.last_selected_tree_nodes = tree_nodes
                    self._validating_tree = False

                # self.observe(ipytree_on_allen_ids_changed, names='selected_allen_ids')
            else:
                raise RuntimeError('Invalid tree type')

        self.labels = np.unique(self.itk_viewer.rendered_label_image)

        super(CCFWidget, self).__init__(children, **kwargs)

        for morphology in swc_morphologies:
            soma_point_set, geometry = swc_morphology_geometry(morphology)
            self.swc_point_sets.append(soma_point_set)
            self.swc_geometries.append(geometry)
        if swc_morphologies:
            self.itk_viewer.point_sets = self.swc_point_sets
            self.itk_viewer.point_set_sizes = [
                3,
            ] * len(self.swc_point_sets)
            self.itk_viewer.point_set_opacities = [
                1.0,
            ] * len(self.swc_point_sets)
            self.itk_viewer.point_set_colors = [
                (1.0, 0.0, 0.0),
            ] * len(self.swc_point_sets)
            self.itk_viewer.geometries = self.swc_geometries

        if selected_acronyms:
            self.selected_acronyms = selected_acronyms
        if selected_allen_ids:
            self.selected_allen_ids = selected_allen_ids

        self.markers = markers
        if marker_sizes:
            self.marker_sizes = marker_sizes
        if marker_opacities:
            self.marker_opacities = marker_opacities
        if marker_colors:
            self.marker_colors = marker_colors