filters¶
Highlight Features of Interest
This module contains a variety of functions for altering images based on the structural characteristics, such as pore sizes. A definition of a filter is a function that returns an image the shape as the original image, but with altered values.
porespy.filters.apply_chords (im[, spacing, …]) 
Adds chords to the void space in the specified direction. 
porespy.filters.apply_chords_3D (im[, …]) 
Adds chords to the void space in all three principle directions. 
porespy.filters.distance_transform_lin (im[, …]) 
Replaces each void voxel with the linear distance to the nearest solid voxel along the specified axis. 
porespy.filters.fill_blind_pores (im) 
Fills all pores that are not connected to the edges of the image. 
porespy.filters.find_disconnected_voxels (im) 
This identifies all pore (or solid) voxels that are not connected to the edge of the image. 
porespy.filters.find_dt_artifacts (dt) 
Finds points in a distance transform that are closer to wall than solid. 
porespy.filters.find_peaks (dt[, r_max, …]) 
Returns all local maxima in the distance transform 
porespy.filters.flood 
Floods/fills each region in an image with a single value based on the specific values in that region. 
porespy.filters.local_thickness (im[, sizes, …]) 
For each voxel, this functions calculates the radius of the largest sphere that both engulfs the voxel and fits entirely within the foreground. 
porespy.filters.porosimetry (im[, sizes, …]) 
Performs a porosimetry simulution on the image 
porespy.filters.region_size (im) 
Replace each voxel with size of region to which it belongs 
porespy.filters.snow_partitioning (im[, dt, …]) 
Partitions the void space into pore regions using a markerbased watershed algorithm, with specially filtered peaks as markers. 
porespy.filters.trim_disconnected_blobs (im, …) 
Removes foreground voxels not connected to specified inlets 
porespy.filters.trim_extrema (im, h[, mode]) 
Trims local extrema in greyscale values by a specified amount. 
porespy.filters.trim_floating_solid (im) 
Removes all solid that that is not attached to the edges of the image. 
porespy.filters.trim_nearby_peaks (peaks, dt) 
Finds pairs of peaks that are nearer to each other than to the solid phase, and removes the peak that is closer to the solid. 
porespy.filters.trim_nonpercolating_paths (im) 
Removes all nonpercolating paths between specified edges 
porespy.filters.trim_saddle_points (peaks, dt) 
Removes peaks that were mistakenly identified because they lied on a saddle or ridge in the distance transform that was not actually a true local peak. 

porespy.filters.
apply_chords
(im, spacing=1, axis=0, trim_edges=True, label=False)[source]¶ Adds chords to the void space in the specified direction. The chords are separated by 1 voxel plus the provided spacing.
Parameters:  im (NDarray) – An image of the porous material with void marked as
True
.  spacing (int) – Separation between chords. The default is 1 voxel. This can be
decreased to 0, meaning that the chords all touch each other, which
automatically sets to the
label
argument toTrue
.  axis (int (default = 0)) – The axis along which the chords are drawn.
 trim_edges (bool (default =
True
)) – Whether or not to remove chords that touch the edges of the image. These chords are artifically shortened, so skew the chord length distribution.  label (bool (default is
False
)) – IfTrue
the chords in the returned image are each given a unique label, such that all voxels lying on the same chord have the same value. This is automatically set toTrue
if spacing is 0, but isFalse
otherwise.
Returns: image – A copy of
im
with nonzero values indicating the chords.Return type: NDarray
See also
 im (NDarray) – An image of the porous material with void marked as

porespy.filters.
apply_chords_3D
(im, spacing=0, trim_edges=True)[source]¶ Adds chords to the void space in all three principle directions. The chords are seprated by 1 voxel plus the provided spacing. Chords in the X, Y and Z directions are labelled 1, 2 and 3 resepctively.
Parameters:  im (NDarray) – A 3D image of the porous material with void space marked as True.
 spacing (int (default = 0)) – Chords are automatically separed by 1 voxel on all sides, and this argument increases the separation.
 trim_edges (bool (default is
True
)) – Whether or not to remove chords that touch the edges of the image. These chords are artifically shortened, so skew the chord length distribution
Returns: image – A copy of
im
with values of 1 indicating xdirection chords, 2 indicating ydirection chords, and 3 indicating zdirection chords.Return type: NDarray
Notes
The chords are separated by a spacing of at least 1 voxel so that tools that search for connected components, such as
scipy.ndimage.label
can detect individual chords.See also

porespy.filters.
distance_transform_lin
(im, axis=0, mode='both')[source]¶ Replaces each void voxel with the linear distance to the nearest solid voxel along the specified axis.
Parameters:  im (NDarray) – The image of the porous material with
True
values indicating the void phase (or phase of interest)  axis (int) – The direction along which the distance should be measured, the default is 0 (i.e. along the xdirection)
 mode (string) –
Controls how the distance is measured. Options are:
’forward’  Distances are measured in the increasing direction along the specified axis
’reverse’  Distances are measured in the reverse direction. ‘backward’ is also accepted.
’both’  Distances are calculated in both directions (by recursively calling itself), then reporting the minimum value of the two results.
Returns: image – A copy of
im
with each foreground voxel containing the distance to the nearest background along the specified axis.Return type: NDarray
 im (NDarray) – The image of the porous material with

porespy.filters.
fftmorphology
(im, strel, mode='opening')[source]¶ Perform morphological operations on binary images using fft approach for improved performance
Parameters:  im (ndarray) – The binary image on which to perform the morphological operation
 strel (ndarray) – The structuring element to use. Must have the same dims as
im
.  mode (string) – The type of operation to perform. Options are ‘dilation’, ‘erosion’, ‘opening’ and ‘closing’.
Returns: image – A copy of the image with the specified moropholgical operation applied using the fftbased methods available in scipy.fftconvolve.
Return type: NDarray
Notes
This function uses
scipy.signal.fftconvolve
which can be more than 10x faster than the standard binary morphology operation inscipy.ndimage
. This speed up may not always be realized, depending on the scipy distribution used.Examples
>>> import porespy as ps >>> from numpy import array_equal >>> import scipy.ndimage as spim >>> from skimage.morphology import disk >>> im = ps.generators.blobs(shape=[100, 100], porosity=0.8)
Check that erosion, dilation, opening, and closing are all the same as the
scipy.ndimage
functions:>>> result = ps.filters.fftmorphology(im, strel=disk(5), mode='erosion') >>> temp = spim.binary_erosion(im, structure=disk(5)) >>> array_equal(result, temp) True
>>> result = ps.filters.fftmorphology(im, strel=disk(5), mode='dilation') >>> temp = spim.binary_dilation(im, structure=disk(5)) >>> array_equal(result, temp) True
>>> result = ps.filters.fftmorphology(im, strel=disk(5), mode='opening') >>> temp = spim.binary_opening(im, structure=disk(5)) >>> array_equal(result, temp) True
>>> result = ps.filters.fftmorphology(im, strel=disk(5), mode='closing') >>> temp = spim.binary_closing(im, structure=disk(5)) >>> array_equal(result, temp) True

porespy.filters.
fill_blind_pores
(im)[source]¶ Fills all pores that are not connected to the edges of the image.
Parameters: im (NDarray) – The image of the porous material Returns: image – A version of im
but with all the disconnected pores removed.Return type: NDarray See also

porespy.filters.
find_disconnected_voxels
(im, conn=None)[source]¶ This identifies all pore (or solid) voxels that are not connected to the edge of the image. This can be used to find blind pores, or remove artifacts such as solid phase voxels that are floating in space.
Parameters:  im (NDimage) – A Boolean image, with True values indicating the phase for which disconnected voxels are sought.
 conn (int) – For 2D the options are 4 and 8 for square and diagonal neighbors, while for the 3D the options are 6 and 26, similarily for square and diagonal neighbors. The default is max
Returns: image – An NDimage the same size as
im
, with True values indicating voxels of the phase of interest (i.e. True values in the original image) that are not connected to the outer edges.Return type: NDarray
Notes
 image : NDarray
 The returned array (e.g.
holes
) be used to trim blind pores fromim
using:im[holes] = False

porespy.filters.
find_dt_artifacts
(dt)[source]¶ Finds points in a distance transform that are closer to wall than solid.
These points could potentially be erroneously high since their distance values do not reflect the possibility that solid may have been present beyond the border of the image but lost by trimming.
Parameters: dt (NDarray) – The distance transform of the phase of interest Returns: image – An NDarray the same shape as dt
with numerical values indicating the maximum amount of error in each volxel, which is found by subtracting the distance to nearest edge of image from the distance transform value. In other words, this is the error that would be found if there were a solid voxel lurking just beyond the nearest edge of the image. Obviously, voxels with a value of zero have no error.Return type: NDarray

porespy.filters.
find_peaks
(dt, r_max=4, footprint=None)[source]¶ Returns all local maxima in the distance transform
Parameters:  dt (NDarray) – The distance transform of the pore space. This may be calculated and filtered using any means desired.
 r_max (scalar) – The size of the structuring element used in the maximum filter. This controls the localness of any maxima. The default is 4 voxels.
 footprint (NDarray) – Specifies the shape of the structuring element used to define the neighborhood when looking for peaks. If none is specified then a spherical shape is used (or circular in 2D).
Returns: image – An array of booleans with
True
values at the location of any local maxima.Return type: NDarray
Notes
It is also possible ot the
peak_local_max
function from theskimage.feature
module as follows:peaks = peak_local_max(image=dt, min_distance=r, exclude_border=0, indices=False)
This automatically uses a square structuring element which is significantly faster than using a circular or spherical element.

porespy.filters.
flood
()[source]¶ Floods/fills each region in an image with a single value based on the specific values in that region. The
mode
argument is used to determine how the value is calculated.Parameters:  im (array_like) – An ND image with isolated regions containing 0’s elsewhere.
 regions (array_like) – An array the same shape as
im
with each region labeled. If None is supplied (default) thenscipy.ndimage.label
is used with its default arguments.  mode (string) –
Specifies how to determine which value should be used to flood each region. Options are:
’max’  Floods each region with the local maximum in that region
’min’  Floods each region the local minimum in that region
’size’  Floods each region with the size of that region
Returns: image – A copy of
im
with new values placed in each forground voxel based on themode
.Return type: NDarray
See also
props_to_image()

porespy.filters.
local_thickness
(im, sizes=25, mode='hybrid')[source]¶ For each voxel, this functions calculates the radius of the largest sphere that both engulfs the voxel and fits entirely within the foreground. This is not the same as a simple distance transform, which finds the largest sphere that could be centered on each voxel.
Parameters:  im (array_like) – A binary image with the phase of interest set to True
 sizes (array_like or scalar) – The sizes to invade. If a list of values of provided they are used directly. If a scalar is provided then that number of points spanning the min and max of the distance transform are used.
 mode (string) –
Controls with method is used to compute the result. Options are:
’hybrid’  (default) Performs a distance tranform of the void space, thresholds to find voxels larger than
sizes[i]
, trims the resulting mask ifaccess_limitations
isTrue
, then dilates it using the efficient fftmethod to obtain the nonwetting fluid configuration.’dt’  Same as ‘hybrid’, except uses a second distance transform, relative to the thresholded mask, to find the invading fluid configuration. The choice of ‘dt’ or ‘hybrid’ depends on speed, which is system and installation specific.
’mio’  Using a single morphological image opening step to obtain the invading fluid confirguration directly, then trims if
access_limitations
isTrue
. This method is not ideal and is included mostly for comparison purposes.
Returns: image – A copy of
im
with the pore size values in each voxelReturn type: NDarray
See also
Notes
The term foreground is used since this function can be applied to both pore space or the solid, whichever is set to
True
.This function is identical to
porosimetry
withaccess_limited
set toFalse
.The way local thickness is found in PoreSpy differs from the traditional method (i.e. used in ImageJ). Our approach is probably slower, but it allows for the same code to be used for
local_thickness
andporosimetry
, since we can ‘trim’ invaded regions that are not connected to the inlets in theporosimetry
function. This is not needed inlocal_thickness
however.

porespy.filters.
nphase_border
(im, include_diagonals=False)[source]¶ Identifies the voxels in regions that border N other regions.
Useful for finding triplephase boundaries.
Parameters:  im (NDarray) – An ND image of the porous material containing discrete values in the pore space identifying different regions. e.g. the result of a snowpartition
 include_diagonals (boolean) – When identifying bordering pixels (2D) and voxels (3D) include those shifted along more than one axis
Returns: image – A copy of
im
with voxel values equal to the number of uniquely different bordering valuesReturn type: NDarray

porespy.filters.
porosimetry
(im, sizes=25, inlets=None, access_limited=True, mode='hybrid')[source]¶ Performs a porosimetry simulution on the image
Parameters:  im (NDarray) – An ND image of the porous material containing True values in the pore space.
 sizes (array_like or scalar) – The sizes to invade. If a list of values of provided they are used directly. If a scalar is provided then that number of points spanning the min and max of the distance transform are used.
 inlets (NDarray, boolean) – A boolean mask with True values indicating where the invasion
enters the image. By default all faces are considered inlets,
akin to a mercury porosimetry experiment. Users can also apply
solid boundaries to their image externally before passing it in,
allowing for complex inlets like circular openings, etc. This argument
is only used if
access_limited
isTrue
.  access_limited (Boolean) – This flag indicates if the intrusion should only occur from the
surfaces (
access_limited
is True, which is the default), or if the invading phase should be allowed to appear in the core of the image. The former simulates experimental tools like mercury intrusion porosimetry, while the latter is useful for comparison to gauge the extent of shielding effects in the sample.  mode (string) –
Controls with method is used to compute the result. Options are:
’hybrid’  (default) Performs a distance tranform of the void space, thresholds to find voxels larger than
sizes[i]
, trims the resulting mask ifaccess_limitations
isTrue
, then dilates it using the efficient fftmethod to obtain the nonwetting fluid configuration.’dt’  Same as ‘hybrid’, except uses a second distance transform, relative to the thresholded mask, to find the invading fluid configuration. The choice of ‘dt’ or ‘hybrid’ depends on speed, which is system and installation specific.
’mio’  Using a single morphological image opening step to obtain the invading fluid confirguration directly, then trims if
access_limitations
isTrue
. This method is not ideal and is included mostly for comparison purposes. The morphological operations are done using fftbased method implementations.
Returns: image – A copy of
im
with voxel values indicating the sphere radius at which it becomes accessible from the inlets. This image can be used to find invading fluid configurations as a function of applied capillary pressure by applying a boolean comparison:inv_phase = im > r
wherer
is the radius (in voxels) of the invading sphere. Of course,r
can be converted to capillary pressure using your favorite model.Return type: NDarray
Notes
There are many ways to perform this filter, and PoreSpy offer 3, which users can choose between via the
mode
argument. These methods all work in a similar way by finding which foreground voxels can accomodate a sphere of a given radius, then repeating for smaller radii.See also

porespy.filters.
region_size
(im)[source]¶ Replace each voxel with size of region to which it belongs
Parameters: im (NDarray) – Either a boolean image wtih True
indicating the features of interest, in which casescipy.ndimage.label
will be applied to find regions, or a greyscale image with integer values indicating regions.Returns: image – A copy of im
with each voxel value indicating the size of the region to which it belongs. This is particularly useful for finding chord sizes on the image produced byapply_chords
.Return type: NDarray

porespy.filters.
snow_partitioning
(im, dt=None, r_max=4, sigma=0.4, return_all=False, mask=True, randomize=True)[source]¶ Partitions the void space into pore regions using a markerbased watershed algorithm, with specially filtered peaks as markers.
The SNOW network extraction algorithm (SubNetwork of an Oversegmented Watershed) was designed to handle to perculiarities of high porosity materials, but it applies well to other materials as well.
Parameters:  im (array_like) – A boolean image of the domain, with
True
indicating the pore space andFalse
elsewhere.  dt (array_like, optional) – The distance transform of the pore space. This is done automatically if not provided, but if the distance transform has already been computed then supplying it can save some time.
 r_max (int) – The radius of the spherical structuring element to use in the Maximum filter stage that is used to find peaks. The default is 4
 sigma (float) – The standard deviation of the Gaussian filter used in step 1. The
default is 0.4. If 0 is given then the filter is not applied, which is
useful if a distance transform is supplied as the
im
argument that has already been processed.  return_all (boolean) – If set to
True
a named tuple is returned containing the original image, the distance transform, the filtered peaks, and the final pore regions. The default isFalse
 mask (boolean) – Apply a mask to the regions where the solid phase is. Default is
True
 randomize (boolean) – If
True
(default), then the region colors will be randomized before returning. This is helpful for visualizing otherwise neighboring regions have simlar coloring are are hard to distinguish.
Returns: image – An image the same shape as
im
with the void space partitioned into pores using a marker based watershed with the peaks found by the SNOW algorithm [1].Return type: NDarray
Notes
If
return_all
isTrue
then a named tuple is returned containing all of the images used during the process. They can be access as attriutes with the following names:im
: The binary image of the void spacedt
: The distance transform of the imagepeaks
: The peaks of the distance transform after applying the
steps of the SNOW algorithm *
regions
: The void space partitioned into pores using a marker based watershed with the peaks found by the SNOW algorithmReferences
[1] Gostick, J. “A versatile and efficient network extraction algorithm using markerbased watershed segmenation”. Physical Review E. (2017)
 im (array_like) – A boolean image of the domain, with

porespy.filters.
snow_partitioning_n
(im, r_max=4, sigma=0.4, return_all=True, mask=True, randomize=False, alias=None)[source]¶ This function partitions an imaging oontain an arbitrary number of phases into regions using a markerbased watershed segmentation. Its an extension of snow_partitioning function with all phases partitioned together.
Parameters:  im (NDarray) – Image of porous material where each phase is represented by unique integer starting from 1 (0’s are ignored).
 r_max (scalar) – The radius of the spherical structuring element to use in the Maximum filter stage that is used to find peaks. The default is 4.
 sigma (scalar) – The standard deviation of the Gaussian filter used. The default is
0.4. If 0 is given then the filter is not applied, which is useful if a
distance transform is supplied as the
im
argument that has already been processed.  return_all (boolean (default is False)) – If set to
True
a named tuple is returned containing the original image, the combined distance transform, list of each phase max label, and the final combined regions of all phases.  mask (boolean (default is True)) – Apply a mask to the regions which are not under concern.
 randomize (boolean) – If
True
(default), then the region colors will be randomized before returning. This is helpful for visualizing otherwise neighboring regions have similar coloring and are hard to distinguish.  alias (dict (Optional)) – A dictionary that assigns unique image label to specific phases. For
example {1: ‘Solid’} will show all structural properties associated
with label 1 as Solid phase properties. If
None
then default labelling will be used i.e {1: ‘Phase1’,..}.
Returns: An image the same shape as
im
with the all phases partitioned intoregions using a marker based watershed with the peaks found by the
SNOW algorithm [1]. If
return_all
isTrue
then a named tupleis returned with the following attribute –
im
: The actual image of the porous materialdt
: The combined distance transform of the imagephase_max_label
: The list of max label of each phase in order to
distinguish between each other *
regions
: The partitioned regions of n phases using a marker based watershed with the peaks found by the SNOW algorithm
References
[1] Gostick, J. “A versatile and efficient network extraction algorithm using markerbased watershed segmentation”. Physical Review E. (2017)
[2] Khan, ZA et al. “Dual network extraction algorithm to investigate multiple transport processes in porous materials: Imagebased modeling of pore and grainscale processes”. Computers in Chemical Engineering. (2019)
See also
Notes
In principle it is possible to perform a distance transform on each phase separately, merge these into a single image, then apply the watershed only once. This, however, has been found to create edge artifacts between regions arising from the way watershed handles plateaus in the distance transform. To overcome this, this function applies the watershed to each of the distance transforms separately, then merges the segmented regions back into a single image.

porespy.filters.
trim_extrema
(im, h, mode='maxima')[source]¶ Trims local extrema in greyscale values by a specified amount.
This essentially decapitates peaks and/or floods valleys.
Parameters:  im (NDarray) – The image whose extrema are to be removed
 h (float) – The height to remove from each peak or fill in each valley
 mode (string {'maxima'  'minima'  'extrema'}) – Specifies whether to remove maxima or minima or both
Returns: image – A copy of the input image with all the peaks and/or valleys removed.
Return type: NDarray
Notes
This function is referred to as imhmax or imhmin in Matlab.

porespy.filters.
reduce_peaks
(peaks)[source]¶ Any peaks that are broad or elongated are replaced with a single voxel that is located at the center of mass of the original voxels.
Parameters: peaks (NDimage) – An image containing True values indicating peaks in the distance transform Returns: image – An array with the same number of isolated peaks as the original image, but fewer total voxels. Return type: NDarray Notes
The center of mass of a group of voxels is used as the new single voxel, so if the group has an odd shape (like a horse shoe), the new voxel may not lie on top of the original set.

porespy.filters.
trim_disconnected_blobs
(im, inlets)[source]¶ Removes foreground voxels not connected to specified inlets
Parameters:  im (NDarray) – The array to be trimmed
 inlets (NDarray of tuple of indices) – The locations of the inlets. Any voxels not connected directly to the inlets will be trimmed
Returns: image – An array of the same shape as
im
, but with all foreground voxels not connected to theinlets
removed.Return type: NDarray

porespy.filters.
trim_floating_solid
(im)[source]¶ Removes all solid that that is not attached to the edges of the image.
Parameters: im (NDarray) – The image of the porous material Returns: image – A version of im
but with all the disconnected solid removed.Return type: NDarray See also

porespy.filters.
trim_nearby_peaks
(peaks, dt)[source]¶ Finds pairs of peaks that are nearer to each other than to the solid phase, and removes the peak that is closer to the solid.
Parameters:  peaks (NDarray) – A boolean image containing True values to mark peaks in the distance
transform (
dt
)  dt (NDarray) – The distance transform of the pore space for which the true peaks are sought.
Returns: image – An array the same size as
peaks
containing a subset of the peaks in the original image.Return type: NDarray
Notes
Each pair of peaks is considered simultaneously, so for a triplet of peaks each pair is considered. This ensures that only the single peak that is furthest from the solid is kept. No iteration is required.
References
[1] Gostick, J. “A versatile and efficient network extraction algorithm using markerbased watershed segmenation”. Physical Review E. (2017)
 peaks (NDarray) – A boolean image containing True values to mark peaks in the distance
transform (

porespy.filters.
trim_nonpercolating_paths
(im, inlet_axis=0, outlet_axis=0)[source]¶ Removes all nonpercolating paths between specified edges
This function is essential when performing transport simulations on an image, since image regions that do not span between the desired inlet and outlet do not contribute to the transport.
Parameters:  im (NDarray) – The image of the porous material with
`True
values indicating the phase of interest  inlet_axis (int) – Inlet axis of boundary condition. For three dimensional image the number ranges from 0 to 2. For two dimensional image the range is between 0 to 1.
 outlet_axis (int) – Outlet axis of boundary condition. For three dimensional image the number ranges from 0 to 2. For two dimensional image the range is between 0 to 1.
Returns: image – A copy of
im
with all the nonpercolating paths removedReturn type: NDarray
See also
find_disconnected_voxels()
,trim_floating_solid()
,trim_blind_pores()
 im (NDarray) – The image of the porous material with

porespy.filters.
trim_saddle_points
(peaks, dt, max_iters=10)[source]¶ Removes peaks that were mistakenly identified because they lied on a saddle or ridge in the distance transform that was not actually a true local peak.
Parameters:  peaks (NDarray) – A boolean image containing True values to mark peaks in the distance
transform (
dt
)  dt (NDarray) – The distance transform of the pore space for which the true peaks are sought.
 max_iters (int) – The maximum number of iterations to run while eroding the saddle points. The default is 10, which is usually not reached; however, a warning is issued if the loop ends prior to removing all saddle points.
Returns: image – An image with fewer peaks than the input image
Return type: NDarray
References
[1] Gostick, J. “A versatile and efficient network extraction algorithm using markerbased watershed segmenation”. Physical Review E. (2017)
 peaks (NDarray) – A boolean image containing True values to mark peaks in the distance
transform (