Exemplo n.º 1
0
def _doBilinear2D(a2d, tyx=(0,0), r=0, mag=1, anismag=1, dyx=(0,0), mr=0, b2d=None):
    if b2d is None:
        b2d = N.empty_like(a2d)
    else:
        b2d = N.ascontiguousarray(b2d)
    a2d = a2d.copy() # otherwise, the following code will mess up the input

    if N.any(dyx[-2:]) or mr:
        temp = b2d
        target = a2d
        U.trans2d(target, temp, (dyx[-1], dyx[-2], mr, 1, 0, 1))
    else:
        temp = a2d
        target = b2d

    # rot mag first to make consistent with affine
    magaxis = 1 # only this axis works
    if r or mag != 1 or anismag != 1:
        U.trans2d(temp, target, (0, 0, r, mag, magaxis, anismag))
    else:
        target[:] = temp[:]

    # then translate
    tyx2 = N.array(tyx) # copy
    tyx2[-2:] -= dyx[-2:]
    if N.any(tyx2[-2:]) or mr:
        U.trans2d(target, temp, (tyx2[-1], tyx2[-2], -mr, 1, 0, 1))
    else:
        temp[:] = target[:]
    #a[z] = temp[:]
    return temp
Exemplo n.º 2
0
def remap(img, mapy, mapx, interp=2):
    """
    transform image using coordinate x,y

    Interpolation method:
    0 = CV_INTER_NN nearest-neigbor interpolation
    1 = CV_INTER_LINEAR bilinear interpolation (used by default)
    2 = CV_INTER_CUBIC bicubic interpolation
    3 = CV_INTER_AREA resampling using pixel area relation. It is the preferred method for image decimation that gives moire-free results. In terms of zooming it is similar to the CV_INTER_NN method

    return resulting array
    """
    des = N.zeros_like(img)

    # cv.fromarray: array can be 2D or 3D only
    if cv2.__version__.startswith('2'):
        cimg = cv.fromarray(img)
        cdes = cv.fromarray(des)

        cmapx = cv.fromarray(mapx.astype(N.float32))
        cmapy = cv.fromarray(mapy.astype(N.float32))
        
        cv.Remap(cimg, cdes, cmapx, cmapy, flags=interp+cv.CV_WARP_FILL_OUTLIERS)
    else:
        cimg = img
        #cdes = des
        cmapx = mapx.astype(N.float32)
        cmapy = mapy.astype(N.float32)

        cdes = cv2.remap(cimg, cmapx, cmapy, interp)

    return N.asarray(cdes)
Exemplo n.º 3
0
def gaussianArrND(shape=(256,256), sigma=2., peakVal=None, orig=None, rot=0):
    try:
        ndim = len(shape)
    except TypeError:
        shape = [shape]
        ndim = 1
    sidx = ndim + 2
    slices = [Ellipsis] + [slice(0,m) for m in shape]
    inds, LD = imgFit.rotateIndicesND(slices, N.float32, rot)
    #inds = N.indices(shape, N.float32)

    try:
        if len(sigma) != ndim:
            raise ValueError('len(sigma) must be the same as len(shape)')
    except TypeError:
        sigma = [sigma] * ndim

    if orig is None:
        c = N.asarray(shape, N.float32)/2.
    else:
        c = N.asarray(orig, N.float32)

    if peakVal:
        k0 = peakVal
    else:
        k0 = 1. / (N.average(sigma) * ((2*N.pi)**0.5))

    param = [0, k0] + list(c) + list(sigma)
    param = N.asarray(param, N.float32)
    return imgFit.yGaussianND(param, inds, sidx)
Exemplo n.º 4
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]
    '''
    vzyx = N.array(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 vzyx[0:1], vzyx[-ndim:], list(sigma)

    if check == 5 or N.any(ret[2:2+ndim] > (vzyx[-ndim:] + win)) or  N.any(ret[2:2+ndim] < (vzyx[-ndim:] - win)):
        imgFit.fitFailedAppend("at %s, %s, check=%i" % (str(vzyx[-ndim:]), str(ret), check))
        sigma = imgFit._scalerToSeq(sigma, ndim)
        return [vzyx[0:1], vzyx[-ndim:], sigma]
    #x= (vzyx[0:1] + [vzyx[-ndim:]] + [sigma])
    #    print x
    #    return x
    else:
        v = ret[1]
        zyx = ret[2:2+ndim]
        sigma = ret[2+ndim:2+ndim*2]
        return [v,zyx,sigma]
Exemplo n.º 5
0
def apodize(img, napodize=10, doZ=True):
    """
    softens the edges of a singe xy section to reduce edge artifacts and improve the fits

    return copy of the img
    """
    img = img.copy()
    img = img.astype(N.float32)  # casting rule

    # determine napodize
    shape = N.array(img.shape) // 2
    napodize = N.where(shape < napodize, shape, napodize)
    if doZ and img.ndim >= 3 and img.shape[0] > 3:
        rr = range(-3, 0)
    else:
        rr = range(-2, 0)
    for idx in rr:
        fact = N.arange(1. / napodize[idx],
                        napodize[idx],
                        1. / napodize[idx],
                        dtype=N.float32)[:napodize[idx]]
        for napo in range(napodize[idx]):
            slc0 = [Ellipsis, slice(napo, napo + 1)
                    ] + [slice(None)] * abs(idx + 1)
            if not napo:
                slc1 = [Ellipsis, slice(-(napo + 1), None)
                        ] + [slice(None)] * abs(idx + 1)
            else:
                slc1 = [Ellipsis, slice(-(napo + 1), -(napo))
                        ] + [slice(None)] * abs(idx + 1)
            img[slc0] *= fact[napo]
            img[slc1] *= fact[napo]
            #img[slc0] = img[slc0] * fact[napo] # casting rule
            #img[slc1] = img[scl1] * fact[napo]
    return img
Exemplo n.º 6
0
def gaussianArrND(shape=(256, 256), sigma=2., peakVal=None, orig=None, rot=0):
    try:
        ndim = len(shape)
    except TypeError:
        shape = [shape]
        ndim = 1
    sidx = ndim + 2
    slices = [Ellipsis] + [slice(0, m) for m in shape]
    inds, LD = imgFit.rotateIndicesND(slices, N.float32, rot)
    #inds = N.indices(shape, N.float32)

    try:
        if len(sigma) != ndim:
            raise ValueError('len(sigma) must be the same as len(shape)')
    except TypeError:
        sigma = [sigma] * ndim

    if orig is None:
        c = N.asarray(shape, N.float32) / 2.
    else:
        c = N.asarray(orig, N.float32)

    if peakVal:
        k0 = peakVal
    else:
        k0 = 1. / (N.average(sigma) * ((2 * N.pi)**0.5))

    param = [0, k0] + list(c) + list(sigma)
    param = N.asarray(param, N.float32)
    return imgFit.yGaussianND(param, inds, sidx)
Exemplo n.º 7
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]
    '''
    vzyx = N.array(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 vzyx[0:1], vzyx[-ndim:], list(sigma)

    if check == 5 or N.any(ret[2:2 + ndim] > (vzyx[-ndim:] + win)) or N.any(
            ret[2:2 + ndim] < (vzyx[-ndim:] - win)):
        imgFit.fitFailedAppend("at %s, %s, check=%i" %
                               (str(vzyx[-ndim:]), str(ret), check))
        sigma = imgFit._scalerToSeq(sigma, ndim)
        return [vzyx[0:1], vzyx[-ndim:], sigma]
    #x= (vzyx[0:1] + [vzyx[-ndim:]] + [sigma])
    #    print x
    #    return x
    else:
        v = ret[1]
        zyx = ret[2:2 + ndim]
        sigma = ret[2 + ndim:2 + ndim * 2]
        return [v, zyx, sigma]
Exemplo n.º 8
0
def _doBilinear2D(a2d, tyx=(0,0), r=0, mag=1, anismag=1, dyx=(0,0), mr=0, b2d=None):
    if b2d is None:
        b2d = N.empty_like(a2d)
    else:
        b2d = N.ascontiguousarray(b2d)
    a2d = a2d.copy() # otherwise, the following code will mess up the input

    if N.any(dyx[-2:]) or mr:
        temp = b2d
        target = a2d
        U.trans2d(target, temp, (dyx[-1], dyx[-2], mr, 1, 0, 1))
    else:
        temp = a2d
        target = b2d

    # rot mag first to make consistent with affine
    magaxis = 1 # only this axis works
    if r or mag != 1 or anismag != 1:
        U.trans2d(temp, target, (0, 0, r, mag, magaxis, anismag))
    else:
        target[:] = temp[:]

    # then translate
    tyx2 = N.array(tyx) # copy
    tyx2[-2:] -= dyx[-2:]
    if N.any(tyx2[-2:]) or mr:
        U.trans2d(target, temp, (tyx2[-1], tyx2[-2], -mr, 1, 0, 1))
    else:
        temp[:] = target[:]
    #a[z] = temp[:]
    return temp
Exemplo n.º 9
0
def _cutoutForAlign2(fn, py, outFn=''):
    """
    if not outFn, default with 'cut' extention
    resulting array is imgSequence=0 (t,w,z,y,x)
    return outFn
    """
    h = imgManager.ImageManager(fn)
    slc, shiftZYX, ZYX = makeSlice(h, py)

    # input
    arr = N.empty((h.nt, h.nw, h.nz, h.ny, h.nx), h.dtype)
    for t in range(h.nt):
        for w in range(h.nw):
            arr[t, w] = h.get3DArr(w=w, t=t)

    canvas = N.squeeze(arr[slc].astype(arr.dtype.type))
    newNum = (canvas.shape[-1], canvas.shape[-2], N.prod(canvas.shape[:-3]))
    if not outFn:
        outFn = '_'.join((h.filePath, EXT_CUTOUT))  #arr.Mrc.path, EXT_CUTOUT))
    hdr = Mrc.makeHdrArray()
    Mrc.initHdrArrayFrom(hdr, h.hdr)  #arr.Mrc.hdr)
    hdr.ImgSequence = 2
    hdr.Num[:] = newNum
    mstart = [sl.start for sl in slc[::-1][:3] if isinstance(sl, slice)]
    hdr.mst[:len(mstart)] += mstart

    Mrc.save(canvas, outFn, ifExists='overwrite', hdr=hdr)
    return outFn
Exemplo n.º 10
0
def remap(img, mapy, mapx, interp=2):
    """
    transform image using coordinate x,y

    Interpolation method:
    0 = CV_INTER_NN nearest-neigbor interpolation
    1 = CV_INTER_LINEAR bilinear interpolation (used by default)
    2 = CV_INTER_CUBIC bicubic interpolation
    3 = CV_INTER_AREA resampling using pixel area relation. It is the preferred method for image decimation that gives moire-free results. In terms of zooming it is similar to the CV_INTER_NN method

    return resulting array
    """
    des = N.empty_like(img)

    # cv.fromarray: array can be 2D or 3D only
    if cv2.__version__.startswith('2'):
        cimg = cv.fromarray(img)
        cdes = cv.fromarray(des)

        cmapx = cv.fromarray(mapx.astype(N.float32))
        cmapy = cv.fromarray(mapy.astype(N.float32))
        
        cv.Remap(cimg, cdes, cmapx, cmapy, flags=interp+cv.CV_WARP_FILL_OUTLIERS)
    else:
        cimg = img
        cdes = des
        cmapx = mapx.astype(N.float32)
        cmapy = mapy.astype(N.float32)

        cdes = cv2.remap(cimg, cmapx, cmapy, interp)

    return N.asarray(cdes)
Exemplo n.º 11
0
    def selectZsecs(self, start=0, stop=None, pattern=[1], pickWhich=1):
        """
        stores section indices to be picked up when doing copy region

        pattern:  smallest pattern of elements eg. [1,1,0,2]
        pickWich: sections corresponding this number in the pattern is picked up
        """
        if stop is None:
            stop = self.cropbox_u[0]
        if start is None:
            start = self.cropbox_l[0]

        unit = len(pattern)

        idx = N.arange(self.nz)
        repeat = N.ceil(self.nz / float(unit))
        repPat = N.tile(pattern, repeat)[:self.nz]
        ids = N.compress(repPat == pickWhich, idx)
        self._zIdx = [i for i in ids if i >= start and i < stop]
        if not self._zIdx:
            self._zIdx = [0]
            print self._zIdx

        self.cropbox_l[0] = start
        self.cropbox_u[0] = stop
        if self.cropbox_l[0] == self.cropbox_u[0]:
            self.cropbox_u[0] += 1

        self._zPtrn = pattern
        self._zPick = pickWhich
Exemplo n.º 12
0
def apodize(img, napodize=10, doZ=True):
    """
    softens the edges of a singe xy section to reduce edge artifacts and improve the fits

    return copy of the img
    """
    img = img.copy()
    img = img.astype(N.float32) # casting rule

    # determine napodize
    shape = N.array(img.shape) // 2
    napodize = N.where(shape < napodize, shape, napodize)
    if doZ and img.ndim >= 3 and img.shape[0] > 3:
        rr = list(range(-3,0))
    else:
        rr = list(range(-2,0))
    for idx in rr:
        fact = N.arange(1./napodize[idx],napodize[idx],1./napodize[idx], dtype=N.float32)[:napodize[idx]]
        for napo in range(napodize[idx]):
            slc0 = [Ellipsis,slice(napo, napo+1)] + [slice(None)] * abs(idx+1)
            if not napo:
                slc1 = [Ellipsis,slice(-(napo+1),None)] + [slice(None)] * abs(idx+1)
            else:
                slc1 = [Ellipsis,slice(-(napo+1),-(napo))] + [slice(None)] * abs(idx+1)
            img[slc0] *= fact[napo]
            img[slc1] *= fact[napo]
                #img[slc0] = img[slc0] * fact[napo] # casting rule
                #img[slc1] = img[scl1] * fact[napo]
    return img
Exemplo n.º 13
0
def normalizedXcorr(a, b):
    std = N.std(a) * N.std(b)
    a_ = (a - N.mean(a)) / std
    b_ = (b - N.mean(b)) / std

    c = F.convolve(a_, b_, conj=1)  # / a.size

    return c
Exemplo n.º 14
0
def normalizedXcorr(a, b):
    std = N.std(a) * N.std(b)
    a_ = (a - N.mean(a)) / std
    b_ = (b - N.mean(b)) / std

    c = F.convolve(a_, b_, conj=1)# / a.size
    
    return c
Exemplo n.º 15
0
def _makeSlice(zyx):
    slcs = []
    for x in zyx:
        if x >= 0:
            slc = slice(int(N.ceil(x)), None, None)
        else:
            slc = slice(0, -int(N.ceil(abs(x))))
        slcs.append(slc)
    return slcs
Exemplo n.º 16
0
def psf__wPSF(parm, t):
    """
    parm: s0, c, d, A, B
    example  (72, 125, 246, 1, 1)
    """
    s0, c, d, A, B = parm
    com = (t - c) / d
    sq = 1 + N.power(com, 2) + A * N.power(com, 3) + B * N.power(com, 4)
    return s0 * N.sqrt(sq)
Exemplo n.º 17
0
def psf__wPSF(parm, t):
    """
    parm: s0, c, d, A, B
    example  (72, 125, 246, 1, 1)
    """
    s0, c, d, A, B = parm
    com = (t - c) / d
    sq = 1 + N.power(com, 2) + A * N.power(com, 3) + B * N.power(com, 4)
    return s0 * N.sqrt(sq)
Exemplo n.º 18
0
def psf__wPSF_fromSigma(t, parm):
    """
    t: now this is sigma that you got
    parm: s0, c, d, A, B (use parm form psf__wPSF fit)
    """
    s0, c, d, A, B = parm
    com = (t - c) / d
    sq = 1 + N.power(com, 2) + A * N.power(com, 3) + B * N.power(com, 4)
    return s0 * N.sqrt( 1 + sq)
Exemplo n.º 19
0
def psf__wPSF_fromSigma(t, parm):
    """
    t: now this is sigma that you got
    parm: s0, c, d, A, B (use parm form psf__wPSF fit)
    """
    s0, c, d, A, B = parm
    com = (t - c) / d
    sq = 1 + N.power(com, 2) + A * N.power(com, 3) + B * N.power(com, 4)
    return s0 * N.sqrt(1 + sq)
Exemplo n.º 20
0
    def __init__(self, fns):
        """
        fns
        """
        # input types
        self.img = load(fns)

        # copy attributes
        self.nt = self.img.nt
        self.nw = self.img.nw
        self.nz = self.img.nz
        self.ny = self.img.ny
        self.nx = self.img.nx
        self.dtype = self.img.dtype
        self.hdr = self.img.hdr
        self.dirname = os.path.dirname(self.img.filename)  #path)
        self.file = self.path = os.path.basename(self.img.filename)  #path)
        self.shape = N.asarray(
            mrcIO.shapeFromNum(self.hdr.Num, self.nw, self.nt,
                               self.hdr.ImgSequence))
        self.ndim = int(self.nz > 1) + int(self.nw > 1) + int(self.nt > 1) + 2
        zwt = ['z', 'w', 't']
        num = [self.nz, self.nw, self.nt]
        maxdim = max(num)
        self.maxaxs = zwt[num.index(maxdim)]

        # slicing parameter
        self.ignor_color_axis = False
        self.sld_axs = 't'

        # cropping region
        self.cropbox_l = N.array([0, 0, 0], N.int32)
        self.cropbox_u = N.array([self.nz, self.ny, self.nx], N.int32)
        self.setMstUse(
            False)  # this has to be False since original shape cannot be known
        self.tSlice = 0
        self.setIndices(range(self.nw), range(self.nt), range(self.nz),
                        self.hdr.ImgSequence, self.dtype)

        self.sliceIdx = [self.nz // 2, self.ny // 2, self.nx // 2]
        self.selectZsecs()

        # output
        self.byteorder = '='
        self.interporder = imgResample.ORDER

        # viewer
        self.vid = None
        self._rub = None
        self.vid_single = None

        # aui
        self.t = 0
        self.w = 0
        self.z = self.nz // 2
        self.y = self.ny // 2
        self.x = self.nx // 2
Exemplo n.º 21
0
def rotateIndices2DNew(shape, rot, orig=None, dtype=N.float64):
    """
    shape: 2D
    rot:   anti-clockwise
    orig:  (y, x)

    return: yi, xi
    """
    # FIX ME Rot is something wrong!! 081027

    shape = N.asarray(shape, N.int)

    if orig is None:
        y, x = shape / 2.
    else:
        y, x = orig

    print(y, x)
    if not rot:
        yi, xi = N.indices(shape, dtype=N.float64)
        yi -= y - 0.5  # remove pix center
        xi -= x - 0.5
        return yi, xi

    # twice as large window

# mo = N.abs(N.mod(shape, 2) + [-1,-1])
    s2 = shape * 2  #+ mo  # always odd for even shape, even for odd shape

    yi, xi = N.indices(s2, dtype=N.float32)

    mm = N.ceil(shape / 2.)  #(s2 -1 - shape)//2 # offset always int
    yi -= mm[0]
    xi -= mm[1]

    pxc = imgGeo.RotateXY((0.5, 0.5), rot)  # remove pix center
    yi += pxc[0]
    xi += pxc[1]

    y0, x0 = shape / 2.  #N.ceil(shape / 2) # img center
    yc = y0 - y  # delta rotation center
    xc = x0 - x

    yi = U.trans2d(yi, None, (xc, yc, rot, 1, 0, 1))
    xi = U.trans2d(xi, None, (xc, yc, rot, 1, 0, 1))
    yi = U.trans2d(yi, None, (-xc, -yc, 0, 1, 0, 1))
    xi = U.trans2d(xi, None, (-xc, -yc, 0, 1, 0, 1))

    yi = yi.astype(dtype)
    xi = xi.astype(dtype)

    yi -= y
    xi -= x

    yi = imgFilters.cutOutCenter(yi, shape)
    xi = imgFilters.cutOutCenter(xi, shape)
    return yi, xi
Exemplo n.º 22
0
def rotateIndices2DNew(shape, rot, orig=None, dtype=N.float64):
    """
    shape: 2D
    rot:   anti-clockwise
    orig:  (y, x)

    return: yi, xi
    """
    # FIX ME Rot is something wrong!! 081027

    shape = N.asarray(shape, N.int)
    
    if orig is None:
        y, x = shape / 2.
    else:
        y, x = orig

    print(y,x)
    if not rot:
        yi,xi = N.indices(shape, dtype=N.float64)
        yi -= y - 0.5 # remove pix center
        xi -= x - 0.5
        return yi,xi

    # twice as large window
   # mo = N.abs(N.mod(shape, 2) + [-1,-1])
    s2 = shape * 2 #+ mo  # always odd for even shape, even for odd shape

    yi, xi = N.indices(s2, dtype=N.float32)

    mm = N.ceil(shape / 2.)#(s2 -1 - shape)//2 # offset always int
    yi -= mm[0]
    xi -= mm[1]

    pxc = imgGeo.RotateXY((0.5,0.5), rot) # remove pix center
    yi += pxc[0]
    xi += pxc[1]

    y0, x0 = shape / 2. #N.ceil(shape / 2) # img center
    yc = y0 - y # delta rotation center
    xc = x0 - x

    yi = U.trans2d(yi, None, (xc,yc,rot,1,0,1))
    xi = U.trans2d(xi, None, (xc,yc,rot,1,0,1))
    yi = U.trans2d(yi, None, (-xc,-yc,0,1,0,1))
    xi = U.trans2d(xi, None, (-xc,-yc,0,1,0,1))

    yi = yi.astype(dtype)
    xi = xi.astype(dtype)

    yi -= y
    xi -= x

    yi = imgFilters.cutOutCenter(yi, shape)
    xi = imgFilters.cutOutCenter(xi, shape)
    return yi, xi
Exemplo n.º 23
0
def nanFilter(af, kernel=3):
    """
    3D phase contrast filter often creates 'nan'
    this filter removes nan by averaging surrounding pixels
    return af
    """
    af = af.copy()
    shape = N.array(af.shape)
    radius = N.subtract(kernel, 1) // 2
    box = kernel * af.ndim
    nan = N.isnan(af)
    nids = N.array(N.nonzero(nan)).T
    for nidx in nids:
        slc = [slice(idx, idx + 1) for idx in nidx]
        slices = []
        for dim in range(af.ndim):
            slc2 = slice(slc[dim].start - radius, slc[dim].stop + radius)
            while slc2.start < 0:
                slc2 = slice(slc2.start + 1, slc2.stop)
            while slc2.stop > shape[dim]:
                slc2 = slice(slc2.start, slc2.stop - 1)
            slices.append(slc2)

        val = af[slices]
        nanlocal = N.isnan(val)
        ss = N.sum(N.where(nanlocal, 0, val)) / float((box - N.sum(nanlocal)))
        af[slc] = ss
    return af
Exemplo n.º 24
0
def nanFilter(af, kernel=3):
    """
    3D phase contrast filter often creates 'nan'
    this filter removes nan by averaging surrounding pixels
    return af
    """
    af = af.copy()
    shape = N.array(af.shape)
    radius = N.subtract(kernel, 1) // 2
    box = kernel * af.ndim
    nan = N.isnan(af)
    nids = N.array(N.nonzero(nan)).T
    for nidx in nids:
        slc = [slice(idx,idx+1) for idx in nidx]
        slices = []
        for dim in range(af.ndim):
            slc2 = slice(slc[dim].start - radius, slc[dim].stop + radius)
            while slc2.start < 0:
                slc2 = slice(slc2.start + 1, slc2.stop)
            while slc2.stop > shape[dim]:
                slc2 = slice(slc2.start, slc2.stop -1)
            slices.append(slc2)
            
        val = af[slices]
        nanlocal = N.isnan(val)
        ss = N.sum(N.where(nanlocal, 0, val)) / float((box - N.sum(nanlocal)))
        af[slc] = ss
    return af
Exemplo n.º 25
0
def transformMatrix(rot=0.0, mag=1.0):
    """
    retrn invmat
    """
    rotRadian = N.pi / 180. * rot
    cosTheta = N.cos(rotRadian)
    sinTheta = N.sin(rotRadian)
    affmatrix = N.array([[cosTheta, sinTheta], [-sinTheta, cosTheta]]) * mag
    invmat = N.linalg.inv(affmatrix)

    return invmat
Exemplo n.º 26
0
def paddingFourier(arr, shape, value=0, interpolate=True):
    """
    arr:         assuming origin at 0, rfft product (half x size), up to 3D
    shape:       target shape
    value:       the value to fill in empty part 
    interpolate: shift by interpolation if necessary

    return array with target shape
    """
    # prepare buffer
    dtype = arr.dtype.type
    canvas = N.empty(shape, dtype)
    canvas[:] = value

    # calc and shift
    shapeS = N.array(arr.shape)
    shapeL = N.asarray(shape)
    halfS = shapeS / 2.
    subpx_shift = halfS % 1
    if interpolate and N.sometrue(subpx_shift):
        arr = U.nd.shift(arr, subpx_shift)
    halfS = [int(s) for s in halfS]

    # create empty list for slices
    nds = arr.ndim - 1
    choices = ['slice(halfS[%i])', 'slice(-halfS[%i], None)']
    nchoices = len(choices)
    nds2 = nds**2
    slcs = []
    for ns in range(nds2):
        slcs.append([])
        for n in range(nchoices * nds):
            slcs[ns].append(
                [Ellipsis])  # Ellipsis help to make arbitray number of list

    # fill the empty list by slice (here I don't know how to use 4D..)
    for i in range(nds2):
        for d in range(nds):
            for x in range(nds):
                for c, choice in enumerate(choices):
                    if d == 0 and x == 0:
                        idx = x * (nchoices) + c
                    else:  # how can I use 4D??
                        idx = x * (nchoices) + (nchoices - 1) - c
                    exec('content=' + choice % d)
                    slcs[i][idx] += [content]

    # cutout and paste
    for slc in slcs:
        for s in slc:
            s.append(slice(int(shapeS[-1])))
            #print s
            canvas[s] = arr[s]
    return canvas
Exemplo n.º 27
0
def transformMatrix(rot=0.0, mag=1.0):
    """
    retrn invmat
    """
    rotRadian = N.pi / 180. * rot
    cosTheta = N.cos(rotRadian)
    sinTheta = N.sin(rotRadian)
    affmatrix = N.array([ [cosTheta, sinTheta], [-sinTheta, cosTheta] ]) * mag
    invmat = N.linalg.inv(affmatrix)

    return invmat
Exemplo n.º 28
0
def arr_edgeFilter(img, sigma=1.5):
    """
    average-deviation with a gaussian prefilter
    img must be in an even shape
    """
    if sigma:
        g = gaussianArrND(img.shape, sigma)
        g = F.shift(g)
        img = F.convolve(img.astype(N.float32), g)
    gr = N.gradient(img.astype(N.float32))
    ff = N.sum(N.power(gr, 2), 0)
    return ff
Exemplo n.º 29
0
def logpolar_cv(img, center=None, mag=1):
    des = N.zeros_like(img)
    if center is None:
        center = N.divide(img.shape, 2)

    # cv.fromarray: array can be 2D or 3D only
    cimg = cv.fromarray(img)
    cdes = cv.fromarray(des)

    cv.LogPolar(cimg, cdes, tuple(center), mag)#, cv.CV_WARP_FILL_OUTLIERS)

    return N.array(cdes)
Exemplo n.º 30
0
def logpolar_cv(img, center=None, mag=1):
    des = N.zeros_like(img)
    if center is None:
        center = N.divide(img.shape, 2)

    # cv.fromarray: array can be 2D or 3D only
    cimg = cv.fromarray(img)
    cdes = cv.fromarray(des)

    cv.LogPolar(cimg, cdes, tuple(center), mag)  #, cv.CV_WARP_FILL_OUTLIERS)

    return N.array(cdes)
Exemplo n.º 31
0
def paddingFourier(arr, shape, value=0, interpolate=True):
    """
    arr:         assuming origin at 0, rfft product (half x size), up to 3D
    shape:       target shape
    value:       the value to fill in empty part 
    interpolate: shift by interpolation if necessary

    return array with target shape
    """
    # prepare buffer
    dtype = arr.dtype.type
    canvas = N.empty(shape, dtype)
    canvas[:] = value
    
    # calc and shift
    shapeS = N.array(arr.shape)
    shapeL = N.asarray(shape)
    halfS = shapeS / 2.
    subpx_shift = halfS % 1
    if interpolate and N.sometrue(subpx_shift):
        arr = U.nd.shift(arr, subpx_shift)
    halfS = [int(s) for s in halfS]

    # create empty list for slices
    nds = arr.ndim - 1
    choices = ['slice(halfS[%i])', 'slice(-halfS[%i], None)']
    nchoices = len(choices)
    nds2 = nds**2
    slcs = []
    for ns in range(nds2):
        slcs.append([])
        for n in range(nchoices*nds):
            slcs[ns].append([Ellipsis]) # Ellipsis help to make arbitray number of list

    # fill the empty list by slice (here I don't know how to use 4D..)
    for i in range(nds2):
        for d in range(nds):
            for x in range(nds):
                for c, choice in enumerate(choices):
                    if d == 0 and x == 0:
                        idx = x*(nchoices) + c
                    else: # how can I use 4D??
                        idx = x*(nchoices) + (nchoices-1) - c
                    exec('content=' + choice % d)
                    slcs[i][idx] += [content]

    # cutout and paste
    for slc in slcs:
        for s in slc:
            s.append(slice(int(shapeS[-1])))
            #print s
            canvas[s] = arr[s]
    return canvas
Exemplo n.º 32
0
def arr_edgeFilter(img, sigma=1.5):
    """
    average-deviation with a gaussian prefilter
    img must be in an even shape
    """
    if sigma:
        g = gaussianArrND(img.shape, sigma)
        g = F.shift(g)
        img = F.convolve(img.astype(N.float32), g)
    gr = N.gradient(img.astype(N.float32))
    ff = N.sum(N.power(gr, 2), 0)
    return ff 
Exemplo n.º 33
0
def zoomFourier(arr, factor, use_abs=False):
    shape = N.array(arr.shape)
    target = [int(s) for s in shape * factor]
    #target[-1] //= 2
    #target[-1] += 1
    af = F.fft(arr)
    ap = paddingFourier(af, target)
    afp = F.ifft(ap)
    factor = target / shape
    if use_abs:
        return N.abs(afp) * N.product(factor)
    else:
        return N.real(afp) * N.product(factor)
Exemplo n.º 34
0
def yExpDecay(rhamda=1, t=0, n0=100):
    """
    rhamda: paramter
    n0:     the first value of the data
    """
    tt = N.asarray(t)
    try:
        if tt[0]:
            tt = tt.copy()
            tt -= tt[0]
    except TypeError:
        pass
    return n0 * N.exp(-rhamda * tt)
Exemplo n.º 35
0
def zoomFourier(arr, factor, use_abs=False):
    shape = N.array(arr.shape)
    target = [int(s) for s in shape * factor]
    #target[-1] //= 2
    #target[-1] += 1
    af = F.fft(arr)
    ap = paddingFourier(af, target)
    afp = F.ifft(ap)
    factor = target / shape
    if use_abs:
        return N.abs(afp) * N.product(factor)
    else:
        return N.real(afp) * N.product(factor)
Exemplo n.º 36
0
def yExpDecay(rhamda=1, t=0, n0=100):
    """
    rhamda: paramter
    n0:     the first value of the data
    """
    tt = N.asarray(t)
    try:
        if tt[0]:
            tt = tt.copy()
            tt -= tt[0]
    except TypeError:
        pass
    return n0 * N.exp(-rhamda * tt)
Exemplo n.º 37
0
def _indLD(win, y, x):
    """
    return yi, xi, LD
    """
    try:
        len(win)
        yi, xi = N.indices(int(win))
    except TypeError:
        yi, xi = N.indices((int(win), int(win)))
    yx = N.asarray((y, x))
    LD = yx - win / 2. + 0.5  # use pixel center
    yi += LD[0]
    xi += LD[1]
    return yi, xi, LD
Exemplo n.º 38
0
def yGaussianND(param, inds, sidx):
    """
    param: (mean, max - mean, z, y, x, sigmaz, sigmay, sigmax)
    ind:   coordinate as N.indices (float32)
    sidx:  idx of param where sigma starts (2 + ndim)
    """
    s = 2. * param[sidx:] * param[sidx:] # sigma
    zyx = param[2:sidx] #- 0.5 # use pixel center
    DST = N.zeros(inds[0].shape, inds[0].dtype.type)
    for i in range(sidx - 2):
        IND = zyx[i] - inds[i]
        DST -= (IND * IND) / s[i]

    return param[0] + param[1] * N.exp(DST)
Exemplo n.º 39
0
def mask_gaussianND(arr, zyx, v, sigma=2., ret=None, rot=0, clipZero=True):
    ''' 
    subtract elliptical gaussian at y,x with peakVal v
    if ret, return arr, else, arr itself is edited
    '''
    from . import imgGeo
    zyx = N.asarray(zyx)
    ndim = arr.ndim
    shape = N.array(arr.shape)
    try:
        if len(sigma) != ndim:
            raise ValueError('len(sigma) must be the same as len(shape)')
        else:
            sigma = N.asarray(sigma)
    except TypeError:#(TypeError, ValueError):
        sigma = N.asarray([sigma]*ndim)

    # prepare small window
    slc = imgGeo.nearbyRegion(shape, N.floor(zyx), sigma * 10)
    inds, LD = imgFit.rotateIndicesND(slc, dtype=N.float32, rot=rot)
    param = (0, v,) + tuple(zyx) + tuple(sigma)
    sidx = 2 + ndim
    g = imgFit.yGaussianND(N.asarray(param), inds, sidx).astype(arr.dtype.type)
    roi = arr[slc]
    if clipZero:
        g = N.where(g > roi, roi, g)

    if ret:
        e = N.zeros_like(arr)
        e[slc] = g  # this may be faster than copy()
        return arr - e
    else:
        arr[slc] -= g
Exemplo n.º 40
0
def yGaussianND(param, inds, sidx):
    """
    param: (mean, max - mean, z, y, x, sigmaz, sigmay, sigmax)
    ind:   coordinate as N.indices (float32)
    sidx:  idx of param where sigma starts (2 + ndim)
    """
    s = 2. * param[sidx:] * param[sidx:]  # sigma
    zyx = param[2:sidx]  #- 0.5 # use pixel center
    DST = N.zeros(inds[0].shape, inds[0].dtype.type)
    for i in range(sidx - 2):
        IND = zyx[i] - inds[i]
        DST -= (IND * IND) / s[i]

    return param[0] + param[1] * N.exp(DST)
Exemplo n.º 41
0
def _indLD(win, y, x):
    """
    return yi, xi, LD
    """
    try:
        len(win)
        yi, xi = N.indices(int(win))
    except TypeError:
        yi, xi = N.indices((int(win), int(win)))
    yx = N.asarray((y, x))
    LD = yx - win/2. + 0.5 # use pixel center
    yi += LD[0]
    xi += LD[1]
    return yi, xi, LD
Exemplo n.º 42
0
    def showSelection(self):
        sentence = []
        sep = ': '
        d = 'default (%i)'
        u = 'unknown'

        s = 'start---%3d   stop---%3d   step---%s (%i)'
        things = [('time', self.nt, self._tIdx), ('zsec', self.nz, self._zIdx),
                  ('wave', self.nw, self._wIdx),
                  ('y   ', self.shape[-2], self._yxSlice[0]),
                  ('x   ', self.shape[-1], self._yxSlice[1])]

        for title, n, idxNow in things:
            if type(idxNow) == slice:
                start = idxNow.start
                if start is None:
                    start = 0
                stop = idxNow.stop
                step = idxNow.step
                if step is None:
                    step = 1
                idxNow = range(int(start), int(stop), int(step))
            else:
                start = idxNow[0]
                stop = idxNow[-1] + 1

            listed = list(idxNow)
            nn = len(listed)
            if listed == range(int(n)):
                sentence.append(sep.join((title, d % nn)))
            else:
                stepGuess = N.ceil((stop - start) / float(len(idxNow)))
                if N.alltrue(idxNow == range(start, stop, int(stepGuess))):
                    step = str(int(stepGuess))
                    sentence.append(
                        sep.join((title, s % (start, stop, step, nn))))
                else:
                    step = u
                    sentence.append(
                        sep.join((title, s % (start, stop, step, nn))))
                    if nn > 20:
                        tail = '...'
                    else:
                        tail = ''
                    sentence.append(' ' * (len(title) + len(sep)) +
                                    ','.join([str(a)
                                              for a in listed[:20]]) + tail)

        return '\n'.join(sentence)
Exemplo n.º 43
0
    def __getitem__(self, idx):
        try:
            idx = int(idx)
            if idx < 0:
                idx = self.shape[0] + idx

            ws = range(self.nw)
            ts = range(self.nt)
            zs = range(self.nz)
            if self.maxaxs == 'w' and not self.ignor_color_axis:
                ws = [idx]
                self.sld_axs = 'w'
            elif self.maxaxs == 't' or (self.ignor_color_axis
                                        and self.ndim > 4):
                ts = [idx]
                self.sld_axs = 't'
            elif self.maxaxs == 'z' or (self.ignor_color_axis
                                        and self.ndim == 4):
                zs = [idx]
                self.sld_axs = 'z'
            else:
                raise ValueError, 'section axis not determined'
            if self.hdr.ImgSequence == 0:
                e = N.empty((len(ws), len(ts), len(zs), self.ny, self.nx),
                            self.dtype)
                for wo, wi in enumerate(ws):
                    for to, ti in enumerate(ts):
                        for zo, zi in enumerate(zs):
                            e[wo, to, zo] = self.img.getArr(w=wi, t=ti, z=zi)
            elif self.hdr.ImgSequence == 1:
                e = N.empty((len(ts), len(zs), len(ws), self.ny, self.nx),
                            self.dtype)
                for to, ti in enumerate(ts):
                    for zo, zi in enumerate(zs):
                        for wo, wi in enumerate(ws):
                            e[to, zo, wo] = self.img.getArr(w=wi, t=ti, z=zi)
            elif self.hdr.ImgSequence == 2:
                e = N.empty((len(ts), len(ws), len(zs), self.ny, self.nx),
                            self.dtype)
                for to, ti in enumerate(ts):
                    for wo, wi in enumerate(ws):
                        for zo, zi in enumerate(zs):
                            e[to, wo, zo] = self.img.getArr(w=wi, t=ti, z=zi)

        except TypeError:
            pass

        return N.squeeze(e)
Exemplo n.º 44
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
Exemplo n.º 45
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
Exemplo n.º 46
0
def mask_value(arr, zyx, r=2.5, value=0):
    ''' Edit the pixels around zyx to be zero 
    r: radius (will be 2*r + 1)
    '''
    from . import imgGeo
    sls = imgGeo.nearbyRegion(arr.shape, zyx, 2*N.asarray(r)+1)
    arr[sls] = value
Exemplo n.º 47
0
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
Exemplo n.º 48
0
def getOffset(shape, invmat, ty, tx, start=0):
    try:
        if len(start) == len(shape):
            yxCenter = [s / 2. + start[i] for i, s in enumerate(shape)]
    except TypeError:
        yxCenter = [s / 2. + start for s in shape]
    return -N.dot(invmat, yxCenter) + yxCenter - [ty, tx]
Exemplo n.º 49
0
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
Exemplo n.º 50
0
def getOffset(shape, invmat, ty, tx, start=0):
    try:
        if len(start) == len(shape):
            yxCenter = [s/2. + start[i] for i, s in enumerate(shape)]
    except TypeError:
        yxCenter = [s/2. + start for s in shape]
    return -N.dot(invmat, yxCenter) + yxCenter -  [ty, tx]
Exemplo n.º 51
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
Exemplo n.º 52
0
def arr_histStretch(img, imgMin=None, imgMax=None, scaleMax=None):
    """
    scaleMax = None: use maximum possible for the dtype
    """
    if imgMin is None:
        imgMin = img.min()
    if imgMax is None:
        imgMax = img.max()
    if scaleMax is None:
        img = N.asarray(img)
        scaleMax = 1 << (img.nbytes // img.size) * 8
        scaleMax -= 1

    img = img - imgMin#img.min()
    ratio = float(scaleMax) / imgMax#img.max()

    return N.asarray(ratio * img, img.dtype.type)
Exemplo n.º 53
0
def psf__wPSF_yPolyInv(t, *parm):
    """
    abs()
    """
    if len(parm) == 1:
        parm = parm[0]
    r = psf__wPSF_yPolyInv_bare(t, parm)
    return N.abs(r)
Exemplo n.º 54
0
def findMaxWithGFitAll(img, thre=0, sigma_peak=0.5, win=11, mask_npxls=3):
    """
    find peaks until either
    1. any pxls becomes below thre
    2. the same peak was found as the maximum

    mask_npxls: number of pixels to mask when Gaussian fitting failed

    return poslist
    """
    img = img.copy()
    imgFit.fitFailedClear()
    ndim = img.ndim
    sigma_peak = imgFit._scalerToSeq(sigma_peak, ndim)

    poses = []
    vzyx = U.findMax(img)
    while vzyx[0] > thre:
        prev = vzyx
        try:
            ret, check = imgFit.fitGaussianND(img, vzyx[-ndim:], sigma_peak, win)
        except IndexError: # too close to the edge
            imgFit.fitFailedAppend("at %s" % str(vzyx[-ndim:]))
            mask_value(img, vzyx[-ndim:], r=mask_npxls, value=img.min())
            poses.append(list(vzyx)[0:1] + [vzyx[-ndim:]] + [list(sigma_peak)])

        if check == 5:
            imgFit.fitFailedAppend("at %s, %s, check=%i" % (str(vzyx[-ndim:]), str(ret), check))
            mask_value(img, vzyx[-ndim:], r=mask_npxls, value=img.min())
            poses.append(list(vzyx)[0:1] + [vzyx[-ndim:]] + [sigma_peak])
        else:
            v = ret[1]
            zyx = ret[2:2+ndim]
            if N.any(N.abs(zyx - vzyx[1:]) > win/2.):#zyx < 0 or zyx > img.shape or ):
                mask_value(img, vzyx[-ndim:], r=mask_npxls, value=img.min())
                poses.append(list(vzyx)[0:1] + [vzyx[-ndim:]] + [sigma_peak])
            else:
                sigma = ret[2+ndim:2+ndim*2]
                mask_gaussianND(img, zyx, v, sigma)
                poses.append([v,zyx,sigma])

        vzyx = U.findMax(img)
        if N.all(vzyx == prev):
            break
        
    return poses#, img
Exemplo n.º 55
0
def cutOutCenter(arr, windowSize, sectWise=None, interpolate=True):
    """
    windowSize:  scalar (in pixel or as percent < 1.) or ((z,)y,x)
    sectWise:    conern only XY of windowSize
    """
    shape = N.array(arr.shape)
    center = shape / 2.
    return pointsCutOutND(arr, [center], windowSize, sectWise, interpolate)[0]
Exemplo n.º 56
0
def arr_histStretch(img, imgMin=None, imgMax=None, scaleMax=None):
    """
    scaleMax = None: use maximum possible for the dtype
    """
    if imgMin is None:
        imgMin = img.min()
    if imgMax is None:
        imgMax = img.max()
    if scaleMax is None:
        img = N.asarray(img)
        scaleMax = 1 << (img.nbytes // img.size) * 8
        scaleMax -= 1

    img = img - imgMin  #img.min()
    ratio = float(scaleMax) / imgMax  #img.max()

    return N.asarray(ratio * img, img.dtype.type)
Exemplo n.º 57
0
def cutOutCenter(arr, windowSize, sectWise=None, interpolate=True):
    """
    windowSize:  scalar (in pixel or as percent < 1.) or ((z,)y,x)
    sectWise:    conern only XY of windowSize
    """
    shape = N.array(arr.shape)
    center = shape / 2.
    return pointsCutOutND(arr, [center], windowSize, sectWise, interpolate)[0]
Exemplo n.º 58
0
def psf__wPSF_yPolyInv(t, *parm):
    """
    abs()
    """
    if len(parm) == 1:
        parm = parm[0]
    r = psf__wPSF_yPolyInv_bare(t, parm)
    return N.abs(r)
Exemplo n.º 59
0
def centerOfMass(img, yx, window=5):
    """
    find peak by center of mass in a 2D image

    img:    a 2D image array
    yx:     (y,x) in the image
    window: a window where CM calculation is performed on

    return yx
    """
    # prepare small image
    s = N.array([window, window])
    c = s / 2.
    yx = N.round_(yx)
    yx -= c
    yi, xi = N.indices(s)
    yi += yx[0]
    xi += yx[1]
    cc = img[yi, xi]

    # calculate center of mass
    yxi = N.indices(s)
    yxi *= cc
    yxi = yxi.T
    vv = N.sum(yxi, axis=0)
    vv = N.sum(vv, axis=0)
    yxs = vv / float(N.sum(cc))
    yxs += yx
    return yxs
Exemplo n.º 60
0
def centerOfMass(img, yx, window=5):
    """
    find peak by center of mass in a 2D image

    img:    a 2D image array
    yx:     (y,x) in the image
    window: a window where CM calculation is performed on

    return yx
    """
    # prepare small image
    s = N.array([window,window])
    c = s/2.
    yx = N.round_(yx)
    yx -= c
    yi, xi = N.indices(s)
    yi += yx[0]
    xi += yx[1]
    cc = img[yi,xi]

    # calculate center of mass
    yxi = N.indices(s)
    yxi *= cc
    yxi = yxi.T
    vv = N.sum(yxi, axis=0)
    vv = N.sum(vv, axis=0)
    yxs = vv / float(N.sum(cc))
    yxs += yx
    return yxs