Пример #1
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))
Пример #2
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))
Пример #3
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()
Пример #4
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))
Пример #5
0
    def OnUnmix(self, event):
        #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:
            sf = None

        flip = True
        if 'Splitter.Flip' in mdh.getEntryNames() and not mdh['Splitter.Flip']:
            flip = False
            
        chanROIs = None
        if 'Splitter.Channel0ROI' in mdh.getEntryNames():
            chanROIs = [mdh['Splitter.Channel0ROI'],mdh['Splitter.Channel1ROI']]

        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, chanROIs=chanROIs, voxelsize=self.image.voxelsize)

        um1 = UnsplitDataSource.DataSource(self.image.data, 
                                           [ROIX1, ROIY1, ROIX2, ROIY2], 1
                                           , flip, sf, chanROIs=chanROIs, voxelsize=self.image.voxelsize)
            
        fns = os.path.split(self.image.filename)[1]
        im = ImageStack([um0, 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'
            
        #print im.data[:,:,1,1].shape

        dv = ViewIm3D(im, mode=mode, glCanvas=self.dsviewer.glCanvas, parent=wx.GetTopLevelParent(self.dsviewer))
Пример #6
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)
Пример #7
0
def flat(dsviewer):
    from PYME.DSView import ViewIm3D, ImageStack
    import numpy as np

    dark = ImageStack(
        load_prompt=
        "Select corresponding DARK image (should have been calculated first)"
    ).data[:, :, 0].squeeze().astype('f')

    illum = 0 * dark

    for i in range(dsviewer.image.data.shape[2]):
        illum += dsviewer.image.data[:, :, i].squeeze().astype('f') - dark

    illum /= dsviewer.image.data.shape[2]

    im = ImageStack(illum.mean() / illum, mdh=dsviewer.image.mdh)

    ViewIm3D(im)
Пример #8
0
    def OnUnmix(self, event):
        #from PYME.Analysis import deTile
        from PYME.DSView import ViewIm3D, ImageStack
        from scipy import linalg

        mdh = self.image.mdh

        if 'Camera.ADOffset' in mdh.getEntryNames():
            offset = mdh['Camera.ADOffset']
        else:
            offset = 0

        dlg = UnMixSettingsDlg(self.dsviewer, offset=offset)
        if dlg.ShowModal() == wx.ID_OK:
            mm = dlg.GetMixMatrix()
            off = dlg.GetOffset()

            mmi = linalg.inv(mm)

            ch0 = self.image.data[:, :, :, 0] - off
            ch1 = self.image.data[:, :, :, 1] - off

            um0 = mmi[0, 0] * ch0 + mmi[0, 1] * ch1
            um1 = mmi[1, 0] * ch0 + mmi[1, 1] * ch1

            im = ImageStack([um0, um1], titleStub='Unmixed Image')
            im.mdh.copyEntriesFrom(self.image.mdh)
            im.mdh['Parent'] = self.image.filename
            im.mdh['Unmixing.MixMatrix'] = mm
            im.mdh['Unmixing.Offset'] = off
            #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))
Пример #9
0
    def OnUnmix(self, event):
        #from PYME.Analysis import deTile
        from PYME.DSView import ViewIm3D, ImageStack
        from scipy import linalg

        mdh = self.image.mdh
        
        if 'Camera.ADOffset' in mdh.getEntryNames():
            offset = mdh['Camera.ADOffset']
        else:
            offset = 0
        
        dlg = UnMixSettingsDlg(self.dsviewer, offset=offset)
        if dlg.ShowModal() == wx.ID_OK:
            mm = dlg.GetMixMatrix()
            off = dlg.GetOffset()
            
            mmi = linalg.inv(mm)
            
            ch0 = self.image.data[:,:,:,0] - off
            ch1 = self.image.data[:,:,:,1] - off
            
            um0 = mmi[0,0]*ch0 + mmi[0,1]*ch1
            um1 = mmi[1,0]*ch0 + mmi[1,1]*ch1
            
            im = ImageStack([um0, um1], titleStub = 'Unmixed Image')
            im.mdh.copyEntriesFrom(self.image.mdh)
            im.mdh['Parent'] = self.image.filename
            im.mdh['Unmixing.MixMatrix'] = mm
            im.mdh['Unmixing.Offset'] = off
            #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))
Пример #10
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))
Пример #11
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

        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 = self.image.mdh["voxelsize.x"] * 1e3
            vy = self.image.mdh["voxelsize.y"] * 1e3
            vz = self.image.mdh["voxelsize.z"] * 1e3

            x0 = 1
            y0 = 1
            if "Camera.ROIPosX" in self.image.mdh.getEntryNames():
                x0 = self.image.mdh["Camera.ROIPosX"]
                y0 = self.image.mdh["Camera.ROIPosY"]

            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 + x0 - 1), vy * (Y + y0 - 1)) / vx
                    dy = spy.ev(vx * (X + x0 - 1), vy * (Y + y0 - 1)) / 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()
Пример #12
0
 def OnOpenRaw(self, event):
     from PYME.DSView import ViewIm3D, ImageStack
     ViewIm3D(ImageStack(), mode='visGUI', glCanvas=self.glCanvas)
Пример #13
0
    def OnDeconvICTM(self, event, beadMode=False):
        from PYME.Deconv.deconvDialogs import DeconvSettingsDialog, DeconvProgressDialog, DeconvProgressPanel

        dlg = DeconvSettingsDialog(self.dsviewer, beadMode,
                                   self.image.data.shape[3])
        if dlg.ShowModal() == wx.ID_OK:
            from PYME.Deconv import dec, decThread, richardsonLucy
            nIter = dlg.GetNumIterationss()
            regLambda = dlg.GetRegularisationLambda()

            decMDH = MetaDataHandler.NestedClassMDHandler(self.image.mdh)
            decMDH['Deconvolution.NumIterations'] = nIter
            decMDH['Deconvolution.OriginalFile'] = self.image.filename

            #self.dlgDeconProg = DeconvProgressDialog(self.dsviewer, nIter)
            #self.dlgDeconProg.Show()
            vx = self.image.mdh.getEntry('voxelsize.x')
            vy = self.image.mdh.getEntry('voxelsize.y')
            vz = self.image.mdh.getEntry('voxelsize.z')

            if beadMode:
                from PYME.Deconv import beadGen
                psf = beadGen.genBeadImage(dlg.GetBeadRadius(),
                                           (1e3 * vx, 1e3 * vy, 1e3 * vz))

                decMDH['Deconvolution.BeadRadius'] = dlg.GetBeadRadius()

            else:
                #psf, vs = numpy.load(dlg.GetPSFFilename())
                #psf = numpy.atleast_3d(psf)
                psfFilename, psf, vs = dlg.GetPSF(vshint=vx)

                decMDH['Deconvolution.PSFFile'] = dlg.GetPSFFilename()

                if not (vs.x == vx and vs.y == vy and vs.z == vz):
                    #rescale psf to match data voxel size
                    psf = ndimage.zoom(psf, [vs.x / vx, vs.y / vy, vs.z / vz])

            data = self.image.data[:, :, :, dlg.GetChannel()].astype(
                'f') - dlg.GetOffset()
            decMDH['Deconvolution.Offset'] = dlg.GetOffset()

            bg = dlg.GetBackground()
            decMDH['Deconvolution.Background'] = bg

            #crop PSF in z if bigger than stack

            print psf.shape, data.shape
            if psf.shape[2] > data.shape[2]:
                dz = psf.shape[2] - data.shape[2]

                psf = psf[:, :,
                          numpy.floor(dz / 2):(psf.shape[2] -
                                               numpy.ceil(dz / 2))]

            print((data.shape, psf.shape))

            if dlg.GetPadding():
                padsize = numpy.array(dlg.GetPadSize())
                decMDH['Deconvolution.Padding'] = padsize
                dp = numpy.ones(numpy.array(data.shape) + 2 * padsize,
                                'f') * data.mean()
                weights = numpy.zeros_like(dp)
                px, py, pz = padsize

                #print data.shape, dp[px:-(px+1), py:-(py+1), pz:-(pz+1)].shape
                dp[px:-px, py:-py, pz:-pz] = data
                #if dlg.GetRemovePadding():
                #    data = dp[px:-px, py:-py, pz:-pz]#should be a slice
                #else:
                #    data = dp
                weights[px:-px, py:-py, pz:-pz] = 1.

                weights = weights.ravel()
            else:
                dp = data
                weights = 1

            if dlg.GetBlocking():
                decMDH['Deconvolution.Method'] = 'Blocked ICTM'
                self.checkTQ()
                from PYME.Deconv import tq_block_dec
                bs = dlg.GetBlockSize()
                self.decT = tq_block_dec.blocking_deconv(self.tq,
                                                         data,
                                                         psf,
                                                         self.image.seriesName,
                                                         blocksize={
                                                             'y': bs,
                                                             'x': bs,
                                                             'z': 256
                                                         })
                self.decT.go()

            else:
                decMDH['Deconvolution.Method'] = dlg.GetMethod()
                if dlg.GetMethod() == 'ICTM':
                    decMDH['Deconvolution.RegularisationParameter'] = regLambda
                    if beadMode:
                        self.dec = dec.dec_bead()
                    else:
                        self.dec = dec.dec_conv()
                else:
                    if beadMode:
                        self.dec = richardsonLucy.rlbead()
                    else:
                        self.dec = richardsonLucy.dec_conv()

                self.dec.psf_calc(psf, dp.shape)

                self.decT = decThread.decThread(self.dec,
                                                dp,
                                                regLambda,
                                                nIter,
                                                weights,
                                                bg=bg)
                self.decT.start()

                tries = 0
                while tries < 10 and not hasattr(self.dec, 'fs'):
                    time.sleep(1)
                    tries += 1

                if dlg.GetPadding() and dlg.GetRemovePadding():
                    fs = self.dec.fs[px:-px, py:-py, pz:-pz]
                else:
                    fs = self.dec.fs

                im = ImageStack(data=fs,
                                mdh=decMDH,
                                titleStub='Deconvolution Result')
                mode = 'lite'
                if beadMode:
                    mode = 'psf'
                    im.defaultExt = '*.psf'  #we want to save as PSF by default
                self.res = ViewIm3D(im,
                                    mode=mode,
                                    parent=wx.GetTopLevelParent(self.dsviewer))

                #self.res = View3D(fs, 'Deconvolution Result', mdh=decMDH, parent=wx.GetTopLevelParent(self.dsviewer), mode=mode)

                self.dlgDeconProg = DeconvProgressPanel(self.res, nIter)

                self.pinfo1 = aui.AuiPaneInfo().Name("deconvPanel").Top(
                ).Caption('Deconvolution Progress').DestroyOnClose(
                    True
                ).CloseButton(
                    False
                )  #.MinimizeButton(True).MinimizeMode(aui.AUI_MINIMIZE_CAPT_SMART|aui.AUI_MINIMIZE_POS_RIGHT)#.CaptionVisible(False)
                self.res._mgr.AddPane(self.dlgDeconProg, self.pinfo1)
                self.res._mgr.Update()

            self.deconTimer = mytimer()
            self.deconTimer.WantNotification.append(self.OnDeconTimer)

            self.deconTimer.Start(500)
Пример #14
0
    def reconstruct_pipeline_from_image_file(self, event=None, filename=None):
        from PYME.DSView import ImageStack
        im = ImageStack(filename=filename)

        self.reconstruct_pipeline_from_image(im)
Пример #15
0
    def OnUnmix(self, event):
        #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:
            sf = None

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

        chanROIs = None
        if 'Splitter.Channel0ROI' in mdh.getEntryNames():
            chanROIs = [
                mdh['Splitter.Channel0ROI'], mdh['Splitter.Channel1ROI']
            ]

        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,
                                           chanROIs=chanROIs,
                                           voxelsize=self.image.voxelsize)

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

        fns = os.path.split(self.image.filename)[1]
        im = ImageStack([um0, 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'

        #print im.data[:,:,1,1].shape

        dv = ViewIm3D(im,
                      mode=mode,
                      glCanvas=self.dsviewer.glCanvas,
                      parent=wx.GetTopLevelParent(self.dsviewer))
Пример #16
0
    def OnDeconvICTM(self, event, beadMode=False):
        from PYME.Deconv.deconvDialogs import DeconvSettingsDialog,DeconvProgressDialog,DeconvProgressPanel

        dlg = DeconvSettingsDialog(self.dsviewer, beadMode, self.image.data.shape[3])
        if dlg.ShowModal() == wx.ID_OK:
            from PYME.Deconv import dec, decThread, richardsonLucy
            nIter = dlg.GetNumIterationss()
            regLambda = dlg.GetRegularisationLambda()

            decMDH = MetaDataHandler.NestedClassMDHandler(self.image.mdh)
            decMDH['Deconvolution.NumIterations'] = nIter
            decMDH['Deconvolution.OriginalFile'] = self.image.filename

            #self.dlgDeconProg = DeconvProgressDialog(self.dsviewer, nIter)
            #self.dlgDeconProg.Show()
            vx = self.image.mdh.getEntry('voxelsize.x')
            vy = self.image.mdh.getEntry('voxelsize.y')
            vz = self.image.mdh.getEntry('voxelsize.z')

            if beadMode:
                from PYME.Deconv import beadGen
                psf = beadGen.genBeadImage(dlg.GetBeadRadius(), (1e3*vx, 1e3*vy, 1e3*vz))

                decMDH['Deconvolution.BeadRadius'] = dlg.GetBeadRadius()
                
            else:
                #psf, vs = numpy.load(dlg.GetPSFFilename())
                #psf = numpy.atleast_3d(psf)
                psfFilename, psf, vs = dlg.GetPSF(vshint = vx)

                decMDH['Deconvolution.PSFFile'] = dlg.GetPSFFilename()

                if not (vs.x == vx and vs.y == vy and vs.z ==vz):
                    #rescale psf to match data voxel size
                    psf = ndimage.zoom(psf, [vs.x/vx, vs.y/vy, vs.z/vz])

            data = self.image.data[:,:,:, dlg.GetChannel()].astype('f') - dlg.GetOffset()
            decMDH['Deconvolution.Offset'] = dlg.GetOffset()
            
            bg = dlg.GetBackground()
            decMDH['Deconvolution.Background'] = bg

            #crop PSF in z if bigger than stack

            print psf.shape, data.shape
            if psf.shape[2] > data.shape[2]:
                dz = psf.shape[2] - data.shape[2]

                psf = psf[:,:,numpy.floor(dz/2):(psf.shape[2]-numpy.ceil(dz/2))]

            print((data.shape, psf.shape))

            if dlg.GetPadding():
                padsize = numpy.array(dlg.GetPadSize())
                decMDH['Deconvolution.Padding'] = padsize
                dp = numpy.ones(numpy.array(data.shape) + 2*padsize, 'f')*data.mean()
                weights = numpy.zeros_like(dp)
                px, py, pz = padsize

                #print data.shape, dp[px:-(px+1), py:-(py+1), pz:-(pz+1)].shape
                dp[px:-px, py:-py, pz:-pz] = data
                #if dlg.GetRemovePadding():
                #    data = dp[px:-px, py:-py, pz:-pz]#should be a slice
                #else:
                #    data = dp
                weights[px:-px, py:-py, pz:-pz] = 1.

                weights = weights.ravel()
            else:
                dp = data
                weights = 1

            if dlg.GetBlocking():
                decMDH['Deconvolution.Method'] = 'Blocked ICTM'
                self.checkTQ()
                from PYME.Deconv import tq_block_dec
                bs = dlg.GetBlockSize()
                self.decT = tq_block_dec.blocking_deconv(self.tq, data, psf, self.image.seriesName, blocksize={'y': bs, 'x': bs, 'z': 256})
                self.decT.go()

            else:
                decMDH['Deconvolution.Method'] = dlg.GetMethod()
                if dlg.GetMethod() == 'ICTM':
                    decMDH['Deconvolution.RegularisationParameter'] = regLambda
                    if beadMode:
                        self.dec = dec.dec_bead()
                    else:
                        self.dec = dec.dec_conv()
                else:
                    if beadMode:
                        self.dec = richardsonLucy.rlbead()
                    else:
                        self.dec = richardsonLucy.dec_conv()

                self.dec.psf_calc(psf, dp.shape)

                self.decT = decThread.decThread(self.dec, dp, regLambda, nIter, weights, bg = bg)
                self.decT.start()

                tries = 0
                while tries < 10 and not hasattr(self.dec, 'fs'):
                    time.sleep(1)
                    tries += 1

                if dlg.GetPadding() and dlg.GetRemovePadding():
                    fs =  self.dec.fs[px:-px, py:-py, pz:-pz]
                else:
                    fs = self.dec.fs

                
                
                im = ImageStack(data = fs, mdh = decMDH, titleStub = 'Deconvolution Result')
                mode = 'lite'
                if beadMode:
                    mode = 'psf'
                    im.defaultExt = '*.psf' #we want to save as PSF by default
                self.res = ViewIm3D(im, mode=mode, parent=wx.GetTopLevelParent(self.dsviewer))                    
                    
                #self.res = View3D(fs, 'Deconvolution Result', mdh=decMDH, parent=wx.GetTopLevelParent(self.dsviewer), mode=mode)

                self.dlgDeconProg = DeconvProgressPanel(self.res, nIter)

                self.pinfo1 = aui.AuiPaneInfo().Name("deconvPanel").Top().Caption('Deconvolution Progress').DestroyOnClose(True).CloseButton(False)#.MinimizeButton(True).MinimizeMode(aui.AUI_MINIMIZE_CAPT_SMART|aui.AUI_MINIMIZE_POS_RIGHT)#.CaptionVisible(False)
                self.res._mgr.AddPane(self.dlgDeconProg, self.pinfo1)
                self.res._mgr.Update()

            self.deconTimer = mytimer()
            self.deconTimer.WantNotification.append(self.OnDeconTimer)

            self.deconTimer.Start(500)
Пример #17
0
    def OnDeconvMovie(self, event, beadMode=False):
        from PYME.Deconv.deconvDialogs import DeconvSettingsDialog  #,DeconvProgressDialog,DeconvProgressPanel
        #import multiprocessing

        dlg = DeconvSettingsDialog(self.dsviewer, beadMode,
                                   self.image.data.shape[3])
        if dlg.ShowModal() == wx.ID_OK:
            from PYME.Deconv import dec, richardsonLucy  #, decThread
            nIter = dlg.GetNumIterationss()
            regLambda = dlg.GetRegularisationLambda()

            decMDH = MetaDataHandler.NestedClassMDHandler(self.image.mdh)
            decMDH['Deconvolution.NumIterations'] = nIter
            decMDH['Deconvolution.OriginalFile'] = self.image.filename

            vx, vy, vz = self.image.voxelsize_nm

            if beadMode:
                from PYME.Deconv import beadGen
                psf = beadGen.genBeadImage(dlg.GetBeadRadius(), (vx, vy, vz))

                decMDH['Deconvolution.BeadRadius'] = dlg.GetBeadRadius()

            else:
                psfFilename, psf, vs = dlg.GetPSF(vshint=vx)

                decMDH['Deconvolution.PSFFile'] = psfFilename

                if not (vs.x == vx and vs.y == vy):  # and vs.z ==vz):
                    #rescale psf to match data voxel size
                    psf = ndimage.zoom(psf, [vs.x / vx, vs.y / vy, 1])

            data = self.image.data[:, :, :, dlg.GetChannel()].astype(
                'f') - dlg.GetOffset()
            decMDH['Deconvolution.Offset'] = dlg.GetOffset()

            bg = dlg.GetBackground()
            decMDH['Deconvolution.Background'] = bg

            #crop PSF in z if bigger than stack

            #print psf.shape, data.shape
            if psf.shape[2] > data.shape[2]:
                dz = psf.shape[2] - data.shape[2]

                psf = psf[:, :,
                          numpy.floor(dz / 2):(psf.shape[2] -
                                               numpy.ceil(dz / 2))]

            print((data.shape, psf.shape))

            dp = numpy.array(data)
            weights = 1

            if dlg.GetBlocking():
                decMDH['Deconvolution.Method'] = 'Blocked ICTM'
                self.checkTQ()
                from PYME.Deconv import tq_block_dec
                bs = dlg.GetBlockSize()
                self.decT = tq_block_dec.blocking_deconv(self.tq,
                                                         data,
                                                         psf,
                                                         self.image.seriesName,
                                                         blocksize={
                                                             'y': bs,
                                                             'x': bs,
                                                             'z': 256
                                                         })
                self.decT.go()

            else:
                decMDH['Deconvolution.Method'] = dlg.GetMethod()
                if dlg.GetMethod() == 'ICTM':
                    decMDH['Deconvolution.RegularisationParameter'] = regLambda
                    if beadMode:
                        self.dec = dec.dec_bead()
                    else:
                        self.dec = dec.dec_conv()
                else:
                    if beadMode:
                        self.dec = richardsonLucy.rlbead()
                    else:
                        self.dec = richardsonLucy.dec_conv()

                self.dec.psf_calc(psf, dp[:, :, 0:1].shape)

                #print dp.__class__

                #self.decT = decThread.decThread(self.dec, dp, regLambda, nIter, weights)
                #self.decT.start()

                #                p = multiprocessing.Pool()
                #                slices = [(self.dec, psf, dp[:,:,i:(i+1)],regLambda, nIter, weights)  for i in range(dp.shape[2])]
                #                r = p.map(_pt, slices)
                #                res = numpy.concatenate(r, 2)

                res = numpy.concatenate([
                    self.dec.deconv(
                        dp[:, :, i:(i + 1)], regLambda, nIter, weights,
                        bg=bg).reshape(self.dec.shape)
                    for i in range(dp.shape[2])
                ], 2)

                im = ImageStack(data=res,
                                mdh=decMDH,
                                titleStub='Deconvolution Result')
                mode = 'lite'

                self.res = ViewIm3D(im,
                                    mode=mode,
                                    parent=wx.GetTopLevelParent(self.dsviewer))
Пример #18
0
    def OnDeconvICTM(self, event, beadMode=False):
        from PYME.Deconv.deconvDialogs import DeconvSettingsDialog, DeconvProgressPanel

        dlg = DeconvSettingsDialog(self.dsviewer, beadMode,
                                   self.image.data.shape[3])
        if dlg.ShowModal() == wx.ID_OK:
            from PYME.Deconv import dec, decThread, richardsonLucy
            nIter = dlg.GetNumIterationss()
            regLambda = dlg.GetRegularisationLambda()

            decMDH = MetaDataHandler.NestedClassMDHandler(self.image.mdh)
            decMDH['Deconvolution.NumIterations'] = nIter
            decMDH['Deconvolution.OriginalFile'] = self.image.filename

            vx, vy, vz = self.image.voxelsize_nm

            if beadMode:
                from PYME.Deconv import beadGen
                psf = beadGen.genBeadImage(dlg.GetBeadRadius(), (vx, vy, vz))

                decMDH['Deconvolution.BeadRadius'] = dlg.GetBeadRadius()

            else:
                psfFilename, psf, vs = dlg.GetPSF(vshint=vx)

                if psf.shape[2] < 2:
                    raise RuntimeError(
                        'Expepected a 3D PSF for 3D deconvolution. For 2D deconvolution use the DeconvMovie function'
                    )

                decMDH['Deconvolution.PSFFile'] = dlg.GetPSFFilename()

                if not (vs.x == vx and vs.y == vy and vs.z == vz):
                    #rescale psf to match data voxel size
                    psf = ndimage.zoom(psf, [vs.x / vx, vs.y / vy, vs.z / vz])

            #crop PSF in z if bigger than stack
            if psf.shape[2] > self.image.data.shape[2]:
                dz = psf.shape[2] - self.image.data.shape[2]

                psf = psf[:, :,
                          int(numpy.floor(dz / 2)):int(psf.shape[2] -
                                                       numpy.ceil(dz / 2))]

            decMDH['Deconvolution.Offset'] = dlg.GetOffset()

            bg = dlg.GetBackground()
            decMDH['Deconvolution.Background'] = bg

            if beadMode and self.image.data.shape[3] > 1:
                #special case for deconvolving multi-channel PSFs
                data = np.concatenate([
                    self.image.data[:, :, :, i].astype('f') - dlg.GetOffset()
                    for i in range(self.image.data.shape[3])
                ], 0)
            else:
                data = self.image.data[:, :, :, dlg.GetChannel()].astype(
                    'f') - dlg.GetOffset()

            if dlg.GetPadding():
                padsize = numpy.array(dlg.GetPadSize())
                decMDH['Deconvolution.Padding'] = padsize
                dp = numpy.ones(numpy.array(data.shape) + 2 * padsize,
                                'f') * data.mean()
                weights = numpy.zeros_like(dp)
                px, py, pz = padsize

                dp[px:-px, py:-py, pz:-pz] = data
                weights[px:-px, py:-py, pz:-pz] = 1.

                weights = weights.ravel()
            else:
                dp = data
                weights = 1

            if dlg.GetBlocking():
                decMDH['Deconvolution.Method'] = 'Blocked ICTM'
                self.checkTQ()
                from PYME.Deconv import tq_block_dec
                bs = dlg.GetBlockSize()
                self.decT = tq_block_dec.blocking_deconv(self.tq,
                                                         data,
                                                         psf,
                                                         self.image.seriesName,
                                                         blocksize={
                                                             'y': bs,
                                                             'x': bs,
                                                             'z': 256
                                                         })
                self.decT.go()

            else:
                decMDH['Deconvolution.Method'] = dlg.GetMethod()
                if dlg.GetMethod() == 'ICTM':
                    decMDH['Deconvolution.RegularisationParameter'] = regLambda
                    if beadMode:
                        self.dec = dec.dec_bead()
                    else:
                        self.dec = dec.dec_conv()
                else:
                    if beadMode:
                        self.dec = richardsonLucy.rlbead()
                    else:
                        self.dec = richardsonLucy.dec_conv()

                self.dec.psf_calc(psf, dp.shape)

                self.decT = decThread.decThread(self.dec,
                                                dp,
                                                regLambda,
                                                nIter,
                                                weights,
                                                bg=bg)
                self.decT.start()

                tries = 0
                while not hasattr(self.dec, 'fs'):
                    if tries > 60:
                        self.decT.kill()
                        raise RuntimeError(
                            'Initialization not complete after 60s, giving up.'
                        )

                    time.sleep(1)
                    tries += 1

                if dlg.GetPadding() and dlg.GetRemovePadding():
                    fs = self.dec.fs[px:-px, py:-py, pz:-pz]
                else:
                    fs = self.dec.fs

                if beadMode and self.image.data.shape[3] > 1:
                    #special case for bead deconvolution - unwind the stacking
                    nChans = self.image.data.shape[3]
                    xs = int(fs.shape[0] / nChans)
                    #NOTE: this relies on the slicing returning a view into the underlying data, not a copy

                    fs = [
                        fs[(i * xs):((i + 1) * xs), :, :]
                        for i in range(nChans)
                    ]

                im = ImageStack(data=fs,
                                mdh=decMDH,
                                titleStub='Deconvolution Result')
                mode = 'lite'
                if beadMode and im.data.shape[1] < 100:
                    mode = 'psf'
                    im.defaultExt = '*.psf'  #we want to save as PSF by default
                self.res = ViewIm3D(im,
                                    mode=mode,
                                    parent=wx.GetTopLevelParent(self.dsviewer))

                #self.res = View3D(fs, 'Deconvolution Result', mdh=decMDH, parent=wx.GetTopLevelParent(self.dsviewer), mode=mode)

                self.dlgDeconProg = DeconvProgressPanel(self.res, nIter)

                self.pinfo1 = aui.AuiPaneInfo().Name("deconvPanel").Top(
                ).Caption('Deconvolution Progress').DestroyOnClose(
                    True
                ).CloseButton(
                    False
                )  #.MinimizeButton(True).MinimizeMode(aui.AUI_MINIMIZE_CAPT_SMART|aui.AUI_MINIMIZE_POS_RIGHT)#.CaptionVisible(False)
                self.res._mgr.AddPane(self.dlgDeconProg, self.pinfo1)
                self.res._mgr.Update()

            self.deconTimer = mytimer()
            self.deconTimer.WantNotification.append(self.OnDeconTimer)

            self.deconTimer.Start(500)