Exemplo n.º 1
0
def _doBilinear2D(a2d, tyx=(0,0), r=0, mag=1, anismag=1, dyx=(0,0), mr=0, b2d=None):
    if b2d is None:
        b2d = N.empty_like(a2d)
    else:
        b2d = N.ascontiguousarray(b2d)
    a2d = a2d.copy() # otherwise, the following code will mess up the input

    if N.any(dyx[-2:]) or mr:
        temp = b2d
        target = a2d
        U.trans2d(target, temp, (dyx[-1], dyx[-2], mr, 1, 0, 1))
    else:
        temp = a2d
        target = b2d

    # rot mag first to make consistent with affine
    magaxis = 1 # only this axis works
    if r or mag != 1 or anismag != 1:
        U.trans2d(temp, target, (0, 0, r, mag, magaxis, anismag))
    else:
        target[:] = temp[:]

    # then translate
    tyx2 = N.array(tyx) # copy
    tyx2[-2:] -= dyx[-2:]
    if N.any(tyx2[-2:]) or mr:
        U.trans2d(target, temp, (tyx2[-1], tyx2[-2], -mr, 1, 0, 1))
    else:
        temp[:] = target[:]
    #a[z] = temp[:]
    return temp
Exemplo n.º 2
0
def _doBilinear2D(a2d, tyx=(0,0), r=0, mag=1, anismag=1, dyx=(0,0), mr=0, b2d=None):
    if b2d is None:
        b2d = N.empty_like(a2d)
    else:
        b2d = N.ascontiguousarray(b2d)
    a2d = a2d.copy() # otherwise, the following code will mess up the input

    if N.any(dyx[-2:]) or mr:
        temp = b2d
        target = a2d
        U.trans2d(target, temp, (dyx[-1], dyx[-2], mr, 1, 0, 1))
    else:
        temp = a2d
        target = b2d

    # rot mag first to make consistent with affine
    magaxis = 1 # only this axis works
    if r or mag != 1 or anismag != 1:
        U.trans2d(temp, target, (0, 0, r, mag, magaxis, anismag))
    else:
        target[:] = temp[:]

    # then translate
    tyx2 = N.array(tyx) # copy
    tyx2[-2:] -= dyx[-2:]
    if N.any(tyx2[-2:]) or mr:
        U.trans2d(target, temp, (tyx2[-1], tyx2[-2], -mr, 1, 0, 1))
    else:
        temp[:] = target[:]
    #a[z] = temp[:]
    return temp
Exemplo n.º 3
0
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
Exemplo n.º 4
0
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
Exemplo n.º 5
0
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
Exemplo n.º 6
0
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
Exemplo n.º 7
0
def trans3D_bilinear(a,
                     tzyx=(0, 0, 0),
                     r=0,
                     mag=1,
                     dzyx=(0, 0, 0),
                     b=None,
                     rzy=0,
                     **kwds):
    """
    magyx: scalar or [y,x] or [y,x, direction in degrees]
    """
    a = a.copy()
    ndim = a.ndim
    if ndim == 2:
        a = a.reshape((1, ) + a.shape)

    try:
        if len(magyx) == 3:
            mr = magyx[-1]
            magyx = magyx[:2]
        else:
            mr = 0
    except:
        mr = 0

    if b is None:
        b2d = N.empty_like(a[0])

    dzyx = N.asarray(dzyx)
    tzyx = N.asarray(tzyx)
    tzyx[-2:] += dzyx[-2:]

    magaxis = 1  # only this axis works
    magz = 1
    try:
        if len(mag) == 3:
            magz, magy, magx = mag
        elif len(mag) == 2:
            magy, magx = mag
        else:
            magy = magx = mag[0]
    except:
        magy = magx = mag
    mag = magy
    anismag = magx / magy

    for z, a2d in enumerate(a):
        if N.any(dzyx[-2:]) or mr:
            temp = N.ascontiguousarray(b2d)
            target = N.ascontiguousarray(a2d)
            #U.trans2d(target, temp, (-dyx[1], -dyx[0], -mr, 1, 0, 1))
            U.trans2d(target, temp, (-dzyx[-1], -dzyx[-2], -mr, 1, 0, 1))
        else:
            temp = N.ascontiguousarray(a2d)
            target = N.ascontiguousarray(b2d)

        if r or mag != 1 or anismag != 1:
            U.trans2d(temp, target, (0, 0, r, mag, magaxis, anismag))
        else:
            target[:] = temp[:]

        #if rzx: # is this correct?? havn't tried yet
        #    target = U.nd.rotate(target, rzx, axes=(0,2), order=1, prefilter=False)

        if N.any(tzyx[-2:]) or mr:  #N.any(dyx) or mr:
            #U.trans2d(target, temp, (dyx[1], dyx[0], mr, 1, 0, 1))
            U.trans2d(target, temp, (tzyx[-1], tzyx[-2], mr, 1, 0, 1))
        else:
            temp[:] = target[:]
        a[z] = temp[:]

    if ndim == 2:
        a = a[0]
    elif ndim == 3 and (magz != 1 or tzyx[-3]):
        at = a.T  # zyx -> xyz
        mag = 1  #magz
        anismag = magz  #magy / magz
        canvas = N.empty_like(at)
        target = b2d.T
        for x, a2d in enumerate(at):
            if dzyx[-3]:
                U.trans2d(a2d, target, (0, -dyzx[-3], 0, 1, 1, 1))
            else:
                target = a2d

            canvas[x] = U.trans2d(target, None,
                                  (tzyx[-3], 0, rzy, mag, magaxis, anismag))
        #canvas = canvas.T
        a = canvas.T

    return a
Exemplo n.º 8
0
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
Exemplo n.º 9
0
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
Exemplo n.º 10
0
def trans3D_bilinear(a, tzyx=(0,0,0), r=0, mag=1, dzyx=(0,0,0), b=None, rzy=0, **kwds):
    """
    magyx: scalar or [y,x] or [y,x, direction in degrees]
    """
    a = a.copy()
    ndim = a.ndim
    if ndim == 2:
        a = a.reshape((1,)+a.shape)
        
    try:
        if len(magyx) == 3:
            mr = magyx[-1]
            magyx = magyx[:2]
        else:
            mr = 0
    except:
        mr = 0

    if b is None:
        b2d = N.empty_like(a[0])

    dzyx = N.asarray(dzyx)
    tzyx = N.asarray(tzyx)
    tzyx[-2:] += dzyx[-2:]

    magaxis = 1 # only this axis works
    magz = 1
    try:
        if len(mag) == 3:
            magz, magy, magx = mag
        elif len(mag) == 2:
            magy, magx = mag
        else:
            magy = magx = mag[0]
    except:
        magy = magx = mag
    mag = magy
    anismag = magx / magy

    for z, a2d in enumerate(a):
        if N.any(dzyx[-2:]) or mr:
            temp = N.ascontiguousarray(b2d)
            target = N.ascontiguousarray(a2d)
            #U.trans2d(target, temp, (-dyx[1], -dyx[0], -mr, 1, 0, 1))
            U.trans2d(target, temp, (-dzyx[-1], -dzyx[-2], -mr, 1, 0, 1))
        else:
            temp = N.ascontiguousarray(a2d)
            target = N.ascontiguousarray(b2d)

        if r or mag != 1 or anismag != 1:
            U.trans2d(temp, target, (0, 0, r, mag, magaxis, anismag))
        else:
            target[:] = temp[:]

        #if rzx: # is this correct?? havn't tried yet
        #    target = U.nd.rotate(target, rzx, axes=(0,2), order=1, prefilter=False)

        if N.any(tzyx[-2:]) or mr:#N.any(dyx) or mr:
            #U.trans2d(target, temp, (dyx[1], dyx[0], mr, 1, 0, 1))
            U.trans2d(target, temp, (tzyx[-1], tzyx[-2], mr, 1, 0, 1))
        else:
            temp[:] = target[:]
        a[z] = temp[:]

    if ndim == 2:
        a = a[0]
    elif ndim == 3 and (magz != 1 or tzyx[-3]):
        at = a.T # zyx -> xyz
        mag = 1#magz
        anismag = magz #magy / magz
        canvas = N.empty_like(at)
        target = b2d.T
        for x, a2d in enumerate(at):
            if dzyx[-3]:
                U.trans2d(a2d, target, (0, -dyzx[-3], 0, 1, 1, 1))
            else:
                target = a2d

            canvas[x] = U.trans2d(target, None, (tzyx[-3], 0, rzy, mag, magaxis, anismag))
        #canvas = canvas.T
        a = canvas.T

    return a