Exemple #1
0
def mexhatFilter(a, mexSize=1):#, trimRatio=0.9):
    """
    returned array is trimmed to remove edge
    """
    global mexhatC, mexhatC_size, mexhatCf

    a = imgFilters.evenShapeArr(a)
    from Priithon.all import F as fftw
    try:
        if mexhatC.shape != a.shape:
            raise ValueError('go to except')
        if mexhatC_size != mexSize:
            raise ValueError('go to except')
    except NameError as ValueError:
        mexhatC_size = mexSize
        shape = N.asarray(a.shape, N.int)#N.float32)
        mexhatC = F.shift(F.mexhatArr(shape, scaleHalfMax=mexhatC_size, orig=None)) # orig 0.5 pixel does not work...
        mexhatCf = fftw.rfft(mexhatC) / N.multiply.reduce( shape )

    ar = fftw.irfft( fftw.rfft(a.astype(N.float32)) * mexhatCf )
    
    #if trimRatio < 1:
    #    ar = trim3D(ar, trimRatio)
    #ar = imgFilters.maskEdgeWithValue2D(ar) # 2 pixels at the edges
    return ar
Exemple #2
0
def mexhatFilter(a, mexSize=1):  #, trimRatio=0.9):
    """
    returned array is trimmed to remove edge
    """
    global mexhatC, mexhatC_size, mexhatCf

    a = imgFilters.evenShapeArr(a)
    from Priithon.all import F as fftw
    try:
        if mexhatC.shape != a.shape:
            raise ValueError('go to except')
        if mexhatC_size != mexSize:
            raise ValueError('go to except')
    except NameError as ValueError:
        mexhatC_size = mexSize
        shape = N.asarray(a.shape, N.int)  #N.float32)
        mexhatC = F.shift(
            F.mexhatArr(shape, scaleHalfMax=mexhatC_size,
                        orig=None))  # orig 0.5 pixel does not work...
        mexhatCf = fftw.rfft(mexhatC) / N.multiply.reduce(shape)

    ar = fftw.irfft(fftw.rfft(a.astype(N.float32)) * mexhatCf)

    #if trimRatio < 1:
    #    ar = trim3D(ar, trimRatio)
    #ar = imgFilters.maskEdgeWithValue2D(ar) # 2 pixels at the edges
    return ar
Exemple #3
0
def phaseContrastFilter(a, inFourier=False, removeNan=True, nyquist=0.6):
    global GAUSS
    if inFourier:
        af = a.copy()
    else:
        af = F.rfft(a)

    # here is the phase contrast
    amp = N.abs(af)
    afa = af / amp

    if removeNan:
        afa = nanFilter(afa)

    # lowpass gaussian filter of phase image
    if nyquist:  # since this takes long time, gaussian array is re-used if possible
        if GAUSS is not None and GAUSS[0] == nyquist and GAUSS[
                1].shape == afa.shape:
            nq, gf = GAUSS
        else:
            sigma = af.shape[-1] * nyquist
            gf = F.gaussianArr(afa.shape,
                               sigma,
                               peakVal=1,
                               orig=0,
                               wrap=(1, ) * (afa.ndim - 1) +
                               (0, ))  #, dtype=afa.dtype.type)
            GAUSS = (nyquist, gf)
        afa *= gf

    if inFourier:
        ap = afa
    else:
        ap = F.irfft(afa)
    return ap
Exemple #4
0
    def OnAutoFocus(self, evt=None):
        """
        please read Chromagnon.alignfuncs.findBestRefZs() for detail of the logic
        """
        if self.doc.nt > 1:
            t = int(self.tSliderBox.GetValue())
        else:
            t = 0
        ws = [
            w for w, hist in enumerate(self.hist_toggleButton)
            if hist.GetValue()
        ]

        ms = N.zeros((len(ws), self.doc.nz), N.float32)

        # FFTW does not work with another program using it
        # here is the workaround for Chromagnon
        try:
            batch = self.GetParent().GetParent().GetParent()
            if hasattr(batch, 'th') and batch.th.isAlive():
                for wi, w in enumerate(ws):
                    arr = self.doc.get3DArr(t=t, w=w)
                    for z in range(self.doc.nz):
                        ms[wi, z] = N.prod(U.mmms(arr[z])[-2:])  # mean * std
                v, _, w, z = U.findMax(ms)
                self.zSliderBox.SetValue(str(z))
                self.OnZSliderBox()
                self.OnAutoScale()

                G.openMsg(
                    parent=self.parent,
                    msg=
                    'A clumsy focusing method was used since another program was using FFTW.\nPlease wait for the better method until the other program is done.',
                    title="Please wait")
                return
        except AttributeError:  # no parent?
            pass

        # Frequency-based caluculation starts
        from Priithon.all import F

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

        for wi, w in enumerate(ws):
            arr = self.doc.get3DArr(t=t, w=w)
            arr = arr / arr.mean()
            for z in range(self.doc.nz):
                af = F.rfft(N.ascontiguousarray(arr[z]))
                ar = af * ring[:, :af.shape[-1]]
                ms[wi, z] = N.sum(N.abs(ar))
        v, _, w, z = U.findMax(ms)

        self.zSliderBox.SetValue(str(z))
        self.OnZSliderBox()
        self.OnAutoScale()
Exemple #5
0
    def OnAutoFocus(self, evt=None):
        """
        please read Chromagnon.alignfuncs.findBestRefZs() for detail of the logic
        """
        if self.doc.nt > 1:
            t = int(self.tSliderBox.GetValue())
        else:
            t = 0
        ws = [w for w, hist in enumerate(self.hist_toggleButton) if hist.GetValue()]

        ms = N.zeros((len(ws),self.doc.nz), N.float32)

        # FFTW does not work with another program using it
        # here is the workaround for Chromagnon
        try:
            batch = self.GetParent().GetParent().GetParent()
            if hasattr(batch, 'th') and batch.th.isAlive():
                for wi, w in enumerate(ws):
                    arr = self.doc.get3DArr(t=t, w=w)
                    for z in range(self.doc.nz):
                        ms[wi,z] = N.prod(U.mmms(arr[z])[-2:]) # mean * std
                v,_,w,z = U.findMax(ms)
                self.zSliderBox.SetValue(str(z))
                self.OnZSliderBox()
                self.OnAutoScale()
                        
                G.openMsg(parent=self.parent, msg='A clumsy focusing method was used since another program was using FFTW.\nPlease wait for the better method until the other program is done.', title="Please wait")
                return
        except AttributeError: # no parent?
            pass

        # Frequency-based caluculation starts 
        from Priithon.all import F
        
        ring = F.ringArr(self.doc.shape[-2:], radius1=self.doc.shape[-1]//10, radius2=self.doc.shape[-2]//4, orig=(0,0), wrap=1)


        for wi, w in enumerate(ws):
            arr = self.doc.get3DArr(t=t, w=w)
            arr = arr / arr.mean()
            for z in range(self.doc.nz):
                af = F.rfft(N.ascontiguousarray(arr[z]))
                ar = af * ring[:,:af.shape[-1]]
                ms[wi,z] = N.sum(N.abs(ar))
        v,_,w,z = U.findMax(ms)

        self.zSliderBox.SetValue(str(z))
        self.OnZSliderBox()
        self.OnAutoScale()
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
Exemple #7
0
def mexhatFilter(a, mexSize=1):  #, trimRatio=0.9):
    """
    returned array is trimmed to remove edge
    """
    global mexhatC, mexhatC_size, mexhatCf

    a = imgFilters.evenShapeArr(a)
    try:  # inside package
        from ..Priithon.all import F as fftw
    except ValueError:  # Attempted relative import beyond toplevel package
        from Priithon.all import F as fftw
    #from Priithon.all import F as fftw
    try:
        if mexhatC.shape != a.shape:
            raise ValueError, 'go to except'
        if mexhatC_size != mexSize:
            raise ValueError, 'go to except'
    except NameError, ValueError:
        mexhatC_size = mexSize
        shape = N.asarray(a.shape, N.float32)
        mexhatC = F.shift(
            F.mexhatArr(shape, scaleHalfMax=mexhatC_size,
                        orig=None))  # orig 0.5 pixel does not work...
        mexhatCf = fftw.rfft(mexhatC) / N.multiply.reduce(shape)
Exemple #8
0
def phaseContrastFilter(a, inFourier=False, removeNan=True, nyquist=0.6):
    global GAUSS
    if inFourier:
        af = a.copy()
    else:
        af = F.rfft(a)

    # here is the phase contrast
    amp = N.abs(af)
    afa = af / amp

    if removeNan:
        afa = nanFilter(afa)

    # lowpass gaussian filter of phase image
    if nyquist: # since this takes long time, gaussian array is re-used if possible
        if GAUSS is not None and GAUSS[0] == nyquist and GAUSS[1].shape == afa.shape:
            nq, gf = GAUSS
        else:
            #sigma = af.shape[-1] * nyquist
            #gf = F.gaussianArr(afa.shape, sigma, peakVal=1, orig=0, wrap=(1,)*(afa.ndim-1)+(0,))#, dtype=afa.dtype.type)
            gshape = N.array(af.shape)
            if inFourier:
                gshape[-1] *= 2
            sigma = gshape * nyquist
            gf = imgFilters.gaussianArrND(gshape, sigma, peakVal=1)
            gf = N.fft.fftshift(gf)[Ellipsis, :af.shape[-1]]
            
            GAUSS = (nyquist, gf)
        afa *= gf

    if inFourier:
        ap = afa
    else:
        ap = F.irfft(afa)
    return ap
Exemple #9
0
def Xcorr(a,
          b,
          phaseContrast=PHASE,
          nyquist=NYQUIST,
          removeEdge=0,
          gFit=True,
          win=11,
          ret=None,
          searchRad=None):
    """
    sigma uses F.gaussianArr in the Fourier domain
    if ret is None:
        return zyx, xcf
    elif ret is 2:
        return s, v, zyx, xcf
    elif ret:
        return v, zyx, xcf
    """
    #print 'phase contrast: %s' % str(phaseContrast)
    #global DATA
    # correct odd shape particularly Z axis
    a = N.squeeze(a)
    b = N.squeeze(b)
    a = imgFilters.evenShapeArr(a)
    b = imgFilters.evenShapeArr(b)
    shape = N.array(a.shape)

    # apodize
    a = apodize(a)
    b = apodize(b)

    # fourier transform
    af = F.rfft(a.astype(N.float32))
    bf = F.rfft(b.astype(N.float32))
    del a, b

    # phase contrast filter (removing any intensity information)
    if phaseContrast:
        afa = phaseContrastFilter(af, True, nyquist=nyquist)
        bfa = phaseContrastFilter(bf, True, nyquist=nyquist)
    else:
        afa = af
        bfa = bf
    del af, bf

    # removing edge if gaussian is not sufficient
    targetShape = shape - N.multiply(removeEdge, 2)
    if removeEdge:
        ap = imgFilters.cutOutCenter(F.irfft(afa), targetShape)
        bp = imgFilters.cutOutCenter(F.irfft(bfa), targetShape)
        afa = F.rfft(ap)
        bfa = F.rfft(bp)
        del ap, bp

    # shift array
    delta = targetShape / 2.
    shiftarr = F.fourierRealShiftArr(tuple(targetShape), delta)
    bfa *= shiftarr

    # cross correlation
    bfa = bfa.conjugate()
    c = cc = F.irfft(afa * bfa)

    center = N.divide(c.shape, 2)
    if searchRad:
        slc = imgGeo.nearbyRegion(c.shape, center, searchRad)
        cc = N.zeros_like(c)
        cc[slc] = c[slc]
    v, zyx, s = _findMaxXcor(cc, win, gFit=gFit)
    zyx -= center

    if ret == 2:
        return s, v, zyx, c
    elif ret:
        return v, zyx, c
    else:
        return zyx, c
Exemple #10
0
        from Priithon.all import F as fftw
    #from Priithon.all import F as fftw
    try:
        if mexhatC.shape != a.shape:
            raise ValueError, 'go to except'
        if mexhatC_size != mexSize:
            raise ValueError, 'go to except'
    except NameError, ValueError:
        mexhatC_size = mexSize
        shape = N.asarray(a.shape, N.float32)
        mexhatC = F.shift(
            F.mexhatArr(shape, scaleHalfMax=mexhatC_size,
                        orig=None))  # orig 0.5 pixel does not work...
        mexhatCf = fftw.rfft(mexhatC) / N.multiply.reduce(shape)

    ar = fftw.irfft(fftw.rfft(a.astype(N.float32)) * mexhatCf)

    #if trimRatio < 1:
    #    ar = trim3D(ar, trimRatio)
    #ar = imgFilters.maskEdgeWithValue2D(ar) # 2 pixels at the edges
    return ar


GAUSS = None


def phaseContrastFilter(a, inFourier=False, removeNan=True, nyquist=0.6):
    global GAUSS
    if inFourier:
        af = a.copy()
    else:
Exemple #11
0
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
Exemple #12
0
def Xcorr(a, b, phaseContrast=PHASE, nyquist=NYQUIST, gFit=True, win=11, ret=None, searchRad=None, npad=4):
    """
    sigma uses F.gaussianArr in the Fourier domain
    if ret is None:
        return zyx, xcf
    elif ret is 2:
        return s, v, zyx, xcf
    elif ret is 3:
        return zyx, xcf, a_phase_cotrast, b_phase_contrast
    elif ret:
        return v, zyx, xcf
    """
    #print 'phase contrast: %s' % str(phaseContrast)
    #global DATA
    # correct odd shape particularly Z axis
    a = N.squeeze(a)
    b = N.squeeze(b)
    a = imgFilters.evenShapeArr(a)
    b = imgFilters.evenShapeArr(b)
    shape = N.array(a.shape)

    # padding strange shape
    #nyx = max(shape[-2:])
    #pshape = N.array(a.shape[:-2] + (nyx,nyx))

    # apodize
    a = paddAndApo(a, npad)#, pshape) #apodize(a)
    b = paddAndApo(b, npad)#, pshape) #apodize(b)

    # fourier transform
    af = F.rfft(a.astype(N.float32))
    bf = F.rfft(b.astype(N.float32))
    del a, b

    # phase contrast filter (removing any intensity information)
    if phaseContrast:
        afa = phaseContrastFilter(af, True, nyquist=nyquist)
        bfa = phaseContrastFilter(bf, True, nyquist=nyquist)
    else:
        afa = af
        bfa = bf
    del af, bf

    #targetShape = shape + (npad * 2)
    targetShape = shape + (npad * 2)

    # shift array
    delta = targetShape / 2.
    shiftarr = F.fourierRealShiftArr(tuple(targetShape), delta)
    bfa *= shiftarr

    # cross correlation
    bfa = bfa.conjugate()
    #c = cc = F.irfft(afa * bfa)
    c = F.irfft(afa * bfa)

    # 20180214 the padded region was cutout before finding the peak.
    c = cc = imgFilters.cutOutCenter(c, N.array(c.shape) - (npad * 2), interpolate=False)
    #cc = c
    center = N.divide(c.shape, 2)
    if searchRad:
        slc = imgGeo.nearbyRegion(c.shape, center, searchRad)
        cc = N.zeros_like(c)
        cc[slc] = c[slc]
    v, zyx, s = _findMaxXcor(cc, win, gFit=gFit)
    #return cc
    #print(zyx, center)
    zyx -= center

    #c = imgFilters.cutOutCenter(c, N.array(c.shape) - (npad * 2), interpolate=False)
    #c = imgFilters.cutOutCenter(c, shape, interpolate=False)

    if ret == 3:
        return zyx, c, F.irfft(afa), F.irfft(bfa)
    elif ret == 2:
        return s, v, zyx, c
    elif ret:
        return v, zyx, c
    else:
        return zyx, c
Exemple #13
0
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
Exemple #14
0
def Xcorr(a,
          b,
          phaseContrast=PHASE,
          nyquist=NYQUIST,
          gFit=True,
          win=11,
          ret=None,
          searchRad=None,
          npad=4):
    """
    sigma uses F.gaussianArr in the Fourier domain
    if ret is None:
        return zyx, xcf
    elif ret is 2:
        return s, v, zyx, xcf
    elif ret is 3:
        return zyx, xcf, a_phase_cotrast, b_phase_contrast
    elif ret:
        return v, zyx, xcf
    """
    #print 'phase contrast: %s' % str(phaseContrast)
    #global DATA
    # correct odd shape particularly Z axis
    a = N.squeeze(a)
    b = N.squeeze(b)
    a = imgFilters.evenShapeArr(a)
    b = imgFilters.evenShapeArr(b)
    shape = N.array(a.shape)

    # padding strange shape
    #nyx = max(shape[-2:])
    #pshape = N.array(a.shape[:-2] + (nyx,nyx))

    # apodize
    a = paddAndApo(a, npad)  #, pshape) #apodize(a)
    b = paddAndApo(b, npad)  #, pshape) #apodize(b)

    # fourier transform
    af = F.rfft(a.astype(N.float32))
    bf = F.rfft(b.astype(N.float32))
    del a, b

    # phase contrast filter (removing any intensity information)
    if phaseContrast:
        afa = phaseContrastFilter(af, True, nyquist=nyquist)
        bfa = phaseContrastFilter(bf, True, nyquist=nyquist)
    else:
        afa = af
        bfa = bf
    del af, bf

    #targetShape = shape + (npad * 2)
    targetShape = shape + (npad * 2)

    # shift array
    delta = targetShape / 2.
    shiftarr = F.fourierRealShiftArr(tuple(targetShape), delta)
    bfa *= shiftarr

    # cross correlation
    bfa = bfa.conjugate()
    c = cc = F.irfft(afa * bfa)

    center = N.divide(c.shape, 2)
    if searchRad:
        slc = imgGeo.nearbyRegion(c.shape, center, searchRad)
        cc = N.zeros_like(c)
        cc[slc] = c[slc]
    v, zyx, s = _findMaxXcor(cc, win, gFit=gFit)
    zyx -= center

    c = imgFilters.cutOutCenter(c,
                                N.array(c.shape) - (npad * 2),
                                interpolate=False)
    #c = imgFilters.cutOutCenter(c, shape, interpolate=False)

    if ret == 3:
        return zyx, c, F.irfft(afa), F.irfft(bfa)
    elif ret == 2:
        return s, v, zyx, c
    elif ret:
        return v, zyx, c
    else:
        return zyx, c