コード例 #1
0
ファイル: threads.py プロジェクト: iandobbie/Chromagnon
    def getAligner(self, fn, index, what='ref'):
        """
        what: 'ref' or 'tgt'
        """
        try:
            an = aligner.Chromagnon(fn)
            an.setImgSuffix(self.img_suffix)
            an.setFileFormats(self.img_ext)
            an.setParmSuffix(self.parm_suffix)

        except IOError:
            raise IOError('filename %s, index %i, fns %s' % (fn, index, fns))

        an.setEchofunc(self.echo)
        return an
コード例 #2
0
ファイル: flatfielder.py プロジェクト: iandobbie/Chromagnon
    def view(self, target):
        """
        view with viewer
        """
        # prepare viewer
        if not self.aui:
            if self.parent and not self.parent.aui:
                self.aui = aui.MyFrame(parent=self.parent)
                self.parent.aui = self.aui
                self.aui.Show()
            elif not self.parent:
                self.aui = aui.MyFrame(parent=self)

                self.aui.Show()

            elif self.parent and self.parent.aui:
                self.aui = self.parent.aui

        # draw
        if isinstance(target, six.string_types):

            if chromformat.is_chromagnon(target):
                target_is_image = False
            else:
                target_is_image = True
                an = aligner.Chromagnon(target)
        else:
            an = target
            target_is_image = True

        if target_is_image:
            newpanel = aui.ImagePanel(self.aui, an.img)

        else:
            #an.close()
            newpanel = chromeditor.ChromagnonEditor(self.aui, target)

        if isinstance(target, six.string_types):
            name = os.path.basename(target)
        else:
            name = target.file
        if sys.platform in ('linux2', 'win32'):
            wx.CallAfter(self.aui.imEditWindows.addPage,
                         newpanel,
                         name,
                         select=True)
        else:
            self.aui.imEditWindows.addPage(newpanel, name, select=True)
コード例 #3
0
    def view(self, fn):
        """
        opens viewer and hide itself.
        """
        try:
            self.doc = aligner.Chromagnon(fn)
            self.doc.zlast = 0
        except:
            G.openMsg(self, 'This file is not a valid image file', 'Error')
            return

        self.loadParm()

        parent = self.GetParent()
        parent._mgr.GetPane('tpanel').Hide()
        parent.addImageXY()
コード例 #4
0
ファイル: threads.py プロジェクト: iandobbie/Chromagnon
    def run(self):
        """
        This function execute the series of processes

        Since it uses GUI, this function uses several events to control GUI
        They are called by wx.PostEvent()
        """
        OLD_SCIK = fftmanager.SCIK
        OLD_REIK = fftmanager.REIK
        fftmanager.SCIK = False
        fftmanager.REIK = False

        fns = self.fns
        targets = self.targets
        parms = self.parms

        # parameters
        cutout = parms[0]
        initGuess = parms[1]
        if initGuess and not os.path.isfile(initGuess):
            raise ValueError(
                'The initial guess is not a valid Chromagnon file')
        local = parms[2]

        maxShift = parms[3]
        zmag = parms[4]
        self.parm_suffix = parms[5]
        self.img_suffix = parms[6]
        nts = parms[7]
        self.img_ext = parms[8]
        min_pxls_yx = parms[9]

        saveAlignParam = True
        alignChannels = True
        alignTimeFrames = True

        outs0 = []
        outs = []
        doneref = []
        donetgt = []
        errs = []

        kwds = {}

        self.progress(0)

        try:
            # calibration
            for index, fn in enumerate(fns):
                #clk0 = time.clock()
                # calculation
                if not chromformat.is_chromagnon(fn):
                    tstf = time.strftime('%Y %b %d %H:%M:%S', time.localtime())
                    self.log('\n**Measuring shifts in %s at %s' %
                             (os.path.basename(fn), tstf))
                    if self.notify_obj:
                        wx.PostEvent(
                            self.notify_obj,
                            MyEvent(EVT_COLOR_ID, ['ref', index, wx.RED]))

                    an = aligner.Chromagnon(fn)
                    an = self.getAligner(fn, index, what='ref')
                    an.setZmagSwitch(zmag)
                    an.setMaxShift(maxShift)

                    pgen = self.progressValues(target=False,
                                               an=an,
                                               alignChannels=alignChannels,
                                               alignTimeFrames=alignTimeFrames,
                                               local=local)
                    an.setProgressfunc(pgen)

                    if initGuess:
                        an.loadParm(initGuess)
                        # mapyx should not be inherited...
                        an.mapyx = None

                    if (an.nw > 1 and an.nt == 1):
                        an.findBestChannel()
                        self.echo('Calculating channel alignment...')

                        for t in range(an.nt):
                            try:
                                an.findAlignParamWave(t=t)
                            except alignfuncs.AlignError:  # in xcorr or else
                                self.echo('Calculation failed, skipping')
                                errs.append(index)
                                continue

                            if local in self.localChoice[1:]:
                                an.findNonLinear2D(t=t, npxls=min_pxls_yx)

                            if local in self.localChoice[2:]:
                                arr = an.findNonLinear3D(t=t,
                                                         npxls=min_pxls_yx)
                                del arr

                    elif an.nt > 1:
                        self.echo('Calculating timelapse alignment...')
                        an.findBestChannel()
                        an.findBestTimeFrame(an.refwave)

                        an.findAlignParamTime(doWave=False)

                    fn = an.saveParm()

                    currlist = None
                    #clk1 = time.clock()
                    #print('Done seconds', (clk1-clk0))

                    an.close()

                doneref.append(index)

                if self.notify_obj:
                    wx.PostEvent(
                        self.notify_obj,
                        MyEvent(EVT_COLOR_ID, ['ref', index, wx.BLUE]))

                if index < len(targets):
                    if self.notify_obj:
                        wx.PostEvent(
                            self.notify_obj,
                            MyEvent(EVT_COLOR_ID, ['tgt', index, wx.RED]))

                    target = targets[index]
                    tstf = time.strftime('%Y %b %d %H:%M:%S', time.gmtime())
                    self.log(
                        '\n**Applying to %s using %s at %s' %
                        (os.path.basename(target), os.path.basename(fn), tstf))

                    an = self.getAligner(target, index, what='target')

                    pgen = self.progressValues(target=True, an=an)
                    an.setProgressfunc(pgen)
                    self.progress(0)

                    an.loadParm(fn)
                    #if cutout:
                    an.setRegionCutOut(cutout)

                    out = an.saveAlignedImage()
                    donetgt.append(index)

                    an.close()

                    if self.notify_obj:
                        wx.PostEvent(
                            self.notify_obj,
                            MyEvent(EVT_COLOR_ID, ['tgt', index, wx.BLUE]))

                    if self.notify_obj:
                        wx.PostEvent(self.notify_obj,
                                     MyEvent(EVT_VIEW_ID, [out]))

                elif self.notify_obj:
                    wx.PostEvent(self.notify_obj, MyEvent(EVT_VIEW_ID, [fn]))

            # remaining target files use the last alignment file
            for index, target in enumerate(targets[len(fns):]):
                index += len(fns)
                if self.notify_obj:
                    wx.PostEvent(
                        self.notify_obj,
                        MyEvent(EVT_COLOR_ID, ['tgt', index, wx.BLUE]))

                target = targets[index]
                tstf = time.strftime('%Y %b %d %H:%M:%S', time.gmtime())
                if fns:
                    self.log(
                        '\n**Applying to %s using %s at %s' %
                        (os.path.basename(target), os.path.basename(fn), tstf))
                else:
                    self.log('\n**Applying to %s at %s' %
                             (os.path.basename(target), tstf))

                an = self.getAligner(target, index, what='target')
                pgen = self.progressValues(target=True, an=an)
                an.setProgressfunc(pgen)
                self.progress(0)

                if len(fns):
                    an.loadParm(fn)

                an.setRegionCutOut(cutout)

                out = an.saveAlignedImage()

                donetgt.append(index)

                an.close()

                if self.notify_obj:
                    wx.PostEvent(
                        self.notify_obj,
                        MyEvent(EVT_COLOR_ID, ['tgt', index, wx.BLUE]))
                    #wx.PostEvent(self.notify_obj, MyEvent(EVT_PROGRESS_ID, [prange.pop(0)]))
                # pgen.next()

                #out = aligner.Chromagnon(out)
                if self.notify_obj:
                    print('event view', out)
                    wx.PostEvent(self.notify_obj, MyEvent(EVT_VIEW_ID, [out]))

        except MyError:
            if self.notify_obj:
                wx.PostEvent(self.notify_obj, MyEvent(EVT_ABORT_ID, []))
                wx.PostEvent(self.notify_obj, MyEvent(EVT_PROGRESS_ID, [0]))
            else:
                pass
        except:
            #exc_type, exc_value, exc_traceback = sys.exc_info()
            #formatted = traceback.format_exception(exc_type, exc_value, exc_traceback)
            if self.notify_obj:
                import traceback, sys
                wx.PostEvent(self.notify_obj,
                             MyEvent(EVT_ERROR_ID,
                                     sys.exc_info()))  #formatted]))
                #wx.PostEvent(self.notify_obj, MyEvent(EVT_PROGRESS_ID, [0]))
                self.progress(0)
            else:
                pass
        else:
            if self.notify_obj:
                wx.PostEvent(self.notify_obj,
                             MyEvent(EVT_DONE_ID, [doneref, donetgt, errs]))
                #wx.PostEvent(self.notify_obj, MyEvent(EVT_PROGRESS_ID, [0]))
                self.progress(0)
            else:
                pass
        finally:
            self.logh.close()
        #bioformatsIO.uninit_javabridge()

        fftmanager.SCIK = OLD_SCIK
        fftmanager.REIK = OLD_REIK
コード例 #5
0
ファイル: threads.py プロジェクト: iandobbie/Chromagnon
    def run(self):
        """
        This function execute the series of processes

        Since it uses GUI, this function uses several events to control GUI
        They are called by wx.PostEvent()
        """
        fn = self.fns[0]
        targets = self.targets
        parms = self.parms

        saveAlignParam = True
        alignChannels = True
        alignTimeFrames = True

        outs0 = []
        outs = []
        doneref = []  #0]
        donetgt = []
        errs = []

        kwds = {}

        try:
            # calibration
            #clk0 = time.clock()
            #an = aligner.Chromagnon(fn)
            #if not hasattr(an.img, 'hdr') or an.img.hdr.type != flatConv.IDTYPE:
            if not flatConv.is_flat(fn):
                #an = aligner.Chromagnon(fn)
                print('The file is not flat file')
                wx.PostEvent(self.notify_obj,
                             MyEvent(EVT_COLOR_ID, ['ref', 0, wx.RED]))
                self.echo('Making a calibration file...')

                flatFile = flatConv.makeFlatConv(fn, suffix=parms[0])

                #out = aligner.Chromagnon(flatFile)
                wx.PostEvent(self.notify_obj, MyEvent(EVT_VIEW_ID,
                                                      [flatFile]))  #out]))
                #clk1 = time.clock()
                #an.close()
            else:
                print('The file is a flat file')
                flatFile = fn

        # an.close()
            wx.PostEvent(self.notify_obj, MyEvent(EVT_SETFLAT_ID, [flatFile]))
            wx.PostEvent(self.notify_obj,
                         MyEvent(EVT_COLOR_ID, ['ref', 0, wx.BLUE]))

            # remaining target files use the last alignment file
            for index, target in enumerate(targets):
                self.echo('Applying flat fielding to %s...' %
                          os.path.basename(target))
                wx.PostEvent(self.notify_obj,
                             MyEvent(EVT_COLOR_ID, ['tgt', index, wx.RED]))

                base, ext = os.path.splitext(target)
                out = ''.join((base, parms[1], parms[2]))
                out = flatConv.flatConv(target, flatFile,
                                        out=out)  #None, suffix=parms[1])

                wx.PostEvent(self.notify_obj,
                             MyEvent(EVT_COLOR_ID, ['tgt', index, wx.BLUE]))

                out = aligner.Chromagnon(out)
                wx.PostEvent(self.notify_obj, MyEvent(EVT_VIEW_ID, [out]))
                donetgt.append(index)

        except MyError:
            wx.PostEvent(self.notify_obj, MyEvent(EVT_ABORT_ID, []))
        except:
            import traceback, sys
            #exc_type, exc_value, exc_traceback = sys.exc_info()
            #formatted = traceback.format_exception(exc_type, exc_value, exc_traceback)
            wx.PostEvent(self.notify_obj,
                         MyEvent(EVT_ERROR_ID, sys.exc_info()))  #formatted]))
        else:
            wx.PostEvent(self.notify_obj,
                         MyEvent(EVT_DONE_ID, [doneref, donetgt, errs]))
コード例 #6
0
    def onViewLocal(self,
                    evnt=None,
                    gridStep=60,
                    t=0,
                    w=None,
                    originalFn=None,
                    **kwds):
        """
        save a '.local' file and opens new image viewer
        """
        import wx, tempfile
        import imgio
        from Priithon.all import Y

        if w is None:
            wave = int(self.wavechoice.GetStringSelection())
            w = self.clist.wave.index(wave)

        if originalFn is None:
            originalFn = self.originalFileTxt.GetValue()

        factor = int(self.factorchoice.GetStringSelection())
        colstr = self.colorchoice.GetStringSelection()
        colortable = [(0, 0, 0)] + microscope.COLOR_TABLE
        col = colortable[self.color_name.index(colstr)]

        parent = self.GetParent()
        book = parent.GetTopLevelParent()

        mapyx = self.clist.mapyx
        name = self.clist.basename + '.Local'

        if originalFn:
            try:
                img = imgio.Reader(originalFn)  #imgfileIO.load(originalFn)
            except:
                G.openMsg(self,
                          'Is this file really a image file?',
                          title='Error')
                return
            if N.any(
                    N.array(img.shape[-2:]) != N.array(
                        self.clist.mapyx.shape[-2:])):
                G.openMsg(self,
                          'Please choose original image file BEFORE alignment',
                          title='Error')
                return
            a = N.zeros(self.clist.mapyx.shape[-3:], img.dtype)
            b = img.get3DArr(w=self.clist.refwave, t=t)
            if self.clist.mapyx.ndim == 5:
                b = N.max(b, 0)
            a[0] = b

            b = img.get3DArr(w=w, t=t)
            if self.clist.mapyx.ndim == 5:
                b = N.max(b, 0)

            a[1] = af.applyShift(b, self.clist.alignParms[t, w])
            pz, py, px = img.pxlsiz
        else:
            a = N.zeros(self.clist.mapyx.shape[-3:], N.uint8)
            pz = py = px = 1

        out = os.path.join(tempfile.gettempdir(), 'Chromagnon.local.tif')

        wtr = imgio.Writer(out)
        wtr.setPixelSize(pz=pz, py=py, px=px)
        wtr.setDim(
            nx=a.shape[-1],
            ny=a.shape[-2],
            nz=1,
            nt=1,
            nw=2,
            dtype=a.dtype.type,
            wave=[self.clist.wave[self.clist.refwave], self.clist.wave[w]],
            imgSequence=1)
        for w, a2d in enumerate(a):
            wtr.writeArr(a2d, w=w)
        wtr.close()

        an = aligner.Chromagnon(out)
        newpanel = aui.ImagePanel(book, an.img)
        book.imEditWindows.AddPage(newpanel, name, select=True)
        v = newpanel.viewers[0]
        wx.Yield()

        inds = N.indices(mapyx.shape[-2:], N.float32)
        slcs1 = [
            slice(gridStep // 2, -gridStep // 2, gridStep) for d in range(2)
        ]

        #for w in xrange(self.clist.nw):
        vs = []
        for d in range(2):
            slcs = [slice(d, d + 1)] + slcs1
            vs.append(inds[slcs].ravel())
        iis = N.array(list(zip(*vs)))

        vs = []
        for d in range(2):
            slcs = [slice(t, t + 1), slice(w, w + 1), slice(d, d + 1)] + slcs1
            vs.append(mapyx[slcs].ravel())
        yxs = N.array(list(zip(*vs)))

        wave = self.clist.wave[w]
        #col = microscope.LUT(wave)
        #col = (1,1,1)
        wx.CallAfter(Y.vgAddArrows,
                     v,
                     iis,
                     iis + yxs,
                     color=col,
                     factor=factor,
                     width=2,
                     **kwds)