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: https://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,barray-like 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:
- rgbndarray
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:
- imgndarray
Any integer image type
- Returns:
- min1,max1,min2,max2int,int,int,int
These are such that
img[min1:max1, min2:max2]
contains all non-zero pixels. Returned whenas_slice
is false (the default)- sslice
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:
- labeledndarray of integer type
input labeled array
- iinteger
- jinteger
- Bcstructure element, optional
- outndarray of same shape as labeled, dtype=bool, optional
where to store the output. If
None
, a new array is allocated- always_returnbool, 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_imgboolean 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:
- labeledndarray of integer type
input labeled array
- Bcstructure element, optional
- outndarray of same shape as labeled, dtype=bool, optional
where to store the output. If
None
, a new array is allocated- mode{‘reflect’, ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’ [default], ‘ignore’}
How to handle borders
- Returns:
- border_imgboolean 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:
- bwndarray
A black-and-white image (any other image will be converted to black & white)
- nint, optional
Connectivity. Must be 4 or 8 (default: 4)
- mode{‘reflect’, ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’ [default], ‘ignore’}
How to handle borders
- Returns:
- perimndarray
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:
- fGray-scale (uint8 or uint16) or binary image.
- gConditioning image. (Gray-scale or binary).
- BcStructuring element (default: 3x3 cross)
- nNumber of iterations (default: 1)
- Returns:
- yImage
- 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:
- imgndarray
- labelsndarray, 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:
- coordsndarray
The exact shape of the output depends on whether the
labels
argument was used. Iflabels is None
, then the return value is a 1-ndarray of coordinates (size = len(img.shape)
); otherwise, the return value is a 2-ndarray 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:
- fndarray
input image
- gndarray
conditional image
- Bcndarray, optional
Structuring element. By default, use a cross (see
get_structuring_elem
for details on the default).
- Returns:
- conditionally_erodedndarray
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 gray-scale case, there is a similar interpretation taking the functions umbra.
- Parameters:
- fndarray
Gray-scale (uint8 or uint16) or binary image.
- Bcndarray, optional
Structuring element. (Default: 3x3 elementary cross).
- outndarray, optional
Output array
- outputdeprecated
Do not use
- Returns:
- yndarray
See also
open
function
- mahotas.close_holes(ref, Bc=None)¶
closed = close_holes(ref, Bc=None):
Close Holes
- Parameters:
- refndarray
Reference image. This should be a binary image.
- Bcstructuring element, optional
Default: 3x3 cross
- Returns:
- closedndarray
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:
- fndarray
input. Any dimension is supported
- weightsndarray
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
- cvaldouble, optional
If mode is constant, which constant to use (default: 0.0)
- outndarray, optional
Output array. Must have same shape and dtype as f as well as be C-contiguous.
- Returns:
- convolvedndarray 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:
- fndarray
input. Any dimension is supported
- weights1-D ndarray
weight filter. If not of the same dtype as f, it is cast
- axisint
Axis along which to convolve
- mode{‘reflect’ [default], ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’, ‘ignore’}
How to handle borders
- cvaldouble, optional
If mode is constant, which constant to use (default: 0.0)
- outndarray, optional
Output array. Must have same shape and dtype as f as well as be C-contiguous.
- Returns:
- convolvedndarray 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:
- imgndarray
Integer image array
- borderint, optional
whether to add a border (default no border)
- Returns:
- nimgndarray
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 sub-image 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 n-dimensions
This function computes the watershed transform on the input surface (which may actually be an n-dimensional 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:
- surfaceimage
- markersimage
initial markers (must be a labeled image, i.e., one where 0 represents the background and higher integers represent different regions)
- Bcndarray, optional
structuring element (default: 3x3 cross)
- return_linesboolean, optional
whether to return separating lines (in addition to regions)
- Returns:
- Winteger ndarray (int64 ints)
Regions image (i.e., W[i,j] == region for pixel (i,j))
- WLLines 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:
- fndarray
2-D image
- codestr
One of ‘D2’, ‘D4’, … ‘D20’
- inlinebool, 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:
- Andarray of bools
input array
- Bcndarray, optional
Structuring element. By default, use a cross (see
get_structuring_elem
for details on the default).- outndarray, optional
output array. If used, this must be a C-array of the same
dtype
asA
. Otherwise, a new array is allocated.- outputdeprecated
Do not use
- Returns:
- dilatedndarray
dilated version of
A
See also
- mahotas.disk(radius, dim=2)¶
Return a binary disk structuring element of radius
radius
and dimensiondim
- Parameters:
- radiusint
Radius (in pixels) of returned disk
- dimint, optional
Dimension of returned array (default: 2)
- Returns:
- Dboolean ndarray
- 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'] }
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:
- bwndarray
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).- metricstr, optional
one of ‘euclidean2’ (default) or ‘euclidean’
- Returns:
- dmapndarray
distance map
References
For 2-D images, the following algorithm is used:
Felzenszwalb P, Huttenlocher D. Distance transforms of sampled functions. Cornell Computing and Information. 2004.
Available at: https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.1647&rep=rep1&type=pdf.
For n-D images (with n > 2), a slower hand-craft 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:
- imgAny 2D-ndarray
- sigma1the sigma value of the first Gaussian filter. The second filter
will have sigma value 1.001*sigma1
- multiplierthe multiplier to get sigma2. sigma2 = sigma1 * multiplier
- just_filterboolean, optional
If true, then return the result of filtering the image with the DoG filters, no zero-crossing is detected (default is False).
- Returns:
- edgesndarray
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:
- Andarray
input image
- Bcndarray, optional
Structuring element. By default, use a cross (see
get_structuring_elem
for details on the default).- outndarray, optional
output array. If used, this must be a C-array of the same
dtype
asA
. Otherwise, a new array is allocated.
- Returns:
- erosionndarray
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:
- fndarray
A 2-D binary image
- nint, optional
Connectivity, one of (4,8). default: 8
- mode{‘reflect’, ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’ [default]}
How to handle borders
- Returns:
- euler_nrint
Euler number
References
https://en.wikipedia.org/wiki/Euler_characteristic
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:
- fndarray
input. Currently, only 2-dimensional images are supported.
- templatendarray
Template to match. Must be explicitly passed, no default.
- Returns:
- matchnp.array
- coordinatesnp.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:
- imgarray-like of an unsigned type
input image.
- Returns:
- histan 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)})¶
Multi-dimensional Gaussian filter.
- Parameters:
- arrayndarray
input array, any dimension is supported. If the array is an integer array, it will be converted to a double array.
- sigmascalar 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
- cvaldouble, optional
If mode is constant, which constant to use (default: 0.0)
- outndarray, optional
Output array. Must have same shape as array as well as be C-contiguous. If array is an integer array, this must be a double array; otherwise, it must have the same type as array.
- Returns:
- filteredndarray
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., out={np.empty_like(array)})¶
One-dimensional Gaussian filter.
- Parameters:
- arrayndarray
input array of a floating-point type
- sigmafloat
standard deviation for Gaussian kernel (in pixel units)
- axisint, 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
- cvaldouble, optional
If mode is constant, which constant to use (default: 0.0)
- outndarray, optional
Output array. Must have same shape and dtype as array as well as be C-contiguous.
- Returns:
- filteredndarray
Filtered version of array
- mahotas.get_structuring_elem(A, Bc)¶
Retrieve appropriate structuring element
- Parameters:
- Andarray
array which will be operated on
- BcNone, 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_outndarray
Structuring element. This array will be of the same type as A, C-contiguous.
- mahotas.haar(f, preserve_energy=True, inline=False)¶
Haar transform
- Parameters:
- f2-D ndarray
Input image
- preserve_energybool, optional
Whether to normalise the result so that energy is preserved (the default).
- inlinebool, 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:
- inputinput ndarray
This is interpreted as a binary array.
- Bcndarray
hit & miss template, values must be one of (0, 1, 2)
- outndarray, optional
Used for output. Must be Boolean ndarray of same size as
input
- outputdeprecated
Do not use
- Returns:
- filteredndarray
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:
- fndarray
2-D image
- codestr
One of ‘D2’, ‘D4’, … ‘D20’
- inlinebool, 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:
- f2-D ndarray
Input image. If it is an integer image, it is converted to floating point (double).
- preserve_energybool, optional
Whether to normalise the result so that energy is preserved (the default).
- inlinebool, 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:
- fndarray
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:
- filenamestr
filename
- as_greyboolean, 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:
- imgndarray
- nsizefloat 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]
- orderinteger, 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:
- filenamestr
path on file system
- arrayndarray-like
- 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: https://en.wikipedia.org/wiki/Connected-component_labeling
- Parameters:
- arrayndarray
This will be interpreted as binary array
- Bcndarray, optional
This is the structuring element to use
- outndarray, optional
Output array. Must be a C-array, of type np.int32
- Returns:
- labeledndarray
Labeled result
- nr_objectsint
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:
- arrayndarray of any type
- labeledint ndarray
Label map. This is the same type as returned from
mahotas.label()
- minlengthint, optional
Minimum size of return array. If labeled has fewer than
minlength
regions, 0s are added to the result. (optional)
- Returns:
- sums1-d ndarray of
array.dtype
- sums1-d ndarray of
- mahotas.laplacian_2D(array, alpha=0.2)¶
2D Laplacian filter.
- Parameters:
- arrayndarray
input 2D array. If the array is an integer array, it will be converted to a double array.
- alphascalar or sequence of scalars
controls the shape of Laplacian operator. Must be 0-1. A larger values makes the operator empahsize the diagonal direction.
- Returns:
- filteredndarray
Filtered version of array
- mahotas.locmax(f, Bc={3x3 cross}, out={np.empty(f.shape, bool)})¶
Local maxima
- Parameters:
- fndarray
- Bcndarray, optional
structuring element
- outndarray, optional
Used for output. Must be Boolean ndarray of same size as f
- outputdeprecated
Do not use
- Returns:
- filteredndarray
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:
- fndarray
- Bcndarray, optional
structuring element
- outndarray, optional
Used for output. Must be Boolean ndarray of same size as f
- outputdeprecated
Do not use
- Returns:
- filteredndarray
boolean image of same size as f.
See also
locmax
function Regional maxima
- mahotas.majority_filter(img, N=3, out={np.empty(img.shape, 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:
- imgndarray
input img (currently only 2-D images accepted)
- Nint, optional
size of filter (must be odd integer), defaults to 3.
- outndarray, optional
Used for output. Must be Boolean ndarray of same size as img
- outputdeprecated
Do not use
- Returns:
- filteredndarray
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:
- fndarray
input. Any dimension is supported
- Bcndarray
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.
- cvaldouble, optional
If mode is constant, which constant to use (default: 0.0)
- outndarray, optional
Output array. Must be a double array with the same shape as f as well as be C-contiguous.
- Returns:
- meanndarray of type double and same shape as
f
- meanndarray of type double and same shape as
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:
- fndarray
input. Any dimension is supported
- Bcndarray 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
- cvaldouble, optional
If mode is constant, which constant to use (default: 0.0)
- outndarray, optional
Output array. Must have same shape and dtype as f as well as be C-contiguous.
- Returns:
- medianndarray of same type and shape as
f
median[i,j] is the median value of the points in f close to (i,j)
- medianndarray of same type and shape as
- 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, unless 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:
- img2-ndarray
An 2-d ndarray
- p0float
Power for first dimension
- p1float
Power for second dimension
- cm(int,int), optional
center of mass (default: 0,0)
- convert_to_floatboolean, optional
whether to convert to floating point (default: True)
- normalizeboolean, optional
whether to normalize to size of image (default: False)
- Returns:
- moment: float
floating point number
Notes
It only works for 2-D 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 gray-scale case, there is a similar interpretation taking the functions umbra.
- Parameters:
- fndarray
Gray-scale (uint8 or uint16) or binary image.
- Bcndarray, optional
Structuring element (default: 3x3 elementary cross).
- outndarray, optional
Output array
- outputdeprecated
Do not use
- Returns:
- yndarray
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: https://en.wikipedia.org/wiki/Otsu’s_method
- Parameters:
- imgan image as a numpy array.
This should be of an unsigned integer type.
- ignore_zerosBoolean
whether to ignore zero-valued pixels (default: False)
- Returns:
- Tinteger
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,bluendarray, optional
boolean arrays
- if_gray_dtype_not_uint8str, 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
- What to do if
- Returns:
- overlaidndarray
Colour image
- mahotas.rank_filter(f, Bc, rank, mode='reflect', cval=0.0, out=None)¶
Rank filter. The value at
ranked[i,j]
will be therank
h largest in the neighbourhood defined byBc
.- Parameters:
- fndarray
input. Any dimension is supported
- Bcndarray
Defines the neighbourhood. Must be explicitly passed, no default.
- rankinteger
- mode{‘reflect’ [default], ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’, ‘ignore’}
How to handle borders
- cvaldouble, optional
If mode is constant, which constant to use (default: 0.0)
- outndarray, optional
Output array. Must have same shape and dtype as f as well as be C-contiguous.
- Returns:
- rankedndarray of same type and shape as
f
ranked[i,j] is the
rank
h value of the points in f close to (i,j)
- rankedndarray of same type and shape as
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.
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:
- imgndarray
Image of any type
- ignore_zerosboolean, optional
Whether to ignore zero valued pixels (default: False)
- Returns:
- Tfloat
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:
- fndarray
- Bcndarray, optional
structuring element
- outndarray, optional
Used for output. Must be Boolean ndarray of same size as f
- outputdeprecated
Do not use
- Returns:
- filteredndarray
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:
- fndarray
- Bcndarray, optional
structuring element
- outndarray, optional
Used for output. Must be Boolean ndarray of same size as f
- outputdeprecated
Do not use
- Returns:
- filteredndarray
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:
- imgAny 2D-ndarray
- just_filterboolean, optional
If true, then return the result of filtering the image with the sobel filters, but do not threashold (default is False).
- Returns:
- edgesndarray
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=<class '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())/np.ptp(img) + min
- Parameters:
- imgndarray
input image. It is not modified by this function
- mininteger, optional
minimum value for output [default: 0]
- maxinteger, optional
maximum value for output [default: 255]
- dtypedtype 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=<class 'numpy.uint8'>)¶
Variation of stretch() function that works per-channel on an RGB image
- Parameters:
- imgndarray
input image. It is not modified by this function
- mininteger, optional
minimum value for output [default: 0]
- maxinteger, optional
maximum value for output [default: 255]
- dtypedtype 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:
- fndarray
input. Any dimension is supported
- templatendarray
Template to match. Must be explicitly passed, no default.
- mode{‘reflect’ [default], ‘nearest’, ‘wrap’, ‘mirror’, ‘constant’, ‘ignore’}
How to handle borders
- cvaldouble, optional
If mode is constant, which constant to use (default: 0.0)
- outndarray, optional
Output array. Must have same shape and dtype as f as well as be C-contiguous.
- Returns:
- matchndarray 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]
andtemplate
(for appropriately defineds0
ands1
).
- matchndarray of same type and shape as
- mahotas.thin(binimg)¶
Skeletonisation by thinning
- Parameters:
- binimgndarray
Binary input image
- max_iterint, optional
Maximum number of iterations (set to a negative number, the default, to run full skeletonization)
- Returns:
- skelSkeletonised 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:
- fndarray
input image
- borderint, optional
The border to use (default is no border)
- dtypetype, optional
Type of
fc
- cvalfloat, optional
Which value to fill the border with (default is 0)
- Returns:
- fcndarray
See also
wavelet_decenter
function Reverse function
- mahotas.wavelet_decenter(w, oshape, border=0)¶
Undoes the effect of
wavelet_center
- Parameters:
- wndarray
Wavelet array
- oshapetuple
Desired shape
- borderint, optional
The desired border. This must be the same value as was used for
wavelet_center
- Returns:
- fndarray
This will have shape
oshape
See also
wavelet_center
function Forward function
- mahotas.features.eccentricity(bwimage)¶
Compute eccentricity
- Parameters:
- bwimagendarray
Interpreted as a boolean image
- Returns:
- rfloat
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:
- bwimagendarray
Interpreted as a boolean image
- Returns:
- semimajorfloat
- semiminorfloat
References
Prokop, RJ, and Reeves, AP. 1992. CVGIP: Graphical Models and Image Processing 54(5):438-460
- mahotas.features.haralick(f, ignore_zeros=False, preserve_haralick_bug=False, compute_14th_feature=False, return_mean=False, return_mean_ptp=False, use_x_minus_y_variance=False, distance=1)¶
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).
ignore_zeros
can be used to have the function ignore any zero-valued pixels (as background). If there are no-nonzero neighbour pairs in all directions, an exception is raised. Note that this can happen even with some non-zero 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 non-zero pairs!- Parameters:
- fndarray of integer type
input image. 2-D and 3-D images are supported.
- distance: int, optional (default=1)
The distance to consider while computing the cooccurence matrix.
- ignore_zerosbool, optional
Whether to ignore zero pixels (default: False).
- Returns:
- featsndarray 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_bugbool, 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_featurebool, optional
whether to compute & return the 14-th feature
- return_meanbool, optional
When set, the function returns the mean across all the directions (default: False).
- return_mean_ptpbool, optional
When set, the function returns the mean and ptp (point-to-point, i.e., difference between max() and min()) across all the directions (default: False).
- use_x_minus_y_variancebool, optional
Feature 10 (index 9) has two interpretations, as the variance of |x-y| or as the variance of P(|x-y|). In order to achieve compatibility with other software and previous versions of mahotas, mahotas defaults to using
VAR[P(\|x-y\|)]
; if this argument is True, then it usesVAR[\|x-y\|]
(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 = {610--621}, publisher = {IEEE}, title = {Textural features for image classification}, url = {https://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:
- imagendarray
input image (2-D numpy ndarray)
- radiusnumber (integer or floating point)
radius (in pixels)
- pointsinteger
nr of points to consider
- ignore_zerosboolean, optional
whether to ignore zeros (default: False)
- Returns:
- features1-D 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 404-420
- 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” (https://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. This was first published by Coelho et al. in “Structured Literature Image Finder: Extracting Information from Text and Images in Biomedical Literature” (https://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:
- imgndarray, 2D or 3D
input image
- Tinteger, optional
Threshold to use (default: compute with otsu)
- Returns:
- valuesndarray
A 1-D ndarray of feature values
- mahotas.features.roundness(bw)¶
Roundness
- Parameters:
- bwndarray
Interpreted as a boolean image
- Returns:
- rfloat
- mahotas.features.tas(img)¶
Compute Threshold Adjacency Statistics
TAS were presented by Hamilton et al. in “Fast automated cell phenotype image classification” (https://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:
- imgndarray, 2D or 3D
input image
- Returns:
- valuesndarray
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
. 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:
- im2-ndarray
input image
- radiusinteger
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.
- degreeinteger, optional
Maximum degree to use (default: 8)
- cmpair of floats, optional
the centre of mass to use. By default, uses the image’s centre of mass.
- Returns:
- zvalues1-ndarray of floats
Zernike moments
References
Teague, MR. (1980). Image Analysis via the General Theory of Moments. J. Opt. Soc. Am. 70(8):920-930.
- mahotas.colors.rgb2gray(rgb_image, dtype=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:
- arrayndarray of shape (a,b,3)
- dtypedtype, optional
dtype of return
- Returns:
- greyndarray of
dtype
- greyndarray of
- mahotas.colors.rgb2grey(rgb_image, dtype=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:
- arrayndarray of shape (a,b,3)
- dtypedtype, optional
dtype of return
- Returns:
- greyndarray of
dtype
- greyndarray of
- mahotas.colors.rgb2lab(rgb, dtype={float})¶
Convert sRGB to L*a*b* coordinates
https://en.wikipedia.org/wiki/CIELAB
- Parameters:
- rgbndarray
Must be of shape (h,w,3)
- dtypedtype, optional
What dtype to return. Default will be floats
- Returns:
- labndarray
- mahotas.colors.rgb2sepia(rgb)¶
sepia = rgb2sepia(rgb)
- Parameters:
- rgbndarray
Must be of shape (h,w,3)
- Returns:
- sepiandarray
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:
https://en.wikipedia.org/wiki/SRGB
- Parameters:
- rgbndarray
- dtypedtype, optional
What dtype to return
- Returns:
- xyzndarray
See also
xyz2rgb
function The reverse function
- mahotas.colors.xyz2lab(xyz, dtype={float})¶
Convert CIE XYZ to L*a*b* coordinates
https://en.wikipedia.org/wiki/CIELAB
- Parameters:
- xyzndarray
- dtypedtype, optional
What dtype to return. Default will be floats
- Returns:
- labndarray
- mahotas.colors.xyz2rgb(xyz, dtype={float})¶
Convert XYZ to sRGB coordinates
The output should be interpreted as sRGB. See Wikipedia for more details:
https://en.wikipedia.org/wiki/SRGB
- Parameters:
- xyzndarray
- dtypedtype, optional
What dtype to return. Default will be floats
- Returns:
- rgbndarray
See also
rgb2xyz
function The reverse function