Full API Documentation¶
A package for computer vision in Python.
Main Features¶
 features
 Compute global and local features (several submodules, include SURF and Haralick features)
 convolve
 Convolution and wavelets
 morph
 Morphological features. Most are available at the mahotas level, include erode(), dilate()...
 watershed
 Seeded watershed implementation
 imread/imsave
 read/write image
Documentation: https://mahotas.readthedocs.io/
Citation:
Coelho, Luis Pedro, 2013. Mahotas: Open source software for scriptable computer vision. Journal of Open Research Software, 1:e3, DOI: http://dx.doi.org/10.5334/jors.ac

mahotas.
as_rgb
(r, g, b)¶ Returns an RGB image with
r
in the red channel,g
in the green, andb
in the blue. The channels are contrast stretched.If any of the channels is None, that channel is set to zero. The same can be achieved by passing
0
as that channels value. In fact, passing a number as a channel value will set the whole channel to that value.Parameters: r,g,b : arraylike or int, 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
Examples
This shows a nice looking picture:
z1 = np.linspace(0, np.pi) X,Y = np.meshgrid(z1, z1) red = np.sin(X) green = np.cos(4*Y) blue = X*Y plt.imshow(mahotas.as_rgb(red, green, blue))
Notice that the scaling on the
blue
channel is so different from the other channels (from 0..2500 compared with 0..1), butas_rgb
stretches each channel independently.

mahotas.
bbox
(img, border={0}, as_slice={False})¶ 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 nonzero pixels. Returned whenas_slice
is false (the default)s : slice
A slice representation of the bounding box. Returned when
as_slice
is true

mahotas.
border
(labeled, i, j, Bc={3x3 cross}, out={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
out : ndarray of same shape as labeled, dtype=bool, optional
where to store the output. If
None
, a new array is allocatedalways_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}, out={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
out : ndarray of same shape as labeled, dtype=bool, optional
where to store the output. If
None
, a new array is allocatedmode : {‘reflect’, ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’ [default], ‘ignore’}
How to handle borders
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 zerovalued 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 blackandwhite image (any other image will be converted to black & white)
n : int, optional
Connectivity. Must be 4 or 8 (default: 4)
mode : {‘reflect’, ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’ [default], ‘ignore’}
How to handle borders
Returns: perim : ndarray
A boolean image
See also
borders
 function This is a more generic function

mahotas.
cdilate
(f, g, Bc={3x3 cross}, n=1)¶ Conditional dilation
cdilate creates the image y by dilating the image f by the structuring element Bc conditionally to the image g. This operator may be applied recursively n times.
Parameters: f : Grayscale (uint8 or uint16) or binary image.
g : Conditioning image. (Grayscale or binary).
Bc : Structuring element (default: 3x3 cross)
n : Number of iterations (default: 1)
Returns: y : Image

mahotas.
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, optional
A labeled array (i.e., an array of integers of the same shape as
img
such that each “object” is identified by areas with different values).Returns: coords : ndarray
The exact shape of the output depends on whether the
labels
argument was used. Iflabels is None
, then the return value is a 1ndarray of coordinates (size = len(img.shape)
); otherwise, the return value is a 2ndarray of coordinates (shape = (labels.max()+1, len(img.shape)
).

mahotas.
cerode
(f, g, Bc={3x3 cross}, out={np.empty_as(A)})¶ Conditional morphological erosion.
The type of operation depends on the
dtype
ofA
! If boolean, then the erosion is binary, else it is greyscale erosion. In the case of greyscale erosion, the smallest value in the domain ofBc
is interpreted as Inf.Parameters: f : ndarray
input image
g : ndarray
conditional image
Bc : ndarray, optional
Structuring element. By default, use a cross (see
get_structuring_elem
for details on the default).Returns: conditionally_eroded : ndarray
eroded version of
f
conditioned ong

mahotas.
close
(f, Bc={3x3 cross}, out={np.empty_like(f)})¶ Morphological closing.
close creates the image y by the morphological closing of the image f by the structuring element Bc. In the binary case, the closing by a structuring element Bc may be interpreted as the intersection of all the binary images that contain the image f and have a hole equal to a translation of Bc. In the grayscale case, there is a similar interpretation taking the functions umbra.
Parameters: f : ndarray
Grayscale (uint8 or uint16) or binary image.
Bc : ndarray, optional
Structuring element. (Default: 3x3 elementary cross).
out : ndarray, optional
Output array
output : deprecated
Do not use
Returns: y : ndarray
See also
open
 function

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, out={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. This conversion may result in over/underflow when using small integer types or unsigned types (if the output is negative). Converting to a floating point representation avoids this issue:
c = convolve(f.astype(float), kernel)
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’, ‘ignore’}
How to handle borders
cval : double, optional
If mode is constant, which constant to use (default: 0.0)
out : ndarray, optional
Output array. Must have same shape and dtype as f as well as be Ccontiguous.
Returns: convolved : ndarray of same dtype as f

mahotas.
convolve1d
(f, weights, axis, mode='reflect', cval=0.0, out={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 : 1D 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’, ‘ignore’}
How to handle borders
cval : double, optional
If mode is constant, which constant to use (default: 0.0)
out : ndarray, optional
Output array. Must have same shape and dtype as f as well as be Ccontiguous.
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.
Notes
Note that the border is on the bounding box, not on the final image! This means that if the image has a positive pixel on its margin, it will still be on the margin.
This ensures that the result is always a subimage of the input.

mahotas.
cwatershed
(surface, markers, Bc=None, return_lines=False) W, WL = cwatershed(surface, markers, Bc=None, return_lines=True)¶ Seeded watershed in ndimensions
This function computes the watershed transform on the input surface (which may actually be an ndimensional volume).
This function requires initial seed points. A traditional way of initializing watershed is to use regional minima:
minima = mh.regmin(f) markers,nr_markers = mh.label(minima) W = cwatershed(f, minima)
Parameters: surface : image
markers : image
initial markers (must be a labeled image, i.e., one where 0 represents the background and higher integers represent different regions)
Bc : ndarray, optional
structuring element (default: 3x3 cross)
return_lines : boolean, optional
whether to return separating lines (in addition to regions)
Returns: W : integer ndarray (int64 ints)
Regions image (i.e., W[i,j] == region for pixel (i,j))
WL : Lines image (if return_lines==True)

mahotas.
daubechies
(f, code, inline=False)¶ Daubechies wavelet transform
This function works best if the image sizes are powers of 2!
Parameters: f : ndarray
2D image
code : str
One of ‘D2’, ‘D4’, ... ‘D20’
inline : bool, optional
Whether to write the results to the input image. By default, a new image is returned. Integer images are always converted to floating point and copied.
See also
haar
 function Haar transform (equivalent to D2)

mahotas.
dilate
(A, Bc=None, out=None, output=None)¶ Morphological dilation.
The type of operation depends on the
dtype
ofA
! If boolean, then the dilation is binary, else it is greyscale dilation. In the case of greyscale dilation, the smallest value in the domain ofBc
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).out : ndarray, optional
output array. If used, this must be a Carray of the same
dtype
asA
. Otherwise, a new array is allocated.output : deprecated
Do not use
Returns: dilated : ndarray
dilated version of
A
See also

mahotas.
disk
(radius, dim=2)¶ Return a binary disk structuring element of radius
radius
and dimensiondim
Parameters: radius : int
Radius (in pixels) of returned disk
dim : int, optional
Dimension of returned array (default: 2)
Returns: D : boolean ndarray

mahotas.
distance
(bw, metric='euclidean2')¶ Computes the distance transform of image bw:
dmap[i,j] = min_{i', j'} { (ii')**2 + (jj')**2  !bw[i', j'] }
That is, at each point, compute the distance to the background.
If there is no background, then a very high value will be returned in all pixels (this is a sort of infinity).
Parameters: bw : ndarray
If boolean,
False
will denote the background andTrue
the foreground. If not boolean, this will be interpreted asbw != 0
(this way you can use labeled images without any problems).metric : str, optional
one of ‘euclidean2’ (default) or ‘euclidean’
Returns: dmap : ndarray
distance map
References
For 2D images, the following algorithm is used:
Felzenszwalb P, Huttenlocher D. Distance transforms of sampled functions. Cornell Computing and Information. 2004.
Available at: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.1647&rep=rep1&type=pdf.
For nD images (with n > 2), a slower handcraft method is used.

mahotas.
dog
(img, sigma1 = 2, thresh= None, just_filter = False)¶ Compute edges using the Difference of Gaussian (DoG) operator.
edges is a binary image of edges.
Parameters: img : Any 2Dndarray
sigma1 : the sigma value of the first Gaussian filter. The second filter
will have sigma value 1.001*sigma1
multiplier : the multiplier to get sigma2. sigma2 = sigma1 * multiplier
just_filter : boolean, optional
If true, then return the result of filtering the image with the DoG filters, no zerocrossing is detected (default is False).
Returns: edges : ndarray
Binary image of edges, unless just_filter, in which case it will be an array of floating point values.

mahotas.
erode
(A, Bc={3x3 cross}, out={np.empty_as(A)})¶ Morphological erosion.
The type of operation depends on the
dtype
ofA
! If boolean, then the erosion is binary, else it is greyscale erosion. In the case of greyscale erosion, the smallest value in the domain ofBc
is interpreted as Inf.Parameters: A : ndarray
input image
Bc : ndarray, optional
Structuring element. By default, use a cross (see
get_structuring_elem
for details on the default).out : ndarray, optional
output array. If used, this must be a Carray of the same
dtype
asA
. Otherwise, a new array is allocated.Returns: erosion : ndarray
eroded version of
A
See also

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 2D binary image
n : int, optional
Connectivity, one of (4,8). default: 8
mode : {‘reflect’, ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’ [default]}
How to handle borders
Returns: euler_nr : int
Euler number
References
The following algorithm is used:
A Fast Algorithm for Computing the Euler Number of an Image and its VLSI Implementation, doi: 10.1109/ICVD.2000.812628

mahotas.
find
(f, template)¶ Match template to image exactly
coordinates = find(f, template)
The output is in the same format as the
np.where
function.Parameters: f : ndarray
input. Currently, only 2dimensional images are supported.
template : ndarray
Template to match. Must be explicitly passed, no default.
Returns: match : np.array
coordinates : np.array
These are the coordinates of the match. The format is similar to the output of
np.where
, but in an ndarray.

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 alli
.Parameters: img : arraylike of an unsigned type
input image.
Returns: hist : an dnarray of type np.uint32
This will be of size
img.max() + 1
.Notes
Only handles unsigned integer arrays.

mahotas.
gaussian_filter
(array, sigma, order=0, mode='reflect', cval=0., out={np.empty_like(array)})¶ Multidimensional Gaussian filter.
Parameters: array : ndarray
input array, any dimension is supported. If the array is an integer array, it will be converted to a double array.
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’, ‘ignore’}
How to handle borders
cval : double, optional
If mode is constant, which constant to use (default: 0.0)
out : ndarray, optional
Output array. Must have same shape as array as well as be Ccontiguous. If array is an integer array, this must be a double array; otherwise, it must have the same type as array.
Returns: filtered : ndarray
Filtered version of array
Notes
The multidimensional filter is implemented as a sequence of onedimensional 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., out={np.empty_like(array)})¶ Onedimensional Gaussian filter.
Parameters: array : ndarray
input array of a floatingpoint type
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’, ‘ignore’}
How to handle borders
cval : double, optional
If mode is constant, which constant to use (default: 0.0)
out : ndarray, optional
Output array. Must have same shape and dtype as array as well as be Ccontiguous.
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 arraylike
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 “4connected”, 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, Ccontiguous.

mahotas.
haar
(f, preserve_energy=True, inline=False)¶ Haar transform
Parameters: f : 2D ndarray
Input image
preserve_energy : bool, optional
Whether to normalise the result so that energy is preserved (the default).
inline : bool, optional
Whether to write the results to the input image. By default, a new image is returned. Integer images are always converted to floating point and copied.
See also
ihaar
 function Reverse Haar transform

mahotas.
hitmiss
(input, Bc, out=np.zeros_like(input))¶ Hit & Miss transform
For a given pixel position, the hit&miss is
True
if, whenBc
is overlaid oninput
, centered at that position, the1
values line up with1
s, while the0
s line up with0
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)
out : ndarray, optional
Used for output. Must be Boolean ndarray of same size as
input
output : deprecated
Do not use
Returns: filtered : ndarray
Examples
print(hitmiss(np.array([ [0,0,0,0,0], [0,1,1,1,1], [0,0,1,1,1]]), np.array([ [0,0,0], [2,1,1], [2,1,1]]))) prints:: [[0 0 0 0 0] [0 0 1 1 0] [0 0 0 0 0]]

mahotas.
idaubechies
(f, code, inline=False)¶ Daubechies wavelet inverse transform
Parameters: f : ndarray
2D image
code : str
One of ‘D2’, ‘D4’, ... ‘D20’
inline : bool, optional
Whether to write the results to the input image. By default, a new image is returned. Integer images are always converted to floating point and copied.
See also
haar
 function Haar transform (equivalent to D2)

mahotas.
ihaar
(f, preserve_energy=True, inline=False)¶ Reverse Haar transform
ihaar(haar(f))
is more or less equal tof
(equal, except for possible rounding issues).Parameters: f : 2D ndarray
Input image. If it is an integer image, it is converted to floating point (double).
preserve_energy : bool, optional
Whether to normalise the result so that energy is preserved (the default).
inline : bool, optional
Whether to write the results to the input image. By default, a new image is returned. Integer images are always converted to floating point and copied.
Returns: f : ndarray
See also
haar
 function Forward Haar transform

mahotas.
imread
(filename, as_grey=False)¶ Read an image into a ndarray from a file.
This function depends on PIL (or Pillow) being installed.
Parameters: filename : str
filename
as_grey : boolean, optional
Whether to convert to grey scale image (default: no)

mahotas.
imresize
(img, nsize, order=3)¶ Resizes image
This function works in two ways: if
nsize
is a tuple or list of integers, then the result will be of this size; otherwise, this function behaves the same asmh.interpolate.zoom
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
zoom
 Similar function
scipy.misc.pilutil.imresize
 Similar function

mahotas.
imsave
(filename, array)¶ Writes array into file filename
This function depends on PIL (or Pillow) being installed.
Parameters: filename : str
path on file system
array : ndarraylike

mahotas.
label
(array, Bc={3x3 cross}, output={new array})¶ Label the array, which is interpreted as a binary array
This is also called connected component labeled, where the connectivity is defined by the structuring element
Bc
.See: http://en.wikipedia.org/wiki/Connectedcomponent_labeling
Parameters: array : ndarray
This will be interpreted as binary array
Bc : ndarray, optional
This is the structuring element to use
out : ndarray, optional
Output array. Must be a Carray, of type np.int32
Returns: labeled : ndarray
Labeled result
nr_objects : int
Number of objects

mahotas.
labeled_sum
(array, labeled, minlength=None)¶ Labeled sum. sum will be an array of size
labeled.max() + 1
, wheresum[i]
is equal tonp.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()
minlength : int, optional
Minimum size of return array. If labeled has fewer than
minlength
regions, 0s are added to the result. (optional)Returns: sums : 1d ndarray of
array.dtype

mahotas.
laplacian_2D
(array, alpha = 0.2)¶ 2D Laplacian filter.
Parameters: array : ndarray
input 2D array. If the array is an integer array, it will be converted to a double array.
alpha : scalar or sequence of scalars
controls the shape of Laplacian operator. Must be 01. A larger values makes the operator empahsize the diagonal direction.
Returns: filtered : ndarray
Filtered version of array

mahotas.
locmax
(f, Bc={3x3 cross}, out={np.empty(f.shape, bool)})¶ Local maxima
Parameters: f : ndarray
Bc : ndarray, optional
structuring element
out : ndarray, optional
Used for output. Must be Boolean ndarray of same size as f
output : deprecated
Do not use
Returns: filtered : ndarray
boolean image of same size as f.
See also
regmax
 function Regional maxima. This is a stricter criterion than the local maxima as it takes the whole object into account and not just the neighbourhood defined by
Bc
:: 0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 0 3 0 0 0 0 3 0 0 0 0 0 0 0 The top 2 is a local maximum because it has the maximal value in its neighbourhood, but it is not a regional maximum. locmin
 function Local minima

mahotas.
locmin
(f, Bc={3x3 cross}, out={np.empty(f.shape, bool)})¶ Local minima
Parameters: f : ndarray
Bc : ndarray, optional
structuring element
out : ndarray, optional
Used for output. Must be Boolean ndarray of same size as f
output : deprecated
Do not use
Returns: filtered : ndarray
boolean image of same size as f.
See also
locmax
 function Regional maxima

mahotas.
majority_filter
(img, N=3, out={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 2D images accepted)
N : int, optional
size of filter (must be odd integer), defaults to 3.
out : ndarray, optional
Used for output. Must be Boolean ndarray of same size as img
output : deprecated
Do not use
Returns: filtered : ndarray
boolean image of same size as img.

mahotas.
mean_filter
(f, Bc, mode='ignore', cval=0.0, out=None)¶ Mean filter. The value at
mean[i,j]
will be the mean of the values in the neighbourhood defined byBc
.Parameters: f : ndarray
input. Any dimension is supported
Bc : ndarray
Defines the neighbourhood. Must be explicitly passed, no default.
mode : {‘reflect’, ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’, ‘ignore’ [ignore]}
How to handle borders. The default is to ignore points beyond the border, so that the means computed near the border include fewer elements.
cval : double, optional
If mode is constant, which constant to use (default: 0.0)
out : ndarray, optional
Output array. Must be a double array with the same shape as f as well as be Ccontiguous.
Returns: mean : ndarray of type double and same shape as
f
See also
median_filter
 An alternative filtering method

mahotas.
median_filter
(f, Bc={square}, mode='reflect', cval=0.0, out={np.empty(f.shape, f.dtype})¶ 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’, ‘ignore’}
How to handle borders
cval : double, optional
If mode is constant, which constant to use (default: 0.0)
out : ndarray, optional
Output array. Must have same shape and dtype as f as well as be Ccontiguous.
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 p0p1 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 : 2ndarray
An 2d 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)
normalize : boolean, optional
whether to normalize to size of image (default: False)
Returns: moment: float
floating point number
Notes
It only works for 2D images

mahotas.
open
(f, Bc={3x3 cross}, out={np.empty_like(f)})¶ Morphological opening.
open creates the image y by the morphological opening of the image f by the structuring element Bc.
In the binary case, the opening by the structuring element Bc may be interpreted as the union of translations of b included in f. In the grayscale case, there is a similar interpretation taking the functions umbra.
Parameters: f : ndarray
Grayscale (uint8 or uint16) or binary image.
Bc : ndarray, optional
Structuring element (default: 3x3 elementary cross).
out : ndarray, optional
Output array
output : deprecated
Do not use
Returns: y : ndarray
See also
open
 function

mahotas.
otsu
(img, ignore_zeros=False)¶ Calculate a threshold according to the Otsu method.
Example:
import mahotas as mh import mahotas.demos im = mahotas.demos.nuclear_image() # im is stored as RGB, let's convert to single 2D format: im = im.max(2) #Now, we compute Otsu: t = mh.otsu(im) # finally, we use the value to form a binary image: bin = (im > t)
See Wikipedia for details on methods: http://en.wikipedia.org/wiki/Otsu’s_method
Parameters: img : an image as a numpy array.
This should be of an unsigned integer type.
ignore_zeros : Boolean
whether to ignore zerovalued pixels (default: False)
Returns: T : integer
the threshold

mahotas.
overlay
(gray, red=None, green=None, blue=None, if_gray_dtype_not_uint8='stretch')¶ Create an image which is greyscale, but with possible boolean overlays.
Parameters: gray: ndarray of type np.uint8
Should be a greyscale image of type np.uint8
red,green,blue : ndarray, optional
boolean arrays
if_gray_dtype_not_uint8 : str, optional
 What to do if
gray
is not of typenp.uint8
, must be one of ‘stretch’ (default): the function
stretch
is called. ‘error’ : in this case, an error is raised
Returns: overlaid : ndarray
Colour image
 What to do if

mahotas.
rank_filter
(f, Bc, rank, mode='reflect', cval=0.0, out=None)¶ Rank filter. The value at
ranked[i,j]
will be therank
th largest in the neighbourhood defined byBc
.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’, ‘ignore’}
How to handle borders
cval : double, optional
If mode is constant, which constant to use (default: 0.0)
out : ndarray, optional
Output array. Must have same shape and dtype as f as well as be Ccontiguous.
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 RiddlerCalvard method.
Example:
import mahotas as mh import mahotas.demos im = mahotas.demos.nuclear_image() # im is stored as RGB, let's convert to single 2D format: im = im.max(2) #Now, we compute a threshold: t = mh.rc(im) # finally, we use the value to form a binary image: bin = (im > t)
Parameters: img : ndarray
Image of any type
ignore_zeros : boolean, optional
Whether to ignore zero valued pixels (default: False)
Returns: T : float
threshold

mahotas.
regmax
(f, Bc={3x3 cross}, out={np.empty(f.shape, bool)})¶ Regional maxima. This is a stricter criterion than the local maxima as it takes the whole object into account and not just the neighbourhood defined by
Bc
:0 0 0 0 0 0 0 2 0 0 0 0 2 0 0 0 0 3 0 0 0 0 3 0 0 0 0 0 0 0
The top 2 is a local maximum because it has the maximal value in its neighbourhood, but it is not a regional maximum.
Parameters: f : ndarray
Bc : ndarray, optional
structuring element
out : ndarray, optional
Used for output. Must be Boolean ndarray of same size as f
output : deprecated
Do not use
Returns: filtered : ndarray
boolean image of same size as f.
See also
locmax
 function Local maxima. The local maxima are a superset of the regional maxima

mahotas.
regmin
(f, Bc={3x3 cross}, out={np.empty(f.shape, bool)})¶ Regional minima. See the documentation for
regmax
for more details.Parameters: f : ndarray
Bc : ndarray, optional
structuring element
out : ndarray, optional
Used for output. Must be Boolean ndarray of same size as f
output : deprecated
Do not use
Returns: filtered : ndarray
boolean image of same size as f.
See also
locmin
 function Local minima

mahotas.
sobel
(img, just_filter=False)¶ 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 2Dndarray
just_filter : boolean, optional
If true, then return the result of filtering the image with the sobel filters, but do not threashold (default is False).
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). The method is simple linear stretching according to the formula:
p' = max * (p  img.min())/img.ptp() + min
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.
Notes
If max > 255, then it truncates the values if dtype is not specified.

mahotas.
stretch_rgb
(img, arg0=None, arg1=None, dtype=<type 'numpy.uint8'>)¶ Variation of stretch() function that works perchannel on an RGB image
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.
See also
stretch
 function

mahotas.
template_match
(f, template, mode='reflect', cval=0.0, out=None, output=None)¶ Match template to image
match = template_match(f, template, mode=’reflect’, cval=0., out={np.empty_like(f)})
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.Note that the computation is performed using the same dtype as
f
. Thus is may overflow if the template is large.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’, ‘ignore’}
How to handle borders
cval : double, optional
If mode is constant, which constant to use (default: 0.0)
out : ndarray, optional
Output array. Must have same shape and dtype as f as well as be Ccontiguous.
Returns: match : ndarray of same type and shape as
f
match[i,j] is the squared euclidean distance between
f[is0:i+s0,js1:j+s1]
andtemplate
(for appropriately defineds0
ands1
).

mahotas.
thin
(binimg)¶ Skeletonisation by thinning
Parameters: binimg : ndarray
Binary input image
max_iter : int, optional
Maximum number of iterations (set to a negative number, the default, to run full skeletonization)
Returns: skel : Skeletonised version of binimg

mahotas.
wavelet_center
(f, border=0, dtype=float, cval=0.0)¶ fc
is a centered version off
with a shape that is composed of powers of 2.Parameters: f : ndarray
input image
border : int, optional
The border to use (default is no border)
dtype : type, optional
Type of
fc
cval : float, optional
Which value to fill the border with (default is 0)
Returns: fc : ndarray
See also
wavelet_decenter
 function Reverse function

mahotas.
wavelet_decenter
(w, oshape, border=0)¶ Undoes the effect of
wavelet_center
Parameters: w : ndarray
Wavelet array
oshape : tuple
Desired shape
border : int, optional
The desired border. This must be the same value as was used for
wavelet_center
Returns: f : ndarray
This will have shape
oshape
See also
wavelet_center
 function Forward function

mahotas.features.
eccentricity
(bwimage)¶ Compute eccentricity
Parameters: bwimage : ndarray
Interpreted as a boolean image
Returns: r : float
Eccentricity measure

mahotas.features.
ellipse_axes
(bwimage)¶ Parameters of the ‘image ellipse’
semimajor,semiminor = ellipse_axes(bwimage)
Returns the parameters of the constant intensity ellipse with the same mass and second order moments as the original image.
Parameters: bwimage : ndarray
Interpreted as a boolean image
Returns: semimajor : float
semiminor : float
References
Prokop, RJ, and Reeves, AP. 1992. CVGIP: Graphical Models and Image Processing 54(5):438460

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 2D directions or thirteen 3D directions (depending on the dimensions of f).
ignore_zeros
can be used to have the function ignore any zerovalued pixels (as background). If there are nononzero neighbour pairs in all directions, an exception is raised. Note that this can happen even with some nonzero pixels, e.g.:0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0
would trigger an error when
ignore_zeros=True
as there are no horizontal nonzero pairs!Parameters: f : ndarray of integer type
input image. 2D and 3D images are supported.
distance: int, optional (default=1)
The distance to consider while computing the cooccurence matrix.
ignore_zeros : bool, optional
Whether to ignore zero pixels (default: False).
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
Also, if eitherreturn_mean
orreturn_mean_ptp
is set, then a single dimensional array is returned.Other Parameters: 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 14th feature
return_mean : bool, optional
When set, the function returns the mean across all the directions (default: False).
return_mean_ptp : bool, optional
When set, the function returns the mean and ptp (pointtopoint, i.e., difference between max() and min()) across all the directions (default: False).
use_x_minus_y_variance : bool, optional
Feature 10 (index 9) has two interpretations, as the variance of xy or as the variance of P(xy). In order to achieve compatibility with other software and previous versions of mahotas, mahotas defaults to using
VAR[P(\xy\)]
; if this argument is True, then it usesVAR[\xy\]
(default: False)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.
References
Cite the following reference for these features:
@article{Haralick1973, author = {Haralick, Robert M. and Dinstein, Its'hak and Shanmugam, K.}, journal = {Ieee Transactions On Systems Man And Cybernetics}, number = {6}, pages = {610621}, publisher = {IEEE}, title = {Textural features for image classification}, url = {http://ieeexplore.ieee.org/lpdocs/epic03/wrapper.htm?arnumber=4309314}, volume = {3}, year = {1973} }

mahotas.features.
lbp
(image, radius, points, ignore_zeros=False)¶ Compute Linear Binary Patterns
The return value is a histogram of feature counts, where position
i
corresponds to the number of pixels that had codei
. The codes are compressed so that impossible codes are not used. Therefore, this is thei``th feature, not just the feature with binary code ``i
.Parameters: image : ndarray
input image (2D 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 : 1D numpy ndarray
histogram of features. See above for a caveat on the interpretation of these.
References
 Gray Scale and Rotation Invariant Texture Classification with Local Binary Patterns
 Ojala, T. Pietikainen, M. Maenpaa, T. Lecture Notes in Computer Science (Springer) 2000, ISSU 1842, pages 404420

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/14712105/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 precomputed and passed in by setting T), the margin around the mean of pixels to be included is the standard deviation. This was first published by Coelho et al. in “Structured Literature Image Finder: Extracting Information from Text and Images in Biomedical Literature” (http://www.springerlink.com/content/60634778710577t0/)
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 1D ndarray of feature values

mahotas.features.
roundness
(bw)¶ Roundness
Parameters: bw : ndarray
Interpreted as a boolean image
Returns: r : float

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/14712105/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 1D 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
. These are computed on a circle of radiusradius
centered aroundcm
(or the center of mass of the image, if thecm
argument is not used).Returns a vector of absolute Zernike moments through
degree
for the imageim
.Parameters: im : 2ndarray
input image
radius : integer
the maximum radius for the Zernike polynomials, in pixels. Note that the area outside the circle (centered on center of mass) defined by this radius is ignored.
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 : 1ndarray of floats
Zernike moments
References
Teague, MR. (1980). Image Analysis via the General Theory of Moments. J. Opt. Soc. Am. 70(8):920930.

mahotas.colors.
rgb2gray
(rgb_image, dtype=np.float)¶ Convert an RGB image to a grayscale image
The interpretation of RGB and greyscale values is very much object dependent (as anyone who has used an overhead projector which mangled their colour figures will have experienced). This function uses a typical method for conversion and will work acceptably well for typical use cases, but if you have strict requirements, consider implementing the conversion by yourself for fine control.
Parameters: array : ndarray of shape (a,b,3)
dtype : dtype, optional
dtype of return
Returns: grey : ndarray of
dtype

mahotas.colors.
rgb2grey
(rgb_image, dtype=np.float)¶ Convert an RGB image to a grayscale image
The interpretation of RGB and greyscale values is very much object dependent (as anyone who has used an overhead projector which mangled their colour figures will have experienced). This function uses a typical method for conversion and will work acceptably well for typical use cases, but if you have strict requirements, consider implementing the conversion by yourself for fine control.
Parameters: array : ndarray of shape (a,b,3)
dtype : dtype, optional
dtype of return
Returns: grey : ndarray of
dtype

mahotas.colors.
rgb2lab
(rgb, dtype={float})¶ Convert sRGB to L*a*b* coordinates
http://en.wikipedia.org/wiki/CIELAB
Parameters: rgb : ndarray
Must be of shape (h,w,3)
dtype : dtype, optional
What dtype to return. Default will be floats
Returns: lab : ndarray

mahotas.colors.
rgb2sepia
(rgb)¶ Parameters: rgb : ndarray
Must be of shape (h,w,3)
Returns: sepia : ndarray
Output is of same shape as
rgb

mahotas.colors.
rgb2xyz
(rgb, dtype={float})¶ Convert RGB to XYZ coordinates
The input is interpreted as sRGB. See Wikipedia for more details:
http://en.wikipedia.org/wiki/SRGB
Parameters: rgb : ndarray
dtype : dtype, optional
What dtype to return
Returns: xyz : ndarray
See also
xyz2rgb
 function The reverse function

mahotas.colors.
xyz2lab
(xyz, dtype={float})¶ Convert CIE XYZ to L*a*b* coordinates
http://en.wikipedia.org/wiki/CIELAB
Parameters: xyz : ndarray
dtype : dtype, optional
What dtype to return. Default will be floats
Returns: lab : ndarray

mahotas.colors.
xyz2rgb
(xyz, dtype={float})¶ Convert XYZ to sRGB coordinates
The output should be interpreted as sRGB. See Wikipedia for more details:
http://en.wikipedia.org/wiki/SRGB
Parameters: xyz : ndarray
dtype : dtype, optional
What dtype to return. Default will be floats
Returns: rgb : ndarray
See also
rgb2xyz
 function The reverse function