コード例 #1
0
def findBestRefZs(ref, sigma=1):
    """
    PSF spread along the Z axis is often tilted in the Y or X axis.
    Thus simple maximum intensity projection may lead to the wrong answer to estimate rotation and magnification.
    On the other hands, taking a single section may also contain out of focus flare from neighboring sections that are tilted.
    Therefore, here sections with high complexity are selected and projected.

    ref: 3D array
    return z idx at the focus
    """
    nz = ref.shape[0]
    if ref.ndim == 2:
        return [0]
    elif nz <= 3:
        return range(nz)

    # Due to the roll up after FFT, the edge sections in Z may contain different information among the channels. Thus these sections are left unused.
    ms = N.zeros((nz - 2, ), N.float32)
    for z in range(1, nz - 1):
        arr = ref[z]
        ms[z - 1] = N.prod(U.mmms(arr)[-2:])  # mean * std

    mi, ma, me, st = U.mmms(ms)
    thr = me + st * sigma

    ids = [idx for idx in range(1, nz - 1) if ms[idx - 1] > thr]
    if not ids:
        ids = range(1, nz - 1)

    return ids
コード例 #2
0
ファイル: splitND2.py プロジェクト: macronucleus/Chromagnon
    def recalcHist(self, i, postponeToIdle):
        if postponeToIdle:
            self.recalcHist_todo_Set.add(i)
            return
        img = self.data[ tuple(self.zsec) ][i]
        from . import useful as U
        mmms = U.mmms( img )
        self.mmms[i] = mmms
        #time import time
        #time x = time.clock()
        # print mmms

        from . import useful as U
        if self.hist_arr[i] is not None:
            #glSeb  import time
            #glSeb  x = time.clock()
            #         print U.mmms(self.hist_arr[i]),
            U.histogram(img, amin=self.hist_min[i], amax=self.hist_max[i], histArr=self.hist_arr[i])
            #         print U.mmms(self.hist_arr[i])
            self.hist[i].setHist(self.hist_arr[i], self.hist_min[i], self.hist_max[i])
            #glSeb  print "ms: %.2f"% ((time.clock()-x)*1000.0)
            ## FIXME  setHist needs to NOT alloc xArray every time !!!
        else:
            resolution = 10000
    
            a_h = U.histogram(img, resolution, mmms[0], mmms[1])

            self.hist[i].setHist(a_h, mmms[0], mmms[1])
コード例 #3
0
    def recalcHist(self, i, postponeToIdle):
        if postponeToIdle:
            self.recalcHist_todo_Set.add(i)
            return
        img = self.data[tuple(self.zsec)][i]
        from . import useful as U
        mmms = U.mmms(img)
        self.mmms[i] = mmms
        #time import time
        #time x = time.clock()
        # print mmms

        from . import useful as U
        if self.hist_arr[i] is not None:
            #glSeb  import time
            #glSeb  x = time.clock()
            #         print U.mmms(self.hist_arr[i]),
            U.histogram(img,
                        amin=self.hist_min[i],
                        amax=self.hist_max[i],
                        histArr=self.hist_arr[i])
            #         print U.mmms(self.hist_arr[i])
            self.hist[i].setHist(self.hist_arr[i], self.hist_min[i],
                                 self.hist_max[i])
            #glSeb  print "ms: %.2f"% ((time.clock()-x)*1000.0)
            ## FIXME  setHist needs to NOT alloc xArray every time !!!
        else:
            resolution = 10000

            a_h = U.histogram(img, resolution, mmms[0], mmms[1])

            self.hist[i].setHist(a_h, mmms[0], mmms[1])
コード例 #4
0
ファイル: imgFit.py プロジェクト: macronucleus/Chromagnon
def _fitGaussian2DR(img, LD, y, x, sigma=[2.,2.], mean_max=None, window=5, rot=0, searchRot=None):
    """
    img: already cut out with indy, indx
    """
    if mean_max is None:
        mi, ma, me, sd = U.mmms(img)
        #ma = img[y,x]
    else:
        me, ma = mean_max

    if searchRot:
        param0 = (me, float(ma-me), y, x, float(sigma[0]), float(sigma[1]), rot)
    else:
        param0 = (me, float(ma-me), y, x, float(sigma[0]), float(sigma[1]))

    img = img.flatten()
    def func(p, shape, LD, rot):
        return yGaussian2DR(p, shape, LD, rot).flatten() - img

    from scipy import optimize
    ret, check = optimize.leastsq(func, param0,
                           args=((window,window), LD, rot), warning=None)
    if searchRot and ret[-1] < 0:
        ret[-1] += 90
    ret[4:] = N.abs(ret[4:])
    return ret, check
コード例 #5
0
ファイル: imgFit.py プロジェクト: macronucleus/Chromagnon
def _fitGaussian2D(img, indy, indx, y, x, sigma=[2.,2.], mean_max=None):
    """
    img: already cut out with indy, indx
    """
    if mean_max is None:
        mi, ma, me, sd = U.mmms(img)
        #ma = img[y,x]
    else:
        me, ma = mean_max

    try:
        sigma, sigma2 = sigma
        param0 = (me, float(ma-me), y, x, float(sigma), float(sigma2))
       # func = _gaussian2D_ellipse
    except (ValueError, TypeError):
        try: 
            len(sigma)
            sigma = [0]
        except TypeError:
            pass
        param0 = (me, float(ma-me), y, x, float(sigma))
        #func = _gaussian2D

    img = img.flatten()
    def func(p, indy, indx):
        return yGaussian2D(p, indy, indx) - img

    from scipy import optimize
    ret, check = optimize.leastsq(func, param0,
                           args=(indy.flatten(), indx.flatten()), warning=None)
    ret[2:4] += 0.5 # use pixel center
    ret[4:] = N.abs(ret[4:])
    return ret, check
コード例 #6
0
ファイル: imgFit.py プロジェクト: macronucleus/Chromagnon
def fitSkew1D(img, ts=None, sigma=0.5, exp=0):
    """
    img: 1D array containg one skewd gaussian peak
    """
    mi, ma, me, sd = U.mmms(img)
    ma, _1, _2, t = U.findMax(img)
    if ts is not None:
        t = ts[t]
        img = list(zip(ts, img))

    return U.fitAny(ySkew, (mi, ma-mi, t, sigma, exp), img, warning=None)
コード例 #7
0
ファイル: imgFit.py プロジェクト: iandobbie/Chromagnon
def fitSkew1D(img, ts=None, sigma=0.5, exp=0):
    """
    img: 1D array containg one skewd gaussian peak
    """
    mi, ma, me, sd = U.mmms(img)
    ma, _1, _2, t = U.findMax(img)
    if ts is not None:
        t = ts[t]
        img = list(zip(ts, img))

    return U.fitAny(ySkew, (mi, ma - mi, t, sigma, exp), img, warning=None)
コード例 #8
0
ファイル: splitND.py プロジェクト: macronucleus/Chromagnon
    def recalcHist(self, triggeredFromIdle):
        if not triggeredFromIdle:
            self.recalcHist_todo_Set.add(0)
            return

        #CHECK img = self.viewer.m_imgArr
        img = self.img
        from . import useful as U
        mmms = U.mmms( img )
        self.mmms = mmms
            #time import time
            #time x = time.clock()
            # print mmms

        if self.hist_arr is not None:
            #glSeb  import time
            #glSeb  x = time.clock()
            if sys.platform.startswith('linux'): # 20180712 win SIM error
                wx.Yield() # 20180406 dileptus linux
            U.histogram(img, amin=self.hist_min, amax=self.hist_max, histArr=self.hist_arr)
            self.hist.setHist(self.hist_arr, self.hist_min, self.hist_max)
            #glSeb  print "ms: %.2f"% ((time.clock()-x)*1000.0)
            ## FIXME  setHist needs to NOT alloc xArray every time !!!
        else:
        
            #          self.viewer.m_imgChanged = True
            #          self.viewer.Refresh(False)
    
            #20040915(OverflowError: float too large to convert)            resolution = int(mmms[1]-mmms[0]+2)
            #20040915if resolution > 10000:
            #20040915   resolution = 10000
            #20040915elif resolution < 1000: #CHECK
            #20040915   resolution = 10000 # CHECK
            resolution = 10000
    
            a_h = U.histogram(img, resolution, mmms[0], mmms[1])

            #    self.hist.setHist(a_h, mmms[0], mmms[1])
            self.recalcHist__a_h = a_h
            self.recalcHist__Done = 1
            #time print "recalcHist ms: %.2f"% ((time.clock()-x)*1000.0)
            #20171225 py2to3
            if wx.VERSION[0] <= 3:
                mainthread = wx.Thread_IsMain()
            elif wx.VERSION[0] >= 4:
                mainthread = wx.IsMainThread()
            if mainthread:#wx.IsMainThread():#Thread_IsMain():
                self.hist.setHist(self.recalcHist__a_h,
                                  self.mmms[0],
                                  self.mmms[1])
            else:
                wx.PostEvent(self.frame, self.__class__.ResultEvent(None))
コード例 #9
0
ファイル: imgFilters.py プロジェクト: macronucleus/Chromagnon
def arr_normalize(a, normalize_with='intens'):
    """
    normalize_with: intens or std
    """
    choices = ('intens', 'std')
    mi, ma, me, sd = U.mmms(a)
    if normalize_with == choices[0]:
        a = (a-mi) / (ma-mi)
    elif normalize_with == choices[1]:
        a = (a - me) / sd
    else:
        raise ValueError('normalize only with %s' % choices)
    return a
コード例 #10
0
ファイル: imgFilters.py プロジェクト: iandobbie/Chromagnon
def arr_normalize(a, normalize_with='intens'):
    """
    normalize_with: intens or std
    """
    choices = ('intens', 'std')
    mi, ma, me, sd = U.mmms(a)
    if normalize_with == choices[0]:
        a = (a - mi) / (ma - mi)
    elif normalize_with == choices[1]:
        a = (a - me) / sd
    else:
        raise ValueError('normalize only with %s' % choices)
    return a
コード例 #11
0
ファイル: splitND.py プロジェクト: iandobbie/Chromagnon
    def recalcHist(self, triggeredFromIdle):
        if not triggeredFromIdle:
            self.recalcHist_todo_Set.add(0)
            return

        #CHECK img = self.viewer.m_imgArr
        img = self.img
        from . import useful as U
        mmms = U.mmms(img)
        self.mmms = mmms
        #time import time
        #time x = time.clock()
        # print mmms

        if self.hist_arr is not None:
            #glSeb  import time
            #glSeb  x = time.clock()
            wx.Yield()  # 20180406 dileptus
            U.histogram(img,
                        amin=self.hist_min,
                        amax=self.hist_max,
                        histArr=self.hist_arr)
            self.hist.setHist(self.hist_arr, self.hist_min, self.hist_max)
            #glSeb  print "ms: %.2f"% ((time.clock()-x)*1000.0)
            ## FIXME  setHist needs to NOT alloc xArray every time !!!
        else:

            #          self.viewer.m_imgChanged = True
            #          self.viewer.Refresh(False)

            #20040915(OverflowError: float too large to convert)            resolution = int(mmms[1]-mmms[0]+2)
            #20040915if resolution > 10000:
            #20040915   resolution = 10000
            #20040915elif resolution < 1000: #CHECK
            #20040915   resolution = 10000 # CHECK
            resolution = 10000

            a_h = U.histogram(img, resolution, mmms[0], mmms[1])

            #    self.hist.setHist(a_h, mmms[0], mmms[1])
            self.recalcHist__a_h = a_h
            self.recalcHist__Done = 1
            #time print "recalcHist ms: %.2f"% ((time.clock()-x)*1000.0)
            #20171225 py2to3
            if wx.IsMainThread():  #Thread_IsMain():
                self.hist.setHist(self.recalcHist__a_h, self.mmms[0],
                                  self.mmms[1])
            else:
                wx.PostEvent(self.frame, self.__class__.ResultEvent(None))
コード例 #12
0
ファイル: imgFit.py プロジェクト: iandobbie/Chromagnon
def rot2D(img2D, yx, sigma, rlist, mean_max=None, win=11):
    y, x = yx
    yi, xi, LD = _indLD(win, y, x)
    imgP = img2D[yi, xi]
    if mean_max is None:
        mi, ma, me, sd = U.mmms(imgP)
    else:
        me, ma = mean_max

    yy = []
    for r in rlist:
        ret, check = _fitGaussian2DR(imgP, LD, y, x, sigma, [me, ma], win, r)
        syx = ret[4] / ret[5]  # width y / x
        yy.append(syx)
    return yy
コード例 #13
0
ファイル: imgFit.py プロジェクト: macronucleus/Chromagnon
def rot2D(img2D, yx, sigma, rlist, mean_max=None, win=11):
    y, x = yx
    yi, xi, LD = _indLD(win, y, x)
    imgP = img2D[yi,xi]
    if mean_max is None:
        mi, ma, me, sd = U.mmms(imgP)
    else:
        me, ma = mean_max

    yy = []
    for r in rlist:
        ret, check = _fitGaussian2DR(imgP, LD, y, x, sigma, [me,ma], win, r)
        syx = ret[4] / ret[5] # width y / x
        yy.append(syx)
    return yy
コード例 #14
0
ファイル: imgFit.py プロジェクト: macronucleus/Chromagnon
def rotND(img, zyx, sigma, rlist, mean_max=None, win=10):
   # y, x = yx
   # yi, xi, LD = _indLD(win, y, x)
    slices = imgGeo.nearbyRegion(img.shape, zyx, win)
    imgP = img[slices]
    if mean_max is None:
        mi, ma, me, sd = U.mmms(imgP)
    else:
        me, ma = mean_max

    yy = []
    for r in rlist:
        ret, check = fitGaussianND(img, zyx, sigma, win, [me, ma], r)#_fitGaussian2DR(imgP, LD, y, x, sigma, [me,ma], win, r)
        syx = ret[4] / ret[5] # width y / x
        yy.append(syx)
    return yy
コード例 #15
0
def findBestRefZs(ref, sigma=0.5):
    """
    PSF spread along the Z axis is often tilted in the Y or X axis.
    Thus simple maximum intensity projection may lead to the wrong answer to estimate rotation and magnification.
    On the other hands, taking a single section may also contain out of focus flare from neighboring sections that are tilted.
    Therefore, here sections with high complexity are selected and projected.

    An intensity-based method does not work for most (eg. tissue or bright field) images.
    Using variance is not enough for bright field image where the right focus loses contrast.
    Thus here we used sections containing higher frequency.

    ref: 3D array
    return z idx at the focus
    """
    from Priithon.all import F
    nz = ref.shape[0]
    if ref.ndim == 2:
        return [0]
    elif nz <= 3:
        return range(nz)

    # ring array
    ring = F.ringArr(ref.shape[-2:],
                     radius1=ref.shape[-1] // 10,
                     radius2=ref.shape[-2] // 4,
                     orig=(0, 0),
                     wrap=1)

    # Due to the roll up after FFT, the edge sections in Z may contain different information among the channels. Thus these sections are left unused.
    ms = N.zeros((nz - 2, ), N.float32)
    for z in xrange(1, nz - 1):
        af = F.rfft(N.ascontiguousarray(ref[z]))
        ar = af * ring[:, :af.shape[-1]]
        ms[z - 1] = N.sum(N.abs(ar))

        #ms[z-1] = N.prod(U.mmms(arr)[-2:]) # mean * std
    del ring, af, ar

    mi, ma, me, st = U.mmms(ms)
    thr = me + st * sigma

    ids = [idx for idx in range(1, nz - 1) if ms[idx - 1] > thr]
    if not ids:
        ids = range(1, nz - 1)

    return ids
コード例 #16
0
ファイル: imgFit.py プロジェクト: iandobbie/Chromagnon
def rotND(img, zyx, sigma, rlist, mean_max=None, win=10):
    # y, x = yx
    # yi, xi, LD = _indLD(win, y, x)
    slices = imgGeo.nearbyRegion(img.shape, zyx, win)
    imgP = img[slices]
    if mean_max is None:
        mi, ma, me, sd = U.mmms(imgP)
    else:
        me, ma = mean_max

    yy = []
    for r in rlist:
        ret, check = fitGaussianND(
            img, zyx, sigma, win, [me, ma],
            r)  #_fitGaussian2DR(imgP, LD, y, x, sigma, [me,ma], win, r)
        syx = ret[4] / ret[5]  # width y / x
        yy.append(syx)
    return yy
コード例 #17
0
ファイル: imgFit.py プロジェクト: macronucleus/Chromagnon
def _fitGaussianND(img, inds, zyx, sigma=0.5, mean_max=None):
    """
    img: already cut out
    """
    ndim = img.ndim
    if mean_max is None:
        mi, ma, me, sd = U.mmms(img)
    else:
        me, ma = mean_max

    try:
        if len(sigma) == ndim:
            sigma = [float(s) for s in sigma]
    except (ValueError, TypeError):
        sigma = [float(sigma) for i in range(ndim)]
    param0 = [me, float(ma-me)] + list(zyx) + sigma
    param0 = N.asarray(param0, N.float64)

    img = img.flatten()
    sidx = 2 + ndim
    def func(p, inds, sidx):
        return yGaussianND(p, inds, sidx) - img

    from scipy import optimize
    inds = [inds[i].flatten().astype(N.float64) for i in range(ndim)]
    if hasattr(optimize, 'least_squares'):
        ret = optimize.least_squares(func, param0, args=(inds, sidx))
        check = ret.status
        if check == -1:
            check = 5
        ret = ret.x
    else:
        try:
            ret, check = optimize.leastsq(func, param0,
                                          args=(inds,sidx), warning=None)
        except TypeError: # python2.6
            ret, check = optimize.leastsq(func, param0,
                                          args=(inds,sidx))
    #ret[2:5] -= 0.5
  #  ret[2:5] += 0.5 # use pixel center
    ret[sidx:] = N.abs(ret[sidx:])
    return ret, check
コード例 #18
0
ファイル: imgFit.py プロジェクト: iandobbie/Chromagnon
def _fitGaussian2DR(img,
                    LD,
                    y,
                    x,
                    sigma=[2., 2.],
                    mean_max=None,
                    window=5,
                    rot=0,
                    searchRot=None):
    """
    img: already cut out with indy, indx
    """
    if mean_max is None:
        mi, ma, me, sd = U.mmms(img)
        #ma = img[y,x]
    else:
        me, ma = mean_max

    if searchRot:
        param0 = (me, float(ma - me), y, x, float(sigma[0]), float(sigma[1]),
                  rot)
    else:
        param0 = (me, float(ma - me), y, x, float(sigma[0]), float(sigma[1]))

    img = img.flatten()

    def func(p, shape, LD, rot):
        return yGaussian2DR(p, shape, LD, rot).flatten() - img

    from scipy import optimize
    ret, check = optimize.leastsq(func,
                                  param0,
                                  args=((window, window), LD, rot),
                                  warning=None)
    if searchRot and ret[-1] < 0:
        ret[-1] += 90
    ret[4:] = N.abs(ret[4:])
    return ret, check
コード例 #19
0
ファイル: imgFit.py プロジェクト: iandobbie/Chromagnon
def _fitGaussianND(img, inds, zyx, sigma=0.5, mean_max=None):
    """
    img: already cut out
    """
    ndim = img.ndim
    if mean_max is None:
        mi, ma, me, sd = U.mmms(img)
    else:
        me, ma = mean_max

    try:
        if len(sigma) == ndim:
            sigma = [float(s) for s in sigma]
    except (ValueError, TypeError):
        sigma = [float(sigma) for i in range(ndim)]
    param0 = [me, float(ma - me)] + list(zyx) + sigma
    param0 = N.asarray(param0, N.float64)

    img = img.flatten()
    sidx = 2 + ndim

    def func(p, inds, sidx):
        return yGaussianND(p, inds, sidx) - img

    from scipy import optimize
    inds = [inds[i].flatten().astype(N.float64) for i in range(ndim)]
    try:
        ret, check = optimize.leastsq(func,
                                      param0,
                                      args=(inds, sidx),
                                      warning=None)
    except TypeError:  # python2.6
        ret, check = optimize.leastsq(func, param0, args=(inds, sidx))
    #ret[2:5] -= 0.5

#  ret[2:5] += 0.5 # use pixel center
    ret[sidx:] = N.abs(ret[sidx:])
    return ret, check
コード例 #20
0
ファイル: imgFit.py プロジェクト: iandobbie/Chromagnon
def _fitGaussian2D(img, indy, indx, y, x, sigma=[2., 2.], mean_max=None):
    """
    img: already cut out with indy, indx
    """
    if mean_max is None:
        mi, ma, me, sd = U.mmms(img)
        #ma = img[y,x]
    else:
        me, ma = mean_max

    try:
        sigma, sigma2 = sigma
        param0 = (me, float(ma - me), y, x, float(sigma), float(sigma2))
    # func = _gaussian2D_ellipse
    except (ValueError, TypeError):
        try:
            len(sigma)
            sigma = [0]
        except TypeError:
            pass
        param0 = (me, float(ma - me), y, x, float(sigma))
        #func = _gaussian2D

    img = img.flatten()

    def func(p, indy, indx):
        return yGaussian2D(p, indy, indx) - img

    from scipy import optimize
    ret, check = optimize.leastsq(func,
                                  param0,
                                  args=(indy.flatten(), indx.flatten()),
                                  warning=None)
    ret[2:4] += 0.5  # use pixel center
    ret[4:] = N.abs(ret[4:])
    return ret, check
コード例 #21
0
ファイル: imgFilters.py プロジェクト: iandobbie/Chromagnon
def Xcorr(a,
          b,
          highpassSigma=2.5,
          wiener=0.2,
          cutoffFreq=3,
          forceSecondPeak=None,
          acceptOrigin=True,
          maskSigmaFact=1.,
          removeY=None,
          removeX=None,
          ret=None,
          normalize=True,
          gFit=True,
          lap=None,
          win=11):
    """
    returns (y,x), image
    if ret is True, returns [v, yx, image]

    to get yx cordinate of the image,
    yx += N.divide(picture.shape, 2)

    a, b:            2D array
    highpassSigma:   sigma value used for highpass pre-filter
    wiener:          wiener value used for highpass pre-filter
    cutoffFreq:      kill lowest frequency component from 0 to this level
    forceSecondPeak: If input is n>0 (True is 1), pick up n-th peak
    acceptOrigin:    If None, result at origin is rejected, look for the next peak
    maskSigmaFact:   Modifier to remove previous peak to look for another peak
    removeYX:        Rremove given number of pixel high intensity lines of the Xcorr
                     Y: Vertical, X: Horizontal
    normalize:       intensity normalized
    gFit:            peak is fitted to 2D gaussian array, if None use center of mass
    win:             window for gFit

    if b is a + (y,x) then, answer is (-y,-x)
    """
    shapeA = N.asarray(a.shape)
    shapeB = N.asarray(b.shape)
    shapeM = N.max([shapeA, shapeB], axis=0)
    shapeM = N.where(shapeM % 2, shapeM + 1, shapeM)
    center = shapeM / 2.

    arrs = [a, b]
    arrsS = ['a', 'b']
    arrsF = []
    for i, arr in enumerate(arrs):
        if arr.dtype not in [N.float32, N.float64]:
            arr = N.asarray(arr, N.float32)
        # this convolution has to be done beforehand to remove 2 pixels at the edge
        if lap == 'nothing':
            pass
        elif lap:
            arr = arr_Laplace(arr, mask=2)
        else:
            arr = arr_sorbel(arr, mask=1)

        if N.sometrue(shapeA < shapeM):
            arr = paddingMed(arr, shapeM)

        if normalize:
            mi, ma, me, sd = U.mmms(arr)
            arr = (arr - me) / sd

        if i == 1:
            arr = F.shift(arr)
        af = F.rfft(arr)

        af = highPassF(af, highpassSigma, wiener, cutoffFreq)
        arrsF.append(af)

    # start cross correlation
    af, bf = arrsF
    bf = bf.conjugate()
    cf = af * bf

    # go back to space domain
    c = F.irfft(cf)
    #  c = _changeOrigin(cr)

    # removing lines
    if removeX:
        yi, xi = N.indices((removeX, shapeM[-1]))  #sx))
        yi += center[-2] - removeX / 2.  #sy/2 - removeX/2
        c[yi, xi] = 0
    if removeY:
        yi, xi = N.indices((shapeM[-2], removeY))  #sy, removeY))
        xi += center[-1] - removeY / 2.  #sx/2 - removeY/2
        c[yi, xi] = 0

    # find the first peak
    if gFit:
        v, yx, s = findMaxWithGFit(c, win=win)  #, window=win, gFit=gFit)
        if v == 0:
            v, yx, s = findMaxWithGFit(c, win=win +
                                       2)  #, window=win+2, gFit=gFit)
            if v == 0:
                v = U.findMax(c)[0]
        yx = N.add(yx, 0.5)
        #yx += 0.5
    else:
        vzyx = U.findMax(c)
        v = vzyx[0]
        yx = vzyx[-2:]
        s = 2.5

    yx -= center

    if N.alltrue(N.abs(yx) < 1.0) and not acceptOrigin:
        forceSecondPeak = True

    # forceSecondPeak:
    if not forceSecondPeak:
        forceSecondPeak = 0
    for i in range(int(forceSecondPeak)):
        print('%i peak was removed' % (i + 1))  #, sigma: %.2f' % (i+1, s)
        yx += center
        g = gaussianArr2D(c.shape, sigma=s / maskSigmaFact, peakVal=v, orig=yx)
        c = c - g
        #c = mask_gaussian(c, yx[0], yx[1], v, s)
        if gFit:
            v, yx, s = findMaxWithGFit(c, win=win)  #, window=win, gFit=gFit)
            if v == 0:
                v, yx, s = findMaxWithGFit(c, win=win +
                                           2)  #, window=win+2, gFit=gFit)
                if v == 0:
                    v = U.findMax(c)[0]
            yx -= (center - 0.5)
        else:
            vzyx = U.findMax(c)
            v = vzyx[0]

    if not gFit:
        yx = centerOfMass(c, vzyx[-2:]) - center
    if lap is not 'nothing':
        c = paddingValue(c, shapeM + 2)

    if ret == 2:
        return yx, af, bf.conjugate()
    elif ret:
        return v, yx, c
    else:
        return yx, c
コード例 #22
0
ファイル: imgFilters.py プロジェクト: macronucleus/Chromagnon
def Xcorr(a, b, highpassSigma=2.5, wiener=0.2, cutoffFreq=3,
forceSecondPeak=None, acceptOrigin=True, maskSigmaFact=1., removeY=None, removeX=None, ret=None, normalize=True, gFit=True, lap=None, win=11):
    """
    returns (y,x), image
    if ret is True, returns [v, yx, image]

    to get yx cordinate of the image,
    yx += N.divide(picture.shape, 2)

    a, b:            2D array
    highpassSigma:   sigma value used for highpass pre-filter
    wiener:          wiener value used for highpass pre-filter
    cutoffFreq:      kill lowest frequency component from 0 to this level
    forceSecondPeak: If input is n>0 (True is 1), pick up n-th peak
    acceptOrigin:    If None, result at origin is rejected, look for the next peak
    maskSigmaFact:   Modifier to remove previous peak to look for another peak
    removeYX:        Rremove given number of pixel high intensity lines of the Xcorr
                     Y: Vertical, X: Horizontal
    normalize:       intensity normalized
    gFit:            peak is fitted to 2D gaussian array, if None use center of mass
    win:             window for gFit

    if b is a + (y,x) then, answer is (-y,-x)
    """
    shapeA = N.asarray(a.shape)
    shapeB = N.asarray(b.shape)
    shapeM = N.max([shapeA, shapeB], axis=0)
    shapeM = N.where(shapeM % 2, shapeM+1, shapeM)
    center = shapeM / 2.

    arrs = [a,b]
    arrsS = ['a','b']
    arrsF = []
    for i, arr in enumerate(arrs):
        if arr.dtype not in [N.float32, N.float64]:
            arr = N.asarray(arr, N.float32)
        # this convolution has to be done beforehand to remove 2 pixels at the edge
        if lap == 'nothing':
            pass
        elif lap:
            arr = arr_Laplace(arr, mask=2)
        else:
            arr = arr_sorbel(arr, mask=1)
    
        if N.sometrue(shapeA < shapeM):
            arr = paddingMed(arr, shapeM)

        if normalize:
            mi, ma, me, sd = U.mmms(arr)
            arr = (arr - me) / sd
    
        if i ==1:
            arr = F.shift(arr)
        af = F.rfft(arr)

        af = highPassF(af, highpassSigma, wiener, cutoffFreq)
        arrsF.append(af)

    # start cross correlation
    af, bf = arrsF
    bf = bf.conjugate()
    cf = af * bf

    # go back to space domain
    c = F.irfft(cf)
  #  c = _changeOrigin(cr)

    # removing lines
    if removeX:
        yi, xi = N.indices((removeX, shapeM[-1]))#sx))
        yi += center[-2] - removeX/2.#sy/2 - removeX/2
        c[yi, xi] = 0
    if removeY:
        yi, xi = N.indices((shapeM[-2], removeY))#sy, removeY))
        xi += center[-1] - removeY/2.#sx/2 - removeY/2
        c[yi, xi] = 0

    # find the first peak
    if gFit:
        v, yx, s = findMaxWithGFit(c, win=win)#, window=win, gFit=gFit)
        if v == 0:
            v, yx, s = findMaxWithGFit(c, win=win+2)#, window=win+2, gFit=gFit)
            if v == 0:
                v = U.findMax(c)[0]
        yx = N.add(yx, 0.5)
        #yx += 0.5
    else:
        vzyx = U.findMax(c)
        v = vzyx[0]
        yx = vzyx[-2:]
        s = 2.5

    yx -= center

    if N.alltrue(N.abs(yx) < 1.0) and not acceptOrigin:
        forceSecondPeak = True

    # forceSecondPeak:
    if not forceSecondPeak:
        forceSecondPeak = 0
    for i in range(int(forceSecondPeak)):
        print('%i peak was removed' % (i+1)) #, sigma: %.2f' % (i+1, s)
        yx += center
        g = gaussianArr2D(c.shape, sigma=s/maskSigmaFact, peakVal=v, orig=yx)
        c = c - g
        #c = mask_gaussian(c, yx[0], yx[1], v, s)
        if gFit:
            v, yx, s = findMaxWithGFit(c, win=win)#, window=win, gFit=gFit)
            if v == 0:
                v, yx, s = findMaxWithGFit(c, win=win+2)#, window=win+2, gFit=gFit)
                if v == 0:
                    v = U.findMax(c)[0]
            yx -= (center - 0.5)
        else:
            vzyx = U.findMax(c)
            v = vzyx[0]

    if not gFit:
        yx = centerOfMass(c, vzyx[-2:]) - center
    if lap is not 'nothing':
        c = paddingValue(c, shapeM+2)

    if ret == 2:
        return yx, af, bf.conjugate()
    elif ret:
        return v, yx, c
    else:
        return yx, c