Beispiel #1
0
def binary_dilation(input,
                    structure=None,
                    iterations=1,
                    mask=None,
                    output=None,
                    border_value=0,
                    origin=0,
                    brute_force=False):
    """Multi-dimensional binary dilation with the given structure.
    
    An output array can optionally be provided. The origin parameter
    controls the placement of the filter. If no structuring element is
    provided an element is generated with a squared connectivity equal
    to one. The dilation operation is repeated iterations times.  If
    iterations is less than 1, the dilation is repeated until the
    result does not change anymore.  If a mask is given, only those
    elements with a true value at the corresponding mask element are
    modified at each iteration.
    """
    input = numarray.asarray(input)
    if structure == None:
        structure = generate_binary_structure(input.rank, 1)
    origin = _ni_support._normalize_sequence(origin, input.rank)
    structure = numarray.asarray(structure)
    structure = structure[tuple([slice(None, None, -1)] * structure.rank)]
    for ii in range(len(origin)):
        origin[ii] = -origin[ii]
        if not structure.shape[ii] & 1:
            origin[ii] -= 1
    return _binary_erosion(input, structure, iterations, mask, output,
                           border_value, origin, 1, brute_force)
Beispiel #2
0
def grey_dilation(input,
                  size=None,
                  footprint=None,
                  structure=None,
                  output=None,
                  mode="reflect",
                  cval=0.0,
                  origin=0):
    """Calculate a grey values dilation.
    
    Either a size or a footprint, or the structure 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'.
    """
    if structure is not None:
        structure = numarray.asarray(structure)
        structure = structure[tuple([slice(None, None, -1)] * structure.rank)]
    if footprint is not None:
        footprint = numarray.asarray(footprint)
        footprint = footprint[tuple([slice(None, None, -1)] * footprint.rank)]
    input = numarray.asarray(input)
    origin = _ni_support._normalize_sequence(origin, input.rank)
    for ii in range(len(origin)):
        origin[ii] = -origin[ii]
        if footprint is not None:
            sz = footprint.shape[ii]
        else:
            sz = size[ii]
        if not sz & 1:
            origin[ii] -= 1
    return filters._min_or_max_filter(input, size, footprint, structure,
                                      output, mode, cval, origin, 0)
Beispiel #3
0
def label(input, structure = None, output = None):
    """Label an array of objects.

    The structure that defines the object connections must be
    symmetric.  If no structuring element is provided an element is
    generated with a squared connectivity equal to one. This function
    returns a tuple consisting of the array of labels and the number
    of objects found. If an output array is provided only the number of
    objects found is returned.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if structure == None:
        structure = morphology.generate_binary_structure(input.rank, 1)
    structure = numarray.asarray(structure, type = numarray.Bool)
    if structure.rank != input.rank:
        raise RuntimeError, 'structure and input must have equal rank'
    for ii in structure.shape:
        if ii != 3:
            raise  RuntimeError, 'structure dimensions must be equal to 3'
    if not structure.iscontiguous():
        structure = structure.copy()
    if isinstance(output, numarray.NumArray):
        if output.type() != numarray.Int32:
            raise RuntimeError, 'output type must be Int32'
    else:
        output = numarray.Int32
    output, return_value = _ni_support._get_output(output, input)
    max_label = _nd_image.label(input, structure, output)
    if return_value == None:
        return max_label
    else:
        return return_value, max_label
Beispiel #4
0
def grey_dilation(input,  size = None, footprint = None, structure = None,
                 output = None, mode = "reflect", cval = 0.0, origin = 0):
    """Calculate a grey values dilation.
    
    Either a size or a footprint, or the structure 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'.
    """
    if structure is not None:
        structure = numarray.asarray(structure)
        structure = structure[tuple([slice(None, None, -1)] *
                                    structure.rank)]
    if footprint is not None:
        footprint = numarray.asarray(footprint)
        footprint = footprint[tuple([slice(None, None, -1)] *
                                    footprint.rank)]
    input = numarray.asarray(input)
    origin = _ni_support._normalize_sequence(origin, input.rank)
    for ii in range(len(origin)):
        origin[ii] = -origin[ii]
        if footprint is not None:
            sz = footprint.shape[ii]
        else:
            sz = size[ii]
        if not sz & 1:
            origin[ii] -= 1
    return filters._min_or_max_filter(input, size, footprint, structure,
                                      output, mode, cval, origin, 0)
Beispiel #5
0
def label(input, structure=None, output=None):
    """Label an array of objects.

    The structure that defines the object connections must be
    symmetric.  If no structuring element is provided an element is
    generated with a squared connectivity equal to one. This function
    returns a tuple consisting of the array of labels and the number
    of objects found. If an output array is provided only the number of
    objects found is returned.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if structure == None:
        structure = morphology.generate_binary_structure(input.rank, 1)
    structure = numarray.asarray(structure, type=numarray.Bool)
    if structure.rank != input.rank:
        raise RuntimeError, 'structure and input must have equal rank'
    for ii in structure.shape:
        if ii != 3:
            raise RuntimeError, 'structure dimensions must be equal to 3'
    if not structure.iscontiguous():
        structure = structure.copy()
    if isinstance(output, numarray.NumArray):
        if output.type() != numarray.Int32:
            raise RuntimeError, 'output type must be Int32'
    else:
        output = numarray.Int32
    output, return_value = _ni_support._get_output(output, input)
    max_label = _nd_image.label(input, structure, output)
    if return_value == None:
        return max_label
    else:
        return return_value, max_label
Beispiel #6
0
def binary_dilation(input, structure = None, iterations = 1, mask = None,
        output = None, border_value = 0, origin = 0, brute_force = False):
    """Multi-dimensional binary dilation with the given structure.
    
    An output array can optionally be provided. The origin parameter
    controls the placement of the filter. If no structuring element is
    provided an element is generated with a squared connectivity equal
    to one. The dilation operation is repeated iterations times.  If
    iterations is less than 1, the dilation is repeated until the
    result does not change anymore.  If a mask is given, only those
    elements with a true value at the corresponding mask element are
    modified at each iteration.
    """
    input = numarray.asarray(input)
    if structure == None:
        structure = generate_binary_structure(input.rank, 1)
    origin = _ni_support._normalize_sequence(origin, input.rank)
    structure = numarray.asarray(structure)
    structure = structure[tuple([slice(None, None, -1)] *
                                structure.rank)]
    for ii in range(len(origin)):
        origin[ii] = -origin[ii]
        if not structure.shape[ii] & 1:
            origin[ii] -= 1
    return _binary_erosion(input, structure, iterations, mask,
                           output, border_value, origin, 1, brute_force)
Beispiel #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. 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
Beispiel #8
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
Beispiel #9
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
Beispiel #10
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
Beispiel #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
Beispiel #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
Beispiel #13
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
Beispiel #14
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
Beispiel #15
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
Beispiel #16
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
Beispiel #17
0
def sum(input, labels = None, index = None):
    """Calculate the sum of the values of the array.

    The index parameter is a single label number or a sequence of
    label numbers of the objects to be measured. If index is None, all
    values are used where labels is larger than zero.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if labels != None:
        labels = numarray.asarray(labels)
        labels = _broadcast(labels, input.shape)
        if labels.shape != input.shape:
            raise RuntimeError, 'input and labels shape are not equal'
    return _nd_image.statistics(input, labels, index, 0)
Beispiel #18
0
def uniform_filter(input,
                   size=3,
                   output=None,
                   mode="reflect",
                   cval=0.0,
                   origin=0):
    """Multi-dimensional uniform filter.

    The sizes of the uniform filter are given for each axis as a
    sequence, or as a single number, in which case the size is equal
    for all axes.

    The multi-dimensional filter is implemented as a sequence of
    one-dimensional uniform filters. The intermediate arrays are stored
    in the same data type as the output. Therefore, for output types
    with a limited precision, the results may be imprecise because
    intermediate results may be stored with insufficient precision.
    """
    input = numarray.asarray(input)
    output, return_value = _ni_support._get_output(output, input)
    sizes = _ni_support._normalize_sequence(size, input.rank)
    origins = _ni_support._normalize_sequence(origin, input.rank)
    axes = range(input.rank)
    axes = [(axes[ii], sizes[ii], origins[ii]) for ii in range(len(axes))
            if sizes[ii] > 1]
    if len(axes) > 0:
        for axis, size, origin in axes:
            uniform_filter1d(input, int(size), axis, output, mode, cval,
                             origin)
            input = output
    else:
        output[...] = input[...]
    return return_value
Beispiel #19
0
def gaussian_gradient_magnitude(input,
                                sigma,
                                output=None,
                                mode="reflect",
                                cval=0.0):
    """Calculate a multidimensional gradient magnitude using gaussian
    derivatives.

    The standard-deviations of the Gaussian filter are given for each
    axis as a sequence, or as a single number, in which case it is
    equal for all axes..
    """
    input = numarray.asarray(input)

    def derivative(input, axis, output, mode, cval, sigma):
        order = [0] * input.rank
        order[axis] = 1
        return gaussian_filter(input, sigma, order, output, mode, cval)

    return generic_gradient_magnitude(input,
                                      derivative,
                                      output,
                                      mode,
                                      cval,
                                      extra_arguments=(sigma, ))
Beispiel #20
0
def uniform_filter(input, size=3, output=None, mode="reflect", cval=0.0, origin=0):
    """Multi-dimensional uniform filter.

    The sizes of the uniform filter are given for each axis as a
    sequence, or as a single number, in which case the size is equal
    for all axes.

    The multi-dimensional filter is implemented as a sequence of
    one-dimensional uniform filters. The intermediate arrays are stored
    in the same data type as the output. Therefore, for output types
    with a limited precision, the results may be imprecise because
    intermediate results may be stored with insufficient precision.
    """
    input = numarray.asarray(input)
    output, return_value = _ni_support._get_output(output, input)
    sizes = _ni_support._normalize_sequence(size, input.rank)
    origins = _ni_support._normalize_sequence(origin, input.rank)
    axes = range(input.rank)
    axes = [(axes[ii], sizes[ii], origins[ii]) for ii in range(len(axes)) if sizes[ii] > 1]
    if len(axes) > 0:
        for axis, size, origin in axes:
            uniform_filter1d(input, int(size), axis, output, mode, cval, origin)
            input = output
    else:
        output[...] = input[...]
    return return_value
Beispiel #21
0
def sum(input, labels=None, index=None):
    """Calculate the sum of the values of the array.

    The index parameter is a single label number or a sequence of
    label numbers of the objects to be measured. If index is None, all
    values are used where labels is larger than zero.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if labels != None:
        labels = numarray.asarray(labels)
        labels = _broadcast(labels, input.shape)
        if labels.shape != input.shape:
            raise RuntimeError, 'input and labels shape are not equal'
    return _nd_image.statistics(input, labels, index, 0)
Beispiel #22
0
def generic_laplace(input,
                    derivative2,
                    output=None,
                    mode="reflect",
                    cval=0.0,
                    extra_arguments=(),
                    extra_keywords={}):
    """Calculate a multidimensional laplace filter using the provided
    second derivative function.

    The derivative2 parameter must be a callable with the following
    signature:

    derivative2(input, axis, output, mode, cval,
                *extra_arguments, **extra_keywords)
                
    The extra_arguments and extra_keywords arguments can be used to pass 
    extra arguments and keywords that are passed to derivative2 at each 
    call.
    """
    input = numarray.asarray(input)
    output, return_value = _ni_support._get_output(output, input)
    axes = range(input.rank)
    if len(axes) > 0:
        derivative2(input, axes[0], output, mode, cval, *extra_arguments,
                    **extra_keywords)
        for ii in range(1, len(axes)):
            tmp = derivative2(input, axes[ii], output.type(), mode, cval,
                              *extra_arguments, **extra_keywords)
            output += tmp
    else:
        output[...] = input[...]
    return return_value
Beispiel #23
0
def generic_gradient_magnitude(
    input, derivative, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords={}
):
    """Calculate a gradient magnitude using the provdide function for
    the gradient.

    The derivative parameter must be a callable with the following 
    signature:
                    
    derivative(input, axis, output, mode, cval,
               *extra_arguments, **extra_keywords)

    The extra_arguments and extra_keywords arguments can be used to pass 
    extra arguments and keywords that are passed to derivative2 at each 
    call.
    """
    input = numarray.asarray(input)
    output, return_value = _ni_support._get_output(output, input)
    axes = range(input.rank)
    if len(axes) > 0:
        derivative(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords)
        numarray.multiply(output, output, output)
        for ii in range(1, len(axes)):
            tmp = derivative(input, axes[ii], output.type(), mode, cval, *extra_arguments, **extra_keywords)
            numarray.multiply(tmp, tmp, tmp)
            output += tmp
        numarray.sqrt(output, output)
    else:
        output[...] = input[...]
    return return_value
Beispiel #24
0
def gaussian_filter(input, sigma, order=0, output=None, mode="reflect", cval=0.0):
    """Multi-dimensional Gaussian filter.

    The standard-deviations of the Gaussian filter are given for each
    axis as a sequence, or as a single number, in which case it is
    equal for all axes. The order of the filter along each axis is
    given as a sequence of integers, or as a single number. An order
    of 0 corresponds to convolution with a Gaussian kernel. An order
    of 1, 2, or 3 corresponds to convolution with the first, second or
    third derivatives of a Gaussian. Higher order derivatives are not
    implemented.'

    Note: The multi-dimensional filter is implemented as a sequence of
    one-dimensional convolution filters. The intermediate arrays are
    stored in the same data type as the output. Therefore, for output
    types with a limited precision, the results may be imprecise
    because intermediate results may be stored with insufficient
    precision.
    """
    input = numarray.asarray(input)
    output, return_value = _ni_support._get_output(output, input)
    orders = _ni_support._normalize_sequence(order, input.rank)
    sigmas = _ni_support._normalize_sequence(sigma, input.rank)
    axes = range(input.rank)
    axes = [(axes[ii], sigmas[ii], orders[ii]) for ii in range(len(axes)) if sigmas[ii] > 1e-15]
    if len(axes) > 0:
        for axis, sigma, order in axes:
            gaussian_filter1d(input, sigma, axis, order, output, mode, cval)
            input = output
    else:
        output[...] = input[...]
    return return_value
Beispiel #25
0
def binary_hit_or_miss(input, structure1 = None, structure2 = None,
                       output = None, origin1 = 0, origin2 = None):
    """Multi-dimensional binary hit-or-miss transform.
    
    An output array can optionally be provided. The origin parameters
    controls the placement of the structuring elements. If the first
    structuring element is not given one is generated with a squared
    connectivity equal to one. If the second structuring element is
    not provided, it set equal to the inverse of the first structuring
    element. If the origin for the second structure is equal to None
    it is set equal to the origin of the first.
    """
    input = numarray.asarray(input)
    if structure1 is None:
        structure1 = generate_binary_structure(input.rank, 1)
    if structure2 is None:
        structure2 = numarray.logical_not(structure1)
    origin1 = _ni_support._normalize_sequence(origin1, input.rank)
    if origin2 is None:
        origin2 = origin1
    else:
        origin2 = _ni_support._normalize_sequence(origin2, input.rank)

    tmp1 = _binary_erosion(input, structure1, 1, None, None, 0, origin1,
                           0, False)
    inplace = isinstance(output, numarray.NumArray)
    result = _binary_erosion(input, structure2, 1, None, output, 0,
                             origin2, 1, False)
    if inplace:
        numarray.logical_not(output, output)
        numarray.logical_and(tmp1, output, output)
    else:
        numarray.logical_not(result, result)
        return numarray.logical_and(tmp1, result)
Beispiel #26
0
def iterate_structure(structure, iterations, origin=None):
    """Iterate a structure by dilating it with itself.

    If origin is None, only the iterated structure is returned. If
    not, a tuple of the iterated structure and the modified origin is
    returned.
    """
    structure = numarray.asarray(structure)
    if iterations < 2:
        return structure.copy()
    ni = iterations - 1
    shape = [ii + ni * (ii - 1) for ii in structure.shape]
    pos = [ni * (structure.shape[ii] / 2) for ii in range(len(shape))]
    slc = [
        slice(pos[ii], pos[ii] + structure.shape[ii], None)
        for ii in range(len(shape))
    ]
    out = numarray.zeros(shape, numarray.Bool)
    out[slc] = structure != 0
    out = binary_dilation(out, structure, iterations=ni)
    if origin is None:
        return out
    else:
        origin = _ni_support._normalize_sequence(origin, structure.rank)
        origin = [iterations * o for o in origin]
        return out, origin
Beispiel #27
0
def generic_laplace(input, derivative2, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords={}):
    """Calculate a multidimensional laplace filter using the provided
    second derivative function.

    The derivative2 parameter must be a callable with the following
    signature:

    derivative2(input, axis, output, mode, cval,
                *extra_arguments, **extra_keywords)
                
    The extra_arguments and extra_keywords arguments can be used to pass 
    extra arguments and keywords that are passed to derivative2 at each 
    call.
    """
    input = numarray.asarray(input)
    output, return_value = _ni_support._get_output(output, input)
    axes = range(input.rank)
    if len(axes) > 0:
        derivative2(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords)
        for ii in range(1, len(axes)):
            tmp = derivative2(input, axes[ii], output.type(), mode, cval, *extra_arguments, **extra_keywords)
            output += tmp
    else:
        output[...] = input[...]
    return return_value
Beispiel #28
0
def inverse(a):
    """inverse(a) -> inverse matrix of a
    
    *a* may be either rank-2 or rank-3. If it is rank-2, it must square.
    
    >>> A = [[1,2,3], [3,5,5], [5,6,7]]
    >>> Ainv = inverse(A)
    >>> _isClose(na.dot(A, Ainv), na.identity(3))
    1
    
    If *a* is rank-3, it is treated as an array of rank-2 matrices and
    must be square along the last 2 axes.
    
    >>> A = [[[1, 3], [2j, 3j]],
    ...      [[2, 4], [4j, 4j]],
    ...      [[3, 5], [6j, 5j]]]
    >>> Ainv = inverse(A)
    >>> _isClose(map(na.dot, A, Ainv), [na.identity(2)]*3)
    1
    
    If *a* is not square along its last two axes, a LinAlgError is raised.
    
    >>> inverse(na.asarray(A)[...,:1])
    Traceback (most recent call last):
       ...
    LinearAlgebraError: Array (or it submatrices) must be square
    
    """
    a = na.asarray(a)
    I = na.identity(a.shape[-2])
    if len(a.shape) == 3:
        I.shape = (1,) + I.shape
    return solve_linear_equations(a, I)
Beispiel #29
0
def determinant(a):
    """determinant(a) -> ||a||
 
    *a* may be either rank-2 or rank-3. If it is rank-2, it must square. 
    
    >>> A = [[1,2,3], [3,4,5], [5,6,7]]
    >>> _isClose(determinant(A), 0)
    1
    
    If *a* is rank-3, it is treated as an array of rank-2 matrices and
    must be square along the last 2 axes.
 
    >>> A = [[[1, 3], [2j, 3j]], [[2, 4], [4j, 4j]], [[3, 5], [6j, 5j]]]
    >>> _isClose(determinant(A), [-3j, -8j, -15j])
    1

    If *a* is not square along its last two axes, a LinAlgError is raised.
    
    >>> determinant(na.asarray(A)[...,:1])
    Traceback (most recent call last):
       ...
    LinearAlgebraError: Array (or it submatrices) must be square
    
    """
    a = na.asarray(a)
    _assertRank((2,3), a)
    _assertSubmatrixSquareness(a)
    stretched = (len(a.shape) == 2)
    if stretched:
        a = a[na.NewAxis,]
    t = _commonType(a)
    a = _castCopyAndTranspose(t, a, indices=(0,2,1))
    n_cases, n = a.shape[:2]
    if _array_kind[t] == 1:
        lapack_routine = lapack_lite2.zgetrf
    else:
        lapack_routine = lapack_lite2.dgetrf
    no_pivoting = na.arrayrange(1, n+1)
    pivots = na.zeros((n,), 'l')
    all_pivots = na.zeros((n_cases, n,), 'l')
    sum , not_equal = na.sum, na.not_equal
    stride = n * n * a.itemsize()
    pivots_stride = n * pivots.itemsize()
    view = a[0].view()
    view_pivots = all_pivots[0]
    a_i = view.copy()
    for i in range(n_cases):
        if i:
            a_i._copyFrom(view)
        outcome = lapack_routine(n, n, a_i, n, pivots, 0)
        view_pivots._copyFrom(pivots)
        view._copyFrom(a_i)
        view._byteoffset += stride
        view_pivots._byteoffset += pivots_stride
    signs = na.where(sum(not_equal(all_pivots, no_pivoting), 1) % 2, -1, 1).astype(t)
    for i in range(n):
        signs *= a[:,i,i]
    if stretched:
        signs = signs[0]
    return signs
Beispiel #30
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
Beispiel #31
0
 def __mul__(self, other):
     aother = asarray(other)
     #if len(aother.shape) == 0:
     #    return self._rc(self*aother)
     #else:
     #    return self._rc(dot(self, aother))
     #return self._rc(dot(self, aother))
     return dot(self, aother)
Beispiel #32
0
 def __mul__(self, other):
     aother = asarray(other)
     #if len(aother.shape) == 0:
     #    return self._rc(self*aother)
     #else:
     #    return self._rc(dot(self, aother))
     #return self._rc(dot(self, aother))
     return dot(self, aother)
Beispiel #33
0
def wmspec(data, windows=None, doxs=1):

    """Compute power and cross spectra, with a window or multitapers.

    data and doxs are as for multispec
    (except the default for doxs is different).

    If windows is one-dimensional, it is treated as a windowing function.

    If windows is two-dimensional, it is treated as a set of multitapers."""

    data = num.asarray(data)

    if windows is None:
        windows = [1]
    else:
        windows = num.array(windows, copy=0)
        win_length = windows.shape[-1]
        windows.shape = (-1, win_length)
    nwin = len(windows)

    # subtract the average
    avg = num.sum(data, -1) / data.shape[-1]
    avg = num.asarray(avg)
    data = data - avg[..., num.NewAxis]

    total_power = 0
    if doxs:
        total_cross = 0
    for window in windows:
        spectra = multispec(data * window, doxs=doxs)
        if doxs:
            total_power += spectra[0]
            total_cross += spectra[1]
        else:
            total_power += spectra
    total_power /= nwin
    if doxs:
        total_cross /= nwin
    
    if doxs:
        return total_power, total_cross
    else:
        return total_power
Beispiel #34
0
def wmspec(data, windows=None, doxs=1):
    """Compute power and cross spectra, with a window or multitapers.

    data and doxs are as for multispec
    (except the default for doxs is different).

    If windows is one-dimensional, it is treated as a windowing function.

    If windows is two-dimensional, it is treated as a set of multitapers."""

    data = num.asarray(data)

    if windows is None:
        windows = [1]
    else:
        windows = num.array(windows, copy=0)
        win_length = windows.shape[-1]
        windows.shape = (-1, win_length)
    nwin = len(windows)

    # subtract the average
    avg = num.sum(data, -1) / data.shape[-1]
    avg = num.asarray(avg)
    data = data - avg[..., num.NewAxis]

    total_power = 0
    if doxs:
        total_cross = 0
    for window in windows:
        spectra = multispec(data * window, doxs=doxs)
        if doxs:
            total_power += spectra[0]
            total_cross += spectra[1]
        else:
            total_power += spectra
    total_power /= nwin
    if doxs:
        total_cross /= nwin

    if doxs:
        return total_power, total_cross
    else:
        return total_power
Beispiel #35
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
Beispiel #36
0
def fourier_uniform(input, size, n = -1, axis = -1, output = None):
    """Multi-dimensional Uniform fourier filter.

    The array is multiplied with the fourier transform of a box of given
    sizes. If the parameter n is negative, then the input is assumed to be 
    the result of a complex fft. If n is larger or equal to zero, the input 
    is assumed to be the result of a real fft, and n gives the length of 
    the of the array before transformation along the the real transform 
    direction. The axis of the real transform is given by the axis 
    parameter.
    """
    input = numarray.asarray(input)
    output, return_value = _get_output_fourier(output, input)
    axis = _ni_support._check_axis(axis, input.rank)
    sizes = _ni_support._normalize_sequence(size, input.rank)
    sizes = numarray.asarray(sizes, type = numarray.Float64)
    if not sizes.iscontiguous():
        sizes = sizes.copy()
    _nd_image.fourier_filter(input, sizes, n, axis, output, 1)
    return return_value
Beispiel #37
0
def maximum_position(input, labels=None, index=None):
    """Find the position of the maximum of the values of the array.

    The index parameter is a single label number or a sequence of
    label numbers of the objects to be measured. If index is None, all
    values are used where labels is larger than zero.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if labels != None:
        labels = numarray.asarray(labels)
        labels = _broadcast(labels, input.shape)
        if labels.shape != input.shape:
            raise RuntimeError, 'input and labels shape are not equal'
    pos = _nd_image.statistics(input, labels, index, 6)
    if (isinstance(pos, types.ListType)):
        return [_index_to_position(x, input.shape) for x in pos]
    else:
        return _index_to_position(pos, input.shape)
Beispiel #38
0
def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0):
    """Calculate a Sobel filter.
    """
    input = numarray.asarray(input)
    axis = _ni_support._check_axis(axis, input.rank)
    output, return_value = _ni_support._get_output(output, input)
    correlate1d(input, [-1, 0, 1], axis, output, mode, cval, 0)
    axes = [ii for ii in range(input.rank) if ii != axis]
    for ii in axes:
        correlate1d(output, [1, 2, 1], ii, output, mode, cval, 0)
    return return_value
Beispiel #39
0
def maximum_position(input, labels = None, index = None):
    """Find the position of the maximum of the values of the array.

    The index parameter is a single label number or a sequence of
    label numbers of the objects to be measured. If index is None, all
    values are used where labels is larger than zero.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if labels != None:
        labels = numarray.asarray(labels)
        labels = _broadcast(labels, input.shape)
        if labels.shape != input.shape:
            raise RuntimeError, 'input and labels shape are not equal'
    pos = _nd_image.statistics(input, labels, index, 6)
    if (isinstance(pos, types.ListType)):
        return [_index_to_position(x, input.shape) for x in pos]
    else:
        return _index_to_position(pos, input.shape)
Beispiel #40
0
def fourier_uniform(input, size, n=-1, axis=-1, output=None):
    """Multi-dimensional Uniform fourier filter.

    The array is multiplied with the fourier transform of a box of given
    sizes. If the parameter n is negative, then the input is assumed to be 
    the result of a complex fft. If n is larger or equal to zero, the input 
    is assumed to be the result of a real fft, and n gives the length of 
    the of the array before transformation along the the real transform 
    direction. The axis of the real transform is given by the axis 
    parameter.
    """
    input = numarray.asarray(input)
    output, return_value = _get_output_fourier(output, input)
    axis = _ni_support._check_axis(axis, input.rank)
    sizes = _ni_support._normalize_sequence(size, input.rank)
    sizes = numarray.asarray(sizes, type=numarray.Float64)
    if not sizes.iscontiguous():
        sizes = sizes.copy()
    _nd_image.fourier_filter(input, sizes, n, axis, output, 1)
    return return_value
Beispiel #41
0
def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0):
    """Calculate a Sobel filter.
    """
    input = numarray.asarray(input)
    axis = _ni_support._check_axis(axis, input.rank)
    output, return_value = _ni_support._get_output(output, input)
    correlate1d(input, [-1, 0, 1], axis, output, mode, cval, 0)
    axes = [ii for ii in range(input.rank) if ii != axis]
    for ii in axes:
        correlate1d(output, [1, 2, 1], ii, output, mode, cval, 0)
    return return_value
Beispiel #42
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
Beispiel #43
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
Beispiel #44
0
def histogram(input, min, max, bins, labels = None, index = None):
    """Calculate a histogram of of the array.

    The histogram is defined by its minimum and maximum value and the
    number of bins.

    The index parameter is a single label number or a sequence of
    label numbers of the objects to be measured. If index is None, all
    values are used where labels is larger than zero.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if labels != None:
        labels = numarray.asarray(labels)
        labels = _broadcast(labels, input.shape)
        if labels.shape != input.shape:
            raise RuntimeError, 'input and labels shape are not equal'
    if bins < 1:
        raise RuntimeError, 'number of bins must be >= 1'
    if min >= max:
        raise RuntimeError, 'min must be < max'
    return _nd_image.histogram(input, min, max, bins, labels, index)
Beispiel #45
0
def histogram(input, min, max, bins, labels=None, index=None):
    """Calculate a histogram of of the array.

    The histogram is defined by its minimum and maximum value and the
    number of bins.

    The index parameter is a single label number or a sequence of
    label numbers of the objects to be measured. If index is None, all
    values are used where labels is larger than zero.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if labels != None:
        labels = numarray.asarray(labels)
        labels = _broadcast(labels, input.shape)
        if labels.shape != input.shape:
            raise RuntimeError, 'input and labels shape are not equal'
    if bins < 1:
        raise RuntimeError, 'number of bins must be >= 1'
    if min >= max:
        raise RuntimeError, 'min must be < max'
    return _nd_image.histogram(input, min, max, bins, labels, index)
Beispiel #46
0
def watershed_ift(input, markers, structure=None, output=None):
    """Apply watershed from markers using a iterative forest transform
    algorithm.

    Negative markers are considered background markers which are
    processed after the other markers. A structuring element defining
    the connectivity of the object can be provided. If none is
    provided an element is generated iwth a squared connecitiviy equal
    to one. An output array can optionally be provided.
    """
    input = numarray.asarray(input)
    if input.type() not in [numarray.UInt8, numarray.UInt16]:
        raise TypeError, 'only 8 and 16 unsigned inputs are supported'
    if structure == None:
        structure = morphology.generate_binary_structure(input.rank, 1)
    structure = numarray.asarray(structure, type=numarray.Bool)
    if structure.rank != input.rank:
        raise RuntimeError, 'structure and input must have equal rank'
    for ii in structure.shape:
        if ii != 3:
            raise RuntimeError, 'structure dimensions must be equal to 3'
    if not structure.iscontiguous():
        structure = structure.copy()
    markers = numarray.asarray(markers)
    if input.shape != markers.shape:
        raise RuntimeError, 'input and markers must have equal shape'
    if not isinstance(markers.type(), numarray.IntegralType):
        raise RuntimeError, 'marker should be of integer type'
    if isinstance(output, numarray.NumArray):
        if not isinstance(output.type(), numarray.IntegralType):
            raise RuntimeError, 'output should be of integer type'
    else:
        output = markers.type()
    output, return_value = _ni_support._get_output(output, input)
    _nd_image.watershed_ift(input, markers, structure, output)
    return return_value
Beispiel #47
0
def extrema(input, labels=None, index=None):
    """Calculate the minimum, the maximum and their positions of the 
       values of the array.

    The index parameter is a single label number or a sequence of
    label numbers of the objects to be measured. If index is None, all
    values are used where labels is larger than zero.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if labels != None:
        labels = numarray.asarray(labels)
        labels = _broadcast(labels, input.shape)
        if labels.shape != input.shape:
            raise RuntimeError, 'input and labels shape are not equal'
    min, max, minp, maxp = _nd_image.statistics(input, labels, index, 7)
    if (isinstance(minp, types.ListType)):
        minp = [_index_to_position(x, input.shape) for x in minp]
        maxp = [_index_to_position(x, input.shape) for x in maxp]
    else:
        minp = _index_to_position(minp, input.shape)
        maxp = _index_to_position(maxp, input.shape)
    return min, max, minp, maxp
Beispiel #48
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
Beispiel #49
0
def binary_closing(input, structure=None, iterations=1, output=None, origin=0):
    """Multi-dimensional binary closing with the given structure.

    An output array can optionally be provided. The origin parameter
    controls the placement of the filter. If no structuring element is
    provided an element is generated with a squared connectivity equal
    to one. The iterations parameter gives the number of times the
    dilations and then the erosions are done.
    """
    input = numarray.asarray(input)
    if structure is None:
        rank = input.rank
        structure = generate_binary_structure(rank, 1)
    tmp = binary_dilation(input, structure, iterations, None, None, 0, origin)
    return binary_erosion(tmp, structure, iterations, None, output, 0, origin)
Beispiel #50
0
def extrema(input, labels = None, index = None):
    """Calculate the minimum, the maximum and their positions of the 
       values of the array.

    The index parameter is a single label number or a sequence of
    label numbers of the objects to be measured. If index is None, all
    values are used where labels is larger than zero.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if labels != None:
        labels = numarray.asarray(labels)
        labels = _broadcast(labels, input.shape)
        if labels.shape != input.shape:
            raise RuntimeError, 'input and labels shape are not equal'
    min, max, minp, maxp = _nd_image.statistics(input, labels, index, 7)
    if (isinstance(minp, types.ListType)):
        minp = [_index_to_position(x, input.shape) for x in minp]
        maxp = [_index_to_position(x, input.shape) for x in maxp]
    else:
        minp = _index_to_position(minp, input.shape)
        maxp = _index_to_position(maxp, input.shape)
    return min, max, minp, maxp
Beispiel #51
0
def watershed_ift(input, markers, structure = None, output = None):
    """Apply watershed from markers using a iterative forest transform
    algorithm.

    Negative markers are considered background markers which are
    processed after the other markers. A structuring element defining
    the connectivity of the object can be provided. If none is
    provided an element is generated iwth a squared connecitiviy equal
    to one. An output array can optionally be provided.
    """
    input = numarray.asarray(input)
    if input.type() not in [numarray.UInt8, numarray.UInt16]:
        raise TypeError, 'only 8 and 16 unsigned inputs are supported'
    if structure == None:
        structure = morphology.generate_binary_structure(input.rank, 1)
    structure = numarray.asarray(structure, type = numarray.Bool)
    if structure.rank != input.rank:
        raise RuntimeError, 'structure and input must have equal rank'
    for ii in structure.shape:
        if ii != 3:
            raise  RuntimeError, 'structure dimensions must be equal to 3'
    if not structure.iscontiguous():
        structure = structure.copy()
    markers = numarray.asarray(markers)
    if input.shape != markers.shape:
        raise RuntimeError, 'input and markers must have equal shape'
    if not isinstance(markers.type(), numarray.IntegralType):
        raise RuntimeError, 'marker should be of integer type'
    if isinstance(output, numarray.NumArray):
        if not isinstance(output.type(), numarray.IntegralType):
            raise RuntimeError, 'output should be of integer type'
    else:
        output = markers.type()
    output, return_value = _ni_support._get_output(output, input)
    _nd_image.watershed_ift(input, markers, structure, output)
    return return_value
Beispiel #52
0
def _combine_f(funcstr, arrays, output=None, outtype=None, nlow=0, nhigh=0, badmasks=None):
    arrays = [ num.asarray(a) for a in arrays ]
    shape = arrays[0].shape
    if output is None:
        if outtype is not None:
            out = arrays[0].astype(outtype)
        else:
            out = arrays[0].copy()
    else:
        out = output
    for a in tuple(arrays[1:])+(out,):
        if a.shape != shape:
            raise ValueError("all arrays must have identical shapes")
    _comb(arrays, out, nlow, nhigh, badmasks, funcstr)
    if output is None:
        return out
Beispiel #53
0
def find_objects(input, max_label=0):
    """Find objects in a labeled array.

    The input must be an array with labeled objects. A list of slices
    into the array is returned that contain the objects. The list
    represents a sequence of the numbered objects. If a number is
    missing, None is returned instead of a slice. If max_label > 0, it
    gives the largest object number that is searched for, otherwise
    all are returned.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if max_label < 1:
        max_label = input.max()
    return _nd_image.find_objects(input, max_label)
Beispiel #54
0
def gaussian_gradient_magnitude(input, sigma, output=None, mode="reflect", cval=0.0):
    """Calculate a multidimensional gradient magnitude using gaussian
    derivatives.

    The standard-deviations of the Gaussian filter are given for each
    axis as a sequence, or as a single number, in which case it is
    equal for all axes..
    """
    input = numarray.asarray(input)

    def derivative(input, axis, output, mode, cval, sigma):
        order = [0] * input.rank
        order[axis] = 1
        return gaussian_filter(input, sigma, order, output, mode, cval)

    return generic_gradient_magnitude(input, derivative, output, mode, cval, extra_arguments=(sigma,))
Beispiel #55
0
def find_objects(input, max_label = 0):
    """Find objects in a labeled array.

    The input must be an array with labeled objects. A list of slices
    into the array is returned that contain the objects. The list
    represents a sequence of the numbered objects. If a number is
    missing, None is returned instead of a slice. If max_label > 0, it
    gives the largest object number that is searched for, otherwise
    all are returned.
    """
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if max_label < 1:
        max_label = input.max()
    return _nd_image.find_objects(input, max_label)
Beispiel #56
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
Beispiel #57
0
def generate_binary_structure(rank, connectivity):
    """Generate a binary structure for binary morphological operations.

    The inputs are the rank of the array to which the structure will
    be applied and the square of the connectivity of the structure.
    """
    if connectivity < 1:
        connectivity = 1
    if rank < 1:
        if connectivity < 1:
            return numarray.array(0, type=numarray.Bool)
        else:
            return numarray.array(1, type=numarray.Bool)
    output = numarray.zeros([3] * rank, numarray.Bool)
    output = numarray.abs(numarray.indices([3] * rank) - 1)
    output = numarray.add.reduce(output, 0)
    return numarray.asarray(output <= connectivity, type=numarray.Bool)
Beispiel #58
0
def multispec(data, doxs=1):
    """Compute power and cross spectra.

    power, cross = multispec(data[, doxs=1])

    data is expected to be a numeric sequence, representing a binned light
    curve.

    If doxs is false or data is one-dimensional, the cross spectra will not
    be calculated as described below, and only the power spectra will be
    returned.

    If data is one-dimensional, its periodogram will be calculated.

    If data is two-dimensional, it will be interpreted as an array of
    one-dimensional curves.  The periodogram will be calculated for each,
    and the cross spectra of all but the first relative to the first.

    If data has more than two dimensions, it will be interpreted as an array
    of two-dimensional sets, and each will be treated as described above."""

    # Figure out what we've got.
    data = num.asarray(data)
    npoints = data.shape[-1]
    if len(data.shape) < 2:
        doxs = 0

    # crunch
    transform = None
    if num.__name__ == 'numarray':
        transform = FFT.real_fft(data)
    else:
        transform = FFT.fft(data)
    conj = num.conjugate(transform)

    # Get the periodogram.
    power = transform * conj
    power = num.array(power.real)

    if doxs:
        # Calculate the cross spectrum.
        cross = transform[..., :1, :] * conj[..., 1:, :]
        return power, cross
    else:
        return power