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
def spline_filter(input, order=3, output = numpy.float64): """ Multi-dimensional spline filter. For more details, see `spline_filter1d`. See Also -------- spline_filter1d Notes ----- The multi-dimensional filter is implemented as a sequence of one-dimensional spline 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. """ if order < 2 or order > 5: raise RuntimeError('spline order not supported') input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) if order not in [0, 1] and input.ndim > 0: for axis in range(input.ndim): spline_filter1d(input, order, axis, output = output) input = output else: output[...] = input[...] return return_value
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
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
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 = _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 = tuple([int(ii * jj) for ii, jj in zip(input.shape, zoom)]) zoom = (numpy.array(input.shape)-1)/(numpy.array(output_shape,float)-1) output, return_value = _ni_support._get_output(output, input, output_type, shape = output_shape) zoom = numpy.asarray(zoom, dtype = numpy.float64) zoom = numpy.ascontiguousarray(zoom) _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval) return return_value
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
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 = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) orders = _ni_support._normalize_sequence(order, input.ndim) sigmas = _ni_support._normalize_sequence(sigma, input.ndim) axes = range(input.ndim) 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
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
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
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
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
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
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 = _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
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 = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) axes = range(input.ndim) 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.dtype, mode, cval, *extra_arguments, **extra_keywords) output += tmp else: output[...] = input[...] return return_value
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
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 = 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 = _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) shift = _ni_support._normalize_sequence(shift, input.ndim) shift = [-ii for ii in shift] shift = numpy.asarray(shift, dtype = numpy.float64) if not shift.flags.contiguous: shift = shift.copy() _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval) return return_value
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 = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError, 'Complex type not supported' if structure is None: structure = morphology.generate_binary_structure(input.ndim, 1) structure = numpy.asarray(structure, dtype=bool) if structure.ndim != input.ndim: 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.flags.contiguous: structure = structure.copy() if isinstance(output, numpy.ndarray): if output.dtype.type != numpy.int32: raise RuntimeError, 'output type must be int32' else: output = numpy.int32 output, return_value = _ni_support._get_output(output, input) max_label = _nd_image.label(input, structure, output) if return_value is None: return max_label else: return return_value, max_label
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
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
def spline_filter(input, order=3, output=numpy.float64): """ Multi-dimensional spline filter. For more details, see `spline_filter1d`. See Also -------- spline_filter1d Notes ----- The multi-dimensional filter is implemented as a sequence of one-dimensional spline 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. """ if order < 2 or order > 5: raise RuntimeError('spline order not supported') input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) if order not in [0, 1] and input.ndim > 0: for axis in range(input.ndim): spline_filter1d(input, order, axis, output=output) input = output else: output[...] = input[...] return return_value
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 = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) sizes = _ni_support._normalize_sequence(size, input.ndim) origins = _ni_support._normalize_sequence(origin, input.ndim) axes = range(input.ndim) 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
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 = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) axes = range(input.ndim) if len(axes) > 0: derivative(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(output, output, output) for ii in range(1, len(axes)): tmp = derivative(input, axes[ii], output.dtype, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(tmp, tmp, tmp) output += tmp numpy.sqrt(output, output) else: output[...] = input[...] return return_value
def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0): """Calculate a Prewitt filter. Parameters ---------- %(input)s %(axis)s %(output)s %(mode)s %(cval)s """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) 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.ndim) if ii != axis] for ii in axes: correlate1d( output, [1, 1, 1], ii, output, mode, cval, 0, ) return return_value
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
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 is None: output_shape = input.shape if input.ndim < 1 or len(output_shape) < 1: raise RuntimeError, 'input and output rank must be > 0' mode = _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
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
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
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
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 ------- >>> 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 is None: output_shape = input.shape if input.ndim < 1 or len(output_shape) < 1: raise RuntimeError, 'input and output rank must be > 0' mode = _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
def sobel(input, axis = -1, output = None, mode = "reflect", cval = 0.0): """Calculate a Sobel filter. """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) 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.ndim) if ii != axis] for ii in axes: correlate1d(output, [1, 2, 1], ii, output, mode, cval, 0) return return_value
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
def gaussian_filter(input, sigma, order=0, output=None, mode="reflect", cval=0.0): """Multi-dimensional Gaussian filter. Parameters ---------- %(input)s sigma : scalar or sequence of scalars standard deviation for Gaussian kernel. 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. order : {0, 1, 2, 3} or sequence from same set, optional 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 %(output)s %(mode)s %(cval)s Notes ----- 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 = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) orders = _ni_support._normalize_sequence(order, input.ndim) if not set(orders).issubset(set(range(4))): raise ValueError('Order outside 0..4 not implemented') sigmas = _ni_support._normalize_sequence(sigma, input.ndim) axes = range(input.ndim) 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
def generic_gradient_magnitude(input, derivative, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords=None): """Calculate a gradient magnitude using the provided function for the gradient. Parameters ---------- %(input)s derivative : callable Callable with the following signature:: derivative(input, axis, output, mode, cval, *extra_arguments, **extra_keywords) See `extra_arguments`, `extra_keywords` below. `derivative` can assume that `input` and `output` are ndarrays. Note that the output from `derivative` is modified inplace; be careful to copy important inputs before returning them. %(output)s %(mode)s %(cval)s %(extra_keywords)s %(extra_arguments)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) axes = range(input.ndim) if len(axes) > 0: derivative(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(output, output, output) for ii in range(1, len(axes)): tmp = derivative(input, axes[ii], output.dtype, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(tmp, tmp, tmp) output += tmp # This allows the sqrt to work with a different default casting if numpy.version.short_version > '1.6.1': numpy.sqrt(output, output, casting='unsafe') else: numpy.sqrt(output, output) else: output[...] = input[...] return return_value
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
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
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
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
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
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
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
def generic_gradient_magnitude(input, derivative, output = None, mode = "reflect", cval = 0.0, extra_arguments = (), extra_keywords = None): """Calculate a gradient magnitude using the provided function for the gradient. Parameters ---------- %(input)s derivative : callable Callable with the following signature:: derivative(input, axis, output, mode, cval, *extra_arguments, **extra_keywords) See `extra_arguments`, `extra_keywords` below. `derivative` can assume that `input` and `output` are ndarrays. Note that the output from `derivative` is modified inplace; be careful to copy important inputs before returning them. %(output)s %(mode)s %(cval)s %(extra_keywords)s %(extra_arguments)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) axes = range(input.ndim) if len(axes) > 0: derivative(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(output, output, output) for ii in range(1, len(axes)): tmp = derivative(input, axes[ii], output.dtype, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(tmp, tmp, tmp) output += tmp # This allows the sqrt to work with a different default casting if numpy.version.short_version > '1.6.1': numpy.sqrt(output, output, casting='unsafe') else: numpy.sqrt(output, output) else: output[...] = input[...] return return_value
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
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 = numpy.asarray(input) if input.dtype.type not in [numpy.uint8, numpy.uint16]: raise TypeError('only 8 and 16 unsigned inputs are supported') if structure is None: structure = morphology.generate_binary_structure(input.ndim, 1) structure = numpy.asarray(structure, dtype = bool) if structure.ndim != input.ndim: 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.flags.contiguous: structure = structure.copy() markers = numpy.asarray(markers) if input.shape != markers.shape: raise RuntimeError('input and markers must have equal shape') integral_types = [numpy.int0, numpy.int8, numpy.int16, numpy.int32, numpy.int_, numpy.int64, numpy.intc, numpy.intp] if markers.dtype.type not in integral_types: raise RuntimeError('marker should be of integer type') if isinstance(output, numpy.ndarray): if output.dtype.type not in integral_types: raise RuntimeError('output should be of integer type') else: output = markers.dtype output, return_value = _ni_support._get_output(output, input) _nd_image.watershed_ift(input, markers, structure, output) return return_value
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 with a squared connectivity equal to one. An output array can optionally be provided. """ input = numpy.asarray(input) if input.dtype.type not in [numpy.uint8, numpy.uint16]: raise TypeError('only 8 and 16 unsigned inputs are supported') if structure is None: structure = morphology.generate_binary_structure(input.ndim, 1) structure = numpy.asarray(structure, dtype = bool) if structure.ndim != input.ndim: 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.flags.contiguous: structure = structure.copy() markers = numpy.asarray(markers) if input.shape != markers.shape: raise RuntimeError('input and markers must have equal shape') integral_types = [numpy.int0, numpy.int8, numpy.int16, numpy.int32, numpy.int_, numpy.int64, numpy.intc, numpy.intp] if markers.dtype.type not in integral_types: raise RuntimeError('marker should be of integer type') if isinstance(output, numpy.ndarray): if output.dtype.type not in integral_types: raise RuntimeError('output should be of integer type') else: output = markers.dtype output, return_value = _ni_support._get_output(output, input) _nd_image.watershed_ift(input, markers, structure, output) return return_value
def spline_filter1d(input, order=3, axis=-1, output=numpy.float64, output_type=None): """ Calculates a one-dimensional spline filter along the given axis. The lines of the array along the given axis are filtered by a spline filter. The order of the spline must be >= 2 and <= 5. Parameters ---------- input : array_like The input array. order : int, optional The order of the spline, default is 3. axis : int, optional The axis along which the spline filter is applied. Default is the last axis. output : ndarray or dtype, optional The array in which to place the output, or the dtype of the returned array. Default is `numpy.float64`. output_type : dtype, optional DEPRECATED, DO NOT USE. If used, a RuntimeError is raised. Returns ------- return_value : ndarray or None The filtered input. If `output` is given as a parameter, None is returned. """ 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' output, return_value = _ni_support._get_output(output, input, output_type) if order in [0, 1]: output[...] = numpy.array(input) else: axis = _ni_support._check_axis(axis, input.ndim) _nd_image.spline_filter1d(input, order, axis, output) return return_value
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
def prewitt(input, axis = -1, output = None, mode = "reflect", cval = 0.0): """Calculate a Prewitt filter. Parameters ---------- %(input)s %(axis)s %(output)s %(mode)s %(cval)s """ input = numpy.asarray(input) axis = _ni_support._check_axis(axis, input.ndim) 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.ndim) if ii != axis] for ii in axes: correlate1d(output, [1, 1, 1], ii, output, mode, cval, 0,) return return_value
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
def spline_filter1d(input, order = 3, axis = -1, output = numpy.float64, output_type = None): """ Calculates a one-dimensional spline filter along the given axis. The lines of the array along the given axis are filtered by a spline filter. The order of the spline must be >= 2 and <= 5. Parameters ---------- input : array_like The input array. order : int, optional The order of the spline, default is 3. axis : int, optional The axis along which the spline filter is applied. Default is the last axis. output : ndarray or dtype, optional The array in which to place the output, or the dtype of the returned array. Default is `numpy.float64`. output_type : dtype, optional DEPRECATED, DO NOT USE. If used, a RuntimeError is raised. Returns ------- return_value : ndarray or None The filtered input. If `output` is given as a parameter, None is returned. """ 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' output, return_value = _ni_support._get_output(output, input, output_type) if order in [0, 1]: output[...] = numpy.array(input) else: axis = _ni_support._check_axis(axis, input.ndim) _nd_image.spline_filter1d(input, order, axis, output) return return_value
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
def spline_filter1d(input, order = 3, axis = -1, output = numpy.float64, output_type = None): """Calculates a one-dimensional spline filter along the given axis. The lines of the array along the given axis are filtered by a spline filter. The order of the spline must be >= 2 and <= 5. """ 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' output, return_value = _ni_support._get_output(output, input, output_type) if order in [0, 1]: output[...] = numpy.array(input) else: axis = _ni_support._check_axis(axis, input.ndim) _nd_image.spline_filter1d(input, order, axis, output) return return_value
def generic_laplace(input, derivative2, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords=None): """Calculate a multidimensional laplace filter using the provided second derivative function. Parameters ---------- %(input)s derivative2 : callable Callable with the following signature:: derivative2(input, axis, output, mode, cval, *extra_arguments, **extra_keywords) See `extra_arguments`, `extra_keywords` below. %(output)s %(mode)s %(cval)s %(extra_keywords)s %(extra_arguments)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) axes = range(input.ndim) 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.dtype, mode, cval, *extra_arguments, **extra_keywords) output += tmp else: output[...] = input[...] return return_value
def spline_filter(input, order=3, output=numarray.Float64, output_type=None): """Multi-dimensional spline filter. Note: The multi-dimensional filter is implemented as a sequence of one-dimensional spline 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. """ if order < 2 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' output, return_value = _ni_support._get_output(output, input, output_type) if order not in [0, 1] and input.rank > 0: for axis in range(input.rank): spline_filter1d(input, order, axis, output=output) input = output else: output[...] = input[...] return return_value
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
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