Ejemplo n.º 1
0
def map_coordinates(input, coordinates, output_type = None, output = None,
                order = 3, mode = 'constant', cval = 0.0, prefilter = True):
    """Apply an arbritrary coordinate transformation.

    The array of coordinates is used to find for each point in the output 
    the corresponding coordinates in the input. The value of the input at 
    that coordinates is determined by spline interpolation of the 
    requested order. Points outside the boundaries of the input are filled 
    according to the given mode. The parameter prefilter determines if the 
    input is pre-filtered before interpolation, if False it is assumed 
    that the input is already filtered.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    coordinates = numarray.asarray(coordinates)
    if isinstance(coordinates.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    output_shape = coordinates.shape[1:]
    if input.rank < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    if coordinates.shape[0] != input.rank:
        raise RuntimeError, 'invalid shape for coordinate array'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output = numarray.Float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output, input,
                                        output_type, shape = output_shape)
    _nd_image.geometric_transform(filtered, None, coordinates, None, None,
               output, order, mode, cval, None, None)
    return return_value
Ejemplo n.º 2
0
def correlate1d(input,
                weights,
                axis=-1,
                output=None,
                mode="reflect",
                cval=0.0,
                origin=0):
    """Calculate a one-dimensional correlation along the given axis.

    The lines of the array along the given axis are correlated with the     
    given weights. The weights parameter must be a one-dimensional sequence 
    of numbers."""
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    output, return_value = _ni_support._get_output(output, input)
    weights = numarray.asarray(weights, type=numarray.Float64)
    if weights.rank != 1 or weights.shape[0] < 1:
        raise RuntimeError, 'no filter weights given'
    if not weights.iscontiguous():
        weights = weights.copy()
    axis = _ni_support._check_axis(axis, input.rank)
    if ((len(weights) // 2 + origin < 0)
            or (len(weights) // 2 + origin > len(weights))):
        raise ValueError, 'invalid origin'
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.correlate1d(input, weights, axis, output, mode, cval, origin)
    return return_value
Ejemplo n.º 3
0
def correlate1d(input, weights, axis = -1, output = None, mode = "reflect",
                cval = 0.0, origin = 0):
    """Calculate a one-dimensional correlation along the given axis.

    The lines of the array along the given axis are correlated with the
    given weights.

    Parameters
    ----------
    %(input)s
    weights : array
        one-dimensional sequence of numbers
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s
    """
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError('Complex type not supported')
    output, return_value = _ni_support._get_output(output, input)
    weights = numpy.asarray(weights, dtype=numpy.float64)
    if weights.ndim != 1 or weights.shape[0] < 1:
        raise RuntimeError('no filter weights given')
    if not weights.flags.contiguous:
        weights = weights.copy()
    axis = _ni_support._check_axis(axis, input.ndim)
    if ((len(weights) // 2 + origin < 0) or
        (len(weights) // 2 + origin > len(weights))):
        raise ValueError('invalid origin')
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.correlate1d(input, weights, axis, output, mode, cval,
                          origin)
    return return_value
Ejemplo n.º 4
0
def generic_filter1d(input, function, filter_size, axis = -1,
                 output = None, mode = "reflect", cval = 0.0, origin = 0,
                 extra_arguments = (), extra_keywords = {}):
    """Calculate a one-dimensional filter along the given axis.

    The function iterates over the lines of the array, calling the given
    function at each line. The arguments of the line are the input line,
    and the output line. The input and output lines are 1D double arrays.
    The input line is extended appropiately according to the filter size
    and  origin. The output line must be modified in-place with the result.
    The origin parameter controls  the placement of the filter. The mode
    parameter determines how the array borders are handled, where cval is
    the value when mode is equal to 'constant'. The extra_arguments and
    extra_keywords arguments can be used to pass extra arguments and
    keywords that are passed to the function at each call."""
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    output, return_value = _ni_support._get_output(output, input)
    if filter_size < 1:
        raise RuntimeError, 'invalid filter size'
    axis = _ni_support._check_axis(axis, input.ndim)
    if ((filter_size // 2 + origin < 0) or
        (filter_size // 2 + origin > filter_size)):
        raise ValueError, 'invalid origin'
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.generic_filter1d(input, function, filter_size, axis, output,
                      mode, cval, origin, extra_arguments, extra_keywords)
    return return_value
Ejemplo n.º 5
0
def _correlate_or_convolve(input, weights, output, mode, cval, origin,
                           convolution):
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    origins = _ni_support._normalize_sequence(origin, input.rank)
    weights = numarray.asarray(weights, type=numarray.Float64)
    wshape = [ii for ii in weights.shape if ii > 0]
    if len(wshape) != input.rank:
        raise RuntimeError, 'filter weights array has incorrect shape.'
    if convolution:
        weights = weights[tuple([slice(None, None, -1)] * weights.rank)]
        for ii in range(len(origins)):
            origins[ii] = -origins[ii]
            if not weights.shape[ii] & 1:
                origins[ii] -= 1
    for origin, lenw in zip(origins, wshape):
        if (lenw // 2 + origin < 0) or (lenw // 2 + origin > lenw):
            raise ValueError, 'invalid origin'
    if not weights.iscontiguous():
        weights = weights.copy()
    output, return_value = _ni_support._get_output(output, input)
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.correlate(input, weights, output, mode, cval, origins)
    return return_value
Ejemplo n.º 6
0
def _min_or_max_filter(input, size, footprint, structure, output, mode, cval,
                       origin, minimum):
    if structure is None:
        if footprint is None:
            if size is None:
                raise RuntimeError, "no footprint provided"
            separable = True
        else:
            footprint = numarray.asarray(footprint, numarray.Bool)
            if numarray.alltrue(numarray.ravel(footprint)):
                size = footprint.shape
                footprint = None
                separable = True
            else:
                separable = False
    else:
        structure = numarray.asarray(structure, type=numarray.Float64)
        separable = False
        if footprint is None:
            footprint = numarray.ones(structure.shape, numarray.Bool)
        else:
            footprint = numarray.asarray(footprint, numarray.Bool)
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    output, return_value = _ni_support._get_output(output, input)
    origins = _ni_support._normalize_sequence(origin, input.rank)
    if separable:
        sizes = _ni_support._normalize_sequence(size, input.rank)
        axes = range(input.rank)
        axes = [(axes[ii], sizes[ii], origins[ii]) for ii in range(len(axes))
                if sizes[ii] > 1]
        if minimum:
            filter = minimum_filter1d
        else:
            filter = maximum_filter1d
        if len(axes) > 0:
            for axis, size, origin in axes:
                filter(input, int(size), axis, output, mode, cval, origin)
                input = output
        else:
            output[...] = input[...]
    else:
        fshape = [ii for ii in footprint.shape if ii > 0]
        if len(fshape) != input.rank:
            raise RuntimeError, 'footprint array has incorrect shape.'
        for origin, lenf in zip(origins, fshape):
            if (lenf // 2 + origin < 0) or (lenf // 2 + origin > lenf):
                raise ValueError, 'invalid origin'
        if not footprint.iscontiguous():
            footprint = footprint.copy()
        if structure is not None:
            if len(structure.shape) != input.rank:
                raise RuntimeError, 'structure array has incorrect shape'
            if not structure.iscontiguous():
                structure = structure.copy()
        mode = _ni_support._extend_mode_to_code(mode)
        _nd_image.min_or_max_filter(input, footprint, structure, output, mode,
                                    cval, origins, minimum)
    return return_value
Ejemplo n.º 7
0
def correlate1d(input, weights, axis = -1, output = None, mode = "reflect",
                cval = 0.0, origin = 0):
    """Calculate a one-dimensional correlation along the given axis.

    The lines of the array along the given axis are correlated with the
    given weights.

    Parameters
    ----------
    %(input)s
    weights : array
        one-dimensional sequence of numbers
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s
    """
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    output, return_value = _ni_support._get_output(output, input)
    weights = numpy.asarray(weights, dtype=numpy.float64)
    if weights.ndim != 1 or weights.shape[0] < 1:
        raise RuntimeError, 'no filter weights given'
    if not weights.flags.contiguous:
        weights = weights.copy()
    axis = _ni_support._check_axis(axis, input.ndim)
    if ((len(weights) // 2 + origin < 0) or
        (len(weights) // 2 + origin > len(weights))):
        raise ValueError, 'invalid origin'
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.correlate1d(input, weights, axis, output, mode, cval,
                          origin)
    return return_value
Ejemplo n.º 8
0
def uniform_filter1d(input,
                     size,
                     axis=-1,
                     output=None,
                     mode="reflect",
                     cval=0.0,
                     origin=0):
    """Calculate a one-dimensional uniform filter along the given axis.

    The lines of the array along the given axis are filtered with a
    uniform filter of given size.

    Parameters
    ----------
    %(input)s
    size : integer
        length of uniform filter
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s
    """
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    axis = _ni_support._check_axis(axis, input.ndim)
    if size < 1:
        raise RuntimeError, 'incorrect filter size'
    output, return_value = _ni_support._get_output(output, input)
    if (size // 2 + origin < 0) or (size // 2 + origin > size):
        raise ValueError, 'invalid origin'
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.uniform_filter1d(input, size, axis, output, mode, cval, origin)
    return return_value
Ejemplo n.º 9
0
def _correlate_or_convolve(input, weights, output, mode, cval, origin,
                           convolution):
    input = numpy.asarray(input)
    if numpy.iscomplexobj(int):
        raise TypeError('Complex type not supported')
    origins = _ni_support._normalize_sequence(origin, input.ndim)
    weights = numpy.asarray(weights, dtype=numpy.float64)
    wshape = [ii for ii in weights.shape if ii > 0]
    if len(wshape) != input.ndim:
        raise RuntimeError('filter weights array has incorrect shape.')
    if convolution:
        weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]
        for ii in range(len(origins)):
            origins[ii] = -origins[ii]
            if not weights.shape[ii] & 1:
                origins[ii] -= 1
    for origin, lenw in zip(origins, wshape):
        if (lenw // 2 + origin < 0) or (lenw // 2 + origin > lenw):
            raise ValueError('invalid origin')
    if not weights.flags.contiguous:
        weights = weights.copy()
    output, return_value = _ni_support._get_output(output, input)
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.correlate(input, weights, output, mode, cval, origins)
    return return_value
Ejemplo n.º 10
0
def maximum_filter1d(input, size, axis = -1, output = None,
                     mode = "reflect", cval = 0.0, origin = 0):
    """Calculate a one-dimensional maximum filter along the given axis.

    The lines of the array along the given axis are filtered with a
    maximum filter of given size.

        Parameters
    ----------
    %(input)s
    size : int
        length along which to calculate 1D maximum
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s
    """
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError('Complex type not supported')
    axis = _ni_support._check_axis(axis, input.ndim)
    if size < 1:
        raise RuntimeError('incorrect filter size')
    output, return_value = _ni_support._get_output(output, input)
    if (size // 2 + origin < 0) or (size // 2 + origin > size):
        raise ValueError('invalid origin')
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
                                  origin, 0)
    return return_value
Ejemplo n.º 11
0
def zoom(input, zoom, output_type = None, output = None, order = 3,
         mode = 'constant', cval = 0.0, prefilter = True):
    """Zoom an array.

    The array is zoomed using spline interpolation of the requested order. 
    Points outside the boundaries of the input are filled according to the 
    given mode. The parameter prefilter determines if the input is pre-
    filtered before interpolation, if False it is assumed that the input 
    is already filtered.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if input.rank < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output = numarray.Float64)
    else:
        filtered = input
    zoom = _ni_support._normalize_sequence(zoom, input.rank)
    output_shape = [int(ii * jj) for ii, jj in zip(input.shape, zoom)]
    zoom = [1.0 / ii for ii in zoom]
    output, return_value = _ni_support._get_output(output, input,
                                        output_type, shape = output_shape)
    zoom = numarray.asarray(zoom, type = numarray.Float64)
    if not zoom.iscontiguous():
        zoom = shift.copy()
    _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval)
    return return_value
Ejemplo n.º 12
0
def affine_transform(input, matrix, offset = 0.0, output_shape = None,
                     output_type = None, output = None, order = 3,
                     mode = 'constant', cval = 0.0, prefilter = True):
    """Apply an affine transformation.

    The given matrix and offset are used to find for each point in the 
    output the corresponding coordinates in the input by an affine 
    transformation. The value of the input at those coordinates is 
    determined by spline interpolation of the requested order. Points 
    outside the boundaries of the input are filled according to the given 
    mode. The output shape can optionally be given. If not given it is 
    equal to the input shape. The parameter prefilter determines if the 
    input is pre-filtered before interpolation, if False it is assumed 
    that the input is already filtered.

    The matrix must be two-dimensional or can also be given as a
    one-dimensional sequence or array. In the latter case, it is
    assumed that the matrix is diagonal. A more efficient algorithms
    is then applied that exploits the separability of the problem.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if output_shape == None:
        output_shape = input.shape
    if input.rank < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output = numarray.Float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output, input,
                                        output_type, shape = output_shape)
    matrix = numarray.asarray(matrix, type = numarray.Float64)
    if matrix.rank not in [1, 2] or matrix.shape[0] < 1:
        raise RuntimeError, 'no proper affine matrix provided'
    if matrix.shape[0] != input.rank:
        raise RuntimeError, 'affine matrix has wrong number of rows'
    if matrix.rank == 2 and matrix.shape[1] != output.rank:
        raise RuntimeError, 'affine matrix has wrong number of columns'
    if not matrix.iscontiguous():
        matrix = matrix.copy()
    offset = _ni_support._normalize_sequence(offset, input.rank)
    offset = numarray.asarray(offset, type = numarray.Float64)
    if offset.rank != 1 or offset.shape[0] < 1:
        raise RuntimeError, 'no proper offset provided'
    if not offset.iscontiguous():
        offset = offset.copy()
    if matrix.rank == 1:
        _nd_image.zoom_shift(filtered, matrix, offset, output, order,
                             mode, cval)
    else:
        _nd_image.geometric_transform(filtered, None, None, matrix, offset,
                            output, order, mode, cval, None, None)
    return return_value
Ejemplo n.º 13
0
def _rank_filter(input,
                 rank,
                 size=None,
                 footprint=None,
                 output=None,
                 mode="reflect",
                 cval=0.0,
                 origin=0,
                 operation='rank'):
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    origins = _ni_support._normalize_sequence(origin, input.rank)
    if footprint == None:
        if size == None:
            raise RuntimeError, "no footprint or filter size provided"
        sizes = _ni_support._normalize_sequence(size, input.rank)
        footprint = numarray.ones(sizes, type=numarray.Bool)
    else:
        footprint = numarray.asarray(footprint, type=numarray.Bool)
    fshape = [ii for ii in footprint.shape if ii > 0]
    if len(fshape) != input.rank:
        raise RuntimeError, 'filter footprint array has incorrect shape.'
    for origin, lenf in zip(origins, fshape):
        if (lenf // 2 + origin < 0) or (lenf // 2 + origin > lenf):
            raise ValueError, 'invalid origin'
    if not footprint.iscontiguous():
        footprint = footprint.copy()
    filter_size = numarray.where(footprint, 1, 0).sum()
    if operation == 'median':
        rank = filter_size // 2
    elif operation == 'percentile':
        percentile = rank
        if percentile < 0.0:
            percentile += 100.0
        if percentile < 0 or percentile > 100:
            raise RuntimeError, 'invalid percentile'
        if percentile == 100.0:
            rank = filter_size - 1
        else:
            rank = int(float(filter_size) * percentile / 100.0)
    if rank < 0:
        rank += filter_size
    if rank < 0 or rank >= filter_size:
        raise RuntimeError, 'rank not within filter footprint size'
    if rank == 0:
        return minimum_filter(input, None, footprint, output, mode, cval,
                              origin)
    elif rank == filter_size - 1:
        return maximum_filter(input, None, footprint, output, mode, cval,
                              origin)
    else:
        output, return_value = _ni_support._get_output(output, input)
        mode = _ni_support._extend_mode_to_code(mode)
        _nd_image.rank_filter(input, rank, footprint, output, mode, cval,
                              origins)
        return return_value
Ejemplo n.º 14
0
def _min_or_max_filter(input, size, footprint, structure, output, mode, cval, origin, minimum):
    if structure is None:
        if footprint is None:
            if size is None:
                raise RuntimeError, "no footprint provided"
            separable = True
        else:
            footprint = numarray.asarray(footprint, numarray.Bool)
            if numarray.alltrue(numarray.ravel(footprint)):
                size = footprint.shape
                footprint = None
                separable = True
            else:
                separable = False
    else:
        structure = numarray.asarray(structure, type=numarray.Float64)
        separable = False
        if footprint is None:
            footprint = numarray.ones(structure.shape, numarray.Bool)
        else:
            footprint = numarray.asarray(footprint, numarray.Bool)
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, "Complex type not supported"
    output, return_value = _ni_support._get_output(output, input)
    origins = _ni_support._normalize_sequence(origin, input.rank)
    if separable:
        sizes = _ni_support._normalize_sequence(size, input.rank)
        axes = range(input.rank)
        axes = [(axes[ii], sizes[ii], origins[ii]) for ii in range(len(axes)) if sizes[ii] > 1]
        if minimum:
            filter = minimum_filter1d
        else:
            filter = maximum_filter1d
        if len(axes) > 0:
            for axis, size, origin in axes:
                filter(input, int(size), axis, output, mode, cval, origin)
                input = output
        else:
            output[...] = input[...]
    else:
        fshape = [ii for ii in footprint.shape if ii > 0]
        if len(fshape) != input.rank:
            raise RuntimeError, "footprint array has incorrect shape."
        for origin, lenf in zip(origins, fshape):
            if (lenf // 2 + origin < 0) or (lenf // 2 + origin > lenf):
                raise ValueError, "invalid origin"
        if not footprint.iscontiguous():
            footprint = footprint.copy()
        if structure is not None:
            if len(structure.shape) != input.rank:
                raise RuntimeError, "structure array has incorrect shape"
            if not structure.iscontiguous():
                structure = structure.copy()
        mode = _ni_support._extend_mode_to_code(mode)
        _nd_image.min_or_max_filter(input, footprint, structure, output, mode, cval, origins, minimum)
    return return_value
Ejemplo n.º 15
0
def generic_filter(input,
                   function,
                   size=None,
                   footprint=None,
                   output=None,
                   mode="reflect",
                   cval=0.0,
                   origin=0,
                   extra_arguments=(),
                   extra_keywords=None):
    """Calculates a multi-dimensional filter using the given function.

    At each element the provided function is called. The input values
    within the filter footprint at that element are passed to the function
    as a 1D array of double values.

    Parameters
    ----------
    %(input)s
    function : callable
        function to apply at each element
    %(size_foot)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s
    %(extra_arguments)s
    %(extra_keywords)s
    """
    if extra_keywords is None:
        extra_keywords = {}
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    origins = _ni_support._normalize_sequence(origin, input.ndim)
    if footprint is None:
        if size is None:
            raise RuntimeError, "no footprint or filter size provided"
        sizes = _ni_support._normalize_sequence(size, input.ndim)
        footprint = numpy.ones(sizes, dtype=bool)
    else:
        footprint = numpy.asarray(footprint)
        footprint = footprint.astype(bool)
    fshape = [ii for ii in footprint.shape if ii > 0]
    if len(fshape) != input.ndim:
        raise RuntimeError, 'filter footprint array has incorrect shape.'
    for origin, lenf in zip(origins, fshape):
        if (lenf // 2 + origin < 0) or (lenf // 2 + origin > lenf):
            raise ValueError, 'invalid origin'
    if not footprint.flags.contiguous:
        footprint = footprint.copy()
    output, return_value = _ni_support._get_output(output, input)
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.generic_filter(input, function, footprint, output, mode, cval,
                             origins, extra_arguments, extra_keywords)
    return return_value
Ejemplo n.º 16
0
def generic_filter1d(input,
                     function,
                     filter_size,
                     axis=-1,
                     output=None,
                     mode="reflect",
                     cval=0.0,
                     origin=0,
                     extra_arguments=(),
                     extra_keywords=None):
    """Calculate a one-dimensional filter along the given axis.

    generic_filter1d iterates over the lines of the array, calling the
    given function at each line. The arguments of the line are the
    input line, and the output line. The input and output lines are 1D
    double arrays.  The input line is extended appropriately according
    to the filter size and origin. The output line must be modified
    in-place with the result.

    Parameters
    ----------
    %(input)s
    function : callable
        function to apply along given axis
    filter_size : scalar
        length of the filter
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s
    %(extra_arguments)s
    %(extra_keywords)s
    """
    if extra_keywords is None:
        extra_keywords = {}
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    output, return_value = _ni_support._get_output(output, input)
    if filter_size < 1:
        raise RuntimeError, 'invalid filter size'
    axis = _ni_support._check_axis(axis, input.ndim)
    if ((filter_size // 2 + origin < 0)
            or (filter_size // 2 + origin > filter_size)):
        raise ValueError, 'invalid origin'
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.generic_filter1d(input, function, filter_size, axis, output,
                               mode, cval, origin, extra_arguments,
                               extra_keywords)
    return return_value
Ejemplo n.º 17
0
def _rank_filter(input, rank, size = None, footprint = None, output = None,
     mode = "reflect", cval = 0.0, origin = 0, operation = 'rank'):
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError('Complex type not supported')
    origins = _ni_support._normalize_sequence(origin, input.ndim)
    if footprint is None:
        if size is None:
            raise RuntimeError("no footprint or filter size provided")
        sizes = _ni_support._normalize_sequence(size, input.ndim)
        footprint = numpy.ones(sizes, dtype=bool)
    else:
        footprint = numpy.asarray(footprint, dtype=bool)
    fshape = [ii for ii in footprint.shape if ii > 0]
    if len(fshape) != input.ndim:
        raise RuntimeError('filter footprint array has incorrect shape.')
    for origin, lenf in zip(origins, fshape):
        if (lenf // 2 + origin < 0) or (lenf // 2 + origin > lenf):
            raise ValueError('invalid origin')
    if not footprint.flags.contiguous:
        footprint = footprint.copy()
    filter_size = numpy.where(footprint, 1, 0).sum()
    if operation == 'median':
        rank = filter_size // 2
    elif operation == 'percentile':
        percentile = rank
        if percentile < 0.0:
            percentile += 100.0
        if percentile < 0 or percentile > 100:
            raise RuntimeError('invalid percentile')
        if percentile == 100.0:
            rank = filter_size - 1
        else:
            rank = int(float(filter_size) * percentile / 100.0)
    if rank < 0:
        rank += filter_size
    if rank < 0  or rank >= filter_size:
        raise RuntimeError('rank not within filter footprint size')
    if rank == 0:
        return minimum_filter(input, None, footprint, output, mode, cval,
                              origin)
    elif rank == filter_size - 1:
        return maximum_filter(input, None, footprint, output, mode, cval,
                              origin)
    else:
        output, return_value = _ni_support._get_output(output, input)
        mode = _ni_support._extend_mode_to_code(mode)
        _nd_image.rank_filter(input, rank, footprint, output, mode, cval,
                              origins)
        return return_value
Ejemplo n.º 18
0
def generic_filter(input, function, size = None, footprint = None,
                   output = None, mode = "reflect", cval = 0.0, origin = 0,
                   extra_arguments = (), extra_keywords = None):
    """Calculates a multi-dimensional filter using the given function.

    At each element the provided function is called. The input values
    within the filter footprint at that element are passed to the function
    as a 1D array of double values.

    Parameters
    ----------
    %(input)s
    function : callable
        function to apply at each element
    %(size_foot)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s
    %(extra_arguments)s
    %(extra_keywords)s
    """
    if extra_keywords is None:
        extra_keywords = {}
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError('Complex type not supported')
    origins = _ni_support._normalize_sequence(origin, input.ndim)
    if footprint is None:
        if size is None:
            raise RuntimeError("no footprint or filter size provided")
        sizes = _ni_support._normalize_sequence(size, input.ndim)
        footprint = numpy.ones(sizes, dtype=bool)
    else:
        footprint = numpy.asarray(footprint)
        footprint = footprint.astype(bool)
    fshape = [ii for ii in footprint.shape if ii > 0]
    if len(fshape) != input.ndim:
        raise RuntimeError('filter footprint array has incorrect shape.')
    for origin, lenf in zip(origins, fshape):
        if (lenf // 2 + origin < 0) or (lenf // 2 + origin > lenf):
            raise ValueError('invalid origin')
    if not footprint.flags.contiguous:
        footprint = footprint.copy()
    output, return_value = _ni_support._get_output(output, input)
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.generic_filter(input, function, footprint, output, mode,
                         cval, origins, extra_arguments, extra_keywords)
    return return_value
Ejemplo n.º 19
0
def _rank_filter(
    input, rank, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0, operation="rank"
):
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, "Complex type not supported"
    origins = _ni_support._normalize_sequence(origin, input.rank)
    if footprint == None:
        if size == None:
            raise RuntimeError, "no footprint or filter size provided"
        sizes = _ni_support._normalize_sequence(size, input.rank)
        footprint = numarray.ones(sizes, type=numarray.Bool)
    else:
        footprint = numarray.asarray(footprint, type=numarray.Bool)
    fshape = [ii for ii in footprint.shape if ii > 0]
    if len(fshape) != input.rank:
        raise RuntimeError, "filter footprint array has incorrect shape."
    for origin, lenf in zip(origins, fshape):
        if (lenf // 2 + origin < 0) or (lenf // 2 + origin > lenf):
            raise ValueError, "invalid origin"
    if not footprint.iscontiguous():
        footprint = footprint.copy()
    filter_size = numarray.where(footprint, 1, 0).sum()
    if operation == "median":
        rank = filter_size // 2
    elif operation == "percentile":
        percentile = rank
        if percentile < 0.0:
            percentile += 100.0
        if percentile < 0 or percentile > 100:
            raise RuntimeError, "invalid percentile"
        if percentile == 100.0:
            rank = filter_size - 1
        else:
            rank = int(float(filter_size) * percentile / 100.0)
    if rank < 0:
        rank += filter_size
    if rank < 0 or rank >= filter_size:
        raise RuntimeError, "rank not within filter footprint size"
    if rank == 0:
        return minimum_filter(input, None, footprint, output, mode, cval, origin)
    elif rank == filter_size - 1:
        return maximum_filter(input, None, footprint, output, mode, cval, origin)
    else:
        output, return_value = _ni_support._get_output(output, input)
        mode = _ni_support._extend_mode_to_code(mode)
        _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins)
        return return_value
Ejemplo n.º 20
0
def generic_filter(
    input,
    function,
    size=None,
    footprint=None,
    output=None,
    mode="reflect",
    cval=0.0,
    origin=0,
    extra_arguments=(),
    extra_keywords={},
):
    """Calculates a multi-dimensional filter using the given function.
    
    At each element the provided function is called. The input values
    within the filter footprint at that element are passed to the function
    as a 1D array of double values.
       
    Either a size or a footprint with the filter must be provided. An
    output array can optionally be provided. The origin parameter
    controls the placement of the filter. The mode parameter
    determines how the array borders are handled, where cval is the
    value when mode is equal to 'constant'. The extra_arguments and
    extra_keywords arguments can be used to pass extra arguments and
    keywords that are passed to the function at each call."""
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, "Complex type not supported"
    origins = _ni_support._normalize_sequence(origin, input.rank)
    if footprint == None:
        if size == None:
            raise RuntimeError, "no footprint or filter size provided"
        sizes = _ni_support._normalize_sequence(size, input.rank)
        footprint = numarray.ones(size, type=numarray.Bool)
    else:
        footprint = numarray.asarray(footprint, type=numarray.Bool)
    fshape = [ii for ii in footprint.shape if ii > 0]
    if len(fshape) != input.rank:
        raise RuntimeError, "filter footprint array has incorrect shape."
    for origin, lenf in zip(origins, fshape):
        if (lenf // 2 + origin < 0) or (lenf // 2 + origin > lenf):
            raise ValueError, "invalid origin"
    if not footprint.iscontiguous():
        footprint = footprint.copy()
    output, return_value = _ni_support._get_output(output, input)
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.generic_filter(input, function, footprint, output, mode, cval, origins, extra_arguments, extra_keywords)
    return return_value
Ejemplo n.º 21
0
def generic_filter(input,
                   function,
                   size=None,
                   footprint=None,
                   output=None,
                   mode="reflect",
                   cval=0.0,
                   origin=0,
                   extra_arguments=(),
                   extra_keywords={}):
    """Calculates a multi-dimensional filter using the given function.

    At each element the provided function is called. The input values
    within the filter footprint at that element are passed to the function
    as a 1D array of double values.

    Either a size or a footprint with the filter must be provided. An
    output array can optionally be provided. The origin parameter
    controls the placement of the filter. The mode parameter
    determines how the array borders are handled, where cval is the
    value when mode is equal to 'constant'. The extra_arguments and
    extra_keywords arguments can be used to pass extra arguments and
    keywords that are passed to the function at each call."""
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    origins = _ni_support._normalize_sequence(origin, input.ndim)
    if footprint == None:
        if size == None:
            raise RuntimeError, "no footprint or filter size provided"
        sizes = _ni_support._normalize_sequence(size, input.ndim)
        footprint = numpy.ones(size, dtype=bool)
    else:
        footprint = numpy.asarray(footprint)
        footprint = footprint.astype(bool)
    fshape = [ii for ii in footprint.shape if ii > 0]
    if len(fshape) != input.ndim:
        raise RuntimeError, 'filter footprint array has incorrect shape.'
    for origin, lenf in zip(origins, fshape):
        if (lenf // 2 + origin < 0) or (lenf // 2 + origin > lenf):
            raise ValueError, 'invalid origin'
    if not footprint.flags.contiguous:
        footprint = footprint.copy()
    output, return_value = _ni_support._get_output(output, input)
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.generic_filter(input, function, footprint, output, mode, cval,
                             origins, extra_arguments, extra_keywords)
    return return_value
Ejemplo n.º 22
0
def geometric_transform(input,
                        mapping,
                        output_shape=None,
                        output_type=None,
                        output=None,
                        order=3,
                        mode='constant',
                        cval=0.0,
                        prefilter=True,
                        extra_arguments=(),
                        extra_keywords={}):
    """Apply an arbritrary geometric transform.

    The given mapping function is used to find for each point in the 
    output the corresponding coordinates in the input. The value of the 
    input at those coordinates is determined by spline interpolation of 
    the requested order. Points outside the boundaries of the input are 
    filled according to the given mode. The output shape can optionally be 
    given. If not given, it is equal to the input shape. The parameter 
    prefilter determines if the input is pre-filtered before 
    interpolation, if False it is assumed that the input is already 
    filtered. The extra_arguments and extra_keywords arguments can be 
    used to provide extra arguments and keywords that are passed to the 
    mapping function at each call.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if output_shape == None:
        output_shape = input.shape
    if input.rank < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output=numarray.Float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output,
                                                   input,
                                                   output_type,
                                                   shape=output_shape)
    _nd_image.geometric_transform(filtered, mapping, None, None, None, output,
                                  order, mode, cval, extra_arguments,
                                  extra_keywords)
    return return_value
Ejemplo n.º 23
0
def maximum_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0):
    """Calculate a one-dimensional maximum filter along the given axis.

    The lines of the array along the given axis are filtered with a     
    maximum filter of given size."""
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, "Complex type not supported"
    axis = _ni_support._check_axis(axis, input.rank)
    if size < 1:
        raise RuntimeError, "incorrect filter size"
    output, return_value = _ni_support._get_output(output, input)
    if (size // 2 + origin < 0) or (size // 2 + origin > size):
        raise ValueError, "invalid origin"
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 0)
    return return_value
Ejemplo n.º 24
0
def minimum_filter1d(input, size, axis = -1, output = None,
                     mode = "reflect", cval = 0.0, origin = 0):
    """Calculate a one-dimensional minimum filter along the given axis.

    The lines of the array along the given axis are filtered with a
    minimum filter of given size."""
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    axis = _ni_support._check_axis(axis, input.ndim)
    if size < 1:
        raise RuntimeError, 'incorrect filter size'
    output, return_value = _ni_support._get_output(output, input)
    if (size // 2 + origin < 0) or (size // 2 + origin > size):
        raise ValueError, 'invalid origin'
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
                                  origin, 1)
    return return_value
Ejemplo n.º 25
0
def map_coordinates(input,
                    coordinates,
                    output_type=None,
                    output=None,
                    order=3,
                    mode='constant',
                    cval=0.0,
                    prefilter=True):
    """Apply an arbritrary coordinate transformation.

    The array of coordinates is used to find for each point in the output 
    the corresponding coordinates in the input. The value of the input at 
    that coordinates is determined by spline interpolation of the 
    requested order. Points outside the boundaries of the input are filled 
    according to the given mode. The parameter prefilter determines if the 
    input is pre-filtered before interpolation, if False it is assumed 
    that the input is already filtered.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    coordinates = numarray.asarray(coordinates)
    if isinstance(coordinates.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    output_shape = coordinates.shape[1:]
    if input.rank < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    if coordinates.shape[0] != input.rank:
        raise RuntimeError, 'invalid shape for coordinate array'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output=numarray.Float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output,
                                                   input,
                                                   output_type,
                                                   shape=output_shape)
    _nd_image.geometric_transform(filtered, None, coordinates, None, None,
                                  output, order, mode, cval, None, None)
    return return_value
Ejemplo n.º 26
0
def generic_filter1d(input, function, filter_size, axis = -1,
                 output = None, mode = "reflect", cval = 0.0, origin = 0,
                 extra_arguments = (), extra_keywords = None):
    """Calculate a one-dimensional filter along the given axis.

    generic_filter1d iterates over the lines of the array, calling the
    given function at each line. The arguments of the line are the
    input line, and the output line. The input and output lines are 1D
    double arrays.  The input line is extended appropriately according
    to the filter size and origin. The output line must be modified
    in-place with the result.

    Parameters
    ----------
    %(input)s
    function : callable
        function to apply along given axis
    filter_size : scalar
        length of the filter
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s
    %(extra_arguments)s
    %(extra_keywords)s
    """
    if extra_keywords is None:
        extra_keywords = {}
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError('Complex type not supported')
    output, return_value = _ni_support._get_output(output, input)
    if filter_size < 1:
        raise RuntimeError('invalid filter size')
    axis = _ni_support._check_axis(axis, input.ndim)
    if ((filter_size // 2 + origin < 0) or
        (filter_size // 2 + origin > filter_size)):
        raise ValueError('invalid origin')
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.generic_filter1d(input, function, filter_size, axis, output,
                      mode, cval, origin, extra_arguments, extra_keywords)
    return return_value
Ejemplo n.º 27
0
def correlate1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0, origin=0):
    """Calculate a one-dimensional correlation along the given axis.

    The lines of the array along the given axis are correlated with the     
    given weights. The weights parameter must be a one-dimensional sequence 
    of numbers."""
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, "Complex type not supported"
    output, return_value = _ni_support._get_output(output, input)
    weights = numarray.asarray(weights, type=numarray.Float64)
    if weights.rank != 1 or weights.shape[0] < 1:
        raise RuntimeError, "no filter weights given"
    if not weights.iscontiguous():
        weights = weights.copy()
    axis = _ni_support._check_axis(axis, input.rank)
    if (len(weights) // 2 + origin < 0) or (len(weights) // 2 + origin > len(weights)):
        raise ValueError, "invalid origin"
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.correlate1d(input, weights, axis, output, mode, cval, origin)
    return return_value
Ejemplo n.º 28
0
def zoom(input,
         zoom,
         output_type=None,
         output=None,
         order=3,
         mode='constant',
         cval=0.0,
         prefilter=True):
    """Zoom an array.

    The array is zoomed using spline interpolation of the requested order.
    Points outside the boundaries of the input are filled according to the
    given mode. The parameter prefilter determines if the input is pre-
    filtered before interpolation, if False it is assumed that the input
    is already filtered.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    if input.ndim < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output=numpy.float64)
    else:
        filtered = input
    zoom = _ni_support._normalize_sequence(zoom, input.ndim)
    output_shape = [int(ii * jj) for ii, jj in zip(input.shape, zoom)]
    zoom = [1.0 / ii for ii in zoom]
    output, return_value = _ni_support._get_output(output,
                                                   input,
                                                   output_type,
                                                   shape=output_shape)
    zoom = numpy.asarray(zoom, dtype=numpy.float64)
    if not zoom.flags.contiguous:
        zoom = shift.copy()
    _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval)
    return return_value
Ejemplo n.º 29
0
def uniform_filter1d(input,
                     size,
                     axis=-1,
                     output=None,
                     mode="reflect",
                     cval=0.0,
                     origin=0):
    """Calculate a one-dimensional uniform filter along the given axis.

    The lines of the array along the given axis are filtered with a     
    uniform filter of given size."""
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    axis = _ni_support._check_axis(axis, input.rank)
    if size < 1:
        raise RuntimeError, 'incorrect filter size'
    output, return_value = _ni_support._get_output(output, input)
    if (size // 2 + origin < 0) or (size // 2 + origin > size):
        raise ValueError, 'invalid origin'
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.uniform_filter1d(input, size, axis, output, mode, cval, origin)
    return return_value
Ejemplo n.º 30
0
def geometric_transform(input, mapping, output_shape = None,
                        output_type = None, output = None, order = 3,
                        mode = 'constant', cval = 0.0, prefilter = True, 
                        extra_arguments = (), extra_keywords = {}):
    """Apply an arbritrary geometric transform.

    The given mapping function is used to find for each point in the 
    output the corresponding coordinates in the input. The value of the 
    input at those coordinates is determined by spline interpolation of 
    the requested order. Points outside the boundaries of the input are 
    filled according to the given mode. The output shape can optionally be 
    given. If not given, it is equal to the input shape. The parameter 
    prefilter determines if the input is pre-filtered before 
    interpolation, if False it is assumed that the input is already 
    filtered. The extra_arguments and extra_keywords arguments can be 
    used to provide extra arguments and keywords that are passed to the 
    mapping function at each call.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if output_shape == None:
        output_shape = input.shape
    if input.rank < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output = numarray.Float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output, input,
                                        output_type, shape = output_shape)
    _nd_image.geometric_transform(filtered, mapping, None, None, None,
               output, order, mode, cval, extra_arguments, extra_keywords)
    return return_value
Ejemplo n.º 31
0
def generic_filter1d(input,
                     function,
                     filter_size,
                     axis=-1,
                     output=None,
                     mode="reflect",
                     cval=0.0,
                     origin=0,
                     extra_arguments=(),
                     extra_keywords={}):
    """Calculate a one-dimensional filter along the given axis.

    The function iterates over the lines of the array, calling the given
    function at each line. The arguments of the line are the input line,
    and the output line. The input and output lines are 1D double arrays. 
    The input line is extended appropiately according to the filter size 
    and  origin. The output line must be modified in-place with the result. 
    The origin parameter controls  the placement of the filter. The mode 
    parameter determines how the array borders are handled, where cval is 
    the value when mode is equal to 'constant'. The extra_arguments and 
    extra_keywords arguments can be used to pass extra arguments and 
    keywords that are passed to the function at each call."""
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    output, return_value = _ni_support._get_output(output, input)
    if filter_size < 1:
        raise RuntimeError, 'invalid filter size'
    axis = _ni_support._check_axis(axis, input.rank)
    if ((filter_size // 2 + origin < 0)
            or (filter_size // 2 + origin > filter_size)):
        raise ValueError, 'invalid origin'
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.generic_filter1d(input, function, filter_size, axis, output,
                               mode, cval, origin, extra_arguments,
                               extra_keywords)
    return return_value
Ejemplo n.º 32
0
def _correlate_or_convolve(input, weights, output, mode, cval, origin, convolution):
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, "Complex type not supported"
    origins = _ni_support._normalize_sequence(origin, input.rank)
    weights = numarray.asarray(weights, type=numarray.Float64)
    wshape = [ii for ii in weights.shape if ii > 0]
    if len(wshape) != input.rank:
        raise RuntimeError, "filter weights array has incorrect shape."
    if convolution:
        weights = weights[tuple([slice(None, None, -1)] * weights.rank)]
        for ii in range(len(origins)):
            origins[ii] = -origins[ii]
            if not weights.shape[ii] & 1:
                origins[ii] -= 1
    for origin, lenw in zip(origins, wshape):
        if (lenw // 2 + origin < 0) or (lenw // 2 + origin > lenw):
            raise ValueError, "invalid origin"
    if not weights.iscontiguous():
        weights = weights.copy()
    output, return_value = _ni_support._get_output(output, input)
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.correlate(input, weights, output, mode, cval, origins)
    return return_value
Ejemplo n.º 33
0
def maximum_filter1d(input,
                     size,
                     axis=-1,
                     output=None,
                     mode="reflect",
                     cval=0.0,
                     origin=0):
    """Calculate a one-dimensional maximum filter along the given axis.

    The lines of the array along the given axis are filtered with a
    maximum filter of given size."""
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    axis = _ni_support._check_axis(axis, input.ndim)
    if size < 1:
        raise RuntimeError, 'incorrect filter size'
    output, return_value = _ni_support._get_output(output, input)
    if (size // 2 + origin < 0) or (size // 2 + origin > size):
        raise ValueError, 'invalid origin'
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
                                  origin, 0)
    return return_value
Ejemplo n.º 34
0
def shift(input,
          shift,
          output_type=None,
          output=None,
          order=3,
          mode='constant',
          cval=0.0,
          prefilter=True):
    """Shift an array.

    The array is shifted using spline interpolation of the requested 
    order. Points outside the boundaries of the input are filled according 
    to the given mode. The parameter prefilter determines if the input is 
    pre-filtered before interpolation, if False it is assumed that the 
    input is already filtered.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if input.rank < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output=numarray.Float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output, input, output_type)
    shift = _ni_support._normalize_sequence(shift, input.rank)
    shift = [-ii for ii in shift]
    shift = numarray.asarray(shift, type=numarray.Float64)
    if not shift.iscontiguous():
        shift = shift.copy()
    _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval)
    return return_value
Ejemplo n.º 35
0
def _extend_mode_to_code(mode):
    mode = _ni_support._extend_mode_to_code(mode)
    return mode
Ejemplo n.º 36
0
def _extend_mode_to_code(mode):
    mode = _ni_support._extend_mode_to_code(mode)
    return mode
Ejemplo n.º 37
0
def _extend_mode_to_code(mode):
    mode = _ni_support._extend_mode_to_code(mode)
    if mode == 2:
        warnings.warn('Mode "reflect" may yield incorrect results on '
                      'boundaries. Please use "mirror" instead.')
    return mode
Ejemplo n.º 38
0
def _min_or_max_filter(input, size, footprint, structure, output, mode,
                       cval, origin, minimum):
    if structure is None:
        if footprint is None:
            if size is None:
                raise RuntimeError("no footprint provided")
            separable= True
        else:
            footprint = numpy.asarray(footprint)
            footprint = footprint.astype(bool)
            if numpy.alltrue(numpy.ravel(footprint),axis=0):
                size = footprint.shape
                footprint = None
                separable = True
            else:
                separable = False
    else:
        structure = numpy.asarray(structure, dtype=numpy.float64)
        separable = False
        if footprint is None:
            footprint = numpy.ones(structure.shape, bool)
        else:
            footprint = numpy.asarray(footprint)
            footprint = footprint.astype(bool)
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError('Complex type not supported')
    output, return_value = _ni_support._get_output(output, input)
    origins = _ni_support._normalize_sequence(origin, input.ndim)
    if separable:
        sizes = _ni_support._normalize_sequence(size, input.ndim)
        axes = range(input.ndim)
        axes = [(axes[ii], sizes[ii], origins[ii])
                               for ii in range(len(axes)) if sizes[ii] > 1]
        if minimum:
            filter_ = minimum_filter1d
        else:
            filter_ = maximum_filter1d
        if len(axes) > 0:
            for axis, size, origin in axes:
                filter_(input, int(size), axis, output, mode, cval, origin)
                input = output
        else:
            output[...] = input[...]
    else:
        fshape = [ii for ii in footprint.shape if ii > 0]
        if len(fshape) != input.ndim:
            raise RuntimeError('footprint array has incorrect shape.')
        for origin, lenf in zip(origins, fshape):
            if (lenf // 2 + origin < 0) or (lenf // 2 + origin > lenf):
                raise ValueError('invalid origin')
        if not footprint.flags.contiguous:
            footprint = footprint.copy()
        if structure is not None:
            if len(structure.shape) != input.ndim:
                raise RuntimeError('structure array has incorrect shape')
            if not structure.flags.contiguous:
                structure = structure.copy()
        mode = _ni_support._extend_mode_to_code(mode)
        _nd_image.min_or_max_filter(input, footprint, structure, output,
                                    mode, cval, origins, minimum)
    return return_value
Ejemplo n.º 39
0
def map_coordinates(input,
                    coordinates,
                    output_type=None,
                    output=None,
                    order=3,
                    mode='constant',
                    cval=0.0,
                    prefilter=True):
    """Apply an arbritrary coordinate transformation.

    The array of coordinates is used to find, for each point in the output,
    the corresponding coordinates in the input. The value of the input at
    that coordinates is determined by spline interpolation of the
    requested order.

    The shape of the output is derived from that of the coordinate
    array by dropping the first axis. The values of the array along
    the first axis are the coordinates in the input array at which the
    output value is found.  For example, if the input has dimensions
    (100,200,3), then the shape of coordinates will be (3,100,200,3),
    where coordinates[:,1,2,3] specify the input coordinate at which
    output[1,2,3] is found.

    Points outside the boundaries of the input are filled according to
    the given mode ('constant', 'nearest', 'reflect' or 'wrap'). The
    parameter prefilter determines if the input is pre-filtered before
    interpolation (necessary for spline interpolation of order >
    1). If False it is assumed that the input is already filtered.

    Example usage:
      >>> a = arange(12.).reshape((4,3))
      >>> print a
      [[  0.   1.   2.]
       [  3.   4.   5.]
       [  6.   7.   8.]
       [  9.  10.  11.]]
      >>> output = map_coordinates(a,[[0.5, 2], [0.5, 1]],order=1)
      >>> print output
      [ 2. 7.]

      Here, the interpolated value of a[0.5,0.5] gives output[0], while
      a[2,1] is output[1].
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    coordinates = numpy.asarray(coordinates)
    if numpy.iscomplexobj(coordinates):
        raise TypeError, 'Complex type not supported'
    output_shape = coordinates.shape[1:]
    if input.ndim < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    if coordinates.shape[0] != input.ndim:
        raise RuntimeError, 'invalid shape for coordinate array'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output=numpy.float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output,
                                                   input,
                                                   output_type,
                                                   shape=output_shape)
    _nd_image.geometric_transform(filtered, None, coordinates, None, None,
                                  output, order, mode, cval, None, None)
    return return_value
Ejemplo n.º 40
0
def affine_transform(input,
                     matrix,
                     offset=0.0,
                     output_shape=None,
                     output_type=None,
                     output=None,
                     order=3,
                     mode='constant',
                     cval=0.0,
                     prefilter=True):
    """Apply an affine transformation.

    The given matrix and offset are used to find for each point in the
    output the corresponding coordinates in the input by an affine
    transformation. The value of the input at those coordinates is
    determined by spline interpolation of the requested order. Points
    outside the boundaries of the input are filled according to the given
    mode. The output shape can optionally be given. If not given it is
    equal to the input shape. The parameter prefilter determines if the
    input is pre-filtered before interpolation, if False it is assumed
    that the input is already filtered.

    The matrix must be two-dimensional or can also be given as a
    one-dimensional sequence or array. In the latter case, it is
    assumed that the matrix is diagonal. A more efficient algorithms
    is then applied that exploits the separability of the problem.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    if output_shape == None:
        output_shape = input.shape
    if input.ndim < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output=numpy.float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output,
                                                   input,
                                                   output_type,
                                                   shape=output_shape)
    matrix = numpy.asarray(matrix, dtype=numpy.float64)
    if matrix.ndim not in [1, 2] or matrix.shape[0] < 1:
        raise RuntimeError, 'no proper affine matrix provided'
    if matrix.shape[0] != input.ndim:
        raise RuntimeError, 'affine matrix has wrong number of rows'
    if matrix.ndim == 2 and matrix.shape[1] != output.ndim:
        raise RuntimeError, 'affine matrix has wrong number of columns'
    if not matrix.flags.contiguous:
        matrix = matrix.copy()
    offset = _ni_support._normalize_sequence(offset, input.ndim)
    offset = numpy.asarray(offset, dtype=numpy.float64)
    if offset.ndim != 1 or offset.shape[0] < 1:
        raise RuntimeError, 'no proper offset provided'
    if not offset.flags.contiguous:
        offset = offset.copy()
    if matrix.ndim == 1:
        _nd_image.zoom_shift(filtered, matrix, offset, output, order, mode,
                             cval)
    else:
        _nd_image.geometric_transform(filtered, None, None, matrix, offset,
                                      output, order, mode, cval, None, None)
    return return_value
Ejemplo n.º 41
0
def geometric_transform(input,
                        mapping,
                        output_shape=None,
                        output_type=None,
                        output=None,
                        order=3,
                        mode='constant',
                        cval=0.0,
                        prefilter=True,
                        extra_arguments=(),
                        extra_keywords={}):
    """Apply an arbritrary geometric transform.

    The given mapping function is used to find, for each point in the
    output, the corresponding coordinates in the input. The value of the
    input at those coordinates is determined by spline interpolation of
    the requested order.

    mapping must be a callable object that accepts a tuple of length
    equal to the output array rank and returns the corresponding input
    coordinates as a tuple of length equal to the input array
    rank. Points outside the boundaries of the input are filled
    according to the given mode ('constant', 'nearest', 'reflect' or
    'wrap'). The output shape can optionally be given. If not given,
    it is equal to the input shape. The parameter prefilter determines
    if the input is pre-filtered before interpolation (necessary for
    spline interpolation of order > 1).  If False it is assumed that
    the input is already filtered. The extra_arguments and
    extra_keywords arguments can be used to provide extra arguments
    and keywords that are passed to the mapping function at each call.

    Example usage:
      >>> a = arange(12.).reshape((4,3))
      >>> def shift_func(output_coordinates):
      ...     return (output_coordinates[0]-0.5, output_coordinates[1]-0.5)
      ...
      >>> print geometric_transform(a,shift_func)
      array([[ 0.    ,  0.    ,  0.    ],
             [ 0.    ,  1.3625,  2.7375],
             [ 0.    ,  4.8125,  6.1875],
             [ 0.    ,  8.2625,  9.6375]])
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError, 'Complex type not supported'
    if output_shape == None:
        output_shape = input.shape
    if input.ndim < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output=numpy.float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output,
                                                   input,
                                                   output_type,
                                                   shape=output_shape)
    _nd_image.geometric_transform(filtered, mapping, None, None, None, output,
                                  order, mode, cval, extra_arguments,
                                  extra_keywords)
    return return_value