示例#1
0
def findMaxWithGFit(img, sigma=0.5, win=11):
    '''
    find sub-pixel peaks from input img using n-dimensional Guassian fitting

    sigma: scaler or [simgaZ,sigmaY..]
    window: a window where the Guassian fit is performed on

    return [v, zyx, sigma]
    '''
    imgFit.fitFailedClear()
    vzyx = U.findMax(img)
    ndim = img.ndim
    try:
        ret, check = imgFit.fitGaussianND(img, vzyx[-ndim:], sigma, win)
    except IndexError:  # too close to the edge
        imgFit.fitFailedAppend("at %s" % str(vzyx[-ndim:]))
        sigma = imgFit._scalerToSeq(sigma, ndim)
        return list(vzyx)[0:1] + [vzyx[-ndim:]] + [list(sigma)]

    if check == 5:
        imgFit.fitFailedAppend("at %s, %s, check=%i" %
                               (str(vzyx[-ndim:]), str(ret), check))
        sigma = imgFit._scalerToSeq(sigma, ndim)
        return list(vzyx)[0:1] + [vzyx[-ndim:]] + [sigma]
    else:
        v = ret[1]
        zyx = ret[2:2 + ndim]
        sigma = ret[2 + ndim:2 + ndim * 2]
        return [v, zyx, sigma]
示例#2
0
def paddingMed(img, shape, shift=None, smooth=10):
    """
    pad with median
    see doc for paddingValue
    """
    try:
        med = N.median(img, axis=None)
    except TypeError:  # numpy version < 1.1
        med = U.median(img)
    return paddingValue(img, shape, med, shift, smooth)
示例#3
0
def maskEdgeWithValue2D(arr, val=None):
    """
    overwrite 2D image edge (s[:-2,2:]) with value **in place**
    
    if val is None, use median
    """
    if not val:
        val = U.median(arr[:-2, 2:])
    arr[-2:] = val
    arr[:, :2] = val
    return arr
示例#4
0
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
示例#5
0
def getSphericalAbbe(arr3D, kmin=2, kmax=60, plot=False):
    """
    compare frequency above and below the focus

    return amplitude var(above)/var(below)
    """
    afz = getFourierZprofile(arr3D)

    # get z profile around the reasonable frequency
    aa = N.abs(N.average(afz[:, kmin:kmax], axis=1))
    # previously it was N.average(N.abs(afz[:,kmin:kmax]), axis=1), but that seems wrong...

    # findMax
    inds = N.indices(aa.shape, dtype=N.float64)
    v, _0, _1, z = U.findMax(aa)
    parm, check = imgFit.fitGaussianND(aa, [z], window=len(aa))
    if check == 5:
        raise RuntimeError, 'Peak not found check=%i' % check

    gg = imgFit.yGaussianND(parm, inds, 3)
    amg = aa - gg

    z0 = parm[2]
    mask = (parm[-1] * 3) / 2.  # sigma * 3 / 2
    ms0 = N.ceil(z0 - mask)
    ms1 = N.ceil(z0 + mask)
    amg[ms0:ms1] = 0

    below = N.var(amg[:ms0])
    above = N.var(amg[ms1:])

    if plot:
        Y.ploty(N.array((aa, gg, amg)))
        print 'below: ', below
        print 'above: ', above
        print ms0, ms1, z0

    return above / (above + below)  #above / below
示例#6
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
示例#7
0
def arr_invert(arr):
    canvas = N.empty_like(arr)
    canvas[:] = U.max(arr)
    return canvas - arr