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 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 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 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 Xcorr(a, b, phaseContrast=PHASE, nyquist=NYQUIST, removeEdge=0, gFit=True, win=11, ret=None, searchRad=None): """ sigma uses F.gaussianArr in the Fourier domain if ret is None: return zyx, xcf elif ret is 2: return s, v, zyx, xcf elif ret: return v, zyx, xcf """ #print 'phase contrast: %s' % str(phaseContrast) #global DATA # correct odd shape particularly Z axis a = N.squeeze(a) b = N.squeeze(b) a = imgFilters.evenShapeArr(a) b = imgFilters.evenShapeArr(b) shape = N.array(a.shape) # apodize a = apodize(a) b = apodize(b) # fourier transform af = F.rfft(a.astype(N.float32)) bf = F.rfft(b.astype(N.float32)) del a, b # phase contrast filter (removing any intensity information) if phaseContrast: afa = phaseContrastFilter(af, True, nyquist=nyquist) bfa = phaseContrastFilter(bf, True, nyquist=nyquist) else: afa = af bfa = bf del af, bf # removing edge if gaussian is not sufficient targetShape = shape - N.multiply(removeEdge, 2) if removeEdge: ap = imgFilters.cutOutCenter(F.irfft(afa), targetShape) bp = imgFilters.cutOutCenter(F.irfft(bfa), targetShape) afa = F.rfft(ap) bfa = F.rfft(bp) del ap, bp # shift array delta = targetShape / 2. shiftarr = F.fourierRealShiftArr(tuple(targetShape), delta) bfa *= shiftarr # cross correlation bfa = bfa.conjugate() c = cc = F.irfft(afa * bfa) center = N.divide(c.shape, 2) if searchRad: slc = imgGeo.nearbyRegion(c.shape, center, searchRad) cc = N.zeros_like(c) cc[slc] = c[slc] v, zyx, s = _findMaxXcor(cc, win, gFit=gFit) zyx -= center if ret == 2: return s, v, zyx, c elif ret: return v, zyx, c else: return zyx, c
from Priithon.all import F as fftw #from Priithon.all import F as fftw try: if mexhatC.shape != a.shape: raise ValueError, 'go to except' if mexhatC_size != mexSize: raise ValueError, 'go to except' except NameError, ValueError: mexhatC_size = mexSize shape = N.asarray(a.shape, N.float32) mexhatC = F.shift( F.mexhatArr(shape, scaleHalfMax=mexhatC_size, orig=None)) # orig 0.5 pixel does not work... mexhatCf = fftw.rfft(mexhatC) / N.multiply.reduce(shape) ar = fftw.irfft(fftw.rfft(a.astype(N.float32)) * mexhatCf) #if trimRatio < 1: # ar = trim3D(ar, trimRatio) #ar = imgFilters.maskEdgeWithValue2D(ar) # 2 pixels at the edges return ar GAUSS = None def phaseContrastFilter(a, inFourier=False, removeNan=True, nyquist=0.6): global GAUSS if inFourier: af = a.copy() else:
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, phaseContrast=PHASE, nyquist=NYQUIST, gFit=True, win=11, ret=None, searchRad=None, npad=4): """ sigma uses F.gaussianArr in the Fourier domain if ret is None: return zyx, xcf elif ret is 2: return s, v, zyx, xcf elif ret is 3: return zyx, xcf, a_phase_cotrast, b_phase_contrast elif ret: return v, zyx, xcf """ #print 'phase contrast: %s' % str(phaseContrast) #global DATA # correct odd shape particularly Z axis a = N.squeeze(a) b = N.squeeze(b) a = imgFilters.evenShapeArr(a) b = imgFilters.evenShapeArr(b) shape = N.array(a.shape) # padding strange shape #nyx = max(shape[-2:]) #pshape = N.array(a.shape[:-2] + (nyx,nyx)) # apodize a = paddAndApo(a, npad)#, pshape) #apodize(a) b = paddAndApo(b, npad)#, pshape) #apodize(b) # fourier transform af = F.rfft(a.astype(N.float32)) bf = F.rfft(b.astype(N.float32)) del a, b # phase contrast filter (removing any intensity information) if phaseContrast: afa = phaseContrastFilter(af, True, nyquist=nyquist) bfa = phaseContrastFilter(bf, True, nyquist=nyquist) else: afa = af bfa = bf del af, bf #targetShape = shape + (npad * 2) targetShape = shape + (npad * 2) # shift array delta = targetShape / 2. shiftarr = F.fourierRealShiftArr(tuple(targetShape), delta) bfa *= shiftarr # cross correlation bfa = bfa.conjugate() #c = cc = F.irfft(afa * bfa) c = F.irfft(afa * bfa) # 20180214 the padded region was cutout before finding the peak. c = cc = imgFilters.cutOutCenter(c, N.array(c.shape) - (npad * 2), interpolate=False) #cc = c center = N.divide(c.shape, 2) if searchRad: slc = imgGeo.nearbyRegion(c.shape, center, searchRad) cc = N.zeros_like(c) cc[slc] = c[slc] v, zyx, s = _findMaxXcor(cc, win, gFit=gFit) #return cc #print(zyx, center) zyx -= center #c = imgFilters.cutOutCenter(c, N.array(c.shape) - (npad * 2), interpolate=False) #c = imgFilters.cutOutCenter(c, shape, interpolate=False) if ret == 3: return zyx, c, F.irfft(afa), F.irfft(bfa) elif ret == 2: return s, v, zyx, c elif ret: return v, zyx, c else: return zyx, c
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, phaseContrast=PHASE, nyquist=NYQUIST, gFit=True, win=11, ret=None, searchRad=None, npad=4): """ sigma uses F.gaussianArr in the Fourier domain if ret is None: return zyx, xcf elif ret is 2: return s, v, zyx, xcf elif ret is 3: return zyx, xcf, a_phase_cotrast, b_phase_contrast elif ret: return v, zyx, xcf """ #print 'phase contrast: %s' % str(phaseContrast) #global DATA # correct odd shape particularly Z axis a = N.squeeze(a) b = N.squeeze(b) a = imgFilters.evenShapeArr(a) b = imgFilters.evenShapeArr(b) shape = N.array(a.shape) # padding strange shape #nyx = max(shape[-2:]) #pshape = N.array(a.shape[:-2] + (nyx,nyx)) # apodize a = paddAndApo(a, npad) #, pshape) #apodize(a) b = paddAndApo(b, npad) #, pshape) #apodize(b) # fourier transform af = F.rfft(a.astype(N.float32)) bf = F.rfft(b.astype(N.float32)) del a, b # phase contrast filter (removing any intensity information) if phaseContrast: afa = phaseContrastFilter(af, True, nyquist=nyquist) bfa = phaseContrastFilter(bf, True, nyquist=nyquist) else: afa = af bfa = bf del af, bf #targetShape = shape + (npad * 2) targetShape = shape + (npad * 2) # shift array delta = targetShape / 2. shiftarr = F.fourierRealShiftArr(tuple(targetShape), delta) bfa *= shiftarr # cross correlation bfa = bfa.conjugate() c = cc = F.irfft(afa * bfa) center = N.divide(c.shape, 2) if searchRad: slc = imgGeo.nearbyRegion(c.shape, center, searchRad) cc = N.zeros_like(c) cc[slc] = c[slc] v, zyx, s = _findMaxXcor(cc, win, gFit=gFit) zyx -= center c = imgFilters.cutOutCenter(c, N.array(c.shape) - (npad * 2), interpolate=False) #c = imgFilters.cutOutCenter(c, shape, interpolate=False) if ret == 3: return zyx, c, F.irfft(afa), F.irfft(bfa) elif ret == 2: return s, v, zyx, c elif ret: return v, zyx, c else: return zyx, c