Full API Documentation

A package for computer vision in Python.

mahotas.as_rgb(r, g, b)

Returns an RGB image

If any of the channels is None, that channel is set to zero.

Parameters :

r,g,b : array-like, optional

The channels can be of any type or None. At least one must be not None and all must have the same shape.

Returns :

rgb : ndarray

RGB ndarray

mahotas.bbox(img)

Calculate the bounding box of image img.

Parameters :

img : ndarray

Any integer image type

Returns :

min1,max1,min2,max2 : int,int,int,int

These are such that img[min1:max1, min2:max2] contains all non-zero pixels

mahotas.border(labeled, i, j, Bc={3x3 cross}, output={np.zeros(labeled.shape, bool)}, always_return=True)

Compute the border region between i and j regions.

A pixel is on the border if it has value i (or j) and a pixel in its neighbourhood (defined by Bc) has value j (or i).

Parameters :

labeled : ndarray of integer type

input labeled array

i : integer

j : integer

Bc : structure element, optional

output : ndarray of same shape as labeled, dtype=bool, optional

where to store the output. If None, a new array is allocated

always_return : bool, optional

if false, then, in the case where there is no pixel on the border, returns None. Otherwise (the default), it always returns an array even if it is empty.

Returns :

border_img : boolean ndarray

Pixels are True exactly where there is a border between i and j in labeled

mahotas.borders(labeled, Bc={3x3 cross}, output={np.zeros(labeled.shape, bool)})

Compute border pixels

A pixel is on a border if it has value i and a pixel in its neighbourhood (defined by Bc) has value j, with i != j.

Parameters :

labeled : ndarray of integer type

input labeled array

Bc : structure element, optional

output : ndarray of same shape as labeled, dtype=bool, optional

where to store the output. If None, a new array is allocated

Returns :

border_img : boolean ndarray

Pixels are True exactly where there is a border in labeled

mahotas.bwperim(bw, n=4)

Find the perimeter of objects in binary images.

A pixel is part of an object perimeter if its value is one and there is at least one zero-valued pixel in its neighborhood.

By default the neighborhood of a pixel is 4 nearest pixels, but if n is set to 8 the 8 nearest pixels will be considered.

Parameters :

bw : ndarray

A black-and-white image (any other image will be converted to black & white)

n : int, optional

Connectivity. Must be 4 or 8 (default: 4)

Returns :

perim : ndarray

A boolean image

See also

borders
function This is a more generic function
mahotas.center_of_mass(img, labels=None) x0, x1, ... = center_of_mass(img, labels=None)

Returns the center of mass of img.

If labels is given, then it returns L centers of mass, one for each region identified by labels (including region 0).

Parameters :

img : ndarray

labels : ndarray

A labeled array

Returns :

coords : ndarray

if not labels, a 1-ndarray of coordinates (size = len(img.shape)), if labels, a 2-ndarray of coordinates (shape = (labels.max()+1) xlen(img.shape))

mahotas.close_holes(ref, Bc=None)

closed = close_holes(ref, Bc=None):

Close Holes

Parameters :

ref : ndarray

Reference image. This should be a binary image.

Bc : structuring element, optional

Default: 3x3 cross

Returns :

closed : ndarray

superset of ref (i.e. with closed holes)

mahotas.convolve(f, weights, mode='reflect', cval=0.0, output={new array})

Convolution of f and weights

Convolution is performed in doubles to avoid over/underflow, but the result is then cast to f.dtype.

Parameters :

f : ndarray

input. Any dimension is supported

weights : ndarray

weight filter. If not of the same dtype as f, it is cast

mode : {‘reflect’ [default], ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’}

How to handle borders

cval : double, optional

If mode is constant, which constant to use (default: 0.0)

output : ndarray, optional

Output array. Must have same shape and dtype as f as well as be C-contiguous.

Returns :

convolved : ndarray of same dtype as f

mahotas.convolve1d(f, weights, axis, mode='reflect', cval=0.0, output={new array})

Convolution of f and weights along axis axis.

Convolution is performed in doubles to avoid over/underflow, but the result is then cast to f.dtype.

Parameters :

f : ndarray

input. Any dimension is supported

weights : 1-D ndarray

weight filter. If not of the same dtype as f, it is cast

axis : int

Axis along which to convolve

mode : {‘reflect’ [default], ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’}

How to handle borders

cval : double, optional

If mode is constant, which constant to use (default: 0.0)

output : ndarray, optional

Output array. Must have same shape and dtype as f as well as be C-contiguous.

Returns :

convolved : ndarray of same dtype as f

See also

convolve
function generic convolution
mahotas.croptobbox(img, border=0)

Returns a version of img cropped to the image’s bounding box

Parameters :

img : ndarray

Integer image array

border : int, optional

whether to add a border (default no border)

Returns :

nimg : ndarray

A subimage of img.

mahotas.cwatershed(surface, markers, Bc=None, return_lines=False) W, WL = cwatershed(surface, markers, Bc=None, return_lines=True)

Seeded Watershed

Parameters :

surface : image

markers : image

initial markers (must be a labeled image)

Bc : ndarray, optional

structuring element (default: 3x3 cross)

return_lines : boolean, optional

whether to return separating lines (in addition to regions)

Returns :

W : Regions image (i.e., W[i,j] == region for pixel (i,j))

WL : Lines image (if return_lines==True)

mahotas.dilate(A, Bc={3x3 cross}, output={np.empty_like(A)})

Morphological dilation.

The type of operation depends on the dtype of A! If boolean, then the dilation is binary, else it is greyscale dilation. In the case of greyscale dilation, the smallest value in the domain of Bc is interpreted as +Inf.

Parameters :

A : ndarray of bools

input array

Bc : ndarray, optional

Structuring element. By default, use a cross (see get_structuring_elem for details on the default).

Returns :

dilated : ndarray

dilated version of A

See also

erode

mahotas.distance(bw, metric='euclidean2')

Computes the distance transform of image bw:

dmap[i,j] = min_{i', j'} { (i-i')**2 + (j-j')**2 | bw[i', j'] }
Parameters :

bw : 2d-ndarray

Black & White image

metric : str, optional

one of ‘euclidean2’ (default) or ‘euclidean’

Returns :

dmap : ndarray

distance map

mahotas.erode(A, Bc={3x3 cross}, output={np.empty_as(A)})

Morphological erosion.

The type of operation depends on the dtype of A! If boolean, then the erosion is binary, else it is greyscale erosion. In the case of greyscale erosion, the smallest value in the domain of Bc is interpreted as -Inf.

Parameters :

A : ndarray of bools

input array

Bc : ndarray, optional

Structuring element. By default, use a cross (see get_structuring_elem for details on the default).

Returns :

erosion : ndarray

eroded version of A

See also

dilate

mahotas.euler(f, n=8)

Compute the Euler number of image f

The Euler number is also known as the Euler characteristic given that many other mathematical objects are also known as Euler numbers.

Parameters :

f : ndarray

A 2-D binary image

n : int, optional

Connectivity, one of (4,8). default: 8

Returns :

euler_nr : int

Euler number

mahotas.fullhistogram(img)

Return a histogram with bins 0, 1, ..., ``img.max()``.

After calling this function, it will be true that hist[i] == (img == i).sum(), for all i.

Parameters :

img : array-like of an unsigned type

input image.

Returns :

hist : an dnarray of type np.uint32

This will be of size img.max() + 1.

mahotas.gaussian_filter(array, sigma, order=0, mode='reflect', cval=0., output={np.empty_like(array)})

Multi-dimensional Gaussian filter.

Parameters :

array : ndarray

input. Any dimension is supported

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

mode : {‘reflect’ [default], ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’}

How to handle borders

cval : double, optional

If mode is constant, which constant to use (default: 0.0)

output : ndarray, optional

Output array. Must have same shape and dtype as array as well as be C-contiguous.

Returns :

filtered : ndarray

Filtered version of array

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.

mahotas.gaussian_filter1d(array, sigma, axis=-1, order=0, mode='reflect', cval=0., output={np.empty_like(array)})

One-dimensional Gaussian filter.

Parameters :

array : ndarray

input array

sigma : float

standard deviation for Gaussian kernel (in pixel units)

axis : int, optional

axis to operate on

order : {0, 1, 2, 3}, optional

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

mode : {‘reflect’ [default], ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’}

How to handle borders

cval : double, optional

If mode is constant, which constant to use (default: 0.0)

output : ndarray, optional

Output array. Must have same shape and dtype as array as well as be C-contiguous.

Returns :

filtered : ndarray

Filtered version of array

mahotas.get_structuring_elem(A, Bc)

Retrieve appropriate structuring element

Parameters :

A : ndarray

array which will be operated on

Bc : None, int, or array-like

None:

Then Bc is taken to be 1

An integer:
There are two associated semantics:
connectivity

Bc[y,x] = [[ is |y - 1| + |x - 1| <= Bc_i ]]

count

Bc.sum() == Bc_i This is the more traditional meaning (when one writes that “4-connected”, this is what one has in mind).

Fortunately, the value itself allows one to distinguish between the two semantics and, if used correctly, no ambiguity should ever occur.

An array:

This should be of the same nr. of dimensions as A and will be passed through if of the right type. Otherwise, it will be cast.

Returns :

Bc_out : ndarray

Structuring element. This array will be of the same type as A, C-contiguous.

mahotas.hitmiss(input, Bc, output=np.zeros_like(input))

Hit & Miss transform

For a given pixel position, the hit&miss is True if, when Bc is overlaid on input, centered at that position, the 1 values line up with ``1``s, while the ``0``s line up with ``0``s (``2``s correspond to don’t care).

Parameters :

input : input ndarray

This is interpreted as a binary array.

Bc : ndarray

hit & miss template, values must be one of (0, 1, 2)

output : output array

Returns :

output : ndarray

mahotas.imresize(img, nsize, order=3)

img’ = imresize(img, nsize)

Resizes img

Parameters :

img : ndarray

nsize : float or tuple(float) or tuple(integers)

Size of return. Meaning depends on the type

float: img’.shape[i] = nsize * img.shape[i] tuple of float: img’.shape[i] = nsize[i] * img.shape[i] tuple of int: img’.shape[i] = nsize[i]

order : integer, optional

Spline order to use (default: 3)

Returns :

img’ : ndarray

See also

scipy.ndimage.zoom
Similar function
scipy.misc.pilutil.imresize
Similar function
mahotas.label(array, Bc={3x3 cross}, output=None)

Label the array

Parameters :

array : ndarray

This will be interpreted as an integer array

Bc : ndarray, optional

This is the structuring element to use

output : ndarray, optional

Output array. Must be a C-array, of type np.int32

Returns :

labeled : ndarray

Labeled result

nr_objects : int

Number of objects

mahotas.labeled_sum(array, labeled)

Labeled sum. sum will be an array of size labeled.max() + 1, where sum[i] is equal to np.sum(array[labeled == i]).

Parameters :

array : ndarray of any type

labeled : int ndarray

Label map. This is the same type as returned from mahotas.label()

Returns :

sums : 1-d ndarray of array.dtype

mahotas.majority_filter(img, N=3, output={np.empty(img.shape, np.bool)})

Majority filter

filtered[y,x] is positive if the majority of pixels in the squared of size N centred on (y,x) are positive.

Parameters :

img : ndarray

input img (currently only 2-D images accepted)

N : int, optional

size of filter (must be odd integer), defaults to 3.

output : ndarray, optional

Used for output. Must be Boolean ndarray of same size as img

Returns :

filtered : ndarray

boolean image of same size as img.

mahotas.median_filter(f, Bc={square}, mode='reflect', cval=0.0, output=None)

Median filter

Parameters :

f : ndarray

input. Any dimension is supported

Bc : ndarray or int, optional

Defines the neighbourhood, default is a square of side 3.

mode : {‘reflect’ [default], ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’}

How to handle borders

cval : double, optional

If mode is constant, which constant to use (default: 0.0)

output : ndarray, optional

Output array. Must have same shape and dtype as f as well as be C-contiguous.

Returns :

median : ndarray of same type and shape as f

median[i,j] is the median value of the points in f close to (i,j)

mahotas.moments(img, p0, p1, cm=(0, 0), convert_to_float=True)

Returns the p0-p1 moment of image img

The formula computed is

sum_{ij} { img[i,j] (i - c0)**p0 (j - c1)**p1 }

where cm = (c0,c1). If cm is not given, then (0,0) is used.

If image is of an integer type, then it is internally converted to np.float64, unlesss convert_to_float is False. The reason is that, otherwise, overflow is likely except for small images. Since this conversion takes longer than the computation, you can turn it off in case you are sure that your images are small enough for overflow to be an issue. Note that no conversion is made if img is of any floating point type.

Parameters :

img : 2-ndarray

An 2-d ndarray

p0 : float

Power for first dimension

p1 : float

Power for second dimension

cm : (int,int), optional

center of mass (default: 0,0)

convert_to_float : boolean, optional

whether to convert to floating point (default: True)

Returns :

moment: float :

floating point number

mahotas.otsu(img, ignore_zeros=False)

Calculate a threshold according to the Otsu method.

Parameters :

img : an image as a numpy array.

This should be of an unsigned integer type.

ignore_zeros : Boolean

whether to ignore zero-valued pixels (default: False)

Returns :

T : integer

the threshold

mahotas.rank_filter(f, Bc, rank, mode='reflect', cval=0.0, output=None)

Rank filter. The value at ranked[i,j] will be the rank``th largest in the neighbourhood defined by ``Bc.

Parameters :

f : ndarray

input. Any dimension is supported

Bc : ndarray

Defines the neighbourhood. Must be explicitly passed, no default.

rank : integer

mode : {‘reflect’ [default], ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’}

How to handle borders

cval : double, optional

If mode is constant, which constant to use (default: 0.0)

output : ndarray, optional

Output array. Must have same shape and dtype as f as well as be C-contiguous.

Returns :

ranked : ndarray of same type and shape as f

ranked[i,j] is the ``rank``th value of the points in f close to (i,j)

See also

median_filter
A special case of rank_filter
mahotas.rc(img, ignore_zeros=False)

Calculate a threshold according to the Riddler-Calvard method.

Parameters :

img : ndarray

Image of any type

ignore_zeros : boolean, optional

Whether to ignore zero valued pixels (default: False)

Returns :

T : float

threshold

mahotas.sobel(img, just_filter=Filter)

Compute edges using Sobel’s algorithm

edges is a binary image of edges computed according to Sobel’s algorithm.

This implementation is tuned to match MATLAB’s implementation.

Parameters :

img : Any 2D-ndarray

just_filter : boolean, optional

If true, then return the result of filtering the image with the sobel filters, but do not threashold.

Returns :

edges : ndarray

Binary image of edges, unless just_filter, in which case it will be an array of floating point values.

mahotas.stretch(img, arg0=None, arg1=None, dtype=<type 'numpy.uint8'>)

img’ = stretch(img, [dtype=np.uint8]) img’ = stretch(img, max, [dtype=np.uint8]) img’ = stretch(img, min, max, [dtype=np.uint8])

Contrast stretch the image to the range [0, max] (first form) or
[min, max] (second form).
Parameters :

img : ndarray

input image. It is not modified by this function

min : integer, optional

minimum value for output [default: 0]

max : integer, optional

maximum value for output [default: 255]

dtype : dtype of output,optional

[default: np.uint8]

Returns :

img’: ndarray :

resulting image. ndarray of same shape as img and type dtype.

mahotas.template_match(f, template, mode='reflect', cval=0., output={np.empty_like(f)})

Match template.

The value at match[i,j] will be the difference (in squared euclidean terms), between template and a same sized window on f centered on that point.

Parameters :

f : ndarray

input. Any dimension is supported

template : ndarray

Template to match. Must be explicitly passed, no default.

mode : {‘reflect’ [default], ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’}

How to handle borders

cval : double, optional

If mode is constant, which constant to use (default: 0.0)

output : ndarray, optional

Output array. Must have same shape and dtype as f as well as be C-contiguous.

Returns :

match : ndarray of same type and shape as f

match[i,j] is the squared euclidean distance between f[i-s0:i+s0,j-s1:j+s1] and template (for appropriately defined s0 and s1).

mahotas.thin(binimg)

Skeletonisation by thinning

Parameters :binimg : Binary input image
Returns :skel : Skeletonised version of binimg
mahotas.imread(filename, as_grey=False, formatstr={filename extension})

Read an image into a ndarray.

Parameters :

filename : str

filename

as_grey : boolean, optional

Whether to convert to grey scale image (default: no)

formatstr : str, optional

Format name. This is typically the same as the extension of the file and inferred from there. However, if you have a file whose extension does not correspond to the format, you can pass it explicitly.

Returns :

im : ndarray

The type of this array will depend on the contents of the file and of as_grey. Conversion from colour to grayscale will return a floating point image.

mahotas.imsave(filename, array, formatstr={auto-detect})

Writes array into file filename

Parameters :

filename : str

path on file system

array : ndarray-like

formatstr: str, optional :

format string

mahotas.features.haralick(f, ignore_zeros=False, preserve_haralick_bug=False, compute_14th_feature=False)

Compute Haralick texture features

Computes the Haralick texture features for the four 2-D directions or thirteen 3-D directions (depending on the dimensions of f).

Parameters :

f : ndarray of integer type

input image. 2-D and 3-D images are supported.

ignore_zeros : bool, optional

Whether to ignore zero pixels (default: False).

preserve_haralick_bug : bool, optional

whether to replicate Haralick’s typo (default: False). You probably want to always set this to False unless you want to replicate someone else’s wrong implementation.

compute_14th_feature : bool, optional

whether to compute & return the 14-th feature

Returns :

feats : ndarray of np.double

A 4x13 or 4x14 feature vector (one row per direction) if f is 2D, 13x13 or 13x14 if it is 3D. The exact number of features depends on the value of compute_14th_feature

Notes

Haralick’s paper has a typo in one of the equations. This function implements the correct feature unless preserve_haralick_bug is True. The only reason why you’d want the buggy behaviour is if you want to match another implementation.

mahotas.features.lbp(image, radius, points, ignore_zeros=False)

Compute Linear Binary Patterns

Parameters :

image : ndarray

input image (2-D numpy ndarray)

radius : number (integer or floating point)

radius (in pixels)

points : integer

nr of points to consider

ignore_zeros : boolean, optional

whether to ignore zeros (default: False)

Returns :

features : 1-D numpy ndarray

histogram of features

mahotas.features.pftas(img, T={mahotas.threshold.otsu(img)})

Compute parameter free Threshold Adjacency Statistics

TAS were presented by Hamilton et al. in “Fast automated cell phenotype image classification” (http://www.biomedcentral.com/1471-2105/8/110)

The current version is an adapted version which is free of parameters. The thresholding is done by using Otsu’s algorithm (or can be pre-computed and passed in by setting T), the margin around the mean of pixels to be included is the standard deviation.

Also returns a version computed on the negative of the binarisation defined by Hamilton et al.

Use tas() to get the original version of the features.

Parameters :

img : ndarray, 2D or 3D

input image

T : integer, optional

Threshold to use (default: compute with otsu)

Returns :

values : ndarray

A 1-D ndarray of feature values

mahotas.features.tas(img)

Compute Threshold Adjacency Statistics

TAS were presented by Hamilton et al. in “Fast automated cell phenotype image classification” (http://www.biomedcentral.com/1471-2105/8/110)

Also returns a version computed on the negative of the binarisation defined by Hamilton et al.

See also pftas() for a variation without any hardcoded parameters.

Parameters :

img : ndarray, 2D or 3D

input image

Returns :

values : ndarray

A 1-D ndarray of feature values

See also

pftas
Parameter free TAS
mahotas.features.zernike(im, degree, radius, cm={center_of_mass(im)})
mahotas.features.zernike_moments(im, radius, degree=8, cm={center_of_mass(im)})

Zernike moments through degree

Returns a vector of absolute Zernike moments through degree for the image im.

Parameters :

im : 2-ndarray

input image

radius : integer

the maximum radius for the Zernike polynomials, in pixels

degree : integer, optional

Maximum degree to use (default: 8)

cm : pair of floats, optional

the centre of mass to use. By default, uses the image’s centre of mass.

Returns :

zvalues : 1-ndarray of floats

Zernike moments

Previous topic

Principles of Mahotas

This Page