Ejemplo n.º 1
0
    def draw(self):
        """Draw data."""
        if len(self.fitResults) == 0:
            return

        # Make sure our figure is the active one
        vv.figure(self.fig.nr)

        if not hasattr(self, 'subplot1'):
            self.subplot1 = vv.subplot(211)
            #self.subplot1.position = (30, 2, -32, -32)
            self.subplot2 = vv.subplot(212)
            #self.subplot1.position = (30, 2, -32, -32)

        a, ed = numpy.histogram(self.fitResults['tIndex'], self.Size[0] / 6)
        print((float(numpy.diff(ed[:2]))))

        self.subplot1.MakeCurrent()
        vv.cla()
        vv.plot(ed[:-1], a / float(numpy.diff(ed[:2])), lc='b', lw=2)
        #self.subplot1.set_xticks([0, ed.max()])
        #self.subplot1.set_yticks([0, numpy.floor(a.max()/float(numpy.diff(ed[:2])))])
        self.subplot2.MakeCurrent()
        vv.cla()
        #cs =
        csa = numpy.cumsum(a)
        vv.plot(ed[:-1], csa / float(csa[-1]), lc='g', lw=2)
        #self.subplot2.set_xticks([0, ed.max()])
        #self.subplot2.set_yticks([0, a.sum()])

        self.fig.DrawNow()
        self.subplot1.position = (20, 2, -22, -32)
        self.subplot2.position = (20, 2, -22, -32)
Ejemplo n.º 2
0
	def DisplayOptimization (self) :
		"""
		Display the progress of optimization
		"""
		wx.Yield()
		# abort, if requested 
		if self.need_abort : return
	
		def GetValueColourIter (d) :
			return izip_longest( d.itervalues(), ['r', 'g', 'b', 'k'],  fillvalue='y' )
	
		visvis.cla(); visvis.clf()
		visvis.subplot(211)
		
		# Plot optimization statistics
		for values, colour in GetValueColourIter(self.optimization_log) :
			try : visvis.plot ( values, lc=colour ) 
			except Exception : pass
		
		visvis.xlabel ('iteration')
		visvis.ylabel ('Objective function')
		visvis.legend( self.optimization_log.keys() )
		
		# Display reference signal
		visvis.subplot(212)
			
		# Plot reference signal
		for values, colour in GetValueColourIter(self.log_reference_signal) :
			try : visvis.plot ( values, lc=colour ) 
			except Exception : pass
		
		visvis.xlabel ('iteration')
		visvis.ylabel ("Signal from reference pulse")
		visvis.legend( ["channel %d" % x for x in self.log_reference_signal.keys()] )
Ejemplo n.º 3
0
    def draw( self ):
            """Draw data."""
            if len(self.fitResults) == 0:
                return
            
            # Make sure our figure is the active one
            vv.figure(self.fig.nr)
            
            if not hasattr( self, 'subplot1' ):
                self.subplot1 = vv.subplot(211)
                #self.subplot1.position = (30, 2, -32, -32)
                self.subplot2 = vv.subplot(212)
                #self.subplot1.position = (30, 2, -32, -32)

            

            a, ed = numpy.histogram(self.fitResults['tIndex'], self.Size[0]/6)
            print((float(numpy.diff(ed[:2]))))

            self.subplot1.MakeCurrent()
            vv.cla()
            vv.plot(ed[:-1], a/float(numpy.diff(ed[:2])), lc='b', lw=2)
            #self.subplot1.set_xticks([0, ed.max()])
            #self.subplot1.set_yticks([0, numpy.floor(a.max()/float(numpy.diff(ed[:2])))])
            self.subplot2.MakeCurrent()
            vv.cla()
            #cs =
            csa = numpy.cumsum(a)
            vv.plot(ed[:-1], csa/float(csa[-1]), lc='g', lw=2)
            #self.subplot2.set_xticks([0, ed.max()])
            #self.subplot2.set_yticks([0, a.sum()])

            self.fig.DrawNow()
            self.subplot1.position = (20, 2, -22, -32)
            self.subplot2.position = (20, 2, -22, -32)
Ejemplo n.º 4
0
def figparts():
    """ Visualize ring parts
    """
    fig = vv.figure(4);
    fig.position = 8.00, 30.00,  944.00, 1002.00
    vv.clf()
    a0 = vv.subplot(121)
    show_ctvolume(vol, model, showVol=showVol, clim=clim0, isoTh=isoTh)
    modelR1, modelR2 = modelsR1R2[0][0], modelsR1R2[0][1]
    modelR1.Draw(mc='g', mw = 10, lc='g') # R1 = green
    modelR2.Draw(mc='c', mw = 10, lc='c') # R2 = cyan
    vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)')
    vv.title('Analysis for model LSPEAS %s  -  %s' % (ptcode[7:], ctcode))
    a0.axis.axisColor= 1,1,1
    a0.bgcolor= 0,0,0
    a0.daspect= 1, 1, -1  # z-axis flipped
    a0.axis.visible = showAxis
    
    a1 = vv.subplot(122)
    show_ctvolume(vol, model, showVol=showVol, clim=clim0, isoTh=isoTh)
    models[0][0].Draw(mc='y', mw = 10, lc='y') # struts = yellow
    models[0][1].Draw(mc='r', mw = 10, lc='r') # hooks = red
    vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)')
    vv.title('Analysis for model LSPEAS %s  -  %s' % (ptcode[7:], ctcode))
    a1.axis.axisColor= 1,1,1
    a1.bgcolor= 0,0,0
    a1.daspect= 1, 1, -1  # z-axis flipped
    a1.axis.visible = showAxis
    
    a0.camera = a1.camera
Ejemplo n.º 5
0
    def PlotReferencePhase(self, event):
        """
		Plot reference phase
		"""
        visvis.cla()
        visvis.clf()

        # get actual amplitude and phased
        phase = self.GetReferencePhase()[0]
        ampl = np.ones(phase.size)
        ampl, phase = self.DevPulseShaper.GetUnwrappedAmplPhase(ampl, phase)

        # Wrap the phase in radians
        phase %= (2 * np.pi)

        # Get the phase in unites of 2*pi
        phase /= (2 * np.pi)

        visvis.subplot(211)
        visvis.plot(phase)
        visvis.ylabel('Reference phase')
        visvis.xlabel('puls shaper pixel number')
        visvis.title('Current reference phase (in unites of 2*pi)')

        visvis.subplot(212)
        visvis.plot(self.corrections, lc='r', ms='*', mc='r')
        visvis.ylabel('Value of coefficients')
        visvis.xlabel('coefficient number')
        visvis.title('Value of corrections')
Ejemplo n.º 6
0
	def PlotReferencePhase (self, event) :
		"""
		Plot reference phase
		"""
		visvis.cla(); visvis.clf(); 
		
		# get actual amplitude and phased
		phase = self.GetReferencePhase()[0]
		ampl = np.ones(phase.size)
		ampl, phase = self.DevPulseShaper.GetUnwrappedAmplPhase(ampl, phase) 
		
		# Wrap the phase in radians
		phase %= (2*np.pi)
		
		# Get the phase in unites of 2*pi
		phase /= (2*np.pi)
		
		visvis.subplot(211)
		visvis.plot(phase)
		visvis.ylabel ('Reference phase')
		visvis.xlabel ('puls shaper pixel number')
		visvis.title ('Current reference phase (in unites of 2*pi)')
		
		visvis.subplot(212)
		visvis.plot( self.corrections, lc='r',ms='*', mc='r' )
		visvis.ylabel ('Value of coefficients')
		visvis.xlabel ('coefficient number')
		visvis.title ('Value of corrections')
Ejemplo n.º 7
0
def select3dpoints(vol, nr_of_stents, fig=None, clim=None):
    """ Manually select 3d points in a volume. In the given figure (or a new 
    figure if None), three axes are created that display the transversal, 
    sagittal and coronal slices of the volume. The user can then use the mouse 
    to scroll to the correct slice and select the current position as an 
    endpoint of a stent. 
    Input: Number of stents to select start- and endpoints for.
    """

    # Create figure
    if fig is None:
        fig = vv.figure()
        figCleanup = True
    else:
        fig.Clear()
        figCleanup = False

    # Create four axes and a wibject to attach text labels to
    fig.position = 0, 22, 750, 700
    fig.title = '3D Point Selector'
    a1 = vv.subplot(321)
    a2 = vv.subplot(322)
    a3 = vv.subplot(323)
    a4 = vv.subplot(324)
    a5 = vv.Wibject(fig)

    # x-richting, y-richting, x-breedte?, y-breedte?
    a5.position = 0.5, 0.7, 0.5, 0.5

    # Set settings
    for a in [a1, a2, a3, a4]:
        a.showAxis = False

    # Create PointSelect instance
    pointselect3d = PointSelect3D(vol, a1, a3, a2, a4, a5, nr_of_stents, clim)

    # Enter a mainloop
    while not pointselect3d._finished:
        pointselect3d.Run()
        time.sleep(0.01)

    # Clean up figure (close if we opened it)
    fig.Clear()
    fig.DrawNow()
    if figCleanup:
        fig.Destroy()

    # Done (return points)
    Startpoints = []
    Endpoints = []
    for i in range(nr_of_stents):
        if isinstance(pointselect3d.endpoints[i * 2], tuple):
            Startpoints.append(pointselect3d.endpoints[i * 2])
        if isinstance(pointselect3d.endpoints[(i * 2) + 1], tuple):
            Endpoints.append(pointselect3d.endpoints[(i * 2) + 1])

    return Startpoints, Endpoints
Ejemplo n.º 8
0
def crop3d(vol, fig=None):
    """ crop3d(vol, fig=None)
    Manually crop a volume. In the given figure (or a new figure if None),
    three axes are created that display the transversal, sagittal and
    coronal MIPs (maximum intensity projection) of the volume. The user
    can then use the mouse to select a 3D range to crop the data to.
    """
    vv.use()

    # Create figure?
    if fig is None:
        fig = vv.figure()
        figCleanup = True
    else:
        fig.Clear()
        figCleanup = False

    # Create three axes and a wibject to attach text labels to
    a1 = vv.subplot(221)
    a2 = vv.subplot(222)
    a3 = vv.subplot(223)
    a4 = vv.Wibject(fig)
    a4.position = 0.5, 0.5, 0.5, 0.5

    # Set settings
    for a in [a1, a2, a3]:
        a.showAxis = False

    # Create cropper3D instance
    cropper3d = Cropper3D(vol, a1, a3, a2, a4)

    # Enter a mainloop
    while not cropper3d._finished:
        vv.processEvents()
        time.sleep(0.01)

    # Clean up figure (close if we opened it)
    fig.Clear()
    fig.DrawNow()
    if figCleanup:
        fig.Destroy()

    # Obtain ranges
    rx = cropper3d._range_transversal._rangex
    ry = cropper3d._range_transversal._rangey
    rz = cropper3d._range_coronal._rangey

    # Perform crop
    # make sure we have int not float
    rzmin, rzmax = int(rz.min), int(rz.max)
    rymin, rymax = int(ry.min), int(ry.max)
    rxmin, rxmax = int(rx.min), int(rx.max)
    vol2 = vol[rzmin:rzmax, rymin:rymax, rxmin:rxmax]
    # vol2 = vol[rz.min:rz.max, ry.min:ry.max, rx.min:rx.max]

    # Done
    return vol2
def main(select=3, **kwargs):
    """Script main function.

    select: int
        1: Medical data
        2: Blocky data, different every time
        3: Two donuts
        4: Ellipsoid

    """
    import visvis as vv  # noqa: delay import visvis and GUI libraries

    # Create test volume
    if select == 1:
        vol = vv.volread('stent')
        isovalue = kwargs.pop('level', 800)
    elif select == 2:
        vol = vv.aVolume(20, 128)
        isovalue = kwargs.pop('level', 0.2)
    elif select == 3:
        with timer('computing donuts'):
            vol = donuts()
        isovalue = kwargs.pop('level', 0.0)
        # Uncommenting the line below will yield different results for
        # classic MC
        # vol *= -1
    elif select == 4:
        vol = ellipsoid(4, 3, 2, levelset=True)
        isovalue = kwargs.pop('level', 0.0)
    else:
        raise ValueError('invalid selection')

    # Get surface meshes
    with timer('finding surface lewiner'):
        vertices1, faces1 = marching_cubes_lewiner(vol, isovalue, **kwargs)[:2]

    with timer('finding surface classic'):
        vertices2, faces2 = marching_cubes_classic(vol, isovalue, **kwargs)

    # Show
    vv.figure(1)
    vv.clf()
    a1 = vv.subplot(121)
    vv.title('Lewiner')
    m1 = vv.mesh(np.fliplr(vertices1), faces1)
    a2 = vv.subplot(122)
    vv.title('Classic')
    m2 = vv.mesh(np.fliplr(vertices2), faces2)
    a1.camera = a2.camera

    # visvis uses right-hand rule, gradient_direction param uses left-hand rule
    m1.cullFaces = m2.cullFaces = 'front'  # None, front or back

    vv.use().Run()
Ejemplo n.º 10
0
def main(select=3, **kwargs):
    """Script main function.

    select: int
        1: Medical data
        2: Blocky data, different every time
        3: Two donuts
        4: Ellipsoid

    """
    import visvis as vv  # noqa: delay import visvis and GUI libraries

    # Create test volume
    if select == 1:
        vol = vv.volread('stent')
        isovalue = kwargs.pop('level', 800)
    elif select == 2:
        vol = vv.aVolume(20, 128)
        isovalue = kwargs.pop('level', 0.2)
    elif select == 3:
        with timer('computing donuts'):
            vol = donuts()
        isovalue = kwargs.pop('level', 0.0)
        # Uncommenting the line below will yield different results for
        # classic MC
        # vol *= -1
    elif select == 4:
        vol = ellipsoid(4, 3, 2, levelset=True)
        isovalue = kwargs.pop('level', 0.0)
    else:
        raise ValueError('invalid selection')

    # Get surface meshes
    with timer('finding surface lewiner'):
        vertices1, faces1 = marching_cubes_lewiner(vol, isovalue, **kwargs)[:2]

    with timer('finding surface classic'):
        vertices2, faces2 = marching_cubes_classic(vol, isovalue, **kwargs)

    # Show
    vv.figure(1)
    vv.clf()
    a1 = vv.subplot(121)
    vv.title('Lewiner')
    m1 = vv.mesh(np.fliplr(vertices1), faces1)
    a2 = vv.subplot(122)
    vv.title('Classic')
    m2 = vv.mesh(np.fliplr(vertices2), faces2)
    a1.camera = a2.camera

    # visvis uses right-hand rule, gradient_direction param uses left-hand rule
    m1.cullFaces = m2.cullFaces = 'front'  # None, front or back

    vv.use().Run()
Ejemplo n.º 11
0
    def DrawSpectrum(self, event):
        """
		Draw spectrum interactively
		"""
        spectrum = self.Spectrometer.AcquiredData()
        if spectrum == RETURN_FAIL: return
        # Display the spectrum
        if len(spectrum.shape) > 1:
            try:
                self.__interact_2d_spectrum__.SetData(spectrum)
            except AttributeError:
                visvis.cla()
                visvis.clf()
                # Spectrum is a 2D image
                visvis.subplot(211)
                self.__interact_2d_spectrum__ = visvis.imshow(spectrum,
                                                              cm=visvis.CM_JET)
                visvis.subplot(212)

            # Plot a vertical binning
            spectrum = spectrum.sum(axis=0)

        # Linear spectrum
        try:
            self.__interact_1d_spectrum__.SetYdata(spectrum)
        except AttributeError:
            if self.wavelengths is None:
                self.__interact_1d_spectrum__ = visvis.plot(spectrum, lw=3)
                visvis.xlabel("pixels")
            else:
                self.__interact_1d_spectrum__ = visvis.plot(self.wavelengths,
                                                            spectrum,
                                                            lw=3)
                visvis.xlabel("wavelength (nm)")
            visvis.ylabel("counts")

        if self.is_autoscaled_spectrum:
            # Smart auto-scale linear plot
            try:
                self.spectrum_plot_limits = GetSmartAutoScaleRange(
                    spectrum, self.spectrum_plot_limits)
            except AttributeError:
                self.spectrum_plot_limits = GetSmartAutoScaleRange(spectrum)

        visvis.gca().SetLimits(rangeY=self.spectrum_plot_limits)

        # Display the current temperature
        try:
            visvis.title("Temperature %d (C)" %
                         self.Spectrometer.GetTemperature())
        except AttributeError:
            pass
Ejemplo n.º 12
0
def crop3d(vol, fig=None):
    """ crop3d(vol, fig=None)
    Manually crop a volume. In the given figure (or a new figure if None),
    three axes are created that display the transversal, sagittal and 
    coronal MIPs (maximum intensity projection) of the volume. The user
    can then use the mouse to select a 3D range to crop the data to.
    """
    app = vv.use()
    
    # Create figure?    
    if fig is None:        
        fig = vv.figure()    
        figCleanup = True
    else:
        fig.Clear()
        figCleanup = False
    
    # Create three axes and a wibject to attach text labels to    
    a1 = vv.subplot(221)
    a2 = vv.subplot(222)
    a3 = vv.subplot(223)
    a4 = vv.Wibject(fig)
    a4.position = 0.5, 0.5, 0.5, 0.5
    
    # Set settings
    for a in [a1, a2, a3]:
        a.showAxis = False
    
    # Create cropper3D instance
    cropper3d = Cropper3D(vol, a1, a3, a2, a4)
    
    # Enter a mainloop
    while not cropper3d._finished:
        vv.processEvents()
        time.sleep(0.01)
    
    # Clean up figure (close if we opened it)
    fig.Clear()
    fig.DrawNow()
    if figCleanup:    
        fig.Destroy()
    
    # Obtain ranges
    rx = cropper3d._range_transversal._rangex
    ry = cropper3d._range_transversal._rangey
    rz = cropper3d._range_coronal._rangey
    
    # Perform crop
    vol2 = vol[rz.min:rz.max, ry.min:ry.max, rx.min:rx.max]
    
    # Done
    return vol2
Ejemplo n.º 13
0
def plot(image):
    # ax = vv.gca()
    # ms = vv.Mesh(ax)
    logging.warning([image.shape, image.spacing])
    vol = image[:, :, :, 0]
    logging.warning([vol.min(), vol.max()])
    vol = util.normalize(vol, 'ADCm')
    logging.warning([vol.min(), vol.max()])
    vol = vv.Aarray(vol, image.spacing)

    cmap = None
    # cmap = vv.CM_VIRIDIS
    render_style = 'mip'
    # render_style = 'iso'
    # render_style = 'ray'
    # render_style = 'edgeray'
    # render_style = 'litray'

    vv.figure()
    vv.xlabel('x axis')
    vv.ylabel('y axis')
    vv.zlabel('z axis')

    a1 = vv.subplot(111)
    t1 = vv.volshow(vol, cm=cmap, renderStyle=render_style)
    t1.isoThreshold = 0.7
    vv.title(render_style)

    # a1.camera = a2.camera = a3.camera
    vv.ColormapEditor(a1)
Ejemplo n.º 14
0
 def __init__(self, parent):
     Figure = app.GetFigureClass()
     self.figure = Figure(parent)
     # init plot
     self.axes = vv.subplot(111)
     # self.axes.axisType = "polar"
     self.activePlot = None
Ejemplo n.º 15
0
Archivo: vis.py Proyecto: jupito/dwilib
def plot(image):
    # ax = vv.gca()
    # ms = vv.Mesh(ax)
    logging.warning([image.shape, image.spacing])
    vol = image[:, :, :, 0]
    logging.warning([vol.min(), vol.max()])
    vol = util.normalize(vol, 'ADCm')
    logging.warning([vol.min(), vol.max()])
    vol = vv.Aarray(vol, image.spacing)

    cmap = None
    # cmap = vv.CM_VIRIDIS
    render_style = 'mip'
    # render_style = 'iso'
    # render_style = 'ray'
    # render_style = 'edgeray'
    # render_style = 'litray'

    vv.figure()
    vv.xlabel('x axis')
    vv.ylabel('y axis')
    vv.zlabel('z axis')

    a1 = vv.subplot(111)
    t1 = vv.volshow(vol, cm=cmap, renderStyle=render_style)
    t1.isoThreshold = 0.7
    vv.title(render_style)

    # a1.camera = a2.camera = a3.camera
    vv.ColormapEditor(a1)
Ejemplo n.º 16
0
    def _visualize(self, gridStep=10):
        """ _visualize(self)
        
        Visualize the registration process.
        
        """

        if self.visualizer.fig is None:
            return

        import visvis as vv

        firstpass = not self.visualizer.fig.children

        if True:
            # Show

            # Apply deformation to image
            im1 = self.get_deformed_image(0, 0)
            im2 = self.get_deformed_image(1, 0)

            # Get grid images
            grid1 = create_grid_image(im1.shape, im1.sampling, gridStep)
            grid2 = grid1.copy()
            deform1, deform2 = self._deforms.get(0, None), self._deforms.get(
                1, None)
            if deform1 and deform2:
                grid1 = deform1.apply_deformation(
                    grid1)  # + 0.1*self._deforms[0][0])
                grid2 = deform2.apply_deformation(
                    grid2)  # + 0.1*self._deforms[1][0])

            # Get images
            ims = [None, im1, grid1, None, im2, grid2]

            # Update textures
            for i in range(len(ims)):
                if ims[i] is not None:
                    self.visualizer.imshow((2, 3, i + 1), ims[i])

        if firstpass:
            # Init

            # Show originals
            self.visualizer.imshow(231, self._ims[0])
            self.visualizer.imshow(234, self._ims[1])

            # Show titles
            title_map = [
                'im 1', 'deformed 1', 'grid 1', 'im 2', 'deformed 2', 'grid 2'
            ]
            for i in range(len(title_map)):
                a = vv.subplot(2, 3, i + 1)
                vv.title(title_map[i])
                a.axis.visible = False

        # Draw now
        self.visualizer.fig.DrawNow()
Ejemplo n.º 17
0
	def DrawSpectrum (self, event) :
		"""
		Draw spectrum interactively
		"""		
		spectrum = self.Spectrometer.AcquiredData() 
		if spectrum == RETURN_FAIL : return
		# Display the spectrum
		if len(spectrum.shape) > 1:
			try :
				self.__interact_2d_spectrum__.SetData(spectrum)
			except AttributeError :
				visvis.cla(); visvis.clf(); 	
				# Spectrum is a 2D image
				visvis.subplot(211)
				self.__interact_2d_spectrum__ = visvis.imshow(spectrum, cm=visvis.CM_JET)
				visvis.subplot(212)
				
			# Plot a vertical binning
			spectrum = spectrum.sum(axis=0)
			
		# Linear spectrum
		try :
			self.__interact_1d_spectrum__.SetYdata(spectrum)	
		except AttributeError :
			if self.wavelengths is None : 
				self.__interact_1d_spectrum__ = visvis.plot (spectrum, lw=3)
				visvis.xlabel ("pixels")
			else : 
				self.__interact_1d_spectrum__ = visvis.plot (self.wavelengths, spectrum, lw=3)
				visvis.xlabel("wavelength (nm)")
			visvis.ylabel("counts")
			
		if self.is_autoscaled_spectrum :
			# Smart auto-scale linear plot
			try :
				self.spectrum_plot_limits = GetSmartAutoScaleRange(spectrum, self.spectrum_plot_limits)
			except AttributeError :
				self.spectrum_plot_limits = GetSmartAutoScaleRange(spectrum)
		
		visvis.gca().SetLimits ( rangeY=self.spectrum_plot_limits )
		
		# Display the current temperature
		try : visvis.title ("Temperature %d (C)" % self.Spectrometer.GetTemperature() )
		except AttributeError : pass
Ejemplo n.º 18
0
def psf_volume(stack, xyz_ratio, filepath):

    app = vv.use()
    # Init a figure with two axes
    a1 = vv.subplot(121)
    vv.title('PSF Volume')
    a2 = vv.subplot(122)
    vv.title('PSF XYZ Cross Sections')
    
    # show
    t1 = vv.volshow(stack, axes=a1)  # volume
    t2 = vv.volshow2(stack, axes=a2)  # cross-section interactive
       
    # set labels for both axes
    vv.xlabel('Pixel X', axes=a1)
    vv.ylabel('Pixel Y', axes=a1)
    vv.zlabel('Z-Slice', axes=a1)
    vv.xlabel('Pixel X', axes=a2)
    vv.ylabel('Pixel Y', axes=a2)
    vv.zlabel('Z-Slice', axes=a2)
    
    # set colormaps
    t1.colormap = vv.CM_JET
    t2.colormap = vv.CM_JET

    # set correct aspect ration corresponding to voxel size    
    a1.daspect = 1, 1, xyz_ratio
    a2.daspect = 1, 1, xyz_ratio
    
    # show grid
    a1.axis.showGrid = 1
    a2.axis.showGrid = 1    
    
    # run visvis and show results
    app.Run()

    # save screenshot
    if filepath != 'nosave':
        print 'Saving PSF volume.'
        savename = filepath[:-4] + '_PSF_3D.png'
        # sf: scale factor
        vv.screenshot(savename, sf=1, bg='w')
Ejemplo n.º 19
0
 def __init__(self, parent, action=None, **kwargs):
     pythics.libcontrol.Control.__init__(self, parent,
                                         action=None,
                                         save=False,
                                         **kwargs)
     Figure = parent.main_window.vv_app.GetFigureClass()
     self.figure = Figure(parent)
     self.widget = self.figure._widget
     #vv.figure(self.figure)
     self.axes = vv.subplot(1,1,1)
     self.items = dict()
Ejemplo n.º 20
0
    def _Plot(self, event):
        
        # update status text
        self.status.SetLabel("CPU:%.1f\nMemory:%.1f" % (cpudata[-1], vmemdata[-1]))
        # Make sure our figure is the active one
        # If only one figure, this is not necessary.
        #vv.figure(self.fig.nr)
        
        # Clear it
        vv.clf()
        
        # Plot
        a = vv.subplot(211)
        vv.plot(cpudata, lw=2, lc="c", mc ='y', ms='d')
        vv.legend("cpu percent ")
        a.axis.showGrid = True
        a.axis.xlabel = "CPU Usage Percent"
        a.axis.ylabel = "sampling time line"

        a = vv.subplot(212)
        vv.plot(vmemdata, lw=2, mew=1, lc='m', mc ='y', ms='d' )
        vv.legend("virtual memory")
        a.axis.showGrid = True
Ejemplo n.º 21
0
    def imshow(self, subplot, im, *args, **kwargs):
        """ imshow(subplot, im, *args, **kwargs)
        
        Show the given image in specified subplot. If possible, 
        updates the previous texture object.
        
        """

        # Check if we can show
        if not self.fig:
            return
        else:
            self._f.MakeCurrent()

        # Import visvis
        import visvis as vv

        # Get axes
        if isinstance(subplot, tuple):
            a = vv.subplot(*subplot)
        else:
            a = vv.subplot(subplot)

        # Get what's in there
        t = None
        if len(a.wobjects) == 2 and isinstance(a.wobjects[1], vv.BaseTexture):
            t = a.wobjects[1]

        # Reuse, or clear and replace
        if t is not None:
            t.SetData(im)
        else:
            a.Clear()
            t = vv.imshow(im, *args, **kwargs)

        # Done
        return t
Ejemplo n.º 22
0
    def _Plot(self, event):

        # update status text
        self.status.SetLabel("CPU:%.1f\nMemory:%.1f" %
                             (cpudata[-1], vmemdata[-1]))
        # Make sure our figure is the active one
        # If only one figure, this is not necessary.
        #vv.figure(self.fig.nr)

        # Clear it
        vv.clf()

        # Plot
        a = vv.subplot(211)
        vv.plot(cpudata, lw=2, lc="c", mc='y', ms='d')
        vv.legend("cpu percent ")
        a.axis.showGrid = True
        a.axis.xlabel = "CPU Usage Percent"
        a.axis.ylabel = "sampling time line"

        a = vv.subplot(212)
        vv.plot(vmemdata, lw=2, mew=1, lc='m', mc='y', ms='d')
        vv.legend("virtual memory")
        a.axis.showGrid = True
Ejemplo n.º 23
0
def plot_progress(plots, sampler_info):

    settings = requests.get(sampler_info['settings']).json()
    lower = settings['lower']
    upper = settings['upper']

    subplt = vv.subplot(*(plots['shape'] + (1 + plots['count'], )))
    plots['count'] += 1

    # Request the training data
    training_data = requests.get(sampler_info['training_data_uri']).json()

    xres = 30
    yres = 30
    xeva, yeva = np.meshgrid(np.linspace(lower[0], upper[0], xres),
                             np.linspace(lower[1], upper[1], yres))
    Xquery = np.array([xeva.flatten(), yeva.flatten()]).T

    #Request the predictions from the server
    r = requests.get(sampler_info['pred_uri'], json=Xquery.tolist())
    r.raise_for_status()
    pred = r.json()
    pred_mean = np.array(pred['predictive_mean'])
    id_matrix = np.reshape(
        np.arange(Xquery.shape[0])[:, np.newaxis], xeva.shape)
    n, n_outputs = pred_mean.shape

    # Plot the training data and the predictions
    vol = np.zeros((n_outputs, xeva.shape[0], xeva.shape[1]))
    for x in range(xres):
        for y in range(yres):
            vol[:, x, y] = pred_mean[id_matrix[x, y]]
    plt = vv.volshow(vol, renderStyle='mip', clim=(-0.5, 1))
    plt.colormap = vv.CM_JET
    subplt.axis.xLabel = 'input 1'
    subplt.axis.yLabel = 'input 2'
    subplt.axis.zLabel = 'model output'
    a = ((np.asarray(training_data['X']) - np.array([np.min(xeva),
          np.min(yeva)])[np.newaxis, :]) / np.array([np.max(xeva) -
          np.min(xeva), np.max(yeva)-np.min(yeva)])[np.newaxis, :])  \
          * np.array(xeva.shape)  # NOQA
    n = a.shape[0]
    a = np.hstack((a, (n_outputs + 0.01) * np.ones((n, 1))))
    pp = vv.Pointset(a)
    vv.plot(pp, ms='.', mc='w', mw='9', ls='')
Ejemplo n.º 24
0
    def __init__(self):

        # Setup visualization
        self._fig = fig = vv.figure()
        self._a1 = a1 = vv.subplot(111)

        # Init pointset with control points
        self._pp = Pointset(2)

        # Init lines to show control points
        self._line1 = vv.plot(self._pp, ls='', ms='.', mc='r', mw=11, axes=a1)
        self._line1.hitTest = True

        # Init grid properties
        self._fieldSize = 100
        self._sampling = 10
        self._levels = 5

        # Member to indicate the point being dragged (as an index)
        self._active = None

        # Bind to events
        a1.eventDoubleClick.Bind(self.on_doubleclick)
        self._line1.eventDoubleClick.Bind(self.on_doubleclick_line)
        self._line1.eventMouseDown.Bind(self.on_down_line)
        self._line1.eventMouseUp.Bind(self.on_up_line)
        a1.eventMotion.Bind(self.on_motion)
        fig.eventKeyDown.Bind(self.on_key_down)

        print(
            'Use left/right to control #levels and up/down to control grid sampling.'
        )

        # Init
        self.apply()
        a1.daspectAuto = False
        a1.SetLimits()
        a1.axis.showGrid = True
Ejemplo n.º 25
0
def show(self):

    import visvis as vv

    # If there are many tests, make a selection
    if len(self._tests) > 1000:
        tests = random.sample(self._tests, 1000)
    else:
        tests = self._tests

    # Get ticks
    nn = [test[0] for test in tests]

    # Create figure
    vv.figure(1)
    vv.clf()

    # Prepare kwargs
    plotKwargsText = {'ms': '.', 'mc': 'b', 'mw': 5, 'ls': ''}
    plotKwargsBin = {'ms': '.', 'mc': 'r', 'mw': 5, 'ls': ''}

    # File size against number of elements
    vv.subplot(221)
    vv.plot(nn, [test[2][0] for test in tests], **plotKwargsText)
    vv.plot(nn, [test[2][1] for test in tests], **plotKwargsBin)
    vv.legend('text', 'binary')
    vv.title('File size')

    # Speed against number of elements
    vv.subplot(223)
    vv.plot(nn, [test[1][4] for test in tests], **plotKwargsText)
    vv.plot(nn, [test[1][6] for test in tests], **plotKwargsBin)
    vv.legend('text', 'binary')
    vv.title('Save time')

    # Speed (file) against number of elements
    vv.subplot(224)
    vv.plot(nn, [test[1][5] for test in tests], **plotKwargsText)
    vv.plot(nn, [test[1][7] for test in tests], **plotKwargsBin)
    vv.legend('text', 'binary')
    vv.title('Load time')
Ejemplo n.º 26
0
def show(self):
    
    import visvis as vv
    
    # If there are many tests, make a selection
    if len(self._tests) > 1000:
        tests = random.sample(self._tests, 1000)
    else:
        tests = self._tests
    
    # Get ticks
    nn = [test[0] for test in tests]
    
    # Create figure
    vv.figure(1)
    vv.clf()
    
    # Prepare kwargs
    plotKwargsText = {'ms':'.', 'mc':'b', 'mw':5, 'ls':''}
    plotKwargsBin = {'ms':'.', 'mc':'r', 'mw':5, 'ls':''}
    
    # File size against number of elements
    vv.subplot(221)
    vv.plot(nn, [test[2][0] for test in tests], **plotKwargsText)
    vv.plot(nn, [test[2][1] for test in tests], **plotKwargsBin)
    vv.legend('text', 'binary')
    vv.title('File size')
    
    # Speed against number of elements
    vv.subplot(223)
    vv.plot(nn, [test[1][4] for test in tests], **plotKwargsText)
    vv.plot(nn, [test[1][6] for test in tests], **plotKwargsBin)
    vv.legend('text', 'binary')
    vv.title('Save time')
    
    # Speed (file) against number of elements
    vv.subplot(224)
    vv.plot(nn, [test[1][5] for test in tests], **plotKwargsText)
    vv.plot(nn, [test[1][7] for test in tests], **plotKwargsBin)
    vv.legend('text', 'binary')
    vv.title('Load time')
Ejemplo n.º 27
0
 ringparts(ringpart=ringpart)
 
 # Visualize ring parts
 if ringpart:
     figparts()
     
 # Area and cyclic change -- ellipse fit
 if ringpart:
     # fit plane and ellipse
     R1 = modelsR1R2[0][0]
     R2 = modelsR1R2[0][1]
     fittedR1, fittedR2, fittedR1R2 = _fit3D(R1), _fit3D(R2), _fit3D(models[0][4]) # [4]=model_noHooks
     print("------------")
     f = vv.figure(); vv.clf()
     f.position = 258.00, 30.00,  1654.00, 1002.00
     a1 = vv.subplot(231)
     vis3Dfit(fittedR1,vol,model,ptcode,ctcode,showAxis,showVol=showVol, clim=clim0, isoTh=isoTh)
     a2 = vv.subplot(232)
     vis3Dfit(fittedR2,vol,model,ptcode,ctcode,showAxis,showVol=showVol, clim=clim0, isoTh=isoTh)
     a3 = vv.subplot(233)
     vis3Dfit(fittedR1R2,vol,model,ptcode,ctcode,showAxis,showVol=showVol, clim=clim0, isoTh=isoTh)
     a1.camera = a2.camera = a3.camera
     a1b = vv.subplot(2,3,4)
     vis2Dfit(fittedR1,ptcode, ctcode, showAxis)
     a2b = vv.subplot(2,3,5)
     vis2Dfit(fittedR2,ptcode, ctcode, showAxis)
     a3b = vv.subplot(2,3,6)
     vis2Dfit(fittedR1R2,ptcode, ctcode, showAxis)    
     # cyclic change
     A_R1 = calculateAreaChange(R1, 'R1')
     A_R2 = calculateAreaChange(R2, 'R2')
Ejemplo n.º 28
0
        if not y0:
            continue

        # Reflect
        for y in range(N):
            y1 = y0 - y - bool(not distance)
            y2 = y0 + y + distance
            im2[y2, x, :] = im1[y1, x, :]
            im2[y2, x, 3] *= startAlpha * (1.0 - float(y / N))
        y2_max = max(y2_max, y2)

    # Return im2, cropped appropriately
    return im2[:y2_max, : shape[1], :]


if __name__ == "__main__":
    filename = "/home/almar/projects/www/pyzo-www/wwwpyzo/_static/pyzo_box.png"

    im1 = imageio.imread(filename)
    im2 = reflect_image(im1)

    import visvis as vv

    vv.clf()
    vv.subplot(121)
    vv.imshow(im1)
    vv.subplot(122)
    vv.imshow(im2)

# reflect(filename)
Ejemplo n.º 29
0
                    ) * ( ( (8*x)**2 + ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2 + 16 - 1.85*1.85 )
                    * ( (8*x)**2 + ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2 + 16 - 1.85*1.85 ) -
                    64 * ( ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2
                    ) ) + 1025
    # Uncommenting the line below will yield different results for classic MC
    #vol = -vol

elif SELECT == 4:
    vol = ellipsoid(4, 3, 2, levelset=True)
    isovalue = 0

# Get surface meshes
t0 = time.time()
vertices1, faces1, _ = marching_cubes_lewiner(vol, isovalue, gradient_direction=gradient_dir, use_classic=False)
print('finding surface lewiner took %1.0f ms' % (1000*(time.time()-t0)) )

t0 = time.time()
vertices2, faces2, _ = marching_cubes_classic(vol, isovalue, gradient_direction=gradient_dir)
print('finding surface classic took %1.0f ms' % (1000*(time.time()-t0)) )

# Show
vv.figure(1); vv.clf()
a1 = vv.subplot(121); m1 = vv.mesh(np.fliplr(vertices1), faces1)
a2 = vv.subplot(122); m2 = vv.mesh(np.fliplr(vertices2), faces2)
a1.camera = a2.camera

# visvis uses right-hand rule, gradient_direction param uses left-hand rule
m1.cullFaces = m2.cullFaces = 'front'  # None, front or back

vv.use().Run()
Ejemplo n.º 30
0
    vv2[i] = cc[2]
    vv3[i] = cc[3]
    vvt[i] = sum(cc)

# Interpolate (0 means Cardinal with tension 0)
samples = np.arange(0,len(data)-1,0.05, dtype=np.float32) 
values1 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 'linear')
values2 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 'basis')
values3 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 0)  


# Visualize
fig = vv.figure(1); vv.clf()
fig.position = 57.00, 45.00,  948.00, 969.00

vv.subplot(211)
vv.title('The basis functions for the %s spline' % type)
vv.plot(tt, vv0, lc='r')
vv.plot(tt, vv1, lc='g')
vv.plot(tt, vv2, lc='b')
vv.plot(tt, vv3, lc='m')
vv.plot(tt, vvt, lc='k', ls='--')

vv.subplot(212)
vv.plot(range(len(data)), data, ms='.', ls='')
vv.plot(samples, values1, lc='r')
vv.plot(samples, values2, lc='g')
vv.plot(samples, values3, lc='b', lw=3)
a = vv.gca()
a.legend = 'data', 'Linear', 'Basis', 'Cardinal'
Ejemplo n.º 31
0
vv.clf()


## 1D

# Input and result
pp = [2, 4, 3]
t_max, polynom = fitting.fit_lq1(pp)

# Sample polynom
polypp = PointSet(2)
for i in np.linspace(-1,1,100):
    polypp.append(i, polynom[0]*i**2 + polynom[1]*i + polynom[2])

# Visualize
vv.subplot(121)
vv.plot([-1,0,1],pp)
vv.plot([t_max, t_max], [0,1], lc='r')
vv.plot(polypp, lc='r')


## 2D


# Input and result    
im = vv.imread('astronaut.png')[::,::,2].copy()
Y,X = np.where(im==im.max())
Y,X = Y[0], X[0]
im[Y-1,X] -= 20 # make more interesting :)
mat = im[Y-1:Y+2, X-1:X+2]
Ejemplo n.º 32
0
    # Normalize
    mass = normalize(mass)

    # Truncate
    if truncate:
        mass[mass < 0] = 0.0
    soft_limit(mass, 1)  # todo: half limit
    #mass = mass**0.5

    return mass


# Show
vv.figure(10)
vv.clf()
for i in range(3):
    a = vv.subplot(3, 3, i + 1)
    vv.imshow(ims[i])
    a.axis.visible = False

for i in range(3):
    a = vv.subplot(3, 3, i + 4)
    vv.imshow(getMass(ims[i]))
    a.axis.visible = False

for i in range(3):
    a = vv.subplot(3, 3, i + 7)
    vv.hist(getMass(ims[i], False), 64)
    a.SetLimits()
Ejemplo n.º 33
0
    im = gl.glReadPixels(x, y, w, h, gl.GL_RGB, gl.GL_FLOAT)
    
    # reshape, flip, and store
    im.shape = h,w,3
    im = np.flipud(im)
    
    # done
    return im
    


if __name__ == '__main__':
    import time
    
    f = vv.figure()
    a1 = vv.subplot(211)
    a2 = vv.subplot(212)
    
    vv.plot([2,3,4,2,4,3], axes=a1)
    
    for i in range(4):
        # draw and wait a bit
        f.DrawNow()
        time.sleep(1)
        # make snapshots
        im1 = getframe(f)
        im2 = getframe(a1)
        # clear and show snapshots
        a1.Clear()
        a2.Clear()
        vv.imshow(im1,axes=a1, clim=(0,1))
Ejemplo n.º 34
0
    
    # create axes in container
    a = Axes(f)
    c = a.parent
    
    # calculate relative coordinates
    dx, dy = 1.0/cols, 1.0/rows
    y = int( nr / cols )
    x = int( nr % cols )
    
    # apply positions
    c.position = dx*x, dy*y, dx, dy
    a.position = 10, 10, -20, -20
    
    # done
    return a
    
    

if __name__ == "__main__":
    f = vv.figure()
    # Get axes on 2x2 grid
    a1 = vv.subplot(221)
    a2 = vv.subplot(221)
    a3 = vv.subplot(224)    
    # Get axes on 3x3 grid
    a4 = vv.subplot(331) # (center is inside 221)
    a5 = vv.subplot(333)
    # Check
    print(a1 is a2, a1 is a4)
Ejemplo n.º 35
0
#!/usr/bin/env python
import visvis as vv
from visvis.pypoints import Aarray
app = vv.use()

# Let's say we have lena, but only the even pixels in the y dimension.
# So each pixel should have twice the size in the y direction.
im = vv.imread('lena.png')
im = im[::2,:,:]

# Init a figure with two axes
vv.figure()
a1 = vv.subplot(121); vv.title('pixel units')
a2 = vv.subplot(122); vv.title('real-world units')

# Method 1: scale the whole scene
# Use this if you want the axis to depict pixel units.
t1 = vv.imshow(im, axes=a1)
a1.daspect = 1,-2 # daspect works x,y,z, the y-axis is flipped for images

# Method 2: use the Aarray class to scale the image
# You could use this is you know the physical dimensions of a pixel,
# to have the axis depict, for example, mm.
im2 = Aarray(im,(2,1,1))  # sampling is given in y,x,color order
t2 = vv.imshow(im2, axes=a2)

app.Run()
Ejemplo n.º 36
0
""" This example demonstrates rendering a color volume.
This example demonstrates two render styles. Note that
all render styles are capable of rendering color data.
"""

import numpy as np
import visvis as vv
app = vv.use()

# Use vv.aVolume to create random bars for each color plane
N = 64
vol = np.empty((N,N,N,3), dtype='float32')
for i in range(3):
    vol[:,:,:,i] = vv.aVolume(10,N)

# Show
vv.figure()
a1 = vv.subplot(121); 
t1 = vv.volshow(vol[:,:,:,:], renderStyle = 'mip')
vv.title('color MIP render')
a2 = vv.subplot(122); 
t2 = vv.volshow(vol[:,:,:,:], renderStyle = 'iso')
t2.isoThreshold = 0.5
vv.title('color ISO-surface render')

# Share cameras
a1.camera = a2.camera

# Run app
app.Run()
    s2 = loadvol(basedir, ptcode, ctcode, 'ring', staticref)
vol = s2.vol

s3 = loadvol(basedir, ptcode, ctcode, cropname, 'phases')
vol0ori = s3.vol0

# todo: backward/forward based on how deforms were obtained??
# deforms was obtained as backward, from original phases to mean volume avgreg
deform = pirt.DeformationFieldBackward(deforms[0])
# vol2 = pirt.interp.deform_backward(vol, deforms[0]) # te low level, gebruikt awarp niet
vol2 = deform.inverse().as_backward().apply_deformation(
    vol0ori)  # gebruikt pirt deformation.py

vv.figure(1)
vv.clf()
a1 = vv.subplot(131)
t1 = vv.volshow(vol)
a1.daspect = (1, 1, -1)
vv.title('vol average of cardiac cycle')
# vv.figure(2); vv.clf()
a2 = vv.subplot(132)
t2 = vv.volshow(vol2)
a2.daspect = (1, 1, -1)
vv.title('vol 0 deformed to avg volume')
# vv.figure(3); vv.clf()
a3 = vv.subplot(133)
t3 = vv.volshow2((vol2 - vol), clim=(-500, 500))
a3.daspect = (1, 1, -1)
vv.title('difference')

a1.camera = a2.camera = a3.camera
Ejemplo n.º 38
0
def demo(*args, **kwargs):
    import math
    m = 80  # width of grid
    n = m ** 2  # number of points

    minVal = -2.0
    maxVal = 2.0
    delta = (maxVal - minVal) / (m - 1)
    X, Y = numpy.mgrid[minVal:maxVal + delta:delta, minVal:maxVal + delta:delta]

    X = X.flatten()
    Y = Y.flatten()

    Z = numpy.sin(X) * numpy.cos(Y)

    # Create the data point-matrix
    M = numpy.array([X, Y, Z]).T

    # Translation values (a.u.):
    Tx = 0.5
    Ty = -0.3
    Tz = 0.2

    # Translation vector
    T = numpyTransform.translation(Tx, Ty, Tz)

    S = numpyTransform.scaling(1.0, N=4)

    # Rotation values (rad.):
    rx = 0.3
    ry = -0.2
    rz = 0.05

    Rx = numpy.matrix([[1, 0, 0, 0],
                      [0, math.cos(rx), -math.sin(rx), 0],
                      [0, math.sin(rx), math.cos(rx), 0],
                      [0, 0, 0, 1]])

    Ry = numpy.matrix([[math.cos(ry), 0, math.sin(ry), 0],
                       [0, 1, 0, 0],
                       [-math.sin(ry), 0, math.cos(ry), 0],
                       [0, 0, 0, 1]])

    Rz = numpy.matrix([[math.cos(rz), -math.sin(rz), 0, 0],
                       [math.sin(rz), math.cos(rz), 0, 0],
                       [0, 0, 1, 0],
                       [0, 0, 0, 1]])

    # Rotation matrix
    R = Rx * Ry * Rz

    transformMat = numpy.matrix(numpy.identity(4))
    transformMat *= T
    transformMat *= R
    transformMat *= S

    # Transform data-matrix plus noise into model-matrix
    D = numpyTransform.transformPoints(transformMat, M)

    # Add noise to model and data
    M = M + 0.01 * numpy.random.randn(n, 3)
    D = D + 0.01 * numpy.random.randn(n, 3)

    # Run ICP (standard settings)
    initialGuess = numpy.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
    lowerBounds = numpy.array([-pi, -pi, -pi, -100.0, -100.0, -100.0])
    upperBounds = numpy.array([pi, pi, pi, 100.0, 100.0, 100.0])
    icp = ICP(M, D, maxIterations=15, dataDownsampleFactor=1, minimizeMethod='fmincon', **kwargs)
#    icp = ICP(M, D, maxIterations=15, dataDownsampleFactor=1, minimizeMethod='point', **kwargs)
    transform, err, t = icp.runICP(x0=initialGuess, lb=lowerBounds, ub=upperBounds)

    # Transform data-matrix using ICP result
    Dicp = numpyTransform.transformPoints(transform[-1], D)

    # Plot model points blue and transformed points red
    if False:
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D
        fig = plt.figure()
        ax = fig.add_subplot(2, 2, 1, projection='3d')
        ax.scatter(M[:, 0], M[:, 1], M[:, 2], c='r', marker='o')
        ax.scatter(D[:, 0], D[:, 1], D[:, 2], c='b', marker='^')
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z Label')

        ax = fig.add_subplot(2, 2, 2, projection='3d')
        ax.scatter(M[:, 0], M[:, 1], M[:, 2], c='r', marker='o')
        ax.scatter(Dicp[:, 0], Dicp[:, 1], Dicp[:, 2], c='b', marker='^')
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z Label')

        ax = fig.add_subplot(2, 2, 3)
        ax.plot(t, err, 'x--')
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')

        plt.show()
    else:
        import visvis as vv
        app = vv.use()
        vv.figure()
        vv.subplot(2, 2, 1)
        vv.plot(M[:, 0], M[:, 1], M[:, 2], lc='b', ls='', ms='o')
        vv.plot(D[:, 0], D[:, 1], D[:, 2], lc='r', ls='', ms='x')
        vv.xlabel('[0,0,1] axis')
        vv.ylabel('[0,1,0] axis')
        vv.zlabel('[1,0,0] axis')
        vv.title('Red: z=sin(x)*cos(y), blue: transformed point cloud')

        # Plot the results
        vv.subplot(2, 2, 2)
        vv.plot(M[:, 0], M[:, 1], M[:, 2], lc='b', ls='', ms='o')
        vv.plot(Dicp[:, 0], Dicp[:, 1], Dicp[:, 2], lc='r', ls='', ms='x')
        vv.xlabel('[0,0,1] axis')
        vv.ylabel('[0,1,0] axis')
        vv.zlabel('[1,0,0] axis')
        vv.title('ICP result')

        # Plot RMS curve
        vv.subplot(2, 2, 3)
        vv.plot(t, err, ls='--', ms='x')
        vv.xlabel('time [s]')
        vv.ylabel('d_{RMS}')
        vv.title('KD-Tree matching')
        if 'optAlg' in kwargs:
            opt2 = nlopt.opt(kwargs['optAlg'], 2)
            vv.title(opt2.get_algorithm_name())
            del opt2
        else:
            vv.title('KD-Tree matching')
        app.Run()
Ejemplo n.º 39
0
    def __init__(self,ptcode,ctcode,basedir, seed_th=[600], show=True, 
                normalize=False, modelname='model'):
        
        import os
        
        import numpy as np
        import visvis as vv
        from visvis import ssdf
        
        from stentseg.utils import PointSet, _utils_GUI
        from stentseg.utils.datahandling import select_dir, loadvol, loadmodel
        from stentseg.stentdirect.stentgraph import create_mesh
        from stentseg.stentdirect import stentgraph, StentDirect, getDefaultParams
        from stentseg.stentdirect import AnacondaDirect, EndurantDirect, NellixDirect
        from stentseg.utils.visualization import show_ctvolume
        from stentseg.utils.picker import pick3d, label2worldcoordinates, label2volindices
        import scipy
        from scipy import ndimage
        import copy
        
        # Select dataset to register
        cropname = 'prox'
        # phase = 10
        #dataset = 'avgreg'
        #what = str(phase) + dataset # avgreg
        what = 'avgreg'
        
        # Load volumes
        s = loadvol(basedir, ptcode, ctcode, cropname, what)
        
        # sampling was not properly stored after registration for all cases: reset sampling
        vol_org = copy.deepcopy(s.vol)
        s.vol.sampling = [vol_org.sampling[1], vol_org.sampling[1], vol_org.sampling[2]] # z,y,x
        s.sampling = s.vol.sampling
        vol = s.vol
        
        ## Initialize segmentation parameters
        stentType = 'nellix'  # 'zenith';'nellix' runs modified pruning algorithm in Step3
        
        p = getDefaultParams(stentType)
        p.seed_threshold = seed_th     # step 1 [lower th] or [lower th, higher th]
        # p.seedSampleRate = 7                  # step 1, nellix
        p.whatphase = what                
        
        
        ## Perform segmentation
        # Instantiate stentdirect segmenter object
        if stentType == 'anacondaRing':
                sd = AnacondaDirect(vol, p) # inherit _Step3_iter from AnacondaDirect class
                #runtime warning using anacondadirect due to mesh creation, ignore
        elif stentType == 'endurant':
                sd = EndurantDirect(vol, p)
        elif stentType == 'nellix':
                sd = NellixDirect(vol, p)
        else:
                sd = StentDirect(vol, p) 

        ## show histogram and normalize
        # f = vv.figure(3)
        # a = vv.gca()
        # vv.hist(vol, drange=(300,vol.max()))
        
        # normalize vol to certain limit
        if normalize:
                sd.Step0(3071)
                vol = sd._vol
                # b= vv.hist(vol, drange=(300,3071))
                # b.color = (1,0,0)
       
        ## Perform step 1 for seeds
        sd.Step1()
        
        ## Visualize
        if show:
                fig = vv.figure(2); vv.clf()
                fig.position = 0.00, 22.00,  1920.00, 1018.00
                clim = (0,2000)
                
                # Show volume and model as graph
                a1 = vv.subplot(121)
                a1.daspect = 1,1,-1
                # t = vv.volshow(vol, clim=clim)
                t = show_ctvolume(vol, axis=a1, showVol='MIP', clim =clim, isoTh=250, 
                                removeStent=False, climEditor=True)
                label = pick3d(vv.gca(), vol)
                sd._nodes1.Draw(mc='b', mw = 2)       # draw seeded nodes
                #sd._nodes2.Draw(mc='b', lc = 'g')    # draw seeded and MCP connected nodes
                vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)')
                
                # Show volume and cleaned up graph
                a2 = vv.subplot(122)
                a2.daspect = 1,1,-1
                sd._nodes1.Draw(mc='b', mw = 2)       # draw seeded nodes
                # t = vv.volshow(vol, clim=clim)
                # label = pick3d(vv.gca(), vol)
                # sd._nodes2.Draw(mc='b', lc='g')
                # sd._nodes3.Draw(mc='b', lc='g')
                vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)')
                
                # # Show the mesh
                #===============================================================================
                # a3 = vv.subplot(133)
                # a3.daspect = 1,1,-1
                # t = vv.volshow(vol, clim=clim)
                # pick3d(vv.gca(), vol)
                # #sd._nodes3.Draw(mc='b', lc='g')
                # m = vv.mesh(bm)
                # m.faceColor = 'g'
                # # _utils_GUI.vis_spared_edges(sd._nodes3)
                # vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)')
                #===============================================================================
                
                # Use same camera
                a1.camera = a2.camera #= a3.camera
                
                switch = True
                a1.axis.visible = switch
                a2.axis.visible = switch
                #a3.axis.visible = switch
                

        ## Store segmentation to disk
        
        # Get graph model
        model = sd._nodes1
                
        # Build struct
        s2 = vv.ssdf.new()
        s2.sampling = s.sampling
        s2.origin = s.origin
        s2.stenttype = s.stenttype
        s2.croprange = s.croprange
        for key in dir(s):
                if key.startswith('meta'):
                    suffix = key[4:]
                    s2['meta'+suffix] = s['meta'+suffix]
        s2.what = what
        s2.params = p
        s2.stentType = stentType
        # Store model (not also volume)
        s2.model = model.pack()
        
        
        # Save
        filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, modelname+ what)
        ssdf.save(os.path.join(basedir, ptcode, filename), s2)
        print('saved to disk as {}.'.format(filename) )

        ## Make model dynamic (and store/overwrite to disk)
        #===============================================================================
        # 
        # import pirt
        # from stentsegf.motion.dynamic import incorporate_motion_nodes, incorporate_motion_edges  
        # 
        # # Load deforms
        # s = loadvol(basedir, ptcode, ctcode, cropname, '10deforms')
        # deformkeys = []
        # for key in dir(s):
        #     if key.startswith('deform'):
        #         deformkeys.append(key)
        # deforms = [s[key] for key in deformkeys]
        # deforms = [pirt.DeformationFieldBackward(*fields) for fields in deforms]
        # paramsreg = s.params
        # 
        # # Load model
        # s = loadmodel(basedir, ptcode, ctcode, cropname, 'model'+what)
        # model = s.model
        # 
        # # Combine ...
        # incorporate_motion_nodes(model, deforms, s.origin)
        # incorporate_motion_edges(model, deforms, s.origin)
        # 
        # # Save back
        # filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'model'+what)
        # s.model = model.pack()
        # s.paramsreg = paramsreg
        # ssdf.save(os.path.join(basedir, ptcode, filename), s)
        # print('saved to disk as {}.'.format(filename) )
        #===============================================================================
Ejemplo n.º 40
0
import visvis as vv

app = vv.use()

# Load volume
vol = vv.volread('stent')

# Create figure and make subplots with different renderers
vv.figure(1)
vv.clf()
RS = ['mip', 'iso', 'edgeray', 'ray', 'litray']
a0 = None
tt = []
for i in range(5):
    a = vv.subplot(3, 2, i + 2)
    t = vv.volshow(vol)
    vv.title('Renderstyle ' + RS[i])
    t.colormap = vv.CM_HOT
    t.renderStyle = RS[i]
    t.isoThreshold = 200  # Only used in iso render style
    tt.append(t)
    if a0 is None:
        a0 = a
    else:
        a.camera = a0.camera

# Create colormap editor in first axes
cme = vv.ColormapEditor(vv.gcf(), *tt[3:])

# Run app
Ejemplo n.º 41
0
	def DoScannning (self, event) :
		"""
		Perform scanning of different phase mask 
		"""
		# Create pseudonyms of necessary devices 
		self.DevSpectrometer 	= self.parent.Spectrometer.dev
		self.DevPulseShaper		= self.parent.PulseShaper.dev
		self.DevSampleSwitcher	= self.parent.SampleSwitcher.dev
			
		# Save global settings and get the name of log file
		self.log_filename = SaveSettings(SettingsNotebook=self.parent, 
								title="Select file to save phase mask scanning", filename="scanning_phase_mask.hdf5")
		if self.log_filename is None : return
		
		####################### Initiate devices #############################
		
		# Initiate spectrometer
		settings = self.parent.Spectrometer.GetSettings()
		if self.DevSpectrometer.SetSettings(settings) == RETURN_FAIL : return
		
		# Initiate pulse shaper
		settings = self.parent.PulseShaper.GetSettings()
		if self.DevPulseShaper.Initialize(settings) == RETURN_FAIL : return
		
		# Get number of optimization variables 
		self.num_pixels = self.DevPulseShaper.GetParamNumber()
		if self.num_pixels == RETURN_FAIL :
			raise RuntimeError ("Optimization cannot be started since calibration file was not loaded")
		
		# Initiate sample switcher
		settings = self.parent.SampleSwitcher.GetSettings()
		if self.DevSampleSwitcher.Initialize(settings) == RETURN_FAIL : return
		
		# Saving the name of channels 
		odd_settings = self.GetSettings()
		self.channels = sorted(eval( "(%s,)" % odd_settings["channels"] ))
		if self.DevSampleSwitcher.GetChannelNum()-1 < max(self.channels) :
			raise ValueError ("Error: Some channels specified are not accessible by sample switcher.")
		
		# Check whether the background signal array is present
		self.CheckBackground()
		
		#####################################################################
		
		# Get range of coefficient 
		coeff_range = np.linspace( odd_settings["coeff_min"], odd_settings["coeff_max"], odd_settings["coeff_num"] )
		
		# List all polynomial coefficients
		N = odd_settings["polynomial_order"]
		poly_coeffs = np.zeros( (coeff_range.size*N, N+1) )
		for n in range(1,N+1) :
			poly_coeffs[(n-1)*coeff_range.size:n*coeff_range.size, n ] = coeff_range
		
		# Chose max amplitude
		max_ampl = odd_settings["max_ampl"]*np.ones(self.num_pixels)
		
		# Arguments of the basis 
		X = np.linspace(-1., 1., self.num_pixels)
		
		# Retrieve the basis type
		polynomial_basis = self.polynomial_bases[ odd_settings["polynomial_basis"] ]
		
		# Adjusting button's settings
		button = event.GetEventObject()
		button.SetLabel (button._stop_label)
		button.SetBackgroundColour('red')
		button.Bind( wx.EVT_BUTTON, button._stop_method)
		self.need_abort = False
		
		#####################################################################
		
		# Start scanning
		with  h5py.File (self.log_filename, 'a') as log_file :
			for channel in self.channels :
				# Move to a selected channel 
				self.DevSampleSwitcher.MoveToChannel(channel)
		
				# abort, if requested 
				wx.Yield()
				if self.need_abort : break
				
				# Looping over pulse shapes
				for scan_num, coeff in enumerate(poly_coeffs) :
				
					# Calculate new phase
					phase = polynomial_basis(coeff)(X)
				
					# Set the pulse shape
					self.DevPulseShaper.SetAmplPhase(max_ampl, phase) 
		
					# Save phase in radians 
					ampl, phase = self.DevPulseShaper.GetUnwrappedAmplPhase(max_ampl, phase)
					if scan_num == 0 :
						# Initialize the array
						phases_rad = np.zeros( (len(poly_coeffs), phase.size), dtype=phase.dtype )
						amplitudes = np.zeros_like(phases_rad)
						amplitudes[:] = ampl.min()
					
					# Save phase
					phases_rad[scan_num] = phase
					amplitudes[scan_num] = ampl
					
					# abort, if requested 
					wx.Yield()
					if self.need_abort : break
					
					# Get spectrum
					spectrum = self.GetSampleSpectrum(channel)
					# Vertical binning
					spectrum = ( spectrum.sum(axis=0) if len(spectrum.shape) == 2 else spectrum )
					
					if scan_num == 0 :
						# Initialize the array
						spectra = np.zeros( (len(poly_coeffs), spectrum.size), dtype=spectrum.dtype )
						spectra[:] = spectrum.min()
						
					# Save the spectrum
					spectra[scan_num] = spectrum
					
					# Display the currently acquired data
					try : 
						spectra_2d_img.SetData(spectra)
						phases_rad_2d_img.SetData( phases_rad%(2*np.pi) )
						#amplitudes_2d_img.SetData( amplitudes )
					except NameError :
						visvis.cla(); visvis.clf()
						
						visvis.subplot(121)
						spectra_2d_img = visvis.imshow(spectra, cm=visvis.CM_JET)
						visvis.ylabel ('scans'); visvis.xlabel ('wavelegth')
						visvis.title("spectral scan")
						
						visvis.subplot(122)
						phases_rad_2d_img = visvis.imshow( phases_rad%(2*np.pi), cm=visvis.CM_JET)
						visvis.title("phase shapes")
						
						#visvis.subplot(133)
						#amplitudes_2d_img = visvis.imshow(amplitudes, cm=visvis.CM_JET)
						#visvis.title("amplitudes")
						
				# Save the data for the given channel
				try : del log_file[ str(channel) ]
				except KeyError : pass
				
				channel_grp = log_file.create_group( str(channel) )
				channel_grp["spectra"] 		= spectra
				channel_grp["phases_rad"]	= phases_rad
				channel_grp["amplitudes"]	= amplitudes
				channel_grp["poly_coeffs"]	= poly_coeffs
				
		# Readjust buttons settings
		self.StopScannning(event)
Ejemplo n.º 42
0
	def GetDeltaScan (self, event) :
		"""
		Measure spectra by varying parameter delta in reference phase mask
		"""
		# Create pseudonyms of necessary devices 
		self.DevSpectrometer 	= self.parent.Spectrometer.dev
		self.DevPulseShaper		= self.parent.PulseShaper.dev
		
		####################### Initiate devices #############################
		
		# Initiate spectrometer
		settings = self.parent.Spectrometer.GetSettings()
		if self.DevSpectrometer.SetSettings(settings) == RETURN_FAIL : return
		
		# Initiate pulse shaper
		settings = self.parent.PulseShaper.GetSettings()
		if self.DevPulseShaper.Initialize(settings) == RETURN_FAIL : return
		
		# Get number of optimization variables 
		self.num_pixels = self.DevPulseShaper.GetParamNumber()
		if self.num_pixels == RETURN_FAIL :
			raise RuntimeError ("Optimization cannot be started since calibration file was not loaded")
		
		miips_settings = self.GetSettings()
		#####################################################################
		
		# Get range of coefficient 
		coeff_range = np.linspace( miips_settings["coeff_min"], miips_settings["coeff_max"], miips_settings["coeff_num"] )
	
		# Get reference phase based on the corrections already obtained
		reference_phase, X, polynomial_basis = self.GetReferencePhase(miips_settings)
		
		# Get new polynomial
		new_coeffs = np.zeros(miips_settings["polynomial_order"] + 1)
		new_coeffs[-1] = 1
		current_polynomial = polynomial_basis(new_coeffs)(X)
	
		# Chose max amplitude
		max_ampl = miips_settings["max_ampl"]*np.ones(self.num_pixels)
		
		# Adjusting button's settings
		button = event.GetEventObject()
		button.SetLabel (button._stop_label)
		button.SetBackgroundColour('red')
		button.Bind( wx.EVT_BUTTON, button._stop_method)
		self.need_abort = False
		
		for scan_num, coeff in enumerate(coeff_range) :
			# Get current phase mask
			current_phase = coeff*current_polynomial
			current_phase += reference_phase
			
			# Check for consistency
			current_phase %= 1
			
			# Set the pulse shape
			self.DevPulseShaper.SetAmplPhase(max_ampl, current_phase) 
			
			wx.Yield()
			# abort, if requested 
			if self.need_abort : break
				
			# Get spectrum
			spectrum = self.DevSpectrometer.AcquiredData()
			
			# Vertical binning
			spectrum = ( spectrum.sum(axis=0) if len(spectrum.shape) == 2 else spectrum )
		
			try : spectral_scans
			except NameError :
				# Allocate space for spectral scans
				spectral_scans = np.zeros( (coeff_range.size, spectrum.size), dtype=spectrum.dtype )
			
			# Save spectrum
			spectral_scans[ scan_num ] = spectrum
			
			# Display the currently acquired data
			try : spectral_scan_2d_img.SetData(spectral_scans)
			except NameError :
				visvis.cla(); visvis.clf(); 	
				spectral_scan_2d_img = visvis.imshow(spectral_scans, cm=visvis.CM_JET)
				visvis.ylabel ('coefficeints')
				visvis.xlabel ('wavelegth')
				
		#######################################################
		
		# Get current wavelength
		wavelength = self.DevSpectrometer.GetWavelengths()
		
		# Adding the scan to log
		self.scan_log.append( {
			"spectral_scans" 	:	spectral_scans,
			"reference_phase" 	:	reference_phase,
			"current_polynomial":	current_polynomial,
			"coeff_range"		: 	coeff_range,
			"wavelength"		:	wavelength
		} )
		
		# Plotting fit
		visvis.cla(); visvis.clf(); 	
		
		################ Find the value of coeff such that it maximizes the total intensity of SHG
		
		# Method 1: use polynomial filter
		
		# Ignored not scanned parameter
		spectral_sum = spectral_scans.sum(axis=1)
		indx = np.nonzero(spectral_sum > 0)		
		# Fit the total spectral intensity with chosen polynomials
		spectral_sum_fit = polynomial_basis.fit(coeff_range[indx], spectral_sum[indx] , 10)
		# Find extrema of the polynomial fit
		opt_coeff = spectral_sum_fit.deriv().roots()
		# Find maximum
		fit_max_sum_val = opt_coeff[ np.argmax(spectral_sum_fit(opt_coeff)) ].real
		print "\n\nOptimal value of the coefficient (using the polynomial fit) is ", fit_max_sum_val
		
		# Method 2: Use Gaussian filter 
		# Smoothing spectral scans
		filtered_spectral_scans = gaussian_filter(spectral_scans, (2, 0.5) )
		gauss_max_sum_val = coeff_range[ np.argmax(filtered_spectral_scans.sum(axis=1)) ]
		print "\nOptimal value of the coefficient (using the Gaussian filter) is ", gauss_max_sum_val
		
		# If the difference between methods is great then use the Gaussian filter 
		if abs(gauss_max_sum_val - fit_max_sum_val)/np.abs([gauss_max_sum_val, fit_max_sum_val]).max() > 0.3 :
			max_sum_val = gauss_max_sum_val
		else : 
			max_sum_val = fit_max_sum_val
		
		self.current_coeff_val.SetValue( max_sum_val )
		filtered_spectral_scans[ np.searchsorted(coeff_range, max_sum_val) ][0:-1:2] = spectral_scans.min()		
		
		################ Plotting results ####################
		#spectral_scan_2d_img.SetData(spectral_scans)
		#spectral_scan_2d_img.SetClim( spectral_scans.min(), spectral_scans.max() )
		
		visvis.subplot(121)
		visvis.title("Raw spectral scans")
		visvis.imshow(spectral_scans, cm=visvis.CM_JET)
		visvis.ylabel ('coefficeints'); visvis.xlabel ('wavelegth')
		
		visvis.subplot(122)
		visvis.title("Finding maximum")
		visvis.imshow(filtered_spectral_scans, cm=visvis.CM_JET)
		visvis.ylabel ('coefficeints'); visvis.xlabel ('wavelegth')
		
		# Readjust buttons settings
		self.StopScannning(event)
Ejemplo n.º 43
0
astro = vv.imread('astronaut.png').astype(np.float32)
astro = astro[100:-100, 100:-100, :]

# Smooth a bit
im = astro.copy()
im[1:, :, :] = astro[:-1, :, :]
im[:-1, :, :] += astro[1:, :, :]
im[:, :-1, :] += astro[:, 1:, :]
im[:, 1:, :] += astro[:, :-1, :]
im /= 4

# Prepare figure
vv.figure()

# Without color, with colormap
a1 = vv.subplot(121)
m1 = vv.surf(im[:, :, 0])
m1.colormap = vv.CM_HOT
vv.title('With colormap')

# With color
a2 = vv.subplot(122)
m2 = vv.surf(im[:, :, 0], im)
vv.title('With original texture')

# Flip y-axis, otherwise the image is upside down
a1.daspect = 1, -1, 1
a2.daspect = 1, -1, 1

# Enter mainloop
app = vv.use()
Ejemplo n.º 44
0
            #if (y-circLoc[0])**2 + (x-circLoc[1])**2 < radius**2: # circles
            if abs(y - circLoc[0]) + abs(
                    x - circLoc[1]) < radius * 1.1:  # diamonds
                im[y, x] += 1.0
    # Add
    ims.append(im)

INDEXMAP = {0: 1, 1: 2, 2: 4, 3: 3}  # map index to subplot location

# Show images
fig = vv.figure(1)
vv.clf()
fig.position = 200, 200, 500, 500
for i in range(4):
    j = INDEXMAP[i]  # map index to subplot location
    a = vv.subplot(2, 2, j)
    vv.imshow(ims[i])
    a.axis.visible = False
# vv.screenshot('c:/almar/projects/fourBlocks_initial.jpg', vv.gcf(), sf=2, bg='w')

## Register groupwise

# Init figure for registration
fig = vv.figure(2)
vv.clf()
fig.position = 200, 100, 900, 500

# Apply registration
reg = pirt.GravityRegistration(*ims)
# reg = pirt.DiffeomorphicDemonsRegistration(*ims)
# reg = pirt.ElastixGroupwiseRegistration(*ims)
Ejemplo n.º 45
0
                a = a.GetAxes()
                f.currentAxes = a
                return a
    
    # create axes in container
    a = Axes(f)
    c = a.parent
    
    # calculate relative coordinates
    dx, dy = 1.0/cols, 1.0/rows
    y = int( nr / cols )
    x = int( nr % cols )
    
    # apply positions
    c.position = dx*x, dy*y, dx, dy
    a.position = 10, 10, -20, -20
    
    # done
    return a
    
    

if __name__ == "__main__":
    f = vv.figure()
    a1=vv.subplot(221); a1.cameraType = '2d'
    a2=vv.subplot(224)    
    a3=vv.subplot(221)
    a3=vv.subplot(333)
    f.Draw()
    print a1 is a3
Ejemplo n.º 46
0
    if not os.path.isfile(fname):
        # try loading from the resource dir
        path = visvis.misc.getResourceDir()
        fname2 = os.path.join(path, fname)
        if os.path.isfile(fname2):
            fname = fname2
        else:
            raise IOError("Mesh file '%s' does not exist." % fname)
    
    # Use file extension to read file
    if fname.lower().endswith('.stl'):
        readFunc = vv.io.stl.StlReader.read
    elif fname.lower().endswith('.obj'):
        readFunc = vv.io.wavefront.WavefrontReader.read
    elif fname.lower().endswith('.ssdf') or fname.lower().endswith('.bsdf'):
        readFunc = ssdfRead
    else:
        raise ValueError('meshRead cannot determine file type.')
    
    # Read
    return readFunc(fname, check)

    
if __name__ == '__main__':
    
    bm = meshRead('bunny.ssdf')
    
    vv.figure(1); vv.clf()
    a = vv.subplot(121)
    m = vv.mesh(bm)
Ejemplo n.º 47
0
        # try loading from the resource dir
        path = visvis.misc.getResourceDir()
        fname2 = os.path.join(path, fname)
        if os.path.isfile(fname2):
            fname = fname2
        else:
            raise IOError("Mesh file '%s' does not exist." % fname)

    # Use file extension to read file
    if fname.lower().endswith('.stl'):
        readFunc = vv.io.stl.StlReader.read
    elif fname.lower().endswith('.obj'):
        readFunc = vv.io.wavefront.WavefrontReader.read
    elif fname.lower().endswith('.ssdf') or fname.lower().endswith('.bsdf'):
        readFunc = ssdfRead
    else:
        raise ValueError('meshRead cannot determine file type.')

    # Read
    return readFunc(fname, check)


if __name__ == '__main__':

    bm = meshRead('bunny.ssdf')

    vv.figure(1)
    vv.clf()
    a = vv.subplot(121)
    m = vv.mesh(bm)
Ejemplo n.º 48
0
# Degrees of freedom per node.

dofsPerNode= 1 

# Create mesh

coords, edof, dofs, bdofs, elementmarkers = cfm.createGmshMesh(geometry=g,
                                                               elType = elType,
                                                               elSizeFactor = 0.3,
                                                               dofsPerNode = dofsPerNode)

# ---- Visualise mesh -------------------------------------------------------

# Create two axes that are viewed from the same camera:

vv.figure()
a1 = vv.subplot(121)
a2 = vv.subplot(122)
cam = vv.cameras.ThreeDCamera()
a1.camera = a2.camera = cam

# Draw geometry and mesh

cfv.drawGeometry(g, axes=a1)
cfv.drawMesh(coords=coords, edof=edof, dofsPerNode=dofsPerNode, elType=elType, filled=False, axes=a2)

# Enter main loop

app = vv.use()
app.Create()
app.Run()
Ejemplo n.º 49
0
        isovalue = 0.0
        #
        vol = np.empty((n,n,n), 'float32')
        for iz in range(vol.shape[0]):
            for iy in range(vol.shape[1]):
                for ix in range(vol.shape[2]):
                    z, y, x = float(iz)*a+b, float(iy)*a+b, float(ix)*a+b
                    vol[iz,iy,ix] = ( ( 
                        (8*x)**2 + (8*y-2)**2 + (8*z)**2 + 16 - 1.85*1.85 ) * ( (8*x)**2 +
                        (8*y-2)**2 + (8*z)**2 + 16 - 1.85*1.85 ) - 64 * ( (8*x)**2 + (8*y-2)**2 )
                        ) * ( ( (8*x)**2 + ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2 + 16 - 1.85*1.85 )
                        * ( (8*x)**2 + ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2 + 16 - 1.85*1.85 ) -
                        64 * ( ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2 
                        ) ) + 1025
        # Uncommenting the line below will yield different results for classic MC
        #vol = -vol
    
    # Get surface meshes
    bm1 = isosurface(vol, isovalue, 1, useClassic=True)
    t0 = time.time()
    bm2 = isosurface(vol, isovalue, 1)
    print('finding surface took %1.0f ms' % (1000*(time.time()-t0)) )
    
    # Show
    vv.figure(1); vv.clf()
    vv.subplot(121); vv.imshow(im); vv.plot(pp, ls='+', lc='r', lw=2)
    a1=vv.subplot(222); m1=vv.mesh(bm1) #t=vv.volshow(vol)
    a2=vv.subplot(224); m2=vv.mesh(bm2)
    a1.camera = a2.camera

        
Ejemplo n.º 50
0
 def __init__(self, im, grid_sampling=40):
     
     # Store image
     self._im = im
     
     # Setup visualization
     self._fig = fig = vv.figure()
     self._a1 = a1 = vv.subplot(231);
     self._a2 = a2 = vv.subplot(232);
     self._a3 = a3 = vv.subplot(233);
     self._a4 = a4 = vv.subplot(234);
     self._a5 = a5 = vv.subplot(235);
     self._a6 = a6 = vv.subplot(236);
     
     # Text objects
     self._text1 = vv.Label(fig)
     self._text1.position = 5, 2
     self._text2 = vv.Label(fig)
     self._text2.position = 5, 20
     
     # Move axes 
     a1.parent.position = 0.0, 0.1, 0.33, 0.45
     a2.parent.position = 0.33, 0.1, 0.33, 0.45
     a3.parent.position = 0.66, 0.1, 0.33, 0.45
     a4.parent.position = 0.0, 0.55, 0.33, 0.45
     a5.parent.position = 0.33, 0.55, 0.33, 0.45
     a6.parent.position = 0.66, 0.55, 0.33, 0.45
     
     # Correct axes, share camera
     cam = vv.cameras.TwoDCamera()
     for a in [a1, a2, a3, a4, a5, a6]:
         a.axis.visible = False
         a.camera = cam
     
     # Show images
     im0 = im*0
     self._t1 = vv.imshow(im, axes=a1)
     self._t2 = vv.imshow(im, axes=a2)
     self._t3 = vv.imshow(im, axes=a3)
     self._t4 = vv.imshow(im0, axes=a4)
     self._t5 = vv.imshow(im0, axes=a5)
     self._t6 = vv.imshow(im0, axes=a6)
     
     # Init pointsets
     self._pp1 = Pointset(2)
     self._pp2 = Pointset(2)
     self._active = None
     self._lines = []
     
     # Init lines to show all deformations
     tmp = vv.Pointset(2)        
     self._line1 = vv.plot(tmp, ls='', ms='.', mc='c', axes=a2)
     self._line2 = vv.plot(tmp, ls='+', lc='c', lw='2', axes=a2)
     
     # Init grid properties
     self._sampling = grid_sampling
     self._levels = 5
     self._multiscale = True
     self._injective = 0.5
     self._frozenedge = 1
     self._forward = True
     
     # Init grid
     self.DeformationField = DeformationFieldForward
     self._field1 = self.DeformationField(FieldDescription(self._im))
     self._field2 = self.DeformationField(FieldDescription(self._im))
     
     # Bind to events
     a2.eventMouseDown.Bind(self.on_down)
     a2.eventMouseUp.Bind(self.on_up)
     a2.eventMotion.Bind(self.on_motion)
     fig.eventKeyDown.Bind(self.on_key_down)
     #a1.eventDoubleClick.Bind(self.OnDone)
     
     # Apply
     self.apply()
Ejemplo n.º 51
0
		if resolution is None:
			resolution = 128
		
		supportedImageFormats = ['.jpg', '.png']
		supportedMeshFormats = ['.stl', '.ply', '.off', '.obj']
		ext = os.path.splitext(fileName)[-1]
		if ext.lower() in supportedImageFormats:
			im = vv.imread(fileName)
			imgArray = imToGS(im)
			if absT is None:
				absT = 5 * max(imgArray.shape) / 100
				relT = 0.5
			T = (np.max(imgArray) + np.min(imgArray))/2
			imgArrayT = (imgArray < T).astype(np.uint8)
			vv.figure()
			ax1 = vv.subplot(121)
			ax2 = vv.subplot(122)
			t1 = vv.imshow(im, axes=ax1)
			t2 = vv.imshow(imgArray, axes=ax2)
			app = vv.use()
			app.Run()
			
			P = mcTSystem()
			P.fromBinaryArray(imgArrayT)
			P.doThinning(absT, relT)
			result = P.cellArray[::2,::2].astype(np.uint8)*255 + 255 - 255*imgArrayT
			Image.fromarray(result).show()
		elif ext.lower() in supportedMeshFormats:
			P = mcTSystem()
			bm = vv.meshRead(fileName)
			m = vv.mesh(bm)
Ejemplo n.º 52
0
    # use floats to prevent strides etc. uint8 caused crash on qt backend.
    im = gl.glReadPixels(x, y, w, h, gl.GL_RGB, gl.GL_FLOAT)

    # reshape, flip, and store
    im.shape = h, w, 3
    im = np.flipud(im)

    # done
    return im


if __name__ == '__main__':

    # Prepare
    f = vv.figure()
    a1 = vv.subplot(211)
    a2 = vv.subplot(212)

    # Draw some data
    vv.plot([2, 3, 4, 2, 4, 3], axes=a1)
    f.DrawNow()

    # Take snapshots
    im1 = vv.getframe(f)
    im2 = vv.getframe(a1)
    # clear and show snapshots
    a1.Clear()
    a2.Clear()
    vv.imshow(im1, axes=a1, clim=(0, 1))
    vv.imshow(im2, axes=a2, clim=(0, 1))
Ejemplo n.º 53
0
    l = vv.Line(axes, pp)
    l.lw = kwargs['lineWidth']
    l.lc = kwargs['lineColor']
    l.ls = kwargs['lineStyle']
    l.mw = kwargs['markerWidth'] 
    l.mc = kwargs['markerColor'] 
    l.ms = kwargs['markerStyle']
    l.mew = kwargs['markerEdgeWidth']
    l.mec = kwargs['markerEdgeColor']
    l.alpha = alpha
    
    ## done...
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = True
        axes.cameraType = str(camDim)+'d'
        axes.SetLimits()
    
    axes.Draw()
    return l


if __name__ == '__main__':
    vv.figure()
    vv.subplot(311)
    vv.plot([1,3,1,4,1,5,1,6,1,7,6,5,4,3,2,1]) # Passing 1D data
    vv.subplot(312)
    vv.plot([3,4,6,7],[7,5,4,6]) # Passing 2D data
    vv.subplot(313)
    vv.plot([3,4,6,7],[7,5,4,6], [1,2,3,2]) # Passing 3D data
Ejemplo n.º 54
0
def subplot(*args):
    """Create a visvis subplot."""
    return vv.subplot(*args)
Ejemplo n.º 55
0
        rData.buffer = self.__ai.integrate2d(data.buffer, self.outshape[0], self.outshape[1], unit="r_mm", method="lut_ocl")[0]
        return rData

extMgr = ctrl.externalOperation()
myOp = extMgr.addOp(Core.USER_LINK_TASK, "myTask", 0)
myTask = MyLink(10)
myOp.setLinkTask(myTask)
a = ctrl.acquisition()
a.setAcqNbFrames(0)
a.setAcqExpoTime(acqt)
ctrl.prepareAcq()
ctrl.startAcq()

while ctrl.getStatus().ImageCounters.LastImageReady < 1:
    print(ctrl.getStatus())
    time.sleep(0.5)
print(ctrl.getStatus())

raw_img = ctrl.ReadBaseImage().buffer
fai_img = ctrl.ReadImage().buffer
vv.figure()
rawplot = vv.subplot(121)
faiplot = vv.subplot(122)
rawtex = vv.imshow(raw_img, axes=rawplot)
faitex = vv.imshow(fai_img, axes=faiplot)
while 1:
    rawtex.SetData(ctrl.ReadBaseImage().buffer)
    faitex.SetData(ctrl.ReadImage().buffer)
    time.sleep(acqt)
    vv.processEvents()
Ejemplo n.º 56
0
#!/usr/bin/env python

import visvis as vv
app = vv.use()

# Get green channel of lena image
im = vv.imread('lena.png')[:,:,1]

# Make 4 subplots with different colormaps
cmaps = [vv.CM_GRAY, vv.CM_JET, vv.CM_SUMMER, vv.CM_HOT]
for i in range(4):
    a = vv.subplot(2,2,i+1)
    t = vv.imshow(im, clim=(0,255))
    a.axis.visible = 0
    t.colormap = cmaps[i]
    vv.colorbar()

app.Run()
Ejemplo n.º 57
0
import visvis as vv

app = vv.use()

# Load volume
vol = vv.volread("stent")

# Create figure and make subplots with different renderers
vv.figure(1)
vv.clf()
RS = ["mip", "iso", "edgeray", "ray", "litray"]
a0 = None
tt = []
for i in range(5):
    a = vv.subplot(3, 2, i + 2)
    t = vv.volshow(vol)
    vv.title("Renderstyle " + RS[i])
    t.colormap = vv.CM_HOT
    t.renderStyle = RS[i]
    t.isoThreshold = 200  # Only used in iso render style
    tt.append(t)
    if a0 is None:
        a0 = a
    else:
        a.camera = a0.camera

# Create colormap editor in first axes
cme = vv.ColormapEditor(vv.gcf(), *tt[3:])

# Run app