def __getitem__(self, idx): try: idx = int(idx) if idx < 0: idx = self.shape[0] + idx ws = range(self.nw) ts = range(self.nt) zs = range(self.nz) if self.maxaxs == 'w' and not self.ignor_color_axis: ws = [idx] self.sld_axs = 'w' elif self.maxaxs == 't' or (self.ignor_color_axis and self.ndim > 4): ts = [idx] self.sld_axs = 't' elif self.maxaxs == 'z' or (self.ignor_color_axis and self.ndim == 4): zs = [idx] self.sld_axs = 'z' else: raise ValueError, 'section axis not determined' if self.hdr.ImgSequence == 0: e = N.empty((len(ws), len(ts), len(zs), self.ny, self.nx), self.dtype) for wo, wi in enumerate(ws): for to, ti in enumerate(ts): for zo, zi in enumerate(zs): e[wo, to, zo] = self.img.getArr(w=wi, t=ti, z=zi) elif self.hdr.ImgSequence == 1: e = N.empty((len(ts), len(zs), len(ws), self.ny, self.nx), self.dtype) for to, ti in enumerate(ts): for zo, zi in enumerate(zs): for wo, wi in enumerate(ws): e[to, zo, wo] = self.img.getArr(w=wi, t=ti, z=zi) elif self.hdr.ImgSequence == 2: e = N.empty((len(ts), len(ws), len(zs), self.ny, self.nx), self.dtype) for to, ti in enumerate(ts): for wo, wi in enumerate(ws): for zo, zi in enumerate(zs): e[to, wo, zo] = self.img.getArr(w=wi, t=ti, z=zi) except TypeError: pass return N.squeeze(e)
def _cutoutForAlign2(fn, py, outFn=''): """ if not outFn, default with 'cut' extention resulting array is imgSequence=0 (t,w,z,y,x) return outFn """ h = imgManager.ImageManager(fn) slc, shiftZYX, ZYX = makeSlice(h, py) # input arr = N.empty((h.nt, h.nw, h.nz, h.ny, h.nx), h.dtype) for t in range(h.nt): for w in range(h.nw): arr[t, w] = h.get3DArr(w=w, t=t) canvas = N.squeeze(arr[slc].astype(arr.dtype.type)) newNum = (canvas.shape[-1], canvas.shape[-2], N.prod(canvas.shape[:-3])) if not outFn: outFn = '_'.join((h.filePath, EXT_CUTOUT)) #arr.Mrc.path, EXT_CUTOUT)) hdr = Mrc.makeHdrArray() Mrc.initHdrArrayFrom(hdr, h.hdr) #arr.Mrc.hdr) hdr.ImgSequence = 2 hdr.Num[:] = newNum mstart = [sl.start for sl in slc[::-1][:3] if isinstance(sl, slice)] hdr.mst[:len(mstart)] += mstart Mrc.save(canvas, outFn, ifExists='overwrite', hdr=hdr) return outFn
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 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 _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 paddingValue(img, shape, value=0, shift=None, smooth=0, interpolate=True): """ shape: in the same dimension as img value: value in padded region, can be scaler or array with the shape shift: scaler or in the same dimension as img and shape (default 0) smooth: scaler value to smoothen border (here value must be scaler) interpolate: shift array by subpixel interpolation to adjust center return: padded array with shape """ # create buffer dtype = img.dtype.type canvas = N.empty(shape, dtype) canvas[:] = value # calculate position shape = N.array(shape) shapeS = img.shape center = N.divide(shape, 2) if shift is None: shift = 0#[0] * len(shapeS) shapeL = shape#N.add(shapeS, center+shift) #start, stop = (shapeL - shapeS)/2., (shapeL + shapeS)/2. start = N.round_((shapeL - shapeS)/2.).astype(N.int) stop = shapeS + start slc = [slice(start[d], stop[d], None) for d in range(img.ndim)] #slc = [slice(int(round(start[d])), int(round(stop[d])), None) for d in range(img.ndim)] #print slc, shapeS, shapeL # shift if necessary if interpolate: subpx_shift = start % 1 # should be 0.5 or 0 if N.sometrue(subpx_shift): img = U.nd.shift(img, subpx_shift) # padding canvas[slc] = img if smooth: canvas = _smoothBorder(canvas, start, stop, smooth, value) canvas = N.ascontiguousarray(canvas) #print shapeS, shapeL, slc return canvas
def paddingValue(img, shape, value=0, shift=None, smooth=0, interpolate=True): """ shape: in the same dimension as img value: value in padded region, can be scaler or array with the shape shift: scaler or in the same dimension as img and shape (default 0) smooth: scaler value to smoothen border (here value must be scaler) interpolate: shift array by subpixel interpolation to adjust center return: padded array with shape """ # create buffer dtype = img.dtype.type canvas = N.empty(shape, dtype) canvas[:] = value # calculate position shape = N.array(shape) shapeS = img.shape center = N.divide(shape, 2) if shift is None: shift = 0 #[0] * len(shapeS) shapeL = shape #N.add(shapeS, center+shift) #start, stop = (shapeL - shapeS)/2., (shapeL + shapeS)/2. start = N.round_((shapeL - shapeS) / 2.).astype(N.int) stop = shapeS + start slc = [slice(start[d], stop[d], None) for d in range(img.ndim)] #slc = [slice(int(round(start[d])), int(round(stop[d])), None) for d in range(img.ndim)] #print slc, shapeS, shapeL # shift if necessary if interpolate: subpx_shift = start % 1 # should be 0.5 or 0 if N.sometrue(subpx_shift): img = U.nd.shift(img, subpx_shift) # padding canvas[slc] = img if smooth: canvas = _smoothBorder(canvas, start, stop, smooth, value) canvas = N.ascontiguousarray(canvas) #print shapeS, shapeL, slc return canvas
def get3DArr(self, w=0, t=None, zs=None): """ t: if None, use self.tSlice zs: if None, all z secs, else supply sequence of z sec return as (z,y,x) shape if self.useTinplaceofZ is True, return as (t,y,x) shape """ if t is None: t = self.tSlice if zs is None: zs = range(self.nz) nz = len(zs) arr = N.empty((nz, self.ny, self.nx), self.dtype) for i, z in enumerate(zs): arr[i] = self.img.getArr(t=t, w=w, z=z) return arr
def radialaverage(data, center=None, useMaxShape=False): """ data: ND array center: coordinate of center of radii useMinShape: the output uses the maximum shape available return 1D array """ if center is None: center = N.array(data.shape) // 2 if len(center) != data.ndim: raise ValueError( 'dimension of center (%i) does not match the dimension of data (%i)' % (len(center), data.ndim)) zyx = N.indices((data.shape)) r = N.zeros(data.shape, N.float32) for i, t in enumerate(zyx): r += (t - center[i])**2 r = N.sqrt(r) #y, x = N.indices((data.shape)) #r = N.sqrt((x - center[0])**2 + (y - center[1])**2) # distance from the center r = r.astype(N.int) if data.dtype.type in (N.complex64, N.complex128): rbin = N.bincount(r.ravel(), data.real.ravel()) ibin = N.bincount(r.ravel(), data.imag.ravel()) tbin = N.empty(rbin.shape, data.dtype.type) tbin.real = rbin tbin.imag = ibin else: tbin = N.bincount(r.ravel(), data.ravel()) nr = N.bincount(r.ravel()) radialprofile = tbin / nr.astype(N.float32) if not useMaxShape: minShape = min(list(N.array(data.shape) - center) + list(center)) radialprofile = radialprofile[:minShape] return radialprofile
def radialaverage(data, center=None, useMaxShape=False): """ data: ND array center: coordinate of center of radii useMinShape: the output uses the maximum shape available return 1D array """ if center is None: center = N.array(data.shape) // 2 if len(center) != data.ndim: raise ValueError('dimension of center (%i) does not match the dimension of data (%i)' % (len(center), data.ndim)) zyx = N.indices((data.shape)) r = N.zeros(data.shape, N.float32) for i, t in enumerate(zyx): r += (t - center[i])**2 r = N.sqrt(r) #y, x = N.indices((data.shape)) #r = N.sqrt((x - center[0])**2 + (y - center[1])**2) # distance from the center r = r.astype(N.int) if data.dtype.type in (N.complex64, N.complex128): rbin = N.bincount(r.ravel(), data.real.ravel()) ibin = N.bincount(r.ravel(), data.imag.ravel()) tbin = N.empty(rbin.shape, data.dtype.type) tbin.real = rbin tbin.imag = ibin else: tbin = N.bincount(r.ravel(), data.ravel()) nr = N.bincount(r.ravel()) radialprofile = tbin / nr.astype(N.float32) if not useMaxShape: minShape = min(list(N.array(data.shape) - center) + list(center)) radialprofile = radialprofile[:minShape] return radialprofile
def radialAverage2D(arr, center=None, useMaxShape=False): """ 2D-wise radial average arr: ND (>2) array center: 2D center to radial average return ND-1 array """ if arr.ndim == 2: return radialaverage(arr, center, useMaxShape) for t, img in enumerate(arr): if img.ndim >= 3: ra = radialaverage2D(img, center, useMaxShape) else: # 2D ra = radialaverage(img, center, useMaxShape) try: canvas[t] = ra except NameError: # canvas was not defined yet canvas = N.empty((arr.shape[0],) + ra.shape, ra.dtype.type) canvas[t] = ra return canvas
def radialAverage2D(arr, center=None, useMaxShape=False): """ 2D-wise radial average arr: ND (>2) array center: 2D center to radial average return ND-1 array """ if arr.ndim == 2: return radialaverage(arr, center, useMaxShape) for t, img in enumerate(arr): if img.ndim >= 3: ra = radialaverage2D(img, center, useMaxShape) else: # 2D ra = radialaverage(img, center, useMaxShape) try: canvas[t] = ra except NameError: # canvas was not defined yet canvas = N.empty((arr.shape[0], ) + ra.shape, ra.dtype.type) canvas[t] = ra return canvas