PYMORPH: IMAGE MORPHOLOGY IN PYTHON

Contents:

Indices and tables

pymorph a powerful collection of state-of-the-art gray-scale morphological tools that can be applied to image segmentation, non-linear filtering, pattern recognition and image analysis.

  • add4dilate() : Addition for dilation
  • addm() : Addition of two images, with saturation.
  • areaclose() : Area closing
  • areaopen() : Area opening
  • asf() : Alternating Sequential Filtering
  • asfrec() : Reconstructive Alternating Sequential Filtering
  • bench() : benchmarking main functions of the toolbox.
  • binary() : Convert a gray-scale image into a binary image
  • blob() : Blob measurements from a labeled image.
  • bshow() : Generate a graphical representation of overlaid binary images.
  • cbisector() : N-Conditional bisector.
  • cdilate() : Dilate an image conditionally.
  • center() : Center filter.
  • cerode() : Erode an image conditionally.
  • close_holes() : Close holes of binary and gray-scale images.
  • close() : Morphological closing.
  • closerec() : Closing by reconstruction.
  • closerecth() : Close-by-Reconstruction Top-Hat.
  • closeth() : Closing Top Hat.
  • concat() : Concatenate two or more images along width, height or depth.
  • cthick() : Image transformation by conditional thickening.
  • cthin() : Image transformation by conditional thinning.
  • cwatershed() : Detection of watershed from markers.
  • datatype() : Return the image datatype string
  • dilate() : Dilate an image by a structuring element.
  • dist() : Distance transform.
  • drawv() : Superpose points, rectangles and lines on an image.
  • edgeoff() : Eliminate the objects that hit the image frame.
  • endpoints() : Interval to detect end-points.
  • erode() : Erode an image by a structuring element.
  • flood() : Flooding filter- h,v,a-basin and dynamics (depth, area, volume)
  • frame() : Create a frame image.
  • freedom() : Control automatic data type conversion.
  • gdist() : Geodesic Distance Transform.
  • gradm() : Morphological gradient.
  • grain() : Gray-scale statistics for each labeled region.
  • gray() : Convert a binary image into a gray-scale image.
  • gshow() : Apply binary overlays as color layers on a binary or gray-scale image
  • histogram() : Find the histogram of the image f.
  • hmax() : Remove peaks with contrast less than h.
  • hmin() : Remove basins with contrast less than h.
  • homothick() : Interval for homotopic thickening.
  • homothin() : Interval for homotopic thinning.
  • img2se() : Create a structuring element from a pair of images.
  • infcanon() : Intersection of inf-generating operators.
  • infgen() : Inf-generating.
  • infrec() : Inf-reconstruction.
  • inpos() : Minima imposition.
  • interot() : Rotate an interval
  • intersec() : Intersection of images.
  • intershow() : Visualize an interval.
  • isbinary() : Check for binary image
  • isolines() : Apply an iso-line color table to a gray-scale image.
  • label() : Label a binary image.
  • labelflat() : Label the flat zones of gray-scale images.
  • lastero() : Last erosion.
  • lblshow() : Display a labeled image assigning a random color for each label.
  • limits() : Get the possible minimum and maximum of an image.
  • mat2set() : Converts image representation from matrix to set
  • maxleveltype() : Returns the maximum value associated to an image datatype
  • neg() : Negate an image.
  • open() : Morphological opening.
  • openrec() : Opening by reconstruction.
  • openrecth() : Open-by-Reconstruction Top-Hat.
  • openth() : Opening Top Hat.
  • opentransf() : Open transform.
  • pad4n() : pad4n
  • patspec() : Pattern spectrum (also known as granulometric size density).
  • plot() : Plot a function.
  • randomcolor() : Apply a random color table to a gray-scale image.
  • regmax() : Regional Maximum.
  • regmin() : Regional Minimum (with generalized dynamics).
  • se2hmt() : Create a Hit-or-Miss Template (or interval) from a pair of structuring elements.
  • se2interval() : Create an interval from a pair of structuring elements.
  • sebox() : Create a box structuring element.
  • secross() : Diamond structuring element and elementary 3x3 cross.
  • sedilate() : Dilate one structuring element by another
  • sedisk() : Create a disk or a semi-sphere structuring element.
  • seline() : Create a line structuring element.
  • sereflect() : Reflect a structuring element
  • serot() : Rotate a structuring element.
  • seshow() : Display a structuring element as an image.
  • sesum() : N-1 iterative Minkowski additions
  • set2mat() : Converts image representation from set to matrix
  • setrans() : Translate a structuring element
  • seunion() : Union of structuring elements
  • skelm() : Morphological skeleton (Medial Axis Transform).
  • skelmrec() : Morphological skeleton reconstruction (Inverse Medial Axis Transform).
  • skiz() : Skeleton of Influence Zone - also know as Generalized Voronoi Diagram
  • subm() : Subtraction of two images, with saturation.
  • supcanon() : Union of sup-generating or hit-miss operators.
  • supgen() : Sup-generating (hit-miss).
  • suprec() : Sup-reconstruction.
  • symdiff() : Symmetric difference between two images
  • text() : Create a binary image of a text.
  • thick() : Image transformation by thickening.
  • thin() : Image transformation by thinning.
  • threshad() : Threshold (adaptive)
  • toggle() : Image contrast enhancement or classification by the toggle operator.
  • union() : Union of images.
  • watershed() : Watershed detection.
  • to_int32() : Convert an image to an int32 image.
  • to_uint16() : Convert an image to a uint16 image.
  • to_uint8() : Convert an image to an uint8 image.
pymorph.concat(dim, img0, img1, ...)

Concatenate two or more images along width, height or depth.

Concatenate two or more images in any of the dimensions: width, height or depth. If the images do not match the dimension, a larger image is create with zero pixels to accommodate them. The images must have the same datatype.

Parameters :

dim : {‘width’, ‘heigh’, ‘depth’, ‘w’, ‘h’, ‘d’ }

Dimension along which to concatenate.

img0, img1, ... : Images to concatenate

Returns :

img : resulting image (of the same type as inputs).

pymorph.limits(f)

Get the possible minimum and maximum of an image. The possible minimum and the possible maximum of an image depend on its data type. These values are important to compute many morphological operators (for instance, negate of an image). The output is a vector, where the first element is the possible minimum and the second, the possible maximum.

Parameters :

f : Unsigned gray-scale (uint8 or uint16), signed (int32) or binary image.

Returns :

y : Two element vector

the first element is the infimum, the second, the supremum.

pymorph.center(f, b={3x3 cross})

Center filter.

center() computes the morphological center of f w.r.t. to the structuring element b.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

b : Structuring element (default: 3x3 cross).

Returns :

y : Image

pymorph.close_holes(f, Bc={3x3 cross})

Close holes of binary and gray-scale images.

close_holes creates the image y by closing the holes of the image f, according with the connectivity defined by the structuring element Bc.The images can be either binary or gray-scale.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

Bc : Connectivity (default: 3x3 cross).

Returns :

y : image (ndarray) of same type as f.

pymorph.dist(f, Bc={3x3 cross}, metric='euclidean')

Distance transform.

dist creates the distance image y of the binary image f. The value of y at the pixel x is the distance of x to the complement of f, that is, the distance of x to nearest point in the complement of f. The distances available are based on the Euclidean metrics and on metrics generated by a a regular graph, that is characterized by a connectivity rule defined by the structuring element Bc. The implementation of the Euclidean algorithm is based on LotuZamp:01 .

Parameters :

f : ndarray of type bool

Input image

Bc : ndarray, optional

Connectivity structure element (default: 3x3 cross)

metric : {‘euclidean’ [default], ‘euclidean2’}, optional

Metric to use.

Returns :

y : ndarray

distance image in uint16, or, if metric==’euclidean2’, in int32

See also

cdist
conditional distance transform
mahotas.distance
in mahotas package, faster C++ implementation
scipy.ndimage.distance_transform_edt
in scipy, faster C implementation
pymorph.cdist(f, g, Bc=None, metric=None)

Conditional (geodesic) distance transform.

cdist creates the conditional distance image y of the binary image f.

y[y,x] = distance of (y,x) to foreground in a path through complement(c) y[y,x] = 0, if f[y,x] == 0 or c[y,x] == 1

The distances available are based on the Euclidean metrics and on metrics generated by a a regular graph, that is characterized by a connectivity rule defined by the structuring element Bc. The implementation of the Euclidean algorithm is based on LotuZamp:01 .

Parameters :

f : Binary image.

g : Binary image.

Bc : Structuring Element Default: None (3x3 elementary

cross). (connectivity)

metric : Metric to use, one of (‘euclidean’, ‘euclidean2’), ‘euclidean’ by default.

Returns :

y : ndarray

distance image in uint16, or, if metric==’euclidean2’, in int32

pymorph.edgeoff(f, Bc={3x3 cross})

Eliminate the objects that hit the image frame.

edgeoff creates the binary image y by eliminating the objects (connected components) of the binary image f that hit the image frame, according to the connectivity defined by the structuring element Bc.

Parameters :

f : Binary image.

Bc : Structuring element (default: 3x3 cross)

Returns :

y : Binary image.

pymorph.frame(f, Dt=1, Wt=1, Dt=0, framevalue={max of f.dtype}, bgvalue={min of f.dtype})

Create a frame image.

frame creates an image `y, with the same dimensions (W,H,D) and same pixel type of the image f, such that the value of the pixels in the image frame is framevalue and the value of the other pixels is k2 . The thickness of the image frame is given by the HT, WT, and DT parameters.

Parameters :

f : Input image

Ht : Height thickness (default 1)

Wt : Width thickness (default 1)

Dt : Depth thickness (default 0)

framevalue : Frame grey-level (default: max of f.dtype)

bgvalue : Background grey-level (default: min of f.dtype)

Returns :

y : image of same type as f .

pymorph.randomcolor(X)

Apply a random color table to a gray-scale image.

Zero is guaranteed to be mapped to black (i.e., (0,0,0) triplet)

Parameters :

X : 2d-array of uint8 of shape (h,w)

Labeled image.

Returns :

y : 3d-array of uint8 of shape (h, w, 3)

Colour image.

pymorph.isolines(X, N=10)

Apply an iso-contour color table to a gray-scale image.

Parameters :

X : 2d-array

Distance transform image.

N : integer, optional

Number of iso-contours (default: 10).

Returns :

Y : Gray-scale (uint8 or uint16) or binary image.

pymorph.overlay(X, red=None, green=None, blue=None, magenta=None, yellow=None, cyan=None)

Apply binary overlays as colour layers on a binary or gray-scale image

Parameters :

X : Gray-scale (uint8 or uint16) or binary image.

red : Red overlay, binary image(default: None)

green : Green overlay, binary image (default: None)

blue : blue overlay, binary image (default: None)

magenta : magenta overlay, binary image (default: None)

yellow : yellow overlay, binary image (default: None)

cyan : cyan overlay, binary image (default: None)

Returns :

Y : Colour image (in HxWx3 format)

pymorph.histogram(f)

Find the histogram of the image f.

Finds the histogram of the image f.

For binary image the vector size is 2. For gray-scale uint8 and uint16 images, the vector size is the maximum pixel value plus one. h[0] gives the number of pixels with value 0.

Parameters :f : Input image (of any integer type).
Returns :h : Histogram in a uint16 or an int32 vector.
pymorph.label(f, Bc={3x3 cross})

Label a binary image.

label creates the image y by labeling the connect components of a binary image f, according to the connectivity defined by the structuring element Bc. The background pixels (with value 0) are not labeled. The maximum label value in the output image gives the number of its connected components.

Parameters :

f : Binary image.

Bc : Connectivity (default: 3x3 cross)

Returns :

y : Image of same size as f.

If number of labels is less than 65535, the data type is uint16, otherwise it is int32.

pymorph.neg(f)

Negate an image.

neg returns an image y that is the negation (i.e., inverse or involution) of the image f. In the binary case, y is the complement of f.

Parameters :f : Unsigned gray-scale (uint8 or uint16), signed (int32) or binary image.
Returns :y : ndarray of same shape and dtype as f
pymorph.threshad(f, f1, f2=None)

Threshold (adaptive)

threshad creates the image y as the threshold of the image f by the images f1 and f2. A pixel in y has the value 1 when the value of the corresponding pixel in f is between the values of the corresponding pixels in f1 and f2.

Parameters :

f : Gray-scale (uint8 or uint16) image.

f1 : Lower value.

f2 : Upper value.

Returns :

y : Binary image.

pymorph.toggle(f, f1, f2, gray_mode=True)

Toggle operator

Image contrast enhancement or classification by the toggle operator.

toggle creates the image y that is an enhancement or classification of the image f by the toggle operator, with parameters f1 and f2. If gray, it performs an enhancement; otherwise, it performs a binary classification.

In the enhancement, a pixel takes the value of the corresponding pixel in f1 or f2, according to a minimum distance criterion from f to f1 or f to f2. In the classification, the pixels in f nearest to f1 receive the value 0, while the ones nearest to f2 receive the value 1.

Parameters :

f : Gray-scale (uint8 or uint16) image.

f1 : Gray-scale (uint8 or uint16) image.

f2 : Gray-scale (uint8 or uint16) image.

gray_mode : boolean, optional

Whether to work in grey mode (default: True)

Returns :

y : ndaimge of same shape and dtype as f

pymorph.addm(f1, f2)

Addition of two images, with saturation.

addm creates the image y by pixelwise addition of images f1 and f2 . When the addition of the values of two pixels saturates the image data type considered, the greatest value of this type is taken as the result of the addition.

Parameters :

f1 : Unsigned gray-scale (uint8 or uint16), signed (int32) or

binary image.

f2 : Unsigned gray-scale (uint8 or uint16), signed (int32) or

binary image. Or constant.

Returns :

y: Unsigned gray-scale (uint8 or uint16), signed (int32) or :

binary image.

Examples

f = to_uint8([255,   255,    0,   10,    0,   255,   250])
g = to_uint8([ 0,    40,   80,   140,  250,    10,    30])
print addm(f,g)
print addm(g, 100)

prints out

[255 255  80 150 250 255 255]
[100 140 180 240 255 110 130]
pymorph.areaclose(f, a, Bc={3x3 cross})

Area closing

areaclose removes any pore (i.e., background connected component) with area less than a in binary image f. The connectivity is given by the structuring element Bc. This operator is generalized to gray-scale images by applying the binary operator successively on slices of f taken from higher threshold levels to lower threshold levels.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

a : Non negative integer.

Bc : Structuring element (default: 3x3 cross).

Returns :

y : Same type of f

pymorph.areaopen(f, a, Bc=None)

Area opening

areaopen removes any grain (i.e., connected component) with area less than a of a binary image f. The connectivity is given by the structuring element Bc. This operator is generalized to gray-scale images by applying the binary operator successively on slices of f taken from higher threshold levels to lower threshold levels.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

a : Double non negative integer.

Bc : Structuring element (default: 3x3 cross).

Returns :

y : Same type of f

Examples

f=binary(to_uint8([
 [1, 1, 0, 0, 0, 0, 1],
 [1, 0, 1, 1, 1, 0, 1],
 [0, 0, 0, 0, 1, 0, 0]]))
y=areaopen(f,4,secross())
print y

example 2

f=to_uint8([
   [10,   11,   0,    0,   0,   0,  20],
   [10,    0,   5,    8,   9,   0,  15],
   [10,    0,   0,    0,  10,   0,   0]])
y=areaopen(f,4,secross())
print y
a=readgray('form-1.tif')
b=areaopen(a,500)
show(a)
show(b)
a=readgray('bloodcells.tif')
b=areaopen(a, 500)
show(a)
show(b)
pymorph.asf(f, seq="OC", B={3x3 cross}, n=1)

Alternating Sequential Filtering

asf creates the image y by filtering the image f by n iterations of the close and open alternating sequential filter characterized by the structuring element B. The sequence of opening and closing is controlled by the parameter seq. ‘OC’ performs opening after closing, ‘CO’ performs closing after opening, ‘OCO’ performs opening after closing after opening, and ‘COC’ performs closing after opening after closing.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

seq : Order of operations, one of (‘OC’, ‘CO’, ‘OCO’, ‘COC’), default: ‘OC’.

B : Structuring element (default: 3x3 cross).

n : integer, optional

Number of iterations (default: 1).

Returns :

y : Image

pymorph.asfrec(f, seq="OC", B={3x3 cross}, Bc={3x3 cross}, N=1)

Reconstructive Alternating Sequential Filtering

asf creates the image y by filtering the image f by n iterations of the close by reconstruction and open by reconstruction alternating sequential filter characterized by the structuring element B. The structure element Bc is used in the reconstruction. The sequence of opening and closing is controlled by the parameter seq. ‘OC’ performs opening after closing, and ‘CO’ performs closing after opening.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

seq : Order of operations, one of (‘OC’, ‘CO’), default: ‘OC’.

B : Structuring element (default: 3x3 cross).

Bc : Structuring element (default: 3x3 cross).

N : Number of iterations (default: 1).

Returns :

y : Same type of f

pymorph.binary(f, k=1)

Convert a gray-scale image into a binary image

binary converts a gray-scale image f into a binary image y by a threshold rule. A pixel in y has the value 1 if and only if the corresponding pixel in f has a value greater or equal to k.

Parameters :

f : Unsigned gray-scale (uint8 or uint16), signed (int32) or binary image.

k : integer, optional

Threshold used inclusively (default: 1)

Returns :

y : Binary image.

pymorph.blob(f, measurement, output="image")

Blob measurements from a labeled image.

Take measurements from the labeled image f.

The measurements are:

  • area,
  • centroid,
  • bounding rectangle.

output controls the output format:

image
the result is an image
data
the result is a double column vector with the measurement for each blob.

The region with label zero is not measured as it is normally the background. The measurement of region with label 1 appears at the first row of the output.

Parameters :

f : Gray-scale (uint8 or uint16) image. Labeled image.

measurement : Measurement. One of (‘area’, ‘centroid’, ‘boundingbox’).

output : {‘image’ [default], ‘data’}, optional

Output format: if ‘image’, returns a binary image; if ‘data’, returns a vector of measurements

Returns :

y : Gray-scale (uint8 or uint16) or binary image.

pymorph.cbisector(f, B, n)

N-Conditional bisector.

cbisector creates the binary image y by performing a filtering of the morphological skeleton of the binary image f, relative to the structuring element B. The strength of this filtering is controlled by the parameter n. Particularly, if n==0 , y is the morphological skeleton of f itself.

Parameters :

f : Binary image.

B : Structuring element

n : filtering rate (positive integer)

Returns :

y : Binary image.

pymorph.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 : Gray-scale (uint8 or uint16) or binary image.

g : Conditioning image. (Gray-scale or binary).

Bc : Structuring element (default: 3x3 cross)

n : Number of iterations (default: 1)

Returns :

y : Image

pymorph.cerode(f, g, Bc=None, n=1)

Conditional erosion

cerode creates the image y by eroding the image f by the structuring element Bc conditionally to g. This operator may be applied recursively n times.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

g : Conditioning image.

Bc : Structuring element (default: 3x3 cross)

n : Number of iterations (default: 1)

Returns :

y : Image

pymorph.close(f, Bc={3x3 cross})

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 :

f : Gray-scale (uint8 or uint16) or binary image.

Bc : Structuring Element Default: None (3x3 elementary cross).

Returns :

y : Image

pymorph.closerec(f, Bdil=None, Bc=None)

Closing by reconstruction.

closerec() creates the image y by a sup-reconstruction (with the connectivity defined by the structuring element Bc) of the image f from its dilation by Bdil.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image

Bdil : Dilation structuring element (default 3x3 elementary cross)

Bc : Connectivity structuring element (default: 3x3 elementary cross)

Returns :

y : Image (same type as f)

pymorph.closerecth(f, Bdil=None, Bc=None)

Close-by-Reconstruction Top-Hat.

closerecth creates the image y by subtracting the image f of its closing by reconstruction, defined by the structuring elements Bc and Bdil.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

Bdil : Dilation structuring element (default: 3x3 cross)

Bc : Connectivity structuring element (default: 3x3 cross)

Returns :

y : Gray-scale (uint8 or uint16) or binary image.

pymorph.closeth(f, B={3x3 cross})

Closing Top Hat.

closeth creates the image y by subtracting the image f of its morphological closing by the structuring element B.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

B : Structuring Element Default: None (3x3 elementary cross).

Returns :

y : ndarray of same shape and dtype as f

pymorph.cthick(f, g, Iab={Homothick interval}, n={infinite}, theta=45, direction="clockwise")

Image transformation by conditional thickening.

cthick creates the binary image y by performing a thickening of the binary image f conditioned to the binary image g. The number of iterations of the conditional thickening is n and in each iteration the thickening is characterized by rotations of theta of the interval Iab.

Parameters :

f : Binary image.

g : Binary image.

Iab : Interval (default: homothick).

n : Number of iterations, -1 for infinite (default: -1)

theta : Degrees of rotation, 45 (default), 90, or 180.

direction: ‘clockwise’ or ‘anti-clockwise’. :

Returns :

y : Binary image.

pymorph.cthin(f, g, Iab={Homothin interval}, n={infinite}, theta=45, direction="clockwise")

Image transformation by conditional thinning.

cthin creates the binary image y by performing a thinning of the binary image f conditioned to the binary image g. The number of iterations of the conditional thinning is n and in each iteration the thinning is characterized by rotations of theta of the interval Iab.

Parameters :

f : Binary image.

g : Binary image.

Iab : Interval (default: homothin()).

n : Number of iterations, -1 for infinite (default: -1)

theta : Degrees of rotation, 45 (default), 90, or 180.

direction: ‘clockwise’ or ‘anti-clockwise’. :

Returns :

y : Binary image.

pymorph.cwatershed(f, g, Bc=None, return_lines=False) R, L = cwatershed(f, g, Bc=None, return_lines=True)

Detection of watershed from markers.

cwatershed creates the image R by detecting the domain of the catchment basins of f indicated by the marker image g, according to the connectivity defined by Bc.

If return_lines, L will be a labeled image of the catchment basins domain or just a binary image that presents the watershed lines. To know more about watershed and watershed from markers, see BeucMeye:93. The implementation of this function is based on LotuFalc:00.

WARNING: There is a common mistake related to the marker image g. If this image contains only zeros and ones, but it is not a binary image, the result will be an image with all ones. If the marker image is binary, you have to set this explicitly (e.g., cwatershed(f,g>0) or cwatershed(f,g.astype(bool)))

Parameters :

f : Gray-scale (uint8 or uint16) image.

markers : Gray-scale (uint8 or uint16) or binary image. marker

image: binary or labeled.

Bc : Watershed connectivity (default: 3x3 cross)

return_lines : Whether to return lines as well as regions (default: False)

Returns :

R : Gray-scale (uint8 or uint16) or binary image.

L : Binary line image

See also

mahotas.cwatershed
implementation of same interface in C++
pymorph.dilate(f, B={3x3 cross})

Dilate an image by a structuring element.

dilate performs the dilation of image f by the structuring element B. Dilation is a neighbourhood operator that compares locally B with f, according to an intersection rule. Since Dilation is a fundamental operator to the construction of all other morphological operators, it is also called an elementary operator of Mathematical Morphology. When f is a gray-scale image, B may be a flat or non-flat structuring element.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

B : Structuring element (default: 3x3 cross).

Returns :

y: Same type as `f` :

pymorph.drawv(f, data, value, geometry)

Superpose points, rectangles and lines on an image.

drawv creates the image y by a superposition of points, rectangles and lines of gray-level value on the image f. The parameters for each geometrical primitive are defined by each line in the data parameter. For points, they are represented by 2-D coordinates. For lines, they are drawn with the same convention used by points, with a straight line connecting them in the order given by the data matrix. For rectangles and filled rectangles, data should be an array of 2 x 2D points.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

data : Vector of coordinates.

value : Gray value(s) for drawing.

If it’s a single value, then it will be used for all objects, otherwise, it should be an array of same length as data.

geometry : { ‘point’, ‘line’, ‘rect’, ‘frect’ (filled rectangles)}

Returns :

y : Image of same type as f

pymorph.endpoints(option="loop")

Interval to detect end-points.

endpoints creates an interval that is useful to detect end-points of curves (i.e., one pixel thick connected components) in binary images. It can be used to prune skeletons and to mark objects transforming them in a single pixel or closed loops if they have holes. There are two options available: ‘loop’, deletes all points but preserves loops if used in thin ; ‘homotopic’, deletes all points but preserves the last single point or loops.

Parameters :

option : {‘loop’ [default], ‘homotopic’}

type of interval

Returns :

Iab : Interval

pymorph.erode(f, b={3x3 cross})

Erode an image by a structuring element.

erode performs the erosion of the image f by the structuring element b. Erosion is a neighbourhood operator that compairs locally b with f, according to an inclusion rule. Since erosion is a fundamental operator to the construction of all other morphological operators, it is called an elementary operator of Mathematical Morphology. When f is a gray-scale image, b may be a flat or non-flat structuring element.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

b : Structuring element (Default: 3x3 elementary cross).

Returns :

y : Image

See also

mahotas.erode
implementation of binary erosion
scipy.ndimage.grey_erosion
implementation of grey erosion
pymorph.gdist(f, g, Bc=None, metric=None)

Geodesic Distance Transform.

gdist creates the geodesic distance image y of the binary image f relative to the binary image g. The value of y at the pixel x is the length of the smallest path between x and f. The distances available are based on the Euclidean metrics and on metrics generated by a neighbourhood graph, that is characterized by a connectivity rule defined by the structuring element Bc. The connectivity for defining the paths is consistent with the metrics adopted to measure their length. In the case of the Euclidean distance, the space is considered continuos and, in the other cases, the connectivity is the one defined by Bc.

Parameters :

f : Binary image.

g : Binary image. Marker image

Bc : Structuring Element Default: None (3x3 elementary

cross). (metric for distance).

metric: string default: none. ‘euclidean’ if specified. :

Returns :

y : uint16 (distance image).

pymorph.gradm(f, Bdil={3x3 cross}, Bero={3x3 cross})

Morphological gradient.

gradm creates the image y by the subtraction of the erosion of the image f by Bero of the dilation of f by Bdil.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

Bdil : Structuring element for dilation (default: 3x3 cross).

Bero : Structuring element for erosion (default: 3x3 cross).

Returns :

y : Image of same type as f.

pymorph.grain(f, labels, measurement, option="image")

Gray-scale statistics for each labeled region.

Computes gray-scale statistics of each grain in the image. The grains regions are specified by the labeled image labels and the gray-scale information is specified by the image f. The statistics to compute is specified by the parameter measurement, which has the same options as in function stats. The parameter option defines the output format:

‘image’
if the output is an uint16 image where each label value is changed to the measurement value
‘data’
a double column vector. In this case, the first element (index 0) is the measurement of region 1. The region with label zero is not measure as it is normally the background.
Parameters :

f : ndarray (gray-scale)

labels : ndarray of integer dtype

Labeled image. As usual, label 0 is backaground.

measurement : {‘max’, ‘min’, ‘median’, ‘mean’, ‘sum’, ‘std’, ‘std1’ }

Which measure to compute.

option : {‘image’ [default], ‘data’ }

Output format: if ‘image’, results as a gray-scale mosaic image (default): if ‘data’, results a column vector of measurements.

Returns :

y: Gray-scale (uint8 or uint16) image. :

Or an array with gray-scale statistics per region

pymorph.gray(f, dtype="uint8", k=None)

Convert a binary image into a gray-scale image.

gray converts a binary image into a gray-scale image of a specified data type. The value k is assigned to the 1 pixels of f, while the 0 pixels are assigned to the minimum value associated to the specified data type.

Parameters :

f : Binary image.

dtype : { ‘uint8’ [default], ‘uint16’, ‘int32’ }

k : scalar, optional

Pixel value to assign to True pixels (default: max value for dtype).

Returns :

y : Unsigned gray-scale (uint8 or uint16), signed (int32) or binary image.

pymorph.hmin(f, h=1, Bc={3x3 cross})

Remove basins with contrast less than h.

hmin sup-reconstructs the gray-scale image f from the marker created by the addition of the positive integer value h to f, using the connectivity Bc. This operator removes connected basins with contrast less than h. This function is very useful for simplifying the basins of the image.

Parameters :

f : Gray-scale (uint8 or uint16) image.

h : Contrast (default: 1).

Bc : Connectivity structuring element (default: 3x3 cross).

Returns :

y : Gray-scale (uint8 or uint16) or binary image.

pymorph.hmax(f, h=1, Bc=None)

Remove peaks with contrast less than h.

y = hmax(f, h=1, Bc={3x3 cross})

hmax inf-reconstructs the gray-scale image f from the marker created by the subtraction of the positive integer value h from f, using connectivity Bc. This operator removes connected peaks with contrast less than h.

Parameters :

f : Gray-scale (uint8 or uint16) image.

h : Contrast (default: 1).

Bc : Connectivity structuring element (default: 3x3 cross).

Returns :

y : Gray-scale (uint8 or uint16) or binary image.

pymorph.homothick()

Interval for homotopic thickening.

homothick creates an interval that is useful for the homotopic (i.e., that conserves the relation between objects and holes) thickening of binary images.

Returns :Iab: Interval :
pymorph.homothin()

Interval for homotopic thinning.

homothin creates an interval that is useful for the homotopic (i.e., that conserves the relation between objects and holes) thinning of binary images.

Returns :Iab : Interval
pymorph.img2se(fd, flat=True, f=None)

Create a structuring element from a pair of images.

img2se creates a flat structuring element B from the binary image fd or creates a non-flat structuring element B from the binary image fd and the gray-scale image f. fd represents the domain of B and f represents the image of the points in fd.

Parameters :

fd : Binary image.

The image is in the matrix format where the origin (0,0) is at the matrix center.

flat : boolean, optional

Whether to return a flat structuring element (default: True)

f : ndarray of type (uint8 or uint16, int32, or bool), optional

Returns :

B : Structuring Element

pymorph.infcanon(f, Iab, theta=45, direction='clockwise')

Intersection of inf-generating operators.

infcanon creates the image y by computing intersections of transformations of the image f by inf-generating (i.e., dual of the hit-or-miss) operators. These inf-generating operators are characterized by rotations (in the clockwise or anti-clockwise direction) of theta degrees of the interval Iab.

Parameters :

f : Binary image.

Iab : Interval

theta : Degrees of rotation (default: 45)

direction : { ‘clockwise’ [default], ‘anti-clockwise’ }

Returns :

y : Binary image.

pymorph.infgen(f, Iab)

Inf-generating.

infgen creates the image y by computing the transformation of the image f by the inf-generating operator (or dual of the hit-or-miss) characterized by the interval Iab.

Parameters :

f : Binary image.

Iab : Interval

Returns :

y: Binary image. :

pymorph.infrec(f, g, Bc={3x3 cross})

Inf-reconstruction.

infrec creates the image y by an infinite number of recursive iterations (iterations until stability) of the dilation of f by Bc conditioned to g. We say the y is the inf-reconstruction of g from the marker f. For algorithms and applications, see Vinc:93b.

Parameters :

f : Marker image (gray or binary).

g : Conditioning image (gray or binary).

Bc : Connectivity Structuring element (default: 3x3 cross).

Returns :

y : Image

pymorph.inpos(f, g, Bc={3x3 cross})

Minima imposition.

Minima imposition on g based on the marker f. inpos creates an image y by filing the valleys of g that do not cover the connect components of f. A remarkable property of y is that its regional minima are exactly the connect components of g.

Parameters :

f : Binary image. Marker image.

g : Gray-scale (uint8 or uint16) image. input image.

Bc : connectivity structuring element (default: 3x3 cross).

Returns :

y : Gray-scale (uint8 or uint16) image.

pymorph.interot(Iab, theta=45, direction="clockwise")

Rotate an interval

interot rotates the interval Iab by theta.

Parameters :

Iab : Interval

theta : Degrees of rotation. Should be a multiple of 45 degrees. If not,

the rotation is approximate (default: 45).

direction : { ‘clockwise’ [default], ‘anti-clockwise’ }

Returns :

Irot : Interval

Examples

b1 = endpoints()
b2 = interot(b1)
print intershow(b1)
print intershow(b2)
pymorph.intersec(f1, f2, f3=None, f4=None, f5=None)

Intersection of images.

intersec creates the image y by taking the pixelwise minimum between the images f1, f2, f3, f4, and f5 . When f1, f2, f3, f4, and f5 are binary images, y is the intersection of them.

Parameters :

f1 : Image (gray or binary) or constant.

f2 : Image (gray or binary) or constant.

f3 : Image (gray or binary) or constant, optional.

f4 : Image (gray or binary) or constant, optional.

f5 : Image (gray or binary) or constant, optional.

Returns :

y : Image

pymorph.intershow(Iab)

Visualize an interval.

intershow creates a representation for an interval using 0, 1 and . (don’t care).

Parameters :Iab : Interval
Returns :s : string representation of the interval.

Examples

print intershow(homothick())

prints out

0 0 0
. 0 .
0 0 0
pymorph.isbinary(f)

Check for binary image

isbinary returns True if the datatype of the input image is binary. A binary image has just the values 0 and 1.

Parameters :

f : Image

Returns :

is_b : bool

Whether f is a binary image

pymorph.asbinary(f)

Transforms f into a binary image

Parameters :f : image of any type, consisting only of 0s and 1s.
Returns :fbin : binary image
pymorph.isequal(f1, f2)

Check if two images are equal

isequal compares the images f1 and f2 and returns True, if f1 and `f2 have the same size and f1(x) == f2(x), for all pixel x; otherwise, returns False.

Parameters :

f1 : Unsigned gray-scale (uint8 or uint16), signed (int32) or binary image.

f2 : Unsigned gray-scale (uint8 or uint16), signed (int32) or binary image.

Returns :

r_eq : Boolean

Whether the two images are equal

pymorph.labelflat(f, Bc=None, lambda_=0)

Label the flat zones of gray-scale images.

labelflat creates the image y by labeling the flat zones of f, according to the connectivity defined by the structuring element Bc. A flat zone is a connected region of the image domain in which all the pixels have the same gray-level (lambda=0). When lambda is different than zero, a quasi-flat zone is detected where two neighboring pixels belong to the same region if their difference gray-levels is smaller or equal lambda. The minimum label of the output image is 1 and the maximum is the number of flat-zones in the image.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

Bc : Structuring element, optional

Connectivity (efault: 3x3 elementary cross).

lambda_ : Default: 0. Connectivity given by |f(q)-f(p)|<=lambda_.

Returns :

y: ndarray of same shape as `f` :

If number of labels is less than 65535, the data type is uint16; otherwise, it is int32.

pymorph.lastero(f, B=None)

Last erosion.

y = lastero(f, B=None)

lastero creates the image y by computing the last erosion by the structuring element B of the image f . The objects found in y are the objects of the erosion by nB that can not be reconstructed from the erosion by (n+1)B , where n is a generic non negative integer. The image y is a proper subset of the morphological skeleton by B of f .

Parameters :

f : Binary image.

B : Structuring Element (default: 3x3 elementary cross).

Returns :

y : Binary image.

pymorph.open(f, b={3x3 cross})

Morphological opening.

open creates the image y by the morphological opening of the image f by the structuring element b. In the binary case, the opening by the structuring element b 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 :

f : Gray-scale (uint8 or uint16) or binary image.

b : Structuring element (default: 3x3 elementary cross).

Returns :

y : Image

pymorph.openrec(f, Bero={3x3 cross}, Bc={3x3 cross})

Opening by reconstruction.

openrec creates the image y by an inf-reconstruction of the image f from its erosion by bero, using the connectivity defined by Bc.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

Bero : Eroding structuring element (default: 3x3 cross).

Bc : Connecting structuring element (default: 3x3 cross).

Returns :

y : Image (same type as f).

pymorph.openrecth(f, Bero={3x3 cross}, Bc={3x3 cross})

Open-by-Reconstruction Top-Hat.

openrecth creates the image y by subtracting the open by reconstruction of f, defined by the structuring elements Bero and Bc, of f itself.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

Bero : Erosion structuring element (default: 3x3 cross).

Bc : Connectivity structuring element (default: 3x3 cross).

Returns :

y : Image of same type as f.

pymorph.openth(f, b={3x3 cross})

Opening Top Hat.

openth creates the image y by subtracting the morphological opening of f by the structuring element b of f itself.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

b : Structuring element (default: 3x3 cross).

Returns :

y : Image of same type as f.

pymorph.opentransf(f, type='octagon', n=65535, Bc={3x3 cross}, Buser={3x3 cross})

Open transform.

Compute the open transform of a binary image. The value of the pixels in the open transform is radius of the smallest disk, which if used to open, nullifies that pixel.

The disk sequence must satisfy the following: if r > s, then rB is sB-open, i.e. open(rB,sB) == rB. Note that the Euclidean disk does not satisfy this property in the discrete grid. This function also computes the reconstructive open transform by adding the suffix ‘-rec’ in the ‘type’ parameter.

Parameters :

f : binary image.

type : { ‘octagon’ [default], ‘chessboard’, ‘citi-block’, ‘linear-h’, ‘linear-v’, ‘linear-45r’, ‘user’ }

disk family.

n : integer, optional

Maximum disk radius (default: 65535).

Bc : Structuring element, optional

Connectivity for the reconstructive opening. Used if ‘-rec’ suffix is appended in the ‘type’ string. default: 3x3 cross

Buser : structure element, optional

user disk, used if ‘type’ is ‘user’.

Returns :

y : Gray-scale (uint16) image.

pymorph.patspec(f, type='octagon', n=65535, Bc={3x3 cross}, Buser=None)

Pattern spectrum (also known as granulometric size density).

Compute the Pattern Spectrum of a binary image. See Mara:89b . The pattern spectrum is the histogram of the open transform, not taking the zero values.

Parameters :

f : Binary image.

type : { ‘octagon’ [default], ‘chessboard’, ‘citi-block’, ‘linear-h’, ‘linear-v’, ‘linear-45r’, ‘user’ }

disk family.

n : integer, optional

Maximum disk radius (default: 65535).

Bc : Structuring element, optional

Connectivity for the reconstructive granulometry. Used if ‘-rec’ suffix is appended in the ‘type’ string. default: 3x3 cross

Buser : structure element, optional

user disk, used if ‘type’ is ‘user’.

Returns :

h : ndarray

pymorph.regmax(f, Bc={3x3 cross})

Regional Maximum.

regmax creates a binary image y by computing the regional maxima of f, according to the connectivity defined by the structuring element Bc. A regional maximum is a flat zone not surrounded by flat zones of higher gray values.

Parameters :

f : Gray-scale image.

Bc : Connectivity structuring element (default: 3x3 cross).

Returns :

y : Binary image.

pymorph.regmin(f, Bc=None, option="binary")

Regional Minimum (with generalized dynamics).

regmin creates a binary image by computing the regional minima of f, according to the connectivity defined by the structuring element Bc.

A regional minimum is a flat zone not surrounded by flat zones of lower gray values. A flat zone is a maximal connected component of a gray-scale image with same pixel values.

Parameters :

f : Gray-scale (uint8 or uint16) image.

Bc : Connectivity structuring element (default: 3x3 cross).

option : ‘binary’

if ‘binary’, outputs a binary image. Currently, it must be set to ‘binary’. Fortunately, that’s the default.

Returns :

y : Gray-scale (uint8 or uint16) or binary image.

pymorph.se2interval(a, b)

Create an interval from a pair of structuring elements.

se2interval creates the interval [a,b] from the structuring elements a and b such that a is less or equal b.

Parameters :

a : Structuring element left extremity

b : Structuring element right extremity

Returns :

Iab : Interval

pymorph.se2hmt(A, Bc)

Create a Hit-or-Miss Template (or interval) from a pair of structuring elements.

se2hmt creates the Hit-or-Miss Template (HMT), also called interval [A,Bc] from the structuring elements A and Bc such that A is included in the complement of Bc . The only difference between this function and se2interval is that here the second structuring element is the complement of the one used in the other function. The advantage of this function over se2interval is that this one is more flexible in the use of the structuring elements as they are not required to have the same size.

Parameters :

A : Structuring Element Left extremity.

Bc : Structuring Element Complement of the right extremity.

Returns :

Iab : Interval

pymorph.se2flatidx(f, Bc)

Transforms the Bc structuring element into an array of indices so that f.flat[Bi[i]] corresponds to the i-th element where Bc is true

Equivalent of:

g = zeros(f.shape)
h,w=Bc.shape
g[:h,:w]=Bc
Bi, = where(g.ravel())

This is useful for implementing many functions. See the implementation of label() for an example.

Parameters :

f : image

Bc : structuring element

Returns :

Bi : array of indice offsets.

pymorph.sebox(r=1)

Create a box structuring element.

sebox creates the structuring element B formed by r successive Minkowski additions of the elementary square (i.e., the 3x3 square centered at the origin) with itself. If R=0, B is the unitary set that contains the origin. If R=1, B is the elementary square itself.

Parameters :

r : integer, optional

size of box (default: 1)

Returns :

B : Structuring Element

pymorph.secross(r=1)

Diamond structuring element and elementary 3x3 cross.

secross creates the structuring element B formed by r successive Minkowski additions of the elementary cross (i.e., the 3x3 cross centered at the origin) with itself. If r=0, B is the unitary set that contains the origin. If r=1 (the default), B is the elementary cross itself.

Parameters :

r : integer, optional

radius (default: 1)

Returns :

B : Structuring Element

pymorph.sedisk(r=3, dim=2, metric="euclidean", flat=True, h=0)

Create a disk or a semi-sphere structuring element.

sedisk creates a flat structuring element B that is disk under the metric metric , centered at the origin and with radius r or a non-flat structuring element that is a semi-sphere under the metric metric, centered at (0, h) and with radius r . this structuring element can be created on the 1D, 2D or 3D space.

Parameters :

r : Non-negative integer. Disk radius (default: 3)

dim : {1, 2 [default], 3}

dimension

metric : {‘euclidean’ [default], ‘city-block’, ‘octagon’, ‘chessboard’ }

flat : boolean, optional

default: True

h : double, optional

elevation of the center of the semi-sphere (default: 0).

Returns :

B : Structuring Element

pymorph.seline(length=3, theta=0)

Create a line structuring element.

seline creates a structuring element B that is a line segment that has an extremity at the origin, length length and angle theta (0 degrees is east direction, clockwise). If length==0 , it generates the origin.

Note that length is simply the number of on-pixels. Therefore, in diagonal directions it is off by a factor of sqrt{2}.

Parameters :

length : Length of line (default: 3)

theta : Degrees, clockwise (default: 0, i.e. east)

Returns :

B : Structuring Element

Examples

>>> import pymorph
>>> pymorph.seline(2)
array([[0],
       [1],
       [1]], dtype=uint8)
>>> pymorph.seline(4)
array([[0],
       [0],
       [0],
       [1],
       [1],
       [1],
       [1]], dtype=uint8)
>>> pymorph.seline(3,45)
array([[0, 0, 0],
       [0, 1, 1],
       [0, 0, 1]], dtype=uint8)
pymorph.serot(b, theta=45, direction="clockwise")

Rotate a structuring element. serot rotates structuring element b by theta degrees.

Parameters :

B : Structuring Element

theta : Degrees of rotation. Should be a multiple of 45 degrees. If not,

the rotation is approximate (default: 45).

direction : { ‘clockwise’ [default], ‘anti-clockwise’ }

Returns :

brot : structuring element

pymorph.seshow(b, option="NORMAL")

Display a structuring element as an image.

seshow used with the option ‘expand’ generates an image y that is a suitable graphical representation of the structuring element b. This function is useful to convert a structuring element to an image. The origin of the structuring element is at the center of the image. If b is flat, y is binary, otherwise, y is signed int32 image. When using the option ‘non-flat’, the output `y is always a signed int32 image.

Parameters :

b : Structuring element

option : { ‘normal’ [default], ‘expand’, ‘non-flat’ }

Mode

Returns :

y : Gray-scale (uint8 or uint16) or binary image.

pymorph.sesum(B=None, N=1)

N-1 iterative Minkowski additions

sesum creates the structuring element Bn from N - 1 iterative Minkowski additions with the structuring element B.

Parameters :

B : Structuring element (Default: 3x3 elementary cross).

N : Non-negative integer. Default: 1.

Returns :

Bn : Structuring Element

pymorph.setrans(Bi, t)

Translate a structuring element

setrans translates a structuring element by a specific value.

Parameters :

Bi : Structuring Element

t : translation amount

Returns :

Bo : Structuring element of same type as Bi

pymorph.sereflect(Bi)

Reflect a structuring element

sereflect reflects a structuring element about the origin

Parameters :Bi : Structuring Element
Returns :Bo : Structuring element of same type as Bi
pymorph.sedilate(B1, B2)

Dilate one structuring element by another

sedilate dilates an structuring element by another. The main difference between this dilation and dilate is that the dilation between structuring elements are not bounded, returning another structuring element usually larger than anyone of them. This gives the composition of the two structuring elements by Minkowski addition.

Parameters :

B1 : Structuring Element

B2 : Structuring Element

Returns :

Bo: Structuring Element :

pymorph.seunion(B1, B2)

Union of structuring elements

seunion creates a structuring element from the union of two structuring elements.

Parameters :

B1 : Structuring element

B2 : Structuring element

Returns :

B : structure element

union of B1 and B2

pymorph.skelm(f, B={3x3 cross}, return_binary=True)

Morphological skeleton (Medial Axis Transform).

skelm creates the image y by computing the morphological skeleton by B of the image f. In this case, the pixels of value 1 in y are center of maximal balls (generated from B ) included in f. This is also called Medial Axis. If return_binary is False, the non zeros pixels in y are the radius plus 1 of the maximal balls. This is called Medial Axis Transform or valued morphological skeleton.

Parameters :

f : Binary image.

B : Structuring Element Default: None (3x3 elementary

cross).

return_binary : boolean, optional

Whether to return a binary image of the medial axis (the default) or a greyscale a binary image (medial axis); value: output a grayscale image with values of the radius of the disk to reconstruct the original image (medial axis transform).

Returns :

y : Gray-scale (uint8 or uint16) or binary image.

pymorph.skelmrec(f, B={3x3 cross})

Morphological skeleton reconstruction (inverse medial axis transform).

skelmrec reconstructs the valued morphological skeleton to recover the original image.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

B : Structuring element (default: 3x3 cross).

Returns :

y : Binary image.

pymorph.skiz(f, Bc={3x3 cross}, return_lines=False, metric=None) labeled, lines = skiz(f, Bc={3x3 cross}, return_lines=True, metric=None)

Skeleton of Influence Zone - also know as Generalized Voronoi Diagram

skiz creates the labeled image by detecting the lines which are equidistant to two or more connected components of f, according to the connectivity defined by Bc.

labeled will be a labeled image, while lines will be a binary image of the lines between the regions Depending on with the flag

When the connected objects of f are single points, the skiz is the Voronoi diagram.

Parameters :

f : Binary image.

Bc : Structuring Element (default: 3x3 cross).

Connectivity for the distance measurement.

return_lines : boolean, optional

Whether to return the lines separating regions in the image. Default: False

metric : str, optional

default: ‘euclidean’

Returns :

y : Gray-scale (uint8 or uint16) image.

lines : binary image.

only returned if return_lines is True

pymorph.subm(f1, f2)

Subtraction of two images, with saturation.

subm creates the image y by pixelwise subtraction of the image f2 from the image f1. When the subtraction of the values of two pixels is negative, 0 is taken as the result of the subtraction. When f1 and f2 are binary images, y represents the set subtraction of f2 from f1.

Parameters :

f1 : Unsigned gray-scale (uint8 or uint16), signed (int32) or binary image.

f2 : Unsigned gray-scale (uint8 or uint16), signed (int32) or binary image. Or constant.

Returns :

y : ndarray of same shape and dtype as f1

Examples

f = to_uint8([255,   255,    0,   10,   20,   10,    0,   255,  255])
g = to_uint8([10,     20,   30,   40,   50,   40,   30,    20,    10])
print subm(f, g)
print subm(f, 100)
print subm(100, f)
a = readgray('boxdrill-C.tif')
b = readgray('boxdrill-B.tif')
c = subm(a,b)
show(a)
show(b)
show(c)
pymorph.supcanon(f, Iab, theta=45, direction="clockwise")

Union of sup-generating or hit-miss operators.

supcanon creates the image y by computing the union of transformations of the image f by sup-generating operators. These hit-miss operators are characterized by rotations (in the clockwise or anti-clockwise direction) of theta degrees of the interval Iab.

Parameters :

f : Binary image.

Iab : Interval

theta : {45 [default], 90, 180 }

Angle of rotation in degrees.

direction : {‘clockwise’ [default], ‘anti-clockwise’}

Direction of rotation

Returns :

—— :

y : Binary image.

pymorph.supgen(f, interval)

Sup-generating (hit-miss).

supgen creates the binary image y by computing the transformation of the image f by the sup-generating operator characterized by the interval Iab. The sup-generating operator is just a relaxed template matching, where the criterion to keep a shape is that it be inside the interval Iab. Note that we have the classical template matching when a==b. Note also that the sup-generating operator is equivalent to the classical hit-miss operator.

Parameters :

f : Binary image.

interval : Interval

Returns :

y : Binary image.

pymorph.suprec(f, g, Bc={3x3 cross})

Sup-reconstruction.

suprec creates the image y by an infinite number of iterations (until stability) of the erosion of f by Bc conditioned to g. We say that y is the sup-reconstruction of g from the marker f.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

Marker image.

g : Gray-scale (uint8 or uint16) or binary image.

Conditioning image.

Bc : Connectivity structuring element (default: 3x3 cross)

Returns :

y : Image

pymorph.bshow(f1, f2=None, f3=None, factor=17)

Generate a graphical representation of overlaid binary images. Does not actually display the image anywhere!

Generate an expanded binary image as a graphical representation of up to three binary input images. The 1-pixels of the first image are represented by square contours, the pixels of the optional second image are represented by circles and for the third image they are represented by shaded squares. This function is useful to create graphical illustration of small images.

Parameters :

f1 : Binary image.

f2 : Binary image. Default: None.

f3 : Binary image. Default: None.

factor : Double Default: 17. Expansion factor for the output

image. Use odd values above 9.

Returns :

y : Binary image.

pymorph.symdiff(f1, f2)

Symmetric difference between two images

symdiff creates the image y by taken the union of the subtractions of f1 from f2 and f2 from f1. When f1 and f2 are binary images, y represents the set of points that are in f1 and not in f2 or that are in f2 and not in f1.

Parameters :

f1 : Gray-scale (uint8 or uint16) or binary image.

f2 : Gray-scale (uint8 or uint16) or binary image.

Returns :

y : Image

pymorph.thick(f, Iab=None, n=-1, theta=45, direction="clockwise")

Image transformation by thickening.

thick creates the binary image y by performing a thickening of the binary image f. The number of iterations of the thickening is n and each iteration is performed by union of f with the points that are detected in f by the hit-miss operators characterized by rotations of theta degrees of the interval Iab.

Parameters :

f : Binary image.

Iab : Interval Default: None (homothick).

n : Number of iterations. Default: -1, i.e., infinite

theta : Degrees of rotation: 45 (default), 90, or 180.

direction : One of (‘clockwise’, ‘anti-clockwise’).

Returns :

y : Binary image.

pymorph.thin(f, Iab={Homothin}, n={infinite}, theta=45, direction="clockwise")

Image transformation by thinning.

thin creates the binary image y by performing a thinning of the binary image f. The number of iterations of the thinning is n and each iteration is performed by subtracting the points that are detect in f by hit-miss operators characterized by rotations of theta of the interval Iab. When n is infinite and the interval is homothin (default conditions), thin gives the skeleton by thinning.

Parameters :

f : Binary image.

Iab : Interval Default:(homothin).

n : Number of iterations. (default: -1, i.e. infinite)

theta : Double Default: 45. Degrees of rotation: 45, 90, or

direction : One of (‘clockwise’, ‘anti-clockwise’). default: clockwise.

Returns :

y : Binary image.

pymorph.union(f1, f2, f3=None, f4=None, f5=None, ...)

Union of images.

union creates the image y by taking the pixelwise maximum between the images given. When the images are binary images, y represents the union of them.

Parameters :

f1 : Gray-scale (uint8 or uint16) or binary image.

f2 : Gray-scale (uint8 or uint16) or binary image. Or constant

args : Gray-scale (uint8 or uint16) or binary images.

Returns :

y : Image

pymorph.watershed(f, Bc={3x3 cross}, return_lines=False) W, Wl = watershed(f, Bc={3x3 cross}, return_lines=True)

Watershed transform.

watershed creates the image y by detecting the domain of the catchment basins of f, according to the connectivity defined by Bc.

The implementation of this function is based on VincSoil:91.

Parameters :

f : Gray-scale (uint8 or uint16) or binary image.

return_lines : boolean

Whether to return the boundaries (default: False)

Returns :

W : labeled image

Wl : separation lines

pymorph.maxleveltype(type='uint8')

Returns the maximum value supported by a datatype

Parameters :

type : { ‘uint8’ [default], ‘uint16’, ‘int32’}

Returns :

max : numeric value

The maximum level value of type

pymorph.to_int32(f)

Convert an image to an int32 image.

img = to_int32(f)

to_int32 clips the input image between the values -2147483648 and 2147483647 and converts it to the signed 32-bit datatype.

Parameters :f : Any image
Returns :img : The converted image
pymorph.to_uint8(f)

Convert an image to an uint8 image.

to_uint8 clips the input image between the values 0 and 255 and converts it to the unsigned 8-bit datatype.

Parameters :f : Any image
Returns :img : Gray-scale uint8 image. The converted image

Examples

print to_uint8([-3, 0, 8, 600])

prints out

[  0   0   8 255]
pymorph.to_uint16(f)

Convert an image to a uint16 image.

to_uint16 clips the input image between the values 0 and 65535 and converts it to the unsigned 16-bit datatype.

Parameters :f : Any image
Returns :img : The converted image
pymorph.to_gray(f)

Transform (possibly colour) image to gray image.

If input file is a color RGB image, it is converted to gray-scale using the equation:

I = 0.2989 * R + 0.587 * G + 0.114 * B
Parameters :

f : ndarray of shape HxWx3

colour image.

Returns :

g : gray image of shape HxW same type as input

pymorph.datatype(f)

Return the image datatype string

datatype returns a string that identifies the pixel datatype of the image f.

Consider using f.dtype.

Parameters :

f : Unsigned gray-scale (uint8 or uint16), signed (int32) or binary image

Any image

Returns :

type : str

String representation of image type: ‘binary’, ‘uint8’, ‘uint16’ or ‘int32’

pymorph.add4dilate(f, c)

Addition for dilation. Assumes that the minimum value of dtype(f) is to represent -inf (where -inf + c == -inf, for all c)

Parameters :

f : Gray-scale or binary image.

c : Gray-scale, binary image, or constant.

Returns :

a : f + c (but with correct implementation of -inf)

pymorph.mat2set(A)

Converts image representation from matrix to set

Return tuple with array of pixel coordinates and array of corresponding pixel values. The input image is in the matrix format, like the structuring element, where the origin (0,0) is at the center of the matrix.

Parameters :

A : ndarray

Image in matrix format, where the origin (0,0) is at the center of the matrix.

Returns :

C : array of pixel coordinates

V : array of pixel values corresponding to the coordinates of C

See also

set2mat
reverse function
pymorph.set2mat(A)

Converts image representation from set to matrix

Return an image in the matrix format built from a tuple of an array of pixel coordinates and a corresponding array of pixel values

Parameters :

A : tuple (ndarray, ndarray) or tuple (ndarray,)

Tuple with array of pixel coordinates and optional array of corresponding pixel values

Returns :

M : Image in matrix format, origin (0,0) at the matrix center

Examples

coords = to_int32([ [0,0] , [-1,0] , [1,1]])
print set2mat( (coords,) )

prints out

[0,1,0]
[0,1,0]
[0,0,1]
pymorph.pad4n(f, Bc, value, scale=1)

pads f with value so that Bc can be applied scaled by scale.

Parameters :

f : Image

Bc : Structuring Element (connectivity).

value : dtype

value to pad borders with

scale : (default=1).

Returns :

y : The converted image

pymorph.text(txt)

Create a binary image of a text.

text creates the binary image y of the text txt . The background of y is 0, while its foreground is 1. The text should be composed only by lower and upper case letters.

Parameters :txt : Text as a string
Returns :y : Binary image.

Table Of Contents

Next topic

Basics

This Page