Esempio n. 1
0
    def _load_func(self, fn):
        if chromformat.is_chromagnon(fn):
            h = chromformat.ChromagnonReader(fn)
        else:
            try:
                h = imgio.Reader(fn)
            except ValueError as e:
                return listbox.imgio_dialog(e, self)

            if aligner.hasSameWave(h):
                dlg = wx.MessageDialog(
                    self,
                    'The image contains multiple channels with the same wavelength. Please use a unique wavelength for each channel',
                    'Error in channel wavelengths',
                    wx.OK | wx.ICON_EXCLAMATION)
                if dlg.ShowModal() == wx.ID_OK:
                    return

            if h.nseries > 1:
                dlg = wx.MessageDialog(
                    self,
                    'Multiple series data sets are not allowed, please make a file with a single image in a file',
                    'Error in image file', wx.OK | wx.ICON_EXCLAMATION)
                if dlg.ShowModal() == wx.ID_OK:
                    return
        self.lastpath = os.path.dirname(fn)
        C.saveConfig(lastpath=self.lastpath)
        return h
Esempio n. 2
0
    def __init__(self,
                 parent,
                 imFile=None,
                 id=wx.ID_ANY,
                 pos=wx.DefaultPosition,
                 size=wx.DefaultSize):
        wx.Panel.__init__(self, parent, id, pos, size, name='')

        # to make consistent with the older viewers
        self.parent = self

        self._mgr = aui.AuiManager()
        self._mgr.SetManagedWindow(self)

        self._perspectives = []

        ## self.doc contains all the information on the displayed image
        if isinstance(imFile, six.string_types):  #str):
            self.doc = imgio.Reader(
                imFile)  #bioformatsIO.load(imFile)#aligner.Chromagnon(imFile)
        else:
            self.doc = imFile

        #self.zsec  = [self.doc.nz//2]
        #self.zlast = [0]

        if self.doc:
            self.doc.zlast = 0
            self.addImageXY()
Esempio n. 3
0
def makeFlatConv(fn, out=None, suffix=''):
    """
    save a calibration file
    
    return output file name
    """
    if not out:
        out = os.path.splitext(fn)[0] + suffix + os.path.extsep + EXT
    elif not out.endswith(EXT):
        out = os.path.extsep.join(os.path.splitext(out)[0], EXT)

    h = imgio.Reader(fn)  #bioformatsIO.load(fn)
    ntz = h.nz * h.nt

    o = imgio.Writer(fn)  #bioformatsIO.getWriter(out)
    o.setFromReader(h)
    o.nt = 1
    o.nz = 1
    o.dtype = N.float32
    o.ome.add_structured_annotation('idtype', IDTYPE)

    for w in range(h.nw):
        canvas = N.zeros((h.nt, h.nz, h.ny, h.nx), N.float32)
        for t in range(h.nt):
            for z in range(h.nz):
                canvas[t, z] = h.getArr(w=w, t=t, z=z)
        arr = canvas.reshape((ntz, h.ny, h.nx)).mean(axis=0)
        arr = arr.mean() / arr
        o.writeArr(arr.astype(N.float32), w=w, z=0)
    o.close()
    h.close()

    return out
Esempio n. 4
0
def flatConv(fn, flatFile, out=None, suffix='_' + EXT.upper()):
    """
    save a normalized image

    return output filename
    """
    if not out:
        base, ext = os.path.splitext(fn)
        out = base + suffix + ext

    h = imgio.Reader(fn)  #bioformatsIO.load(fn)

    f = imgio.Reader(flatFile)  #bioformatsIO.load(flatFile)
    o = imgio.Writer(out)  #bioformatsIO.getWriter(out)
    o.setFromReader(h)
    if out.endswith('ome.tif'):
        o.imgSequence = 0

    for w in range(h.nw):
        tgt_wave = h.getWaveFromIdx(w)

        if tgt_wave in f.wave:
            rw = h.getWaveIdx(tgt_wave)
            fs = f.getArr(w=rw, z=0)

            for t in range(h.nt):
                for z in range(h.nz):
                    a = h.getArr(w=w, t=t, z=z)
                    b = a * fs
                    o.writeArr(b.astype(h.dtype), w=w, t=t, z=z)
        else:
            for t in range(h.nt):
                for z in range(h.nz):
                    a = h.getArr(w=w, t=t, z=z)
                    o.writeArr(a.astype(h.dtype), w=w, t=t, z=z)
    o.close()
    h.close()
    f.close()

    return out
Esempio n. 5
0
def is_flat(fn, check_img_to_open=True):
    check = False
    if fn.endswith(EXT):
        check = True
    else:
        if check_img_to_open:
            rdr = imgio.Reader(fn)  #bioformatsIO.BioformatsReader(fn)
            if hasattr(rdr, 'ome') and \
                rdr.ome.get_structured_annotation('idtype') == IDTYPE:
                check = True
            rdr.close()

    return check
Esempio n. 6
0
    def _load_func(self, fn):
        try:
            h = imgio.Reader(fn)  #bioformatsIO.load(fn)
        except ValueError:
            dlg = wx.MessageDialog(self, '%s is not a valid image file!' % ff,
                                   'Error reading image file',
                                   wx.OK | wx.ICON_EXCLAMATION)
            if dlg.ShowModal() == wx.ID_OK:
                return

        if h.nseries > 1:
            dlg = wx.MessageDialog(
                self,
                'Multiple series data sets are not allowed, please make a file with a single image in a file',
                'Error in image file', wx.OK | wx.ICON_EXCLAMATION)
            if dlg.ShowModal() == wx.ID_OK:
                return
        return h
Esempio n. 7
0
            default=aligner.WRITABLE_FORMATS[0],
            choices=aligner.WRITABLE_FORMATS,
            help=
            'file extension for the target files, choose from %s (default=%s)'
            % (aligner.WRITABLE_FORMATS, aligner.WRITABLE_FORMATS[0]))
        options = p.parse_args()

        ref = glob.glob(
            os.path.expandvars(os.path.expanduser(options.reference)))

        fns = []
        for fn in options.targets:
            fns += glob.glob(os.path.expandvars(os.path.expanduser(fn)))
        nts = []
        for fn in fns:
            h = imgio.Reader(fn)  #bioformatsIO.load(fn)
            nts.append(h.nt)
            h.close()

        parms = [
            True,  # crop mergins
            None,  #options.initguess,
            options.local,
            options.maxShift,
            options.zmag,
            options.parm_suffix,
            options.img_suffix,
            nts,
            options.img_format,
            int(options.localMinWindow)
        ]
Esempio n. 8
0
    def __init__(self, fn):
        """
        usage: 
        ## channel alignment
        ## fn: the reference image
        >>> an = Chromagnon(fn)
        >>> an.findBestChannel()
        >>> an.findAlignParamWave()
        >>> an.setRegionCutOut()
        >>> an.saveAlignedImage()
        >>> out = an.saveParm()

        ## fn2: the target image
        >>> an = Chromagnon(fn2)
        >>> an.loadParm(out)
        >>> an.setRegionCutOut()
        >>> out = an.saveAlignedImage()

        ## time frame alignment
        ## fn: the reference image (time projected for 10 frames for example)
        >>> an = Chromagnon(fn)
        >>> an.findBestTimeFrame()
        >>> an.findAlignParamTime()
        >>> an.setRegionCutOut()
        >>> an.saveAlignedImage()

        """
        self.img = imgio.Reader(fn)

        self.copyAttr()
        self.setMaxError()
        self.setMaxIter()
        self.setReferenceTime()
        self.setReferenceWave()
        self.setReferenceZIndex()
        self.setReferenceXIndex()
        self.setImageCenter()
        self.setMultipageTiff()
        self.setphaseContrast()
        self.setEchofunc()
        self.setProgressfunc()
        self.setImgSuffix()
        self.setFileFormats()
        self.setParmSuffix()
        self.setIf_failed()
        
        self.alignParms = N.zeros((self.img.nt, self.img.nw, NUM_ENTRY), N.float32)
        self.alignParms[:,:,4:] = 1
        self.cropSlice = [Ellipsis, slice(None), slice(None), slice(None)]

        self.saturation = N.zeros((self.img.nt, self.img.nw, 3))

        self.refyz = None
        self.refyx = None
        
        self.mapyx = None
        self.regions = None
        self.byteorder = '<'
        self.setCCthreshold()
        self.setMaxShift()
        self.setZmagSwitch()
Esempio n. 9
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)
Esempio n. 10
0
def main(fn, out=None, otf=None, **kwds):
    # setup
    priismCommands.PriismSetup()

    # byteSwap for Softworx
    if 'littleEndian' in kwds:
        littleEndian = kwds.pop('littleEndian')
    else:
        littleEndian = False

    #bilateral
    if 'filterMethod' in kwds:
        filterMethod = kwds.pop('filterMethod')
    else:
        filterMethod = None

    makelog = kwds.pop('makelog', None)

    if filterMethod:
        OPTS = [opt for opt in DECON_OPT]  # copy
        if not filterMethod.startswith('f'):
            OPTS += FFT_OPT

        fkwds = dict([(key, val) for key, val in kwds.items()
                      if key not in OPTS])

        fn = priismCommands.Filter3D(fn,
                                     out,
                                     filterMethod=filterMethod,
                                     **fkwds)
        if littleEndian:
            out = os.path.extsep.join((fn, byteSwap.DEF_EXT))
            #byteSwap.byteSwap(fn, out)
            # replacing byteSwap
            h = imgio.Reader(fn)  #mrcIO.MrcReader(fn)
            o = imgio.Writer(
                out, hdr=h.hdr,
                byteorder='<')  #mrcIO.MrcWriter(out, h.hdr, byteorder='<')
            for t in range(h.nt):
                for w in range(h.w):
                    o.write3DArr(h.get3DArr(t=t, w=w), t=t, w=w)
            o.close()
            h.close()

            os.remove(fn)
            fn = out

    # decon filename
    if not out or filterMethod:
        out = fn + EXT_DCN
    log = os.path.extsep.join((out, 'log'))

    # decon otf
    if isinstance(otf, six.string_types) and os.path.exists(otf):
        ctf = otf
    elif isinstance(otf, six.string_types) and otf.isdigit():
        ctf = findOTFfromNum(otf)
    else:
        ctf = findOTF(fn)

    # decon
    options = []
    for key, value in kwds.items():
        if key in DECON_OPT:
            if value == True:
                options.append('-%s' % key)
            else:
                options.append('-%s=%s' % (key, value))

    #title = 'OTFfile:%s' % shortenStr(ctf)
    #com = ' '.join(['decon %s %s %s -title="%s" ' % (fn, out, ctf, title)] + options)
    com = ' '.join(['decon %s %s %s ' % (fn, out, ctf)] + options)
    if PRINTOUT:
        print(com)

    if makelog:
        if os.path.exists(log):
            os.remove(log)
        com += ' >> %s' % log
        h = open(log, 'a')
        h.write(com)

    if sys.platform == 'darwin':
        out2 = saveCommand(com)

        import subprocess
        err = subprocess.call(['sh', out2])
        os.remove(out2)
    else:
        err = os.system(com)

    if err:
        raise RuntimeError(
            'Deconvolution failed (exit status %s)\ncommand is: %s' %
            (err, com))

    if makelog:
        h.close()

    if littleEndian:
        fn = out
        out = os.path.extsep.join((fn, byteSwap.DEF_EXT))
        #byteSwap.byteSwap(fn, out)
        h = imgio.Reader(fn)  #mrcIO.MrcReader(fn)
        o = imgio.Writer(
            out, hdr=h.hdr,
            byteorder='<')  #mrcIO.MrcWriter(out, h.hdr, byteorder='<')
        #h = mrcIO.MrcReader(fn)
        #o = mrcIO.MrcWriter(out, h.hdr, byteorder='<')
        for t in range(h.nt):
            for w in range(h.w):
                o.write3DArr(h.get3DArr(t=t, w=w), t=t, w=w)
        o.close()
        h.close()

        os.remove(fn)

    if PRINTOUT:
        print('Done %s' % out)
    return out