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
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
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
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)
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)
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
def _fitGaussianND(img, inds, zyx, sigma=0.5, mean_max=None): """ img: already cut out """ ndim = img.ndim if mean_max is None: mi, ma, me, sd = U.mmms(img) else: me, ma = mean_max try: if len(sigma) == ndim: sigma = [float(s) for s in sigma] except (ValueError, TypeError): sigma = [float(sigma) for i in range(ndim)] param0 = [me, float(ma-me)] + list(zyx) + sigma param0 = N.asarray(param0, N.float64) img = img.flatten() sidx = 2 + ndim def func(p, inds, sidx): return yGaussianND(p, inds, sidx) - img from scipy import optimize inds = [inds[i].flatten().astype(N.float64) for i in range(ndim)] if hasattr(optimize, 'least_squares'): ret = optimize.least_squares(func, param0, args=(inds, sidx)) check = ret.status if check == -1: check = 5 ret = ret.x else: try: ret, check = optimize.leastsq(func, param0, args=(inds,sidx), warning=None) except TypeError: # python2.6 ret, check = optimize.leastsq(func, param0, args=(inds,sidx)) #ret[2:5] -= 0.5 # ret[2:5] += 0.5 # use pixel center ret[sidx:] = N.abs(ret[sidx:]) return ret, check
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
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 _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
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
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 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 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