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 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)
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)
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)
def logpolar(image, center=None, angles=None, radii=None): """Return log-polar transformed image and log base.""" shape = image.shape if center is None: center = shape[0] / 2, shape[1] / 2 if angles is None: angles = shape[0] if radii is None: radii = shape[1] theta = N.zeros((angles, radii), dtype=N.float64) theta.T[:] = -N.linspace(0, N.pi, angles, endpoint=False) #d = radii d = N.hypot(shape[0] - center[0], shape[1] - center[1]) log_base = 10.0**(N.log10(d) / (radii)) radius = N.empty_like(theta) radius[:] = N.power(log_base, N.arange(radii, dtype=N.float64)) - 1.0 x = radius * N.sin(theta) + center[0] y = radius * N.cos(theta) + center[1] output = N.zeros_like(x) ndii.map_coordinates(image, [x, y], output=output) return output, log_base
def logpolar(image, center=None, angles=None, radii=None): """Return log-polar transformed image and log base.""" shape = image.shape if center is None: center = shape[0] / 2, shape[1] / 2 if angles is None: angles = shape[0] if radii is None: radii = shape[1] theta = N.zeros((angles, radii), dtype=N.float64) theta.T[:] = -N.linspace(0, N.pi, angles, endpoint=False) #d = radii d = N.hypot(shape[0]-center[0], shape[1]-center[1]) log_base = 10.0 ** (N.log10(d) / (radii)) radius = N.empty_like(theta) radius[:] = N.power(log_base, N.arange(radii, dtype=N.float64)) - 1.0 x = radius * N.sin(theta) + center[0] y = radius * N.cos(theta) + center[1] output = N.zeros_like(x) ndii.map_coordinates(image, [x, y], output=output) return output, log_base
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)
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 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 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
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, 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
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)