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
def _smoothBorder(arr, start, stop, smooth, value): """ start, stop: [z,y,x] """ # prepare coordinates shape = N.array(arr.shape) start = N.ceil(start).astype(N.int16) stop = N.ceil(stop).astype(N.int16) smooth_start = start - smooth smooth_stop = stop + smooth smooth_start = N.where(smooth_start < 0, 0, smooth_start) smooth_stop = N.where(smooth_stop > shape, shape, smooth_stop) #print smooth_start, smooth_stop import copy sliceTemplate = [slice(None, None, None)] * arr.ndim shapeTemplate = list(shape) for d in range(arr.ndim): smooth_shape = shapeTemplate[:d] + shapeTemplate[d + 1:] # make an array containing the edge value edges = N.empty([2] + smooth_shape, N.float32) # start side slc = copy.copy(sliceTemplate) slc[d] = slice(start[d], start[d] + 1, None) edges[0] = arr[slc].reshape(smooth_shape) # stop side slc = copy.copy(sliceTemplate) slc[d] = slice(stop[d] - 1, stop[d], None) edges[1] = arr[slc].reshape(smooth_shape) edges = (edges - value) / float( smooth + 1) # this value can be array?? # both side for s, side in enumerate([start, stop]): if s == 0: rs = list(range(smooth_start[d], start[d])) rs.sort(reverse=True) elif s == 1: rs = list(range(stop[d], smooth_stop[d])) # smoothing for f, i in enumerate(rs): slc = copy.copy(sliceTemplate) slc[d] = slice(i, i + 1, None) edgeArr = edges[s].reshape(arr[slc].shape) #arr[slc] += edgeArr * (smooth - f) arr[slc] = arr[slc] + edgeArr * (smooth - f) # casting rule arr = N.ascontiguousarray(arr) return arr
def _smoothBorder(arr, start, stop, smooth, value): """ start, stop: [z,y,x] """ # prepare coordinates shape = N.array(arr.shape) start = N.ceil(start).astype(N.int16) stop = N.ceil(stop).astype(N.int16) smooth_start = start - smooth smooth_stop = stop + smooth smooth_start = N.where(smooth_start < 0, 0, smooth_start) smooth_stop = N.where(smooth_stop > shape, shape, smooth_stop) #print smooth_start, smooth_stop import copy sliceTemplate = [slice(None,None,None)] * arr.ndim shapeTemplate = list(shape) for d in range(arr.ndim): smooth_shape = shapeTemplate[:d] + shapeTemplate[d+1:] # make an array containing the edge value edges = N.empty([2] + smooth_shape, N.float32) # start side slc = copy.copy(sliceTemplate) slc[d] = slice(start[d], start[d]+1, None) edges[0] = arr[slc].reshape(smooth_shape) # stop side slc = copy.copy(sliceTemplate) slc[d] = slice(stop[d]-1, stop[d], None) edges[1] = arr[slc].reshape(smooth_shape) edges = (edges - value) / float(smooth + 1) # this value can be array?? # both side for s, side in enumerate([start, stop]): if s == 0: rs = list(range(smooth_start[d], start[d])) rs.sort(reverse=True) elif s == 1: rs = list(range(stop[d], smooth_stop[d])) # smoothing for f,i in enumerate(rs): slc = copy.copy(sliceTemplate) slc[d] = slice(i,i+1,None) edgeArr = edges[s].reshape(arr[slc].shape) #arr[slc] += edgeArr * (smooth - f) arr[slc] = arr[slc] + edgeArr * (smooth - f) # casting rule arr = N.ascontiguousarray(arr) return arr
def img2polar2D(img, center, final_radius=None, initial_radius=None, phase_width=360, return_idx=False): """ img: array center: coordinate y, x final_radius: ending radius initial_radius: starting radius phase_width: npixles / circle return_idx: return transformation coordinates (y,x) """ if img.ndim > 2 or len(center) > 2: raise ValueError( 'this function only support 2D, you entered %i-dim array and %i-dim center coordinate' % (img.ndim, len(center))) if initial_radius is None: initial_radius = 0 if final_radius is None: rad0 = N.ceil(N.array(img.shape) - center) final_radius = min((int(min(rad0)), int(min(N.ceil(center))))) if phase_width is None: phase_width = N.sum(img.shape[-2:]) * 2 theta, R = np.meshgrid(np.linspace(0, 2 * np.pi, phase_width), np.arange(initial_radius, final_radius)) Ycart, Xcart = polar2cart2D(R, theta, center) Ycart = N.where(Ycart >= img.shape[0], img.shape[0] - 1, Ycart) Xcart = N.where(Xcart >= img.shape[1], img.shape[1] - 1, Xcart) Ycart = Ycart.astype(int) Xcart = Xcart.astype(int) polar_img = img[Ycart, Xcart] polar_img = np.reshape(polar_img, (final_radius - initial_radius, phase_width)) if return_idx: return polar_img, Ycart, Xcart else: return polar_img
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
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 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 img2polar2D(img, center, final_radius=None, initial_radius = None, phase_width = 360, return_idx=False): """ img: array center: coordinate y, x final_radius: ending radius initial_radius: starting radius phase_width: npixles / circle return_idx: return transformation coordinates (y,x) """ if img.ndim > 2 or len(center) > 2: raise ValueError('this function only support 2D, you entered %i-dim array and %i-dim center coordinate' % (img.ndim, len(center))) if initial_radius is None: initial_radius = 0 if final_radius is None: rad0 = N.ceil(N.array(img.shape) - center) final_radius = min((int(min(rad0)), int(min(N.ceil(center))))) if phase_width is None: phase_width = N.sum(img.shape[-2:]) * 2 theta , R = np.meshgrid(np.linspace(0, 2*np.pi, phase_width), np.arange(initial_radius, final_radius)) Ycart, Xcart = polar2cart2D(R, theta, center) Ycart = N.where(Ycart >= img.shape[0], img.shape[0]-1, Ycart) Xcart = N.where(Xcart >= img.shape[1], img.shape[1]-1, Xcart) Ycart = Ycart.astype(int) Xcart = Xcart.astype(int) polar_img = img[Ycart,Xcart] polar_img = np.reshape(polar_img,(final_radius-initial_radius,phase_width)) if return_idx: return polar_img, Ycart, Xcart else: return polar_img
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)
def keepShape(a, shape, difmod=None): canvas = N.zeros(shape, a.dtype.type) if difmod is None: dif = (shape - N.array(a.shape, N.float32)) / 2. mod = N.ceil(N.mod(dif, 1)) else: dif, mod = difmod 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] if difmod is None: return canvas, mod else: return canvas
def keepShape(a, shape, difmod=None): canvas = N.zeros(shape, a.dtype.type) if difmod is None: dif = (shape - N.array(a.shape, N.float32)) / 2. mod = N.ceil(N.mod(dif, 1)) else: dif, mod = difmod 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] if difmod is None: return canvas, mod else: return canvas
def selectTimes(self, start=None, 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.nt if start is None: start = 0 unit = len(pattern) idx = N.arange(self.nt) repeat = N.ceil(self.nt / float(unit)) repPat = N.tile(pattern, repeat)[:len(idx)] ids = N.compress(repPat == pickWhich, idx) self._tIdx = [i for i in ids if i >= start and i < stop] self._tPtrn = pattern self._tPick = pickWhich
def rotateIndicesND(slicelist, dtype=N.float64, rot=0, mode=2): """ slicelist: even shape works much better than odd shape rot: counter-clockwise, xy-plane mode: testing different ways of doing, (1 or 2 and the same result) return inds, LD """ global INDS_DIC shape = [] LD = [] for sl in slicelist: if isinstance(sl, slice): shape.append(sl.stop - sl.start) LD.append(sl.start) shapeTuple = tuple(shape+[rot]) if shapeTuple in INDS_DIC: inds = INDS_DIC[shapeTuple] else: shape = N.array(shape) ndim = len(shape) odd_even = shape % 2 s2 = N.ceil(shape * (2**0.5)) if mode == 1: # everything is even s2 = N.where(s2 % 2, s2 + 1, s2) elif mode == 2: # even & even or odd & odd for d, s in enumerate(shape): if (s % 2 and not s2[d] % 2) or (not s % 2 and s2[d] % 2): s2[d] += 1 cent = s2 / 2. dif = (s2 - shape) / 2. dm = dif % 1 # print s2, cent, dif, dm slc = [Ellipsis] + [slice(int(d), int(d)+shape[i]) for i, d in enumerate(dif)] # This slice is float which shift array when cutting out!! s2 = tuple([int(ss) for ss in s2]) # numpy array cannot use used for slice inds = N.indices(s2, N.float32) ind_shape = inds.shape nz = N.product(ind_shape[:-2]) nsec = nz / float(ndim) if ndim > 2: inds = N.reshape(inds, (nz,)+ind_shape[-2:]) irs = N.empty_like(inds) for d, ind in enumerate(inds): idx = int(d//nsec) c = cent[idx] if rot and inds.ndim > 2: U.trans2d(ind - c, irs[d], (0,0,rot,1,0,1)) irs[d] += c - dif[idx] else: irs[d] = ind - dif[idx] if len(ind_shape) > 2: irs = N.reshape(irs, ind_shape) irs = irs[slc] if mode == 1 and N.sometrue(dm): inds = N.empty_like(irs) # print 'translate', dm for d, ind in enumerate(irs): U.trans2d(ind, inds[d], (-dm[1], -dm[0], 0, 1, 0, 1)) else: inds = irs INDS_DIC[shapeTuple] = inds r_inds = N.empty_like(inds) for d, ld in enumerate(LD): r_inds[d] = inds[d] + ld return r_inds, LD
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 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 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 rotateIndicesND(slicelist, dtype=N.float64, rot=0, mode=2): """ slicelist: even shape works much better than odd shape rot: counter-clockwise, xy-plane mode: testing different ways of doing, (1 or 2 and the same result) return inds, LD """ global INDS_DIC shape = [] LD = [] for sl in slicelist: if isinstance(sl, slice): shape.append(sl.stop - sl.start) LD.append(sl.start) shapeTuple = tuple(shape + [rot]) if shapeTuple in INDS_DIC: inds = INDS_DIC[shapeTuple] else: shape = N.array(shape) ndim = len(shape) odd_even = shape % 2 s2 = N.ceil(shape * (2**0.5)) if mode == 1: # everything is even s2 = N.where(s2 % 2, s2 + 1, s2) elif mode == 2: # even & even or odd & odd for d, s in enumerate(shape): if (s % 2 and not s2[d] % 2) or (not s % 2 and s2[d] % 2): s2[d] += 1 cent = s2 / 2. dif = (s2 - shape) / 2. dm = dif % 1 # print s2, cent, dif, dm slc = [Ellipsis] + [ slice(int(d), int(d) + shape[i]) for i, d in enumerate(dif) ] # This slice is float which shift array when cutting out!! s2 = tuple([int(ss) for ss in s2]) # numpy array cannot use used for slice inds = N.indices(s2, N.float32) ind_shape = inds.shape nz = N.product(ind_shape[:-2]) nsec = nz / float(ndim) if ndim > 2: inds = N.reshape(inds, (nz, ) + ind_shape[-2:]) irs = N.empty_like(inds) for d, ind in enumerate(inds): idx = int(d // nsec) c = cent[idx] if rot and inds.ndim > 2: U.trans2d(ind - c, irs[d], (0, 0, rot, 1, 0, 1)) irs[d] += c - dif[idx] else: irs[d] = ind - dif[idx] if len(ind_shape) > 2: irs = N.reshape(irs, ind_shape) irs = irs[slc] if mode == 1 and N.sometrue(dm): inds = N.empty_like(irs) # print 'translate', dm for d, ind in enumerate(irs): U.trans2d(ind, inds[d], (-dm[1], -dm[0], 0, 1, 0, 1)) else: inds = irs INDS_DIC[shapeTuple] = inds r_inds = N.empty_like(inds) for d, ld in enumerate(LD): r_inds[d] = inds[d] + ld return r_inds, LD
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] + tuple(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 #print(slc, slc_edge) try: canvas = arr[slc] if SHIFT: # 20180214 subpixel shift +0.5 was fixed #raise RuntimeError('check') if sectWise: subpxl[-2:] = N.where(windowSize[-2:] > 1, subpxl[-2:]-0.5, subpxl[-2:]) else: subpxl[-n:] = N.where(windowSize[-n:] > 1, subpxl[-n:]-0.5, subpxl[-n:]) 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 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