def OnPick(self, event):
     from PYME.IO import tabular
     k = event.artist._data
     if not (isinstance(k, six.string_types)):
         if not self._editing:
             self._editing = True
             self.configureModule(k)
             self._editing = False
     else:
         outp = self.recipes.activeRecipe.namespace[k]
         if isinstance(outp, ImageStack):
             if not 'dsviewer' in dir(self.recipes):
                 dv = ViewIm3D(outp, mode='lite')
             else:
                 if self.recipes.dsviewer.mode == 'visGUI':
                     mode = 'visGUI'
                 else:
                     mode = 'lite'
                                
                 dv = ViewIm3D(outp, mode=mode, glCanvas=self.recipes.dsviewer.glCanvas)
                 
         elif isinstance(outp, tabular.TabularBase):
             from PYME.ui import recArrayView
             f = recArrayView.ArrayFrame(outp, parent=self, title='Data table - %s' % k)
             f.Show()
def on_map(image, parentWindow=None, glCanvas=None):
    from PYME.Analysis import gen_sCMOS_maps
    from PYME.DSView import ViewIm3D

    im_dark, im_variance = gen_sCMOS_maps.generate_maps(image, 0, -1)

    ViewIm3D(im_dark, title='Dark Map', parent=parentWindow, glCanvas=glCanvas)
    ViewIm3D(im_variance, title='Variance Map', parent=parentWindow, glCanvas=glCanvas)

    # TODO - check if we generated the map from a sub ROI and deflect from the default path if needed ???
    darkmapname = gen_sCMOS_maps.mkDefaultPath('dark', image.mdh)
    varmapname = gen_sCMOS_maps.mkDefaultPath('variance', image.mdh)

    dark_dlg = wx.FileDialog(parentWindow, message="Save dark map as...",
                             defaultDir=os.path.dirname(darkmapname),
                             defaultFile=os.path.basename(darkmapname), 
                             wildcard='TIFF (*.tif)|*.tif', 
                             style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
    
    if dark_dlg.ShowModal() == wx.ID_OK:
        darkfn = dark_dlg.GetPath()
        im_dark.Save(filename=darkfn)

    var_dlg = wx.FileDialog(parentWindow, message="Save variance map as...",  
                             defaultDir=os.path.dirname(varmapname),
                             defaultFile=os.path.basename(varmapname), 
                             wildcard='TIFF (*.tif)|*.tif', 
                             style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
    
    if var_dlg.ShowModal() == wx.ID_OK:
        varfn = var_dlg.GetPath()
        im_variance.Save(filename=varfn)
    def OnPSFFromZernikeModes(self, event):
        import numpy as np
        #import pylab
        from PYME.Analysis.PSFGen import fourierHNA
        
        from PYME.IO.image import ImageStack
        from PYME.DSView import ViewIm3D
        
        self.configure_traits(kind='modal')

        z_ = np.arange(self.sizeZ)*float(self.zSpacing)
        z_ -= z_.mean()        
        
        #if self.vectorial:
        #    ps = fourierHNA.PsfFromPupilVect(self.image.data[:,:], z_, self.image.mdh['voxelsize.x']*1e3, self.wavelength, apodization=self.apodization, NA=self.NA)#, shape = [self.sizeX, self.sizeX])
        #    #ps = abs(ps*np.conj(ps))
        #else:
        #    ps = fourierHNA.PsfFromPupil(self.image.data[:,:], z_, self.image.mdh['voxelsize.x']*1e3, self.wavelength, apodization=self.apodization, NA=self.NA)#, shape = [self.sizeX, self.sizeX])
        
        ps = fourierHNA.GenZernikeDPSF(z_, dx = self.image.voxelsize_nm.x,
                                       zernikeCoeffs = self.dsviewer.zernModes, lamb=self.wavelength, 
                                       n=1.51, NA = self.NA, ns=1.51, beadsize=0, 
                                       vect=self.vectorial, apodization=self.apodization)
        #ps = ps/ps[:,:,self.sizeZ/2].sum()
        
        ps = ps/ps.max()
        
        im = ImageStack(ps, titleStub = 'Generated PSF')
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename
        #im.mdh['Processing.CropROI'] = roi
        mode = 'psf'

        dv = ViewIm3D(im, mode=mode, glCanvas=self.dsviewer.glCanvas, parent=wx.GetTopLevelParent(self.dsviewer))     
Beispiel #4
0
    def OnExtractPupil(self, event):
        import numpy as np
        import pylab
        from PYME.PSFGen import fourierHNA
        
        from PYME.DSView.image import ImageStack
        from PYME.DSView import ViewIm3D

        z_ = np.arange(self.image.data.shape[2])*self.image.mdh['voxelsize.z']*1.e3
        z_ -= z_.mean()  
        
        self.configure_traits(kind='modal')
        
        pupil = fourierHNA.ExtractPupil(np.maximum(self.image.data[:,:,:] - .001, 0), z_, self.image.mdh['voxelsize.x']*1e3, self.wavelength, self.NA, nIters=self.iterations, size=self.pupilSize)
        
        pylab.figure()
        pylab.subplot(121)
        pylab.imshow(np.abs(pupil), interpolation='nearest')
        pylab.subplot(122)
        pylab.imshow(np.angle(pupil)*(np.abs(pupil) > 0), interpolation='nearest')
        
        pupil = pupil*(np.abs(pupil) > 0)
        
        #im = ImageStack([np.abs(pupil), np.angle(pupil)*(np.abs(pupil) > 0)], titleStub = 'Extracted Pupil')
        im = ImageStack(pupil, titleStub = 'Extracted Pupil')
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename
        #im.mdh['Processing.CropROI'] = roi
        mode = 'pupil'

        dv = ViewIm3D(im, mode=mode, glCanvas=self.dsviewer.glCanvas, parent=wx.GetTopLevelParent(self.dsviewer))
Beispiel #5
0
    def OnUnmixMax(self, event):
        #unmix and take brightest channel
        #from PYME.Analysis import deTile
        from PYME.DSView import ViewIm3D, ImageStack

        usds = self._getUSDataSources()

        fns = os.path.split(self.image.filename)[1]

        zm = usds[0].shape[2] / 2

        maxs = [u[:, :, zm].max() for u in usds]
        im = ImageStack(usds[np.argmax(maxs)], titleStub='%s - unsplit' % fns)

        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename

        if 'fitResults' in dir(self.image):
            im.fitResults = self.image.fitResults
        #im.mdh['Processing.GaussianFilter'] = sigmas

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        dv = ViewIm3D(im,
                      mode=mode,
                      glCanvas=self.dsviewer.glCanvas,
                      parent=wx.GetTopLevelParent(self.dsviewer))
Beispiel #6
0
    def Generate(self, event=None):
        dlg = genImageDialog.GenImageDialog(self.mainWind, mode=self.mode)
        ret = dlg.ShowModal()

        bCurr = wx.BusyCursor()

        if ret == wx.ID_OK:
            mdh = MetaDataHandler.NestedClassMDHandler()
            mdh['Rendering.Method'] = self.name
            if 'imageID' in self.pipeline.mdh.getEntryNames():
                mdh['Rendering.SourceImageID'] = self.pipeline.mdh['imageID']
            mdh['Rendering.SourceFilename'] = self.pipeline.filename
            
            for cb in renderMetadataProviders:
                cb(mdh)            
            
            pixelSize = dlg.getPixelSize()

            imb = self._getImBounds()

            im = self.genIm(dlg, imb, mdh)
            img = GeneratedImage(im,imb, pixelSize, 0, ['Image'] , mdh = mdh)
            imf = ViewIm3D(img, mode='visGUI', title='Generated %s - %3.1fnm bins' % (self.name, pixelSize), glCanvas=self.visFr.glCanvas, parent=self.mainWind)
            #imf = imageView.ImageViewFrame(self.visFr,img, self.visFr.glCanvas)
            #imageView.MultiChannelImageViewFrame(self.visFr, self.visFr.glCanvas, img, title='Generated %s - %3.1fnm bins' % (self.name, pixelSize))
            #self.visFr.generatedImages.append(imf)
            #imf.Show()

            self.visFr.RefreshView()

        dlg.Destroy()
        return imf
Beispiel #7
0
    def OnApplyThreshold(self, event):
        import numpy as np
        from PYME.DSView.image import ImageStack
        from PYME.DSView import ViewIm3D

       
        filt_ims = [np.atleast_3d(self.image.data[:,:,:,chanNum].squeeze() > self.dsviewer.do.thresholds[chanNum]) for chanNum in range(self.image.data.shape[3])]
        

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        elif self.dsviewer.mode == 'graph':
            mode = 'graph'
            filt_ims = [fi.squeeze() for fi in filt_ims]
        else:
            mode = 'lite'
            
        im = ImageStack(sum(filt_ims) > 0.5, titleStub = 'Thresholded Image')
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename

        dv = ViewIm3D(im, mode=mode, glCanvas=self.dsviewer.glCanvas, parent=wx.GetTopLevelParent(self.dsviewer))

        #set scaling to (0,1)
        for i in range(im.data.shape[3]):
            dv.do.Gains[i] = 1.0
Beispiel #8
0
    def OnGaussianFilter(self, event):
        import numpy as np
        from scipy.ndimage import gaussian_filter
        from PYME.DSView.image import ImageStack
        from PYME.DSView import ViewIm3D

        dlg = wx.TextEntryDialog(self.dsviewer, 'Blur size [pixels]:', 'Gaussian Blur', '[1,1,1]')

        if dlg.ShowModal() == wx.ID_OK:
            sigmas = eval(dlg.GetValue())
            #print sigmas
            #print self.images[0].img.shape
            filt_ims = [np.atleast_3d(gaussian_filter(self.image.data[:,:,:,chanNum].squeeze(), sigmas)) for chanNum in range(self.image.data.shape[3])]
            
            im = ImageStack(filt_ims, titleStub = 'Filtered Image')
            im.mdh.copyEntriesFrom(self.image.mdh)
            im.mdh['Parent'] = self.image.filename
            im.mdh['Processing.GaussianFilter'] = sigmas

            if self.dsviewer.mode == 'visGUI':
                mode = 'visGUI'
            else:
                mode = 'lite'

            dv = ViewIm3D(im, mode=mode, glCanvas=self.dsviewer.glCanvas)

            #set scaling to (0,1)
            for i in range(im.data.shape[3]):
                dv.do.Gains[i] = 1.0

            

        dlg.Destroy()
Beispiel #9
0
    def Project(self, projType):
        import numpy as np
        from PYME.DSView.image import ImageStack
        from PYME.DSView import ViewIm3D
        import os

        if projType == 'mean':        
            filt_ims = [np.atleast_3d(self.image.data[:,:,:,chanNum].mean(2)) for chanNum in range(self.image.data.shape[3])]
        elif projType == 'max':
            filt_ims = [np.atleast_3d(self.image.data[:,:,:,chanNum].max(2)) for chanNum in range(self.image.data.shape[3])]

        fns = os.path.split(self.image.filename)[1]        
        
        im = ImageStack(filt_ims, titleStub = '%s - %s' %(fns, projType))
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename
        im.mdh['Processing.Projection'] = projType

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        dv = ViewIm3D(im, mode=mode, glCanvas=self.dsviewer.glCanvas)

        #set scaling to (0,1)
        for i in range(im.data.shape[3]):
            dv.do.Gains[i] = 1.0
Beispiel #10
0
    def OnCrop(self, event):
        import numpy as np
        #from scipy.ndimage import gaussian_filter

        from PYME.DSView import ViewIm3D

        if not (self.do.selectionMode == self.do.SELECTION_RECTANGLE):
            wx.MessageBox(
                'Cropping only supported for rectangular selections\n For non-rectangular masking see the `annotation` module',
                'Error', wx.OK | wx.ICON_ERROR)
            return

        x0, x1, y0, y1, z0, z1 = self.do.sorted_selection
        roi = [[x0, x1 + 1], [y0, y1 + 1], [0, self.image.data.shape[2]]]
        im = crop_2D(self.image, roi)

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        dv = ViewIm3D(im,
                      mode=mode,
                      glCanvas=self.dsviewer.glCanvas,
                      parent=wx.GetTopLevelParent(self.dsviewer))

        #set scaling to (0,1)
        for i in range(im.data.shape[3]):
            dv.do.Gains[i] = 1.0
Beispiel #11
0
    def OnLabel(self, event):
        import numpy as np
        from scipy import ndimage
        from PYME.DSView.image import ImageStack
        from PYME.DSView import ViewIm3D

        filt_ims = [np.atleast_3d(self.image.data[:,:,:,chanNum].squeeze() > self.dsviewer.do.thresholds[chanNum]) for chanNum in range(self.image.data.shape[3])]

        #print sum(filt_ims).shape
        mask = sum(filt_ims) > 0.5
        labs, nlabs = ndimage.label(mask)

        im = ImageStack(labs, titleStub = 'Thresholded Image')
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename
        #im.mdh['Processing.CropROI'] = roi

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        dv = ViewIm3D(im, mode=mode, glCanvas=self.dsviewer.glCanvas, parent=wx.GetTopLevelParent(self.dsviewer))

        #set scaling to (0,1)
        for i in range(im.data.shape[3]):
            dv.do.Gains[i] = 1.0
    def OnMakeComposites(self, event):
        dlg = CompositeDialog(self.dsviewer, self.image)

        if dlg.ShowModal() == wx.ID_OK:
            imgs = []
            for im_name in dlg.GetSelections():
                im, chan = _getImage(im_name)
                shiftfield = dlg.GetShiftmap(im_name)

                imgs.append((im, chan, shiftfield))

            if len(imgs) > 0:
                out = make_composite(imgs,
                                     ignoreZ=dlg.GetIgnoreZ(),
                                     interp=dlg.GetInterp(),
                                     shape=dlg.shape,
                                     origin=dlg.origin,
                                     voxelsize=dlg.voxelsize)

                ViewIm3D(out,
                         'Composite',
                         mode=self.dsviewer.mode,
                         parent=wx.GetTopLevelParent(self.dsviewer),
                         glCanvas=self.dsviewer.glCanvas)

        dlg.Destroy()
def redimension(parent, img):
    with RedimensionDialog(parent, img) as dlg:
        if dlg.ShowModal() == wx.ID_OK:
            from PYME.IO.image import ImageStack
            from PYME.DSView import ViewIm3D
            from PYME.IO.DataSources.BaseDataSource import XYZTCWrapper

            
            
            d = XYZTCWrapper(img.data_xyztc)
            d.set_dim_order_and_size(dlg.cOrder.GetStringSelection(), size_z=int(dlg.tSizeZ.GetValue()),
                                     size_t=int(dlg.tSizeT.GetValue()), size_c=int(dlg.tSizeC.GetValue()))
            im = ImageStack(data=d, titleStub='Redimensioned')
            
            im.mdh.copyEntriesFrom(img.mdh)
            im.mdh['Parent'] = img.filename
            #im.mdh['Processing.CropROI'] = roi

            # if self.dsviewer.mode == 'visGUI':
            #     mode = 'visGUI'
            # else:
            #     mode = 'lite'

            dv = ViewIm3D(im, mode=parent.mode, glCanvas=parent.glCanvas, parent=wx.GetTopLevelParent(parent))

            #set scaling to (0,1)
            for i in range(im.data.shape[3]):
                dv.do.Gains[i] = 1.0
    def OnOpenOMERO(self, wx_event=None):
        # from pyme_omero.core import localization_files_from_image_url
        from PYME.IO.image import ImageStack
        from PYME.DSView import ViewIm3D
        import wx
        from pyme_omero.core import download_image

        dlg = wx.TextEntryDialog(self.dsviewer, 'OMERO URL',
                                 'URL to OMERO image', '')

        if dlg.ShowModal() == wx.ID_OK:
            image_url = dlg.GetValue()
        else:
            dlg.Destroy()
            return

        dlg.Destroy()

        path = download_image(image_url, self._tempdir.name)
        logger.debug('temporary file path: %s' % path)

        im = ImageStack(filename=path)

        dv = ViewIm3D(im,
                      glCanvas=self.dsviewer.glCanvas,
                      parent=wx.GetTopLevelParent(self.dsviewer))

        #set scaling to (0,1)
        for i in range(im.data.shape[3]):
            dv.do.Gains[i] = 1.0
Beispiel #15
0
    def dsviewer_plugin_callback(cls, dsviewer, showGUI=True, **kwargs):
        """Implements a callback which allows this module to be used as a plugin for dsviewer.

        Parameters
        ----------

        dsviewer : :class:`PYME.DSView.dsviewer.DSViewFrame` instance
            This is the current :class:`~PYME.DSView.dsviewer.DSViewFrame` instance. The filter will be run with the
            associated ``.image`` as input and display the output in a new window.

        showGUI : bool
            Should we show a GUI to set parameters (generated by calling configure_traits()), or just run with default
            parameters.

        **kwargs : dict
            Optionally, provide default values for parameters. Makes most sense when used with showGUI = False

        """
        from PYME.DSView import ViewIm3D

        mod = cls(inputName='input', outputName='output', **kwargs)
        if (not showGUI) or mod.configure_traits(kind='modal'):
            namespace = {'input': dsviewer.image}
            mod.execute(namespace)

            ViewIm3D(mod['output'],
                     parent=dsviewer,
                     glCanvas=dsviewer.glCanvas)
    def OnSegmentAnneal(self, event):
        newImages = [
            np.zeros(self.image.data.shape[:3], 'b')
            for i in range(self.image.data.shape[3])
        ]

        im = ImageStack(newImages)
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        self.res = ViewIm3D(im,
                            parent=wx.GetTopLevelParent(self.dsviewer),
                            mode=mode,
                            glCanvas=self.dsviewer.glCanvas)

        self.panAnneal = SegmentationPanel(self.res, self.image, newImages)

        self.pinfo1 = aui.AuiPaneInfo().Name("annealPanel").Left(
        ).Caption('Segmentation').DestroyOnClose(
            True
        ).CloseButton(False).MinimizeButton(True).MinimizeMode(
            aui.AUI_MINIMIZE_CAPT_SMART | aui.AUI_MINIMIZE_POS_RIGHT
        )  #.MinimizeButton(True).MinimizeMode(aui.AUI_MINIMIZE_CAPT_SMART|aui.AUI_MINIMIZE_POS_RIGHT)#.CaptionVisible(False)
        self.res._mgr.AddPane(self.panAnneal, self.pinfo1)
        self.res._mgr.Update()
Beispiel #17
0
    def OnUnmix(self, event):
        #from PYME.Analysis import deTile
        from PYME.DSView import ViewIm3D, ImageStack

        usds = self._getUSDataSources()

        fns = os.path.split(self.image.filename)[1]
        im = ImageStack(usds, titleStub='%s - unsplit' % fns)
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename
        # grab events from the first data source TODO - do this need to be smarter?
        try:
            im.events = usds[0].getEvents()
        except:
            logger.warning('No Events found when coalescing UnsplitDataSource')

        if 'fitResults' in dir(self.image):
            im.fitResults = self.image.fitResults
        #im.mdh['Processing.GaussianFilter'] = sigmas

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        print(im.data[:, :, 1, 1].shape)

        dv = ViewIm3D(im,
                      mode=mode,
                      glCanvas=self.dsviewer.glCanvas,
                      parent=wx.GetTopLevelParent(self.dsviewer))
Beispiel #18
0
    def OnPSFFromPupil(self, event):
        import numpy as np
        #import pylab
        from PYME.PSFGen import fourierHNA

        from PYME.DSView.image import ImageStack
        from PYME.DSView import ViewIm3D

        self.configure_traits(kind='modal')

        z_ = np.arange(self.sizeZ) * float(self.zSpacing)
        z_ -= z_.mean()

        ps = fourierHNA.PsfFromPupil(
            self.image.data[:, :], z_, self.image.mdh['voxelsize.x'] * 1e3,
            self.wavelength)  #, shape = [self.sizeX, self.sizeX])

        ps = ps / ps[:, :, self.sizeZ / 2].sum()

        im = ImageStack(ps, titleStub='Generated PSF')
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename
        #im.mdh['Processing.CropROI'] = roi
        mode = 'psf'

        dv = ViewIm3D(im,
                      mode=mode,
                      glCanvas=self.dsviewer.glCanvas,
                      parent=wx.GetTopLevelParent(self.dsviewer))
Beispiel #19
0
def dark(dsviewer):
    from PYME.DSView import ViewIm3D, ImageStack

    im = ImageStack(dsviewer.image.data[:, :, :].astype('f').mean(2),
                    mdh=dsviewer.image.mdh)

    ViewIm3D(im)
Beispiel #20
0
            def _display_output_image(outp):
                if self.dsviewer.mode == 'visGUI':
                    mode = 'visGUI'
                elif 'out_tracks' in self.activeRecipe.namespace.keys():
                    mode = 'tracking'
                else:
                    mode = 'default'

                dv = ViewIm3D(outp, mode=mode, glCanvas=self.dsviewer.glCanvas)

                if 'out_meas' in self.activeRecipe.namespace.keys():
                    #have measurements as well - add to / overlay with output image
                    if not 'pipeline' in dir(dv):
                        dv.pipeline = pipeline.Pipeline()

                    from PYME.IO import tabular
                    cache = tabular.CachingResultsFilter(
                        self.activeRecipe.namespace['out_meas'])
                    dv.pipeline.OpenFile(ds=cache)
                    dv.view.filter = dv.pipeline

                #set scaling to (0,1)
                for i in range(outp.data.shape[3]):
                    dv.do.Gains[i] = 1.0

                if ('out_tracks' in self.activeRecipe.namespace.keys()
                    ) and 'tracker' in dir(dv):
                    dv.tracker.SetTracks(
                        self.activeRecipe.namespace['out_tracks'])
Beispiel #21
0
 def OnOpenRaw(self, event):
     from PYME.IO import image
     from PYME.DSView import ViewIm3D
     try:
         ViewIm3D(image.ImageStack(haveGUI=True), mode='visGUI', glCanvas=self.glCanvas)
     except image.FileSelectionError:
         # the user canceled the open dialog
         pass
Beispiel #22
0
 def OnApplyShiftmap(self, event):
     """apply a vectorial correction for chromatic shift to an image - this
     is a generic vectorial shift compensation, rather than the secial case 
     correction used with the splitter."""
     from scipy import ndimage
     import numpy as np
     from PYME.DSView import ImageStack, ViewIm3D
     from PYME.IO.MetaDataHandler import get_camera_roi_origin
     
     dlg = ShiftmapSelectionDialog(self.dsviewer, self.image)
     succ = dlg.ShowModal()
     if (succ == wx.ID_OK):
         #self.ds = example.CDataStack(fdialog.GetPath().encode())
         #self.ds =
         ds = []
         shiftFiles = {}
         X, Y, Z = np.mgrid[0:self.image.data.shape[0], 0:self.image.data.shape[1], 0:self.image.data.shape[2]]
         
         vx, vy, vz = self.image.voxelsize_nm
         
         roi_x0, roi_y0 = get_camera_roi_origin(self.image.mdh)
         
         for ch in range(self.image.data.shape[3]):
             sfFilename = dlg.GetChanFilename(ch)
             shiftFiles[ch] = sfFilename
             
             data = self.image.data[:,:,:, ch]
             
             if os.path.exists(sfFilename):
                 spx, spy, dz = np.load(sfFilename)
                 
                 dx = spx.ev(vx*(X+roi_x0), vy*(Y+roi_y0))/vx
                 dy = spy.ev(vx*(X+roi_x0), vy*(Y+roi_y0))/vy
                 dz = dz/vz
                 
                 ds.append(ndimage.map_coordinates(data, [X+dx, Y+dy, Z+dz], mode='nearest'))
             else:
                 ds.append(data)
             
         
         fns = os.path.split(self.image.filename)[1]
         im = ImageStack(ds, titleStub = '%s - corrected' % fns)
         im.mdh.copyEntriesFrom(self.image.mdh)
         im.mdh['Parent'] = self.image.filename
         im.mdh.setEntry('ChromaCorrection.ShiftFilenames', shiftFiles)
         
         if 'fitResults' in dir(self.image):
             im.fitResults = self.image.fitResults
         #im.mdh['Processing.GaussianFilter'] = sigmas
 
         if self.dsviewer.mode == 'visGUI':
             mode = 'visGUI'
         else:
             mode = 'lite'
 
         dv = ViewIm3D(im, mode=mode, glCanvas=self.dsviewer.glCanvas, parent=wx.GetTopLevelParent(self.dsviewer))
         
     dlg.Destroy()
    def OnBSavePSF(self, event):
        from PYME.DSView import ViewIm3D
        
        #fn = wx.SaveFileSelector('Save PSF to file', '.tif')
        #if fn is None:
        #    print('No file selected')
        #    return

        ViewIm3D(rend_im.get_psf(), mode='psf')
Beispiel #24
0
    def OnPick(self, event):
        k = event.artist._data
        if not (isinstance(k, six.string_types)):
            self.configureModule(k)
        else:
            outp = self.recipes.activeRecipe.namespace[k]
            if isinstance(outp, ImageStack):
                if not 'dsviewer' in dir(self.recipes):
                    dv = ViewIm3D(outp, mode='lite')
                else:
                    if self.recipes.dsviewer.mode == 'visGUI':
                        mode = 'visGUI'
                    else:
                        mode = 'lite'

                    dv = ViewIm3D(outp,
                                  mode=mode,
                                  glCanvas=self.recipes.dsviewer.glCanvas)
Beispiel #25
0
def on_map(image, parentWindow=None, glCanvas=None):
    from PYME.Analysis import gen_sCMOS_maps
    from PYME.DSView import ViewIm3D
    from PYMEcs.Analysis.MapUtils import combine_maps

    # combine maps with dialogue here
    # also show valid map

    with wx.FileDialog(parentWindow, "Choose maps", wildcard='TIFF (*.tif)|*.tif',
                       style=wx.FD_OPEN | wx.FD_MULTIPLE) as dialog:

        if dialog.ShowModal() == wx.ID_CANCEL:
            return

        filelist = dialog.GetPaths()

        combinedMap, vMap = combine_maps(filelist,return_validMap=True)

        if combinedMap.mdh['CameraMap.Type'] == 'mean':
            mapType = 'dark'
        elif combinedMap.mdh['CameraMap.Type'] == 'variance':
            mapType = 'variance'
            
    if mapType == 'dark':
        ViewIm3D(combinedMap, title='Dark Map', parent=parentWindow, glCanvas=glCanvas)
    else:
        ViewIm3D(combinedMap, title='Variance Map', parent=parentWindow, glCanvas=glCanvas)

    ViewIm3D(vMap, title='Valid Regions', parent=parentWindow, glCanvas=glCanvas)
    
    if mapType == 'dark':
        mapname = gen_sCMOS_maps.mkDefaultPath('dark', image.mdh)
    else:
        mapname = gen_sCMOS_maps.mkDefaultPath('variance', image.mdh)

    map_dlg = wx.FileDialog(parentWindow, message="Save dark map as...",
                             defaultDir=os.path.dirname(mapname),
                             defaultFile=os.path.basename(mapname), 
                             wildcard='TIFF (*.tif)|*.tif', 
                             style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
    
    if map_dlg.ShowModal() == wx.ID_OK:
        mapfn = map_dlg.GetPath()
        combinedMap.Save(filename=mapfn)
Beispiel #26
0
    def OnUnmixMax(self, event):
        #unmix and take brightest channel
        #from PYME.Analysis import deTile
        from PYME.DSView import ViewIm3D, ImageStack

        mdh = self.image.mdh
        if 'chroma.dx' in mdh.getEntryNames():
            sf = (mdh['chroma.dx'], mdh['chroma.dy'])
        elif global_shiftfield:
            sf = global_shiftfield
        else:
            #self.OnSetShiftField()
            #sf = (mdh['chroma.dx'], mdh['chroma.dy'])
            sf = None

        flip = True
        if 'Splitter.Flip' in mdh.getEntryNames() and not mdh['Splitter.Flip']:
            flip = False

        ROIX1 = mdh.getEntry('Camera.ROIPosX')
        ROIY1 = mdh.getEntry('Camera.ROIPosY')

        ROIX2 = ROIX1 + mdh.getEntry('Camera.ROIWidth')
        ROIY2 = ROIY1 + mdh.getEntry('Camera.ROIHeight')

        um0 = UnsplitDataSource.DataSource(self.image.data,
                                           [ROIX1, ROIY1, ROIX2, ROIY2], 0,
                                           flip, sf)

        um1 = UnsplitDataSource.DataSource(self.image.data,
                                           [ROIX1, ROIY1, ROIX2, ROIY2], 1,
                                           flip, sf)

        fns = os.path.split(self.image.filename)[1]
        zm = um0.shape[2] / 2
        if um0[:, :, zm].max() > um1[:, :, zm].max():
            im = ImageStack(um0, titleStub='%s - unsplit' % fns)
        else:
            im = ImageStack(um1, titleStub='%s - unsplit' % fns)
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename

        if 'fitResults' in dir(self.image):
            im.fitResults = self.image.fitResults
        #im.mdh['Processing.GaussianFilter'] = sigmas

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        dv = ViewIm3D(im,
                      mode=mode,
                      glCanvas=self.dsviewer.glCanvas,
                      parent=wx.GetTopLevelParent(self.dsviewer))
Beispiel #27
0
    def OnLabelWatershed(self, event):
        import numpy as np
        from PYME.contrib.cpmath import watershed
        from PYME.IO.image import ImageStack
        from PYME.DSView import ViewIm3D

        nChans = self.image.data.shape[3]

        filt_ims = [
            np.atleast_3d(self.image.data[:, :, :, chanNum].squeeze())
            for chanNum in range(nChans)
        ]

        img = (-sum([im / im.max()
                     for im in filt_ims]) * (2**15) / nChans).astype('int16')

        mask = (sum([
            filt_ims[chanNum] > self.do.thresholds[chanNum]
            for chanNum in range(nChans)
        ]) > .5).astype('int16')

        #self.image.labelThresholds = [(self.dsviewer.do.Offs[chanNum] + 0.5/self.dsviewer.do.Gains[chanNum]) for chanNum in range(self.image.data.shape[3])]

        #print sum(filt_ims).shape

        labs = watershed.fast_watershed(img,
                                        self.image.labels.astype('int16'),
                                        mask=mask)

        #store a copy in the image for measurements etc ...
        self.image.labels = labs

        im = ImageStack(labs, titleStub='Labelled Image')
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename

        im.mdh['Labelling.WatershedThresholds'] = self.do.thresholds

        #im.mdh['Labelling.MinSize'] = rSize
        #im.mdh['Labelling.Thresholds'] = self.image.labelThresholds
        #im.mdh['Processing.CropROI'] = roi

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        dv = ViewIm3D(im,
                      mode=mode,
                      glCanvas=self.dsviewer.glCanvas,
                      parent=wx.GetTopLevelParent(self.dsviewer))

        #set scaling to (0,1)
        for i in range(im.data.shape[3]):
            dv.do.Gains[i] = 1.0
Beispiel #28
0
    def OnDiagSplit(self, event):
        import numpy as np
        #from scipy.ndimage import gaussian_filter
        from PYME.IO.image import ImageStack
        from PYME.DSView import ViewIm3D

        #dlg = wx.TextEntryDialog(self.dsviewer, 'Blur size [pixels]:', 'Gaussian Blur', '[1,1,1]')

        #if dlg.ShowModal() == wx.ID_OK:
        #sigmas = eval(dlg.GetValue())
        #print sigmas
        #print self.images[0].img.shape

        x0, x1, y0, y1 = [
            self.do.selection_begin_x, self.do.selection_end_x,
            self.do.selection_begin_y, self.do.selection_end_y
        ]

        dx = x1 - x0
        dy = y1 - y0

        m = dy / dx
        c = y0 - m * x0

        d = self.image.data

        X, Y = np.ogrid[:d.shape[0], :d.shape[1]]

        msk = Y > (m * X + c)

        #filt_ims = [np.atleast_3d(self.image.data[roi[0][0]:roi[0][1],roi[1][0]:roi[1][1],:,chanNum].squeeze()) for chanNum in range(self.image.data.shape[3])]
        imn = (d[:, :, :, 0] -
               self.do.Offs[0]) * self.do.Gains[0] * msk[:, :, None] + (
                   d[:, :, :, 1] -
                   self.do.Offs[1]) * self.do.Gains[1] * (1 - msk)[:, :, None]

        im = ImageStack(imn, titleStub='Cropped Image')
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename
        #im.mdh['Processing.CropROI'] = roi

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        dv = ViewIm3D(im,
                      mode=mode,
                      glCanvas=self.dsviewer.glCanvas,
                      parent=wx.GetTopLevelParent(self.dsviewer))

        #set scaling to (0,1)
        for i in range(im.data.shape[3]):
            dv.do.Gains[i] = 1.0
Beispiel #29
0
    def OnSubtractBackground(self, event):
        from PYME.IO.image import ImageStack
        from PYME.DSView import ViewIm3D
        from PYME.Analysis.PSFEst import extractImages

        d_bg = extractImages.backgroundCorrectPSFWF(self.image.data[:, :, :])

        im = ImageStack(d_bg, titleStub='Filtered Image')
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename

        dv = ViewIm3D(im, mode='psf', glCanvas=self.dsviewer.glCanvas)
Beispiel #30
0
def project(dsviewer, axis, type, crop=False):
    from PYME.recipes import processing
    from PYME.DSView import ViewIm3D

    if crop:
        from .cropping import crop_2D
        x0, x1, y0, y1, z0, z1 = dsviewer.do.sorted_selection
        roi = [[x0, x1 + 1], [y0, y1 + 1], [0, dsviewer.image.data.shape[2]]]
        im = crop_2D(dsviewer.image, roi)
    else:
        im = dsviewer.image

    ViewIm3D(processing.Projection(kind=type, axis=axis).apply_simple(im),
             parent=dsviewer)