def grey_encrypt():

    try:

        img = cv.imread(askopenfilename(), 0)
        #print(type(img))
        img = img.astype(np.uint16)
        a, b = img.shape
        print('\n\nOriginal image: ')
        print(img)
        print((a, b))
        tup = a, b
        for i in tqdm(range(0, tup[0])):
            for j in (range(0, tup[1])):
                x = img[i][j]
                x = (pow(x, 3) % 25777)
                img[i][j] = x
        print('\n\nEncrypted Image:\n\n')
        print(img)
        vv.imshow(img)
        #imageio.imshow('EnImage', img) ##TODO this part
        cv.imwrite('EnImg.png', img)
        end = time.time()
        eTime = end - start
        print(eTime)

        enfinish()

    except TypeError:
        filenameerror()

    except AttributeError:
        filenameerror()
Example #2
0
    def test_jacobian(self, show=True):
        """ test_jacobian(show=True)
        
        Test the determinand of the field's Jacobian. It should be all 
        positive for the field to be diffeomorphic.
        
        Returns the number of pixels where the Jacobian <= 0. If show==True,
        will show a figure with these pixels indicated.
        
        """

        if self.ndim == 2:

            # Calculate gradients
            gradYY, gradYX = np.gradient(np.asarray(self[0]))
            gradXY, gradXX = np.gradient(np.asarray(self[1]))

            # Calculate determinants
            det = (gradYY + 1) * (gradXX + 1) - gradXY * gradYX

            if show:
                import visvis as vv
                vv.figure()
                vv.imshow(det <= 0)

            # Done
            return (det <= 0).sum()

        else:
            raise ValueError('Cannot yet check if 3D field is diffeomorphic.')
    def ShowImg(self):
        """
		Draw image
		"""
        if self._abort_img:
            # Exit
            return

        # Get image
        img = self.dev.StopImgAqusition()

        # Display image
        try:
            if img <> RETURN_FAIL:
                self._img_plot.SetData(img)
        except AttributeError:
            visvis.cla()
            visvis.clf()
            self._img_plot = visvis.imshow(img)
            visvis.title('Camera view')
            ax = visvis.gca()
            ax.axis.xTicks = []
            ax.axis.yTicks = []

        # Start acquisition of histogram
        self.dev.StartImgAqusition()
        wx.CallAfter(self.ShowImg)
Example #4
0
def visualize(im, vol, sz=0.25, thr=0.99):
    im, vol = im.numpy(), vol.numpy()
    print("Image shape:", im.shape)
    print("Volume shape:", vol.shape)

    # overlap with 3d representation + BGR->RGB
    im = im.transpose(1, 2, 0)  # H,W,C
    im = im[:, :, ::-1]
    im = cv2.resize(im, (128, 128))

    t = vv.imshow(im)
    t.interpolate = True  # interpolate pixels

    # volshow will use volshow3 and rendering the isosurface if OpenGL version is >= 2.0
    # Otherwise, it will show slices with bars that you can move (much less useful).
    im = (im * 128 + 128).astype(np.uint8)
    # im = np.ones_like(im)

    volRGB = np.stack(((vol >= thr) * im[:, :, 0], (vol >= thr) * im[:, :, 1],
                       (vol >= thr) * im[:, :, 2]),
                      axis=3)

    v = vv.volshow(volRGB, renderStyle='iso')
    v.transformations[1].sz = sz  # Z rescaling

    l0 = vv.gca()
    l0.light0.ambient = 0.9  # 0.2 is default for light 0
    l0.light0.diffuse = 1.0  # 1.0 is default

    a = vv.gca()
    a.axis.visible = 0
    a.camera.fov = 0  # orthographic
    vv.use().Run()
Example #5
0
    def makeFullSpec(self):
        i = 0
        j=0
        while i < len(self.signal)-self.NFFT:
            zpSignal = np.append(self.win*self.signal[i:i+self.NFFT], np.zeros((1,1024-self.NFFT)))
            spec = np.fft.rfft(zpSignal)/self.NFFT
        
            psd = abs(spec)
            psd = 20*np.log10(psd)

            self.imgArray[:,j]=psd
            j+=1
            i= i+ self.NFFT-self.overlap
            
        self.imgArray[self.imgArray>np.amax(self.imgArray)-3]= np.amax(self.imgArray)-3
        self.imgArray[self.imgArray<(np.amax(self.imgArray)-self.dynamicRange)]=self.noiseFloor   
        print self.imgArray.shape
        self.t = vv.imshow(np.flipud(self.imgArray[:,0:15000]), cm = [(1,1,1),(0,0,0)])
        self.axisLabeler = self.axes.axis
        self.axes.cameraType = 3
        self.axes.daspectAuto= False
        self.axisLabeler.showGrid = True
        self.t.interpolate = False
        self.axes.cameraType = 2
        self.axes.SetLimits(rangeX = (4800,4900),rangeY = (self.imgArray.shape[0],(self.freqRange/self.fs)*self.imgArray.shape[0]))
	def ShowImg (self) :
		"""
		Draw image
		"""
		if self._abort_img  :
			# Exit
			return
		
		# Get image
		img = self.dev.StopImgAqusition()
		
		# Display image
		try :
			if img <> RETURN_FAIL :
				self._img_plot.SetData(img)
		except AttributeError :
			visvis.cla()
			visvis.clf()
			self._img_plot = visvis.imshow(img)
			visvis.title ('Camera view')
			ax = visvis.gca()
			ax.axis.xTicks = []
			ax.axis.yTicks = []
		
		# Start acquisition of histogram
		self.dev.StartImgAqusition()
		wx.CallAfter(self.ShowImg)
Example #7
0
	def _createWindow(self, name, im, axis):

		vv.figure()
		vv.gca()
		vv.clf()
		fig = vv.imshow(im)
		dims = im.shape

		''' Change color bounds '''
		if im.dtype == np.uint8:
			fig.clim.Set(0, 255)
		else:
			fig.clim.Set(0., 1.)
		
		fig.GetFigure().title = name
		
		''' Show ticks on axes? '''
		if not axis:
			fig.GetAxes().axis.visible = False
			bgcolor = (0.,0.,0.)
		else:
			fig.GetAxes().axis.showBox = False
			bgcolor = (1.,1.,1.)

		''' Set background color '''
		fig.GetFigure().bgcolor = bgcolor
		fig.GetAxes().bgcolor = bgcolor

		''' Setup keyboard event handler '''
		fig.eventKeyDown.Bind(self._keyHandler)

		win = {'name':name, 'canvas':fig, 'shape':dims, 'keyEvent':None, 'text':[]}
		self.open_windows.append(win)

		return win
Example #8
0
    def __init__(self, vol, direction, axes=None, clim=None):
        self.direction = direction
        # Store vol and init
        if self.direction == 0:
            self.vol = vol
        elif self.direction == 1:
            self.vol = np.transpose(vol, (1, 0, 2))
            self.vol.origin = (vol.origin[1], vol.origin[0], vol.origin[2])
            self.vol.sampling = (vol.sampling[1], vol.sampling[0],
                                 vol.sampling[2])
        elif self.direction == 2:
            self.vol = np.transpose(vol, (2, 0, 1))
            self.vol.origin = (vol.origin[2], vol.origin[0], vol.origin[1])
            self.vol.sampling = (vol.sampling[2], vol.sampling[0],
                                 vol.sampling[1])
        else:
            S('No valid input for direction, only 1,2 or 3 is possible')
        self.slice = 0

        # Prepare figure and axex
        if axes is None:
            self.a = vv.gca()
        else:
            self.a = axes

        self.f = vv.gcf()

        # Create slice in 2D texture
        if clim:
            self.t = vv.imshow(self.vol[self.round_slice, :, :],
                               clim=clim,
                               axes=self.a)
        else:
            self.t = vv.imshow(self.vol[self.round_slice, :, :], axes=self.a)

        # Bind
        self.a.eventScroll.Bind(self.on_scroll)
        self.eventPositionUpdate = vv.events.BaseEvent(self)

        axes.eventMouseDown.Bind(self.on_click)

        # Fig properties
        self.a.bgcolor = [0, 0, 0]
        self.a.axis.visible = False
        self.a.showAxis = False
Example #9
0
def show():
    reader = imageio.read('<video0>')
    
    import visvis as vv
    im = reader.get_next_data()
    t = vv.imshow(im)
    
    while True:
        t.SetData(reader.get_next_data())
        vv.processEvents()
    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
Example #11
0
def show_in_visvis():
    reader = imageio.read('cockatoo.mp4', 'ffmpeg')
    #reader = imageio.read('<video0>')
    
    import visvis as vv
    im = reader.get_next_data()
    f = vv.clf()
    f.title = reader.format.name
    t = vv.imshow(im, clim=(0, 255))
    
    while not f._destroyed:
        t.SetData(reader.get_next_data())
        vv.processEvents()
Example #12
0
def show_in_visvis():
    reader = imageio.read('cockatoo.mp4', 'ffmpeg')
    #reader = imageio.read('<video0>')

    import visvis as vv
    im = reader.get_next_data()
    f = vv.clf()
    f.title = reader.format.name
    t = vv.imshow(im, clim=(0, 255))

    while not f._destroyed:
        t.SetData(reader.get_next_data())
        vv.processEvents()
Example #13
0
 def __init__(self, vol):
     # Store vol and init
     self.vol = vol
     self.z = 0
     # Prepare figure and axex
     self.f = vv.figure(1001)
     self.f.Clear()
     self.a = vv.gca()
     # Create slice in 2D texture
     self.t = vv.imshow(vol[self.z,:,:])
     # Bind
     self.f.eventScroll.Bind(self.on_scroll)
     self.a.eventScroll.Bind(self.on_scroll)
Example #14
0
def show_in_visvis():
    # reader = imageio.read("imageio:cockatoo.mp4", "ffmpeg")
    reader = imageio.read("<video0>", fps=20)

    import visvis as vv

    im = reader.get_next_data()
    f = vv.clf()
    f.title = reader.format.name
    t = vv.imshow(im, clim=(0, 255))

    while not f._destroyed:
        im = reader.get_next_data()
        if im.meta["new"]:
            t.SetData(im)
        vv.processEvents()
Example #15
0
    def __init__(self, vol, a_transversal, a_coronal, a_sagittal, a_text):

        # Create text objects
        self._labelx = vv.Label(a_text)
        self._labely = vv.Label(a_text)
        self._labelz = vv.Label(a_text)
        self._labelx.position = 10, 10
        self._labely.position = 10, 30
        self._labelz.position = 10, 50

        # Create Finish button
        self._finished = False
        self._but = vv.PushButton(a_text)
        self._but.position = 10, 80
        self._but.text = 'Finish'

        # Get short name for sampling
        if isinstance(vol, Aarray):
            self._sam = sam = vol.sampling
        else:
            self._sam = None
            sam = (1, 1, 1)

        # Calculate mips and deal with anisotropy
        mipz = np.max(vol, 0)
        mipz = Aarray(mipz, (sam[1], sam[2]))
        mipy = np.max(vol, 1)
        mipy = Aarray(mipy, (sam[0], sam[2]))
        mipx = np.max(vol, 2)
        mipx = Aarray(mipx, (sam[0], sam[1]))

        # Display the mips
        vv.imshow(mipz, axes=a_transversal)
        vv.imshow(mipy, axes=a_coronal)
        vv.imshow(mipx, axes=a_sagittal)

        # Initialize range objects
        self._range_transversal = RangeWobject2D(a_transversal, mipz)
        self._range_coronal = RangeWobject2D(a_coronal, mipy)
        self._range_sagittal = RangeWobject2D(a_sagittal, mipx)

        # Get list of all range wobjects
        self._rangeWobjects = [
            self._range_transversal, self._range_coronal, self._range_sagittal
        ]

        # Bind events
        fig = a_text.GetFigure()
        fig.eventClose.Bind(self._OnFinish)
        self._but.eventPress.Bind(self._OnFinish)
        for r in self._rangeWobjects:
            r.eventRangeUpdated.Bind(self._OnRangeUpdated)

        # Almost done
        self._SetTexts()
Example #16
0
def show_in_visvis():
    # reader = imageio.read("imageio:cockatoo.mp4", "ffmpeg")
    reader = imageio.read("<video0>", fps=20)

    import visvis as vv

    im = reader.get_next_data()
    f = vv.clf()
    f.title = reader.format.name
    t = vv.imshow(im, clim=(0, 255))

    while not f._destroyed:
        im = reader.get_next_data()
        if im.meta["new"]:
            t.SetData(im)
        vv.processEvents()
Example #17
0
 def __init__(self, vol, a_transversal, a_coronal, a_sagittal, a_text):
     
     # Create text objects
     self._labelx = vv.Label(a_text)        
     self._labely = vv.Label(a_text)        
     self._labelz = vv.Label(a_text)
     self._labelx.position = 10,10
     self._labely.position = 10,30
     self._labelz.position = 10,50
     
     # Create Finish button
     self._finished = False
     self._but = vv.PushButton(a_text)
     self._but.position = 10,80
     self._but.text = 'Finish'
     
     # Get short name for sampling
     if isinstance(vol, Aarray):
         self._sam = sam = vol.sampling
     else:
         self._sam = None
         sam = (1,1,1)
     
     # Calculate mips and deal with anisotropy
     mipz = np.max(vol,0)
     mipz = Aarray(mipz, (sam[1], sam[2]))
     mipy = np.max(vol,1)
     mipy = Aarray(mipy, (sam[0], sam[2]))
     mipx = np.max(vol,2)
     mipx = Aarray(mipx, (sam[0], sam[1]))
     
     # Display the mips
     vv.imshow(mipz, axes=a_transversal)
     vv.imshow(mipy, axes=a_coronal)
     vv.imshow(mipx, axes=a_sagittal)
     
     # Initialize range objects
     self._range_transversal = RangeWobject2D(a_transversal, mipz)
     self._range_coronal = RangeWobject2D(a_coronal, mipy)
     self._range_sagittal = RangeWobject2D(a_sagittal, mipx)
     
     # Get list of all range wobjects
     self._rangeWobjects = [self._range_transversal, 
         self._range_coronal, self._range_sagittal]
     
     # Bind events
     fig = a_text.GetFigure()
     fig.eventClose.Bind(self._OnFinish)
     self._but.eventPress.Bind(self._OnFinish)
     for r in self._rangeWobjects:
         r.eventRangeUpdated.Bind(self._OnRangeUpdated)
     
     # Almost done
     self._SetTexts()
Example #18
0
    def show(self, axes=None, axesAdjust=True, showGrid=True):
        """ show(axes=None, axesAdjust=True, showGrid=True)
        
        For 2D grids, shows the field and the knots of the grid.
        The image is displayed in the given (or current) axes. By default
        the positions of the underlying knots are also shown using markers.
        Returns the texture object of the field image.
        
        Requires visvis.
        
        """
        import visvis as vv

        # Test dimensions
        if self.ndim != 2:
            raise RuntimeError('Show only works for 2D data.')

        # Get field
        field = Aarray(self.get_field(), self.field_sampling)

        # Get points for all knots
        pp = PointSet(2)
        for gy in range(self.grid_shape[0]):
            for gx in range(self.grid_shape[0]):
                x = (gx - 1) * self.grid_sampling
                y = (gy - 1) * self.grid_sampling
                pp.append(x, y)

        # Draw
        if showGrid:
            vv.plot(pp,
                    ms='.',
                    mc='g',
                    ls='',
                    axes=axes,
                    axesAdjust=axesAdjust)
            return vv.imshow(field, axes=axes)
        else:
            return vv.plot(pp,
                           ms='.',
                           mc='g',
                           ls='',
                           axes=axes,
                           axesAdjust=axesAdjust)
	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
Example #20
0
    def show(self, axes=None, axesAdjust=True):
        """ show(axes=None, axesAdjust=True)
        
        Illustrates 2D deformations.
        
        It does so by creating an image of a grid and deforming it.
        The image is displayed in the given (or current) axes. 
        Returns the texture object of the grid image.
        
        Requires visvis.
        
        """
        import visvis as vv

        # Test dimensions
        if self.ndim != 2:
            raise RuntimeError('Show only works for 2D data.')

        # Create image
        shape, sampling = self.field_shape, self.field_sampling
        im = Aarray(shape, sampling, fill=0.0, dtype=np.float32)
        #
        step = 10
        mayorStep = step * 5
        #
        im[1::step, :] = 1
        im[:, 1::step] = 1
        im[::mayorStep, :] = 1.2
        im[1::mayorStep, :] = 1.2
        im[2::mayorStep, :] = 1.2
        im[:, ::mayorStep] = 1.2
        im[:, 1::mayorStep] = 1.2
        im[:, 2::mayorStep] = 1.2

        # Deform
        im2 = self.apply_deformation(im)

        # Draw
        t = vv.imshow(im2, axes=axes, axesAdjust=axesAdjust)

        # Done
        return t
Example #21
0
def movieShow(images, clim=None, duration=0.1, axesAdjust=True, axes=None):
    """ movieShow(images, duration=0.1)
    
    Show the images in the given list as a movie. 
    
    Parameters
    ----------
    images : list
        The 2D images (can be color images) that the movie consists of.
    clim : (min, max)
        The color limits to apply. See imshow.
    duration : scalar
        The duration (in seconds) of each frame. The real duration can
        differ from the given duration, depending on the performance of
        your system.
    axesAdjust : bool
        If axesAdjust==True, this function will call axes.SetLimits(), set
        the camera type to 2D, and make axes.daspect[1] negative (i.e. flip 
        the y-axis). If daspectAuto has not been set yet, it is set to False.
    axes : Axes instance
        Display the image in this axes, or the current axes if not given.
    
    """
    
    # Get axes
    if axes is None:
        axes = vv.gca()
    
    # Create container
    m = vv.MotionDataContainer(axes, duration*1000)
    
    # Create images and put in container
    for im in images:
        t = vv.imshow(im, clim=clim, axesAdjust=axesAdjust, axes=axes)
        t.parent = m
    
    # Return container object
    return m
Example #22
0
    def _createWindow(self, name, im, axis):

        vv.figure()
        vv.gca()
        vv.clf()
        fig = vv.imshow(im)
        dims = im.shape
        ''' Change color bounds '''
        if im.dtype == np.uint8:
            fig.clim.Set(0, 255)
        else:
            fig.clim.Set(0., 1.)

        fig.GetFigure().title = name
        ''' Show ticks on axes? '''
        if not axis:
            fig.GetAxes().axis.visible = False
            bgcolor = (0., 0., 0.)
        else:
            fig.GetAxes().axis.showBox = False
            bgcolor = (1., 1., 1.)
        ''' Set background color '''
        fig.GetFigure().bgcolor = bgcolor
        fig.GetAxes().bgcolor = bgcolor
        ''' Setup keyboard event handler '''
        fig.eventKeyDown.Bind(self._keyHandler)

        win = {
            'name': name,
            'canvas': fig,
            'shape': dims,
            'keyEvent': None,
            'text': []
        }
        self.open_windows.append(win)

        return win
Example #23
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
Example #24
0
 def __init__(self, c=None, p1=None, p2=None):
     
     # Init visualization
     fig = vv.figure(101); vv.clf()
     a = vv.gca()
     
     # Init patch
     self._patchSize = patchSize = 64
     self._im = np.zeros((patchSize,patchSize), dtype=np.float32)
     self._t = vv.imshow(self._im, clim=(0,10))
     
     # Init points
     if c is None: c = Point(14,12)
     if p1 is None: p1 = Point(12,16)
     if p2 is None: p2 = Point(16,16)
     
     #
     self._c = vv.plot(c, ls='', ms='+', mw=10, mc='k')
     self._p1 = vv.plot(p1, ls='', ms='.', mw=10, mc='r')
     self._p2 = vv.plot(p2, ls='', ms='.', mw=10, mc='b')
     
     
     
     # Init object being moved
     self._movedPoint = None
     
     # Enable callbacks
     for line in [self._c, self._p1, self._p2]:
         line.hitTest = True
         line.eventMouseDown.Bind(self.OnDown)
         line.eventMotion.Bind(self.OnMotion)
         line.eventMouseUp.Bind(self.OnUp)
     a.eventMotion.Bind(self.OnMotion)
     a.eventMouseUp.Bind(self.OnUp)
     
     # Start
     self.Apply()
Example #25
0
	def createWindow(self, name, im, axis):

		vv.figure()
		vv.gca()
		vv.clf()
		fig = vv.imshow(im)
		dims = im.shape

		''' Change color bounds '''
		if im.dtype == np.uint8:
			fig.clim.Set(0, 255)
		else:
			fig.clim.Set(im.min(), im.max())
		
		fig.GetFigure().title = name
		
		''' Show ticks on axes? '''

		if not axis:
			fig.GetAxes().axis.visible = False
			bgcolor = (0.,0.,0.)
		else:
			fig.GetAxes().axis.showBox = False
			bgcolor = (1.,1.,1.)

		fig.GetFigure().bgcolor = bgcolor
		fig.GetAxes().bgcolor = bgcolor



		fig.eventKeyUp.Bind(self.keyHandler)

		win = {'name':name, 'figure':fig, 'shape':dims, 'keyEvent':None}
		self.open_windows.append(win)

		return win
Example #26
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()
Example #27
0
def create_icons():
    icon = Icon()
    for n in (16, 32, 48, 64, 128, 256):
        icon.add(create_icon(n).tobytes())
    icon.write(os.path.join(flexx.__path__[0], 'resources', 'flexx.ico'))


def create_silly_icon():

    im = np.zeros((16, 16, 4), 'uint8')
    im[3:-3, 3:-3] = 200
    im[:, :, 3] = 255
    
    icon = Icon()
    icon.add(im.tobytes())
    bb = icon._to_png(icon._ims[16])
    print(base64.encodebytes(bb).decode())


if __name__ == '__main__':
    
    rgba = create_icon(48)
    
    import visvis as vv
    vv.figure(1)
    vv.clf()
    vv.imshow(rgba)
    
    create_icons()
Example #28
0
import imageio
import visvis as vv

im = imageio.imread(
    'http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png'
)
vv.imshow(im)
Example #29
0
            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)
# -*- coding: utf-8 -*-
"""
Created on Thu Jan  4 21:03:33 2018

@author: Saurav
"""

import imageio
import visvis as vv

reader = imageio.get_reader('<video0>')
t = vv.imshow(reader.get_next_data(), clim=(0, 255))
for im in reader:
    vv.processEvents()
    t.SetData(im)
Example #31
0
    reg.params.final_scale = 1
    reg.params.final_grid_sampling = 20
    reg.params.grid_sampling_factor = 0.5  # !! important especially for Laplace !!
    reg.params.frozenedge = True
    reg.params.mass_transforms = 2
    reg.params.speed_factor = 1.0

# Register, pass the figure so that the algorithm can show progress
reg.register(1, fig)

# Visualize end results
vv.figure(2)
vv.clf()
reg.show_result('diff', vv.figure(2))

# Get tge found deform and the error compared to the known deform
deform = reg.get_final_deform(0, 1, 'backward')
refErr = np.abs(im1 - im2)
err = np.abs(deform.apply_deformation(im1) - im2)

# Analyse errors in registration
parts = []
for def1, def2 in zip(rd, deform):
    parts.append(def1 - def2)
D = (parts[0]**2 + parts[1]**2)**0.5
#
print('error', err.mean() / refErr.mean(), D.mean())
vv.imshow(D)

vv.use().Run()
Example #32
0
Note that the alpha value is always asumed between 0 and 1, so a
transparant texture should always be of float type.
"""

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

# Lena is our original image
vv.clf()
im = vv.imread('lena.png')

# Find the regions where there's relatively much blue
mask = (im[:, :, 0] < 200) & (im[:, :, 2] > 0.7 * im[:, :, 0])

# Create an RGBA texture and fill in the found region in blue
mask2 = np.zeros(mask.shape + (4, ), dtype=np.float32)
mask2[:, :, 2] = mask
mask2[:, :, 3] = mask * 0.5

# Add a black, green, red, and yellow region in the corner
mask2[100:200, :200, 0] = 1.0
mask2[:200, 100:200, 1] = 1.0
mask2[:200, :200, 3] = 0.5

# Show image and mask
t1 = vv.imshow(im)
t2 = vv.imshow(mask2)

app.Run()
Example #33
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)
Note that the alpha value is always asumed between 0 and 1, so a
transparant texture should always be of float type.
"""

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

# Lena is our original image
vv.clf()
im = vv.imread('lena.png')

# Find the regions where there's relatively much blue
mask = (im[:,:,0] < 200) & (im[:,:,2]>0.7*im[:,:,0])

# Create an RGBA texture and fill in the found region in blue
mask2 = np.zeros(mask.shape+(4,), dtype=np.float32)
mask2[:,:,2] = mask
mask2[:,:,3] = mask * 0.5

# Add a black, green, red, and yellow region in the corner
mask2[100:200,:200,0] = 1.0
mask2[:200,100:200,1] = 1.0
mask2[:200,:200,3] = 0.5
  
# Show image and mask
t1=vv.imshow(im)
t2=vv.imshow(mask2)

app.Run()
Example #35
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))
Example #36
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)
Example #37
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()
Example #38
0
    
    >>--post-loop--
    float th = 0.05;
    vec4 normalColor = texture2D(texture, pos);
    // Element-wise mask on blurred image (color1), using a threshold    
    float mask = float(length(color1.rgb)-length(color2.rgb)>th);
    normalColor.rgb += mask * amount * (normalColor.rgb -color1.rgb);
    color1 = normalColor;
    // --post-loop--    
""")

# Read image
im = vv.imread('lena.png')

# Show two times, the second will be sharpened
vv.subplot(121); t1 = vv.imshow(im)
vv.subplot(122); t2 = vv.imshow(im)

# Share cameras and turn off anti-aliasing for proper comparison
t1.parent.camera = t2.parent.camera
t1.aa = 0

# Insert our part in the fragment shader program
t2.shader.fragment.AddOrReplace(SH_2F_SHARPEN, after='base')
if False: # Execute this line to turn it off:
    t2.shader.fragment.RemovePart('sharpen')

# Make a slider to set the amount
def sliderCallback(event):
    t2.shader.SetStaticUniform('amount', slider.value)
    t2.Draw()
Example #39
0
parser.add_argument('--image',
                    dest='image',
                    help="The background image to display")
parser.add_argument('--volume', dest='volume', help="The volume to render")
parser.add_argument('--texture',
                    dest='texture',
                    help="Show textured mesh NOT YET IMPLEMENTED")

args = parser.parse_args()

vol = np.fromfile(args.volume, dtype=np.int8)
# vol = vol.reshape((200, 192, 192))

im = vv.imread(args.image)

t = vv.imshow(im)
t.interpolate = True  # interpolate pixels

# volshow will use volshow3 and rendering the isosurface if OpenGL
# version is >= 2.0. Otherwise, it will show slices with bars that you
# can move (much less useful).
volRGB = np.stack(((vol > 1) * im[:, :, 0], (vol > 1) * im[:, :, 1],
                   (vol > 1) * im[:, :, 2]),
                  axis=3)

v = vv.volshow(volRGB, renderStyle='iso')
v.transformations[1].sz = 0.5  # Z was twice as deep during training

l0 = vv.gca()
l0.light0.ambient = 0.9  # 0.2 is default for light 0
l0.light0.diffuse = 1.0  # 1.0 is default
Example #40
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()
Example #41
0
    # 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))
        vv.imshow(im2,axes=a2, clim=(0,1))
Example #42
0
		
		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)
			app = vv.use()
			app.Run()
#!/usr/bin/env python

""" This example shows how to use the same camera for multiple axes, 
which can be helpful if for example the axes show a different view 
on the same data.
"""

import visvis as vv
app = vv.use()

# Read lena
im1 = vv.imread('lena.png')

# Our second image is a thresholded image
im2 = im1 > 100

# Create figure with two axes
vv.figure()
a1 = vv.subplot(121)
a2 = vv.subplot(122)

# Create new camera and attach
cam = vv.cameras.TwoDCamera()
a1.camera = a2.camera = cam

# Draw images
vv.imshow(im1, axes=a1)
vv.imshow(im2, axes=a2)

app.Run()
Example #44
0
"""
    >>color1 += texture2D(texture, pos+dpos) * k;
    vec2 dposx = vec2(dx, 0.0);
    vec2 dposy = vec2(0.0, dy);
    vec4 gradx = texture2D(texture, pos+dpos+dposx) - texture2D(texture, pos+dpos-dposx);
    vec4 grady = texture2D(texture, pos+dpos+dposy) - texture2D(texture, pos+dpos-dposy);
    vec4 tmpColor = gradx*gradx + grady*grady;
    tmpColor = sqrt(tmpColor);
    tmpColor.a = texture2D(texture, pos+dpos).a;
    color1 += tmpColor * k;
""")

# Read image
im = vv.imread('lena.png')

# Show two times, the second will be sharpened
t = vv.imshow(im)

# Insert our part in the fragment shader program
t.shader.fragment.AddPart(SH_2F_EDGE)
if False: # Use this line to switch back:
    t.shader.fragment.RemovePart(SH_2F_EDGEL)

# In case there are bugs in the code, it might be helpfull to see the code
# t2.fragmentShader.ShowCode() # Shows the whole code
t.shader.fragment.ShowCode('edge') # Shows only our bit, with line numbers

# Run app
app = vv.use()
app.Run()
Example #45
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()
is also still available (on index 2).
"""

import visvis as vv

class OurCamera1(vv.cameras.TwoDCamera):
    _NAMES = ('our1', 8)
    # a string name to be able to set cameraType
    # an int so it has an index, allowing changing the camera via a shortcut

class OurCamera2(vv.cameras.TwoDCamera):
    _NAMES = ('our2', 9)

# Draw an image    
im = vv.imread('lena.png')
vv.imshow(im)
vv.title('Press ALT+8 for cam1 and ALT+9 for cam2')

# Get axes
a = vv.gca()

# Add cameras and select the first
a.camera = OurCamera1()
a.camera = OurCamera2()
a.cameraType = 'our1' # We can do this because we set the _NAMES attribute

# Increase zoom 
a.camera.zoom *= 2

# Enter mainloop
app = vv.use()
Example #47
0
    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]

# Get result and scale mat
ymin, ymax, surface = fitting.fit_lq2(mat, True)
mat = Aarray(mat, sampling=(100, 100), origin=(50, 50))

# Visualize
vv.subplot(122)
vv.imshow(mat)
m = vv.surf(surface)
a = vv.gca()
a.SetLimits()
m.colormap = vv.CM_MAGMA
Example #48
0
#!/usr/bin/env python
import visvis as vv

# Create figure and make it wider than the default
fig = vv.figure()
fig.position.w = 700


# Create first axes
a1 = vv.subplot(121)

# Display an image
im = vv.imread('lena.png') # returns a numpy array
texture2d = vv.imshow(im)
texture2d.interpolate = True # if False the pixels are visible when zooming in

# Display two lines (values obtained via vv.ginput())
x = [220, 258, 308, 336, 356, 341, 318, 311, 253, 225, 220]
y = [287, 247, 212, 201, 253, 318, 364, 385, 382, 358, 287]
line1 = vv.plot(x, y, ms='.', mw=4, lw=2)
#
x = [237, 284, 326, 352, 381, 175, 195, 217, 232, 237]
y = [385, 386, 394, 413, 507, 507, 476, 441, 399, 385]
line2 = vv.plot(x, y, ms='s', mw=4, lw=2)

# The appearance of the line objects can be set in their
# constructor, or by using their properties
line1.lc, line1.mc = 'g', 'b'
line2.lc, line2.mc = 'y', 'r'

# Display a legend
Example #49
0
    def show_result(self, how=None, fig=None):
        """ show_result(self, how=None, fig=None)
        
        Convenience method to show the registration result. Only 
        works for two dimensional data.
        Requires visvis.
        
        """

        # Check if dimension ok
        if self._ims[0].ndim != 2:
            raise RuntimeError('show_result only works for 2D data.')

        # Check if result is set
        if not self._deforms:
            raise RuntimeError('The result is not available; run register().')

        # Make how lower if string
        if isinstance(how, str):
            how = how.lower()

        # Import visvis
        import visvis as vv

        # Create figure
        if fig is None:
            fig = vv.figure()
        else:
            fig = vv.figure(fig.nr)
            fig.Clear()

        if how in [None, 'grid', 'diff', 'dx', 'dy']:

            # Title map
            title_map = ['Moving', 'Static', 'Deformed', 'Grid']

            # Get deform
            deform = self.get_final_deform(0, 1)

            # Create third image
            im1_ = deform.apply_deformation(self._ims[0])

            # Create fourth image
            if how in [None, 'grid']:
                im2_ = create_grid_image(im1_.shape, im1_.sampling)
                im2_ = deform.apply_deformation(im2_)
            elif how == 'diff':
                im2_ = np.abs(im1_ - self._ims[1])
                title_map[3] = 'Diff'
            elif how == 'dx':
                im2_ = deform[1]
                title_map[3] = 'dx'
            elif how == 'dy':
                im2_ = deform[0]
                title_map[3] = 'dy'

            # Set images
            ims = [self._ims[0], self._ims[1], im1_, im2_]

            # Imshow all figures
            aa, tt = [], []
            for i in range(len(ims)):
                a = vv.subplot(2, 2, i + 1)
                t = vv.imshow(ims[i])
                vv.title(title_map[i])
                a.axis.visible = False
                aa.append(a)
                tt.append(t)

            # Done
            return tuple(tt)
Example #50
0
"""

import visvis as vv
from visvis.pypoints import Aarray
app = vv.use()

# Load image and make Aarray
im = vv.imread('lena.png')
im = Aarray(im)

# Cut in four pieces, but also change resolution using different step sizes
im1 = im[:300,:300]
im2 = im[300:,:300:7]
im3 = im[:300:5,300:]
im4 = im[300::4,300::4]

# Get an axes
a = vv.gca()

# Show all images
tt = []
for im in [im1, im2, im3, im4]:
    tt.append(vv.imshow(im))

# Note that some parts seem to stick out. This is because visvis
# renders data such that the pixel center is at the spefied position;
# larger pixels thus stick out more.

# Enter mainloop
app.Run()
import imageio
import visvis as vv
from mask_rcnn.ez import EZ

ez = EZ()

reader = imageio.get_reader('<video0>')
init_img = reader.get_next_data()
init_out, info = ez.detect(init_img)
t = vv.imshow(init_out, clim=(0, 255))
for im in reader:
    vv.processEvents()
    current_out, current_info = ez.detect(im)
    t.SetData(current_out)
Example #52
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)
Example #53
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()
Example #54
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

        
Example #55
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()
	def ExtractPhaseFunc (self, event=None, filename=None) :
		"""
		This function is the last stage of calibration, 
		when measured data is mathematically processed to obtain the calibration curves.
		"""
		
		# If filename is not specified, open the file dialogue
		if filename is None : 
			filename = self.LoadSettings (title="Load calibration file...")
			# Update the name of pulse shaper calibration file
			import os
			self.SettingsNotebook.PulseShaper.SetSettings({"calibration_file_name" : os.path.abspath(filename)})
			
		visvis.clf()
		
		# Loading the file calibration file
		with h5py.File(filename, 'a') as calibration_file :
			############### Loading data ####################
			wavelengths 		= calibration_file["calibration_settings/wavelengths"][...]
			fixed_voltage 		= calibration_file["calibration_settings/fixed_voltage"][...]
			pulse_shaper_pixel_num = calibration_file["calibration_settings/pulse_shaper_pixel_num"][...]
			initial_pixel	 	= calibration_file["settings/CalibrateShaper/initial_pixel"][...]
			final_pixel 		= calibration_file["settings/CalibrateShaper/final_pixel"][...]
			pixel_bundle_width 	= calibration_file["settings/CalibrateShaper/pixel_bundle_width"][...]
			pixel_to_lamba		= str(calibration_file["settings/CalibrateShaper/pixel_to_lamba"][...])
			# Convert to dict
			pixel_to_lamba 		= eval( "{%s}" % pixel_to_lamba )
			
			# Loading scans of slave and masker masks
			master_mask_scans = []; slave_mask_scans = []
			for key, spectrum in calibration_file["spectra_from_uniform_masks"].items() :
				master_volt, slave_volt = map(int, key.split('_')[-2:])
				if master_volt == fixed_voltage : slave_mask_scans.append( (slave_volt, spectrum[...]) )
				if slave_volt == fixed_voltage	: master_mask_scans.append( (master_volt, spectrum[...]) )
			
			# Sort by voltage
			master_mask_scans.sort(); slave_mask_scans.sort()
			
			# Extract spectral scans and voltages for each mask
			master_mask_voltage, master_mask_scans = zip(*master_mask_scans) 
			master_mask_voltage = np.array(master_mask_voltage); master_mask_scans = np.array(master_mask_scans)
			
			slave_mask_voltage, slave_mask_scans = zip(*slave_mask_scans)
			slave_mask_voltage = np.array(slave_mask_voltage); slave_mask_scans = np.array(slave_mask_scans)
			
			################### Find the edges of pixels #################
			
			# function that converts pixel number to pulse shaper
			# `pixel_to_lamba` is a dictionary  with key = pixel, value = lambda
			deg = 1 #min(1,len(pixel_to_lamba)-1)
			print np.polyfit(pixel_to_lamba.keys(), pixel_to_lamba.values(), 1 )
			pixel2lambda_func = np.poly1d( np.polyfit(pixel_to_lamba.keys(), pixel_to_lamba.values(), deg=deg ) )
			#lambda2pixel_func = np.poly1d( np.polyfit(pixel_to_lamba.values(), pixel_to_lamba.keys(), deg=deg ) )
			
			# Get pixels_edges in shaper pixels 
			pixels_edges_num = np.arange(initial_pixel, final_pixel, pixel_bundle_width)
			if pixels_edges_num[-1] < final_pixel :
				pixels_edges_num = np.append( pixels_edges_num, [final_pixel])
			
			# Get pixels_edges in logical_pixel_lambda
			pixels_edges = pixel2lambda_func(pixels_edges_num)
			
			# Get pixels_edges in positions of the spectrometer spectra
			pixels_edges = np.abs(wavelengths - pixels_edges[:,np.newaxis]).argmin(axis=1)
			
			# Sorting
			indx = np.argsort(pixels_edges)
			pixels_edges = pixels_edges[indx]
			pixels_edges_num = pixels_edges_num[indx]
			
			# Plot
			visvis.cla(); visvis.clf()
			visvis.plot( pixel_to_lamba.values(), pixel_to_lamba.keys(), ls=None, ms='*', mc='g', mw=15)
			visvis.plot ( wavelengths[pixels_edges], pixels_edges_num, ls='-',lc='r')
			visvis.xlabel('wavelength (nm)')
			visvis.ylabel ('pulse shaper pixel')
			visvis.legend( ['measured', 'interpolated'])
			self.fig.DrawNow()
			 
			################ Perform fitting of the phase masks #################	
			master_mask_fits = self.FitSpectralScans(  master_mask_scans, master_mask_voltage, pixels_edges )
			slave_mask_fits = self.FitSpectralScans(  slave_mask_scans, slave_mask_voltage, pixels_edges )
			
			################# Perform fitting of dispersion and phase functions #################
			master_mask_TC_fitted, master_mask_scans, master_mask_disp_ph_curves = \
				self.GetDispersionPhaseCurves (wavelengths, master_mask_scans, master_mask_voltage, 
					pixels_edges, master_mask_fits, pixel2lambda_func, pulse_shaper_pixel_num ) 
			
			slave_mask_TC_fitted, slave_mask_scans, slave_mask_disp_ph_curves = \
				self.GetDispersionPhaseCurves (wavelengths, slave_mask_scans, slave_mask_voltage, 
					pixels_edges, slave_mask_fits, pixel2lambda_func, pulse_shaper_pixel_num ) 
			
			################ Saving fitting parameters ####################
			
			#################################################################
			# Save surface calibration
			try : del calibration_file["calibrated_surface"]
			except KeyError : pass
			
			CalibratedSurfaceGroupe = calibration_file.create_group("calibrated_surface")
			
			master_mask_calibrated_surface = CalibratedSurfaceGroupe.create_group("master_mask")
			for key, value in master_mask_disp_ph_curves.items() :
				master_mask_calibrated_surface[key] = value
			
			slave_mask_calibrated_surface = CalibratedSurfaceGroupe.create_group("slave_mask")
			for key, value in slave_mask_disp_ph_curves.items() :
				slave_mask_calibrated_surface[key] = value
			
			#################################################################
			# Clear the group, if it exits 
			try : del calibration_file["calibrated_pixels"]
			except KeyError : pass
			
			# This group is self consistent, thus the redundancy in saved data (with respect to other group in the file)
			CalibratedPixelsGroupe = calibration_file.create_group ("calibrated_pixels")
			CalibratedPixelsGroupe["pixels_edges"] 			= pixels_edges
			
			# Finding spectral bounds for each pixel
			pixels_spectral_bounds = zip( wavelengths[pixels_edges[:-1]], wavelengths[pixels_edges[1:]] )
			
			# Pulse shaper pixel bounds
			pixels_bounds = zip(pixels_edges_num[:-1], pixels_edges_num[1:])
			
			PixelsGroup = CalibratedPixelsGroupe.create_group("pixels")
			for pixel_num, master_mask_calibration, slave_mask_calibration, \
				spectral_bound, pixel_bound in zip( range(len(master_mask_fits)), \
						master_mask_fits, slave_mask_fits, pixels_spectral_bounds, pixels_bounds  ) :
				pixel =	PixelsGroup.create_group("pixel_%d" % pixel_num)
				pixel["spectral_bound"] 		= spectral_bound
				pixel["pixel_bound"]			= pixel_bound
				# Saving fitted calibration data in the tabular form
				pixel["voltage_master_mask"] 	= master_mask_calibration[0]
				pixel["phase_master_mask"] 		= master_mask_calibration[1]
				pixel["voltage_slave_mask"] 	= slave_mask_calibration[0]
				pixel["phase_slave_mask"]		= slave_mask_calibration[1]
						
						
		################ Plotting results of calibration ####################
		visvis.cla(); visvis.clf(); 
		
		visvis.subplot(2,2,1)
		visvis.imshow( master_mask_scans, cm=visvis.CM_JET )
		visvis.title ("Master mask (measured data)")
		visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)')
		
		visvis.subplot(2,2,3)
		visvis.imshow( master_mask_TC_fitted, cm=visvis.CM_JET )
		visvis.title ("Master mask (fitted data)")
		visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)')
		
		visvis.subplot(2,2,2)
		visvis.imshow( slave_mask_scans, cm=visvis.CM_JET )
		visvis.title ("Slave mask (measured data)")
		visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)')
		
		visvis.subplot(2,2,4)
		visvis.imshow( slave_mask_TC_fitted, cm=visvis.CM_JET )
		visvis.title ("Slave mask (fitted data)")
		visvis.ylabel ('voltage'); visvis.xlabel ('wavelength (nm)')