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)
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
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)
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)
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
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
def fitExpDecay(data, t, p0=1): """ return rhamda, mean_lifetime, half_life, check """ data = N.asarray(data, N.float64) t = N.asarray(t, N.float64) def f(p, n0): return yExpDecay(p, t, n0) - data x0 = p0 from scipy import optimize rhamda, check = optimize.leastsq(f, x0, args=(data[0], )) if check in [1, 2, 3, 4]: mean_lifetime = 1. / rhamda + t[0] half_life = N.log(2.) * mean_lifetime else: mean_lifetime = half_life = 0 return rhamda, mean_lifetime, half_life, check
def fitAny(func, data, t, p0): """ func: your function data: 1D data t: 1D coordinate (same length as data) p0: parameter tuple """ data = N.asarray(data, N.float64) t = N.asarray(t, N.float64) def f(p): return func(p, t) - data x0 = p0 from scipy import optimize try: ret = optimize.leastsq(f, x0, warning=None) except TypeError: # python 2.6 ret = optimize.leastsq(f, x0) return ret
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
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)
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
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
def gaussianArr2D( shape=(256, 256), sigma=[2., 2.], peakVal=None, orig=None, rot=0): """ >1.5x faster implemetation than gaussianArrND shape: (y,x) sigma: scaler or [sigmay, sigmax] orig: (y,x) rot: scaler anti-clockwise return N.float32 """ shape = N.asarray(shape, N.uint) try: if len(sigma) == len(shape): sy = 2 * (sigma[0] * sigma[0]) sx = 2 * (sigma[1] * sigma[1]) elif len(sigma) == 1: sx = sy = 2 * (sigma[0] * sigma[0]) else: raise ValueError('sigma must be scaler or [sigmay, sigmax]') except TypeError: # sigma scaler sx = sy = 2 * (sigma * sigma) # print y, x if rot: yyi, xxi = imgFit.rotateIndices2D(shape, rot, orig, N.float32) else: if orig is None: y, x = shape / 2. - 0.5 # pixel center remove else: y, x = N.subtract(orig, 0.5) # pixel center remove yi, xi = N.indices(shape, dtype=N.float32) yyi = y - yi xxi = x - xi k1 = -(yyi) * (yyi) / (sy) - (xxi) * (xxi) / (sx) if peakVal: k0 = peakVal else: k0 = 1. / ((sx + sy) / 2. * ((2 * N.pi)**0.5)) return k0 * N.exp(k1)
def highPassF(af, highpassSigma=2.5, wiener=0.2, cutoffFreq=3): """ fourie space operations af: array after rfft half_nyx: half shape required for highpass filter highpassSigma: highpass filter, if 0, highpass is not done wiener: wiener coefficient for highpass filte cutoffFreq: band-pass around origin return: array BEFORE irfft WARNING: af will be changed, so use copy() if necessary """ global _G, _G_SHAPE if highpassSigma: shape = N.array(af.shape) shape[-1] = (shape[-1] - 1) * 2 szyx = shape / 2. if _G is not None and N.alltrue(_G_SHAPE == shape): g = _G else: g = imgFilters.gaussianArrND(shape, highpassSigma, peakVal=1, orig=szyx) g = F.shift(g)[..., :af.shape[-1]] _G = g _G_SHAPE = N.asarray(g.shape) g += wiener af /= g # kill DC af.flat[0] = 0 # kill lowest freq in YX for d in range(af.ndim - 2, af.ndim): upperdim = ':,' * d exec('af[%s0:cutoffFreq] = 0' % upperdim) return af
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
def evenShapeArr(a): """ return even shaped array """ shapeA = N.asarray(a.shape) shapeM = shapeA.copy() for i, s in enumerate(shapeM): if not i and s == 1: continue elif s % 2: shapeM[i] -= 1 #sy,sx = shapeA #if sx % 2:# or sy %2: # sx += 1 #if sy % 2: # sy += 1 #shapeM = N.array([sy, sx]) if N.sometrue(shapeA < shapeM): a = paddingMed(a, shapeM) elif N.sometrue(shapeA > shapeM): a = cutOutCenter(a, shapeM, interpolate=False) return a
def highPassF(af, highpassSigma=2.5, wiener=0.2, cutoffFreq=3): """ fourie space operations af: array after rfft half_nyx: half shape required for highpass filter highpassSigma: highpass filter, if 0, highpass is not done wiener: wiener coefficient for highpass filte cutoffFreq: band-pass around origin return: array BEFORE irfft WARNING: af will be changed, so use copy() if necessary """ global _G, _G_SHAPE if highpassSigma: # if half_nyx is None: ny, nx = af.shape sy2 = ny / 2. sx2 = nx - 1 shape = (sy2 * 2, sx2 + 1) if _G is not None and N.alltrue(_G_SHAPE == shape): g = _G else: g = gaussianArr2D(shape, highpassSigma, peakVal=1, orig=(sy2, 0)) _G = g _G_SHAPE = N.asarray(shape) g += wiener af[:sy2] /= g[sy2:] af[sy2:] /= g[:sy2] # kill DC af.flat[0] = 0 # kill lowest freq af[0:cutoffFreq] = 0 af[:, 0:cutoffFreq] = 0 return af
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)
def trans3D_affine(arr, tzyx=(0, 0, 0), r=0, mag=1, dzyx=(0, 0, 0), rzy=0, ncpu=NCPU, order=ORDER): #**kwds): """ return array """ dtype = arr.dtype.type arr = arr.astype(N.float32) ndim = arr.ndim if ndim == 2: arr = arr.reshape((1, ) + arr.shape) elif ndim == 3: if len(tzyx) < ndim: tzyx = (0, ) * (ndim - len(tzyx)) + tuple(tzyx) if len(dzyx) < ndim: dzyx = (0, ) * (ndim - len(dzyx)) + tuple(dzyx) dzyx = N.asarray(dzyx) magz = 1 try: if len(mag) == 3: magz = mag[0] mag = mag[1:] except TypeError: pass if ndim == 3 and (magz != 1 or tzyx[-3] or rzy): #print magz, arr.shape # because, mergins introduced after 2D transformation may interfere the result of this vertical transform, vertical axis was processed first, since rzy is 0 usually. arrT = arr.T # zyx -> xyz magzz = (1, magz) canvas = N.zeros_like(arrT) tzy = (0, tzyx[-3]) dzy = (dzyx[-2], dzyx[-3]) #if ncpu > 1 and mp: ret = ppro.pmap(_dothat, arrT, ncpu, tzy, rzy, magzz, dzy, order) for x, a in enumerate(ret): canvas[x] = a #else: # for x, a in enumerate(arrT): # canvas[x] = _dothat(a, tzy, rzy, magzz, dzy, order) arr = canvas.T #del arrT if N.any(tzyx[-2:]) or r or N.any(mag): #print ndim, arr.shape canvas = N.zeros_like(arr) if ndim == 3: # and ncpu > 1 and mp: # dividing XY into pieces did not work for rotation and magnification # here parallel processing is done section-wise since affine works only for 2D ret = ppro.pmap(_dothat, arr, ncpu, tzyx[-2:], r, mag, dzyx[-2:], order) for z, a in enumerate(ret): canvas[z] = a else: for z, a in enumerate(arr): canvas[z] = _dothat(a, tzyx[-2:], r, mag, dzyx[-2:], order) if ndim == 2: canvas = canvas[0] arr = canvas if dtype in (N.int, N.uint8, N.uint16, N.uint32): arr = N.where(arr < 0, 0, arr) return arr.astype(dtype)
def trans3D_spline(a, tzyx=(0, 0, 0), r=0, mag=1, dzyx=(0, 0), rzy=0, mr=0, reshape=False, ncpu=1, **splinekwds): """ mag: scalar_for_yx or [y,x] or [z,y,x] mr: rotational direction of yx-zoom in degrees ncpu: no usage """ splinekwds['prefilter'] = splinekwds.get('prefilter', True) splinekwds['order'] = splinekwds.get('order', 3) ndim = a.ndim shape = N.array(a.shape, N.float32) tzyx = N.asarray(tzyx, N.float32) # rotation axis if ndim == 3: axes = (1, 2) else: axes = (1, 0) # magnification try: if len(mag) == 1: # same as scalar mag = [1] * (ndim - 2) + list(mag) * 2 else: mag = [1] * (ndim - 2) * (3 - len(mag)) + list(mag) except: # scalar -> convert to yx mag only mag = [1] * (ndim - 2) + ([mag] * ndim)[:2] mag = N.asarray(mag) try: dzyx = N.array([0] * (ndim - 2) * (3 - len(dzyx)) + list(dzyx)) except: # scalar pass if mr: a = U.nd.rotate(a, mr, axes=axes, reshape=reshape, **splinekwds) splinekwds['prefilter'] = False if N.any(dzyx): a = U.nd.shift(a, -dzyx, **splinekwds) splinekwds['prefilter'] = False if r: a = U.nd.rotate(a, -r, axes=axes, reshape=reshape, **splinekwds) splinekwds['prefilter'] = False if N.any(mag != 1): a = U.nd.zoom(a, zoom=mag, **splinekwds) splinekwds['prefilter'] = False if not reshape: dif = (shape - N.array(a.shape, N.float32)) / 2. mod = N.ceil(N.mod(dif, 1)) tzyx[-ndim:] -= (mod / 2.) if rzy and ndim >= 3: # is this correct?? havn't tried yet a = U.nd.rotate(a, -rzy, axes=(0, 1), reshape=reshape, **splinekwds) if N.any(dzyx): a = U.nd.shift(a, dzyx, **splinekwds) if mr: a = U.nd.rotate(a, -mr, axes=axes, reshape=reshape, **splinekwds) if reshape: a = U.nd.shift(a, tzyx[-ndim:], **splinekwds) else: tzyx0 = N.where(mag >= 1, tzyx[-ndim:], 0) if N.any(tzyx0[-ndim:]): a = U.nd.shift(a, tzyx0[-ndim:], **splinekwds) if N.any(mag != 1) and not reshape: a = keepShape(a, shape, (dif, mod)) old = """ canvas = N.zeros(shape, a.dtype.type) #dif = (shape - N.array(a.shape, N.float32)) / 2 #mod = N.ceil(N.mod(dif, 1)) dif = N.where(dif > 0, N.ceil(dif), N.floor(dif)) # smaller aoff = N.where(dif < 0, 0, dif) aslc = [slice(dp, shape[i]-dp+mod[i]) for i, dp in enumerate(aoff)] # larger coff = N.where(dif > 0, 0, -dif) cslc = [slice(dp, a.shape[i]-dp+mod[i]) for i, dp in enumerate(coff)] canvas[aslc] = a[cslc] a = canvas""" if not reshape: tzyx0 = N.where(mag < 1, tzyx[-ndim:], 0) if N.any(mag != 1): tzyx0[-ndim:] -= (mod / 2.) if N.any(tzyx0[-ndim:]): a = U.nd.shift(a, tzyx0[-ndim:], **splinekwds) return a
def trans3D_bilinear(a, tzyx=(0, 0, 0), r=0, mag=1, dzyx=(0, 0, 0), b=None, rzy=0, **kwds): """ magyx: scalar or [y,x] or [y,x, direction in degrees] """ a = a.copy() ndim = a.ndim if ndim == 2: a = a.reshape((1, ) + a.shape) try: if len(magyx) == 3: mr = magyx[-1] magyx = magyx[:2] else: mr = 0 except: mr = 0 if b is None: b2d = N.empty_like(a[0]) dzyx = N.asarray(dzyx) tzyx = N.asarray(tzyx) tzyx[-2:] += dzyx[-2:] magaxis = 1 # only this axis works magz = 1 try: if len(mag) == 3: magz, magy, magx = mag elif len(mag) == 2: magy, magx = mag else: magy = magx = mag[0] except: magy = magx = mag mag = magy anismag = magx / magy for z, a2d in enumerate(a): if N.any(dzyx[-2:]) or mr: temp = N.ascontiguousarray(b2d) target = N.ascontiguousarray(a2d) #U.trans2d(target, temp, (-dyx[1], -dyx[0], -mr, 1, 0, 1)) U.trans2d(target, temp, (-dzyx[-1], -dzyx[-2], -mr, 1, 0, 1)) else: temp = N.ascontiguousarray(a2d) target = N.ascontiguousarray(b2d) if r or mag != 1 or anismag != 1: U.trans2d(temp, target, (0, 0, r, mag, magaxis, anismag)) else: target[:] = temp[:] #if rzx: # is this correct?? havn't tried yet # target = U.nd.rotate(target, rzx, axes=(0,2), order=1, prefilter=False) if N.any(tzyx[-2:]) or mr: #N.any(dyx) or mr: #U.trans2d(target, temp, (dyx[1], dyx[0], mr, 1, 0, 1)) U.trans2d(target, temp, (tzyx[-1], tzyx[-2], mr, 1, 0, 1)) else: temp[:] = target[:] a[z] = temp[:] if ndim == 2: a = a[0] elif ndim == 3 and (magz != 1 or tzyx[-3]): at = a.T # zyx -> xyz mag = 1 #magz anismag = magz #magy / magz canvas = N.empty_like(at) target = b2d.T for x, a2d in enumerate(at): if dzyx[-3]: U.trans2d(a2d, target, (0, -dyzx[-3], 0, 1, 1, 1)) else: target = a2d canvas[x] = U.trans2d(target, None, (tzyx[-3], 0, rzy, mag, magaxis, anismag)) #canvas = canvas.T a = canvas.T return a
def getShift(shift, ZYX, erosionZYX=0): """ shift: zyxrmm return [zmin,zmax,ymin,ymax,xmin,xmax] """ # erosion try: if len(erosionZYX) == 3: erosionZ = erosionZYX[0] erosionYX = erosionZYX[1:] elif len(erosionZYX) == 2: erosionZ = 0 erosionYX = erosionZYX elif len(erosionZYX) == 1: erosionZ = 0 erosionYX = erosionZYX[0] except TypeError: # scalar erosionZ = erosionZYX erosionYX = erosionZYX # magnification magZYX = N.ones((3, ), N.float32) magZYX[3 - len(shift[4:]):] = shift[4:] if len(shift[4:]) == 1: magZYX[1] = shift[4] # rotation r = shift[3] # target shape ZYX = N.asarray(ZYX, N.float32) ZYXm = ZYX * magZYX # Z z = N.where(shift[0] < 0, N.floor(shift[0]), N.ceil(shift[0])) ztop = ZYXm[0] + z nz = N.ceil(N.where(ztop > ZYX[0], ZYX[0], ztop)) z += erosionZ nz -= erosionZ if z < 0: z = 0 if nz < 0: nz = z + 1 zyx0 = N.ceil((ZYX - ZYXm) / 2.) #print zyx0 #if zyx0[0] > 0: # z -= zyx0[0] # nz += zyx0[0] zs = N.array([z, nz]) # YX #try: # if len(erosionYX) != 2: # raise ValueError, 'erosion is only applied to lateral dimension' #except TypeError: # erosionYX = (erosionYX, erosionYX) yxShift = N.where(shift[1:3] < 0, N.floor(shift[1:3]), N.ceil(shift[1:3])) # rotate the magnified center xyzm = N.ceil(ZYXm[::-1]) / 2. xyr = imgGeo.RotateXY(xyzm[:-1], r) xyr -= xyzm[:-1] yx = xyr[::-1] leftYX = N.ceil(N.abs(yx)) rightYX = -N.ceil(N.abs(yx)) # then translate leftYXShift = (leftYX + yxShift) + zyx0[1:] leftYXShift = N.where(leftYXShift < 0, 0, leftYXShift) rightYXShift = (rightYX + yxShift) - zyx0[1:] YXmax = N.where(ZYXm[1:] > ZYX[1:], ZYXm[1:], ZYX[1:]) rightYXShift = N.where(rightYXShift > 0, YXmax, rightYXShift + YXmax) # deal with - idx rightYXShift = N.where(rightYXShift > ZYX[1:], ZYX[1:], rightYXShift) leftYXShift += erosionYX rightYXShift -= erosionYX # (z0,z1,y0,y1,x0,x1) tempZYX = N.array( (zs[0], zs[1], int(N.ceil(leftYXShift[0])), int(rightYXShift[0]), int(N.ceil(leftYXShift[1])), int(rightYXShift[1]))) return tempZYX
def pointsCutOutND(arr, posList, windowSize=100, sectWise=None, interpolate=True): """ array: nd array posList: ([(z,)y,x]...) windowSize: scalar (in pixel or as percent < 1.) or ((z,)y,x) if arr.ndim > 2, and len(windowSize) == 2, then cut out section-wise (higher dimensions stay the same) sectWise: conern only XY of windowSize (higher dimensions stay the same) interpolate: shift array by subpixel interpolation to adjust center return: list of array centered at each pos in posList """ shape = N.array(arr.shape) center = shape / 2. # prepare N-dimensional window size try: len(windowSize) # seq if sectWise: windowSize = windowSize[-2:] if len(windowSize) != arr.ndim: dim = len(windowSize) windowSize = tuple(shape[:-dim]) + tuple(windowSize) except TypeError: # scaler if windowSize < 1 and windowSize > 0: # percentage w = shape * windowSize if sectWise: w[:-2] = shape[:-2] windowSize = w.astype(N.uint16) else: windowSize = N.where(shape >= windowSize, windowSize, shape) if sectWise: windowSize = arr.shape[:-2] + windowSize[-2:] windowSize = N.asarray(windowSize) # cutout individual position arrList = [] for pos in posList: # prepare N-dimensional coordinate n = len(pos) if n != len(windowSize): temp = center.copy() center[-n:] = pos pos = center # calculate idx ori = pos - (windowSize / 2.) # float value oidx = N.ceil(ori) # idx subpxl = oidx - ori # subpixel mod if interpolate and N.sometrue(subpxl): # comit to make shift SHIFT = 1 else: SHIFT = 0 # prepare slice # when comitted to make shift, first cut out window+1, # then make subpixle shift, and then cutout 1 edge slc = [Ellipsis] # Ellipsis is unnecessary, just in case... slc_edge = [slice(1, -1, None)] * arr.ndim for d in range(arr.ndim): start = oidx[d] - SHIFT if start < 0: start = 0 slc_edge[d] = slice(0, slc_edge[d].stop, None) stop = oidx[d] + windowSize[d] + SHIFT if stop > shape[d]: stop = shape[d] slc_edge[d] = slice(slc_edge[d].start, shape[d], None) slc += [slice(int(start), int(stop), None)] # cutout, shift and cutout try: canvas = arr[slc] if SHIFT: canvas = U.nd.shift(canvas, subpxl) canvas = canvas[slc_edge] check = 1 except IndexError: print('position ', pos, ' was skipped') check = 0 raise if check: arrList += [N.ascontiguousarray(canvas)] return arrList
def yExpProb(rhamda=1, t=0): t = N.asarray(t) return rhamda * N.exp(-rhamda * t)
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
def mask_value(arr, zyx, r=2.5, value=0): ''' Edit the pixels around zyx to be zero ''' from . import imgGeo sls = imgGeo.nearbyRegion(arr.shape, zyx, 2 * N.asarray(r) + 1) arr[sls] = value