Module: graph
¶

Find the pixel with the highest closeness centrality. 

Create an adjacency graph of pixels in an image. 

Simple example of how to use the MCP and MCP_Geometric classes. 

Find the shortest path through an nd array from one side to another. 

A class for finding the minimum cost path through a given nd costs array. 

Connect source points using the distanceweighted minimum cost function. 

Find minimum cost paths through an Nd costs array. 

Find distanceweighted minimum cost paths through an nd costs array. 
central_pixel¶

skimage.graph.
central_pixel
(graph, nodes=None, shape=None, partition_size=100)[source]¶ Find the pixel with the highest closeness centrality.
Closeness centrality is the inverse of the total sum of shortest distances from a node to every other node.
 Parameters
 graphscipy.sparse.csr_matrix
The sparse matrix representation of the graph.
 nodesarray of int
The raveled index of each node in graph in the image. If not provided, the returned value will be the index in the input graph.
 shapetuple of int
The shape of the image in which the nodes are embedded. If provided, the returned coordinates are a NumPy multiindex of the same dimensionality as the input shape. Otherwise, the returned coordinate is the raveled index provided in nodes.
 partition_sizeint
This function computes the shortest path distance between every pair of nodes in the graph. This can result in a very large (N*N) matrix. As a simple performance tweak, the distance values are computed in lots of partition_size, resulting in a memory requirement of only partition_size*N.
 Returns
 positionint or tuple of int
If shape is given, the coordinate of the central pixel in the image. Otherwise, the raveled index of that pixel.
 distancesarray of float
The total sum of distances from each node to each other reachable node.
Examples using skimage.graph.central_pixel
¶
pixel_graph¶

skimage.graph.
pixel_graph
(image, *, mask=None, edge_function=None, connectivity=1, spacing=None)[source]¶ Create an adjacency graph of pixels in an image.
Pixels where the mask is True are nodes in the returned graph, and they are connected by edges to their neighbors according to the connectivity parameter. By default, the value of an edge when a mask is given, or when the image is itself the mask, is the euclidean distance betwene the pixels.
However, if an int or floatvalued image is given with no mask, the value of the edges is the absolute difference in intensity between adjacent pixels, weighted by the euclidean distance.
 Parameters
 imagearray
The input image. If the image is of type bool, it will be used as the mask as well.
 maskarray of bool
Which pixels to use. If None, the graph for the whole image is used.
 edge_functioncallable
A function taking an array of pixel values, and an array of neighbor pixel values, and an array of distances, and returning a value for the edge. If no function is given, the value of an edge is just the distance.
 connectivityint
The square connectivity of the pixel neighborhood: the number of orthogonal steps allowed to consider a pixel a neigbor. See
scipy.ndimage.generate_binary_structure
for details. spacingtuple of float
The spacing between pixels along each axis.
 Returns
 graphscipy.sparse.csr_matrix
A sparse adjacency matrix in which entry (i, j) is 1 if nodes i and j are neighbors, 0 otherwise.
 nodesarray of int
The nodes of the graph. These correspond to the raveled indices of the nonzero pixels in the mask.
Examples using skimage.graph.pixel_graph
¶
route_through_array¶

skimage.graph.
route_through_array
(array, start, end, fully_connected=True, geometric=True)[source]¶ Simple example of how to use the MCP and MCP_Geometric classes.
See the MCP and MCP_Geometric class documentation for explanation of the pathfinding algorithm.
 Parameters
 arrayndarray
Array of costs.
 startiterable
nd index into
array
defining the starting point enditerable
nd index into
array
defining the end point fully_connectedbool (optional)
If True, diagonal moves are permitted, if False, only axial moves.
 geometricbool (optional)
If True, the MCP_Geometric class is used to calculate costs, if False, the MCP base class is used. See the class documentation for an explanation of the differences between MCP and MCP_Geometric.
 Returns
 pathlist
List of nd index tuples defining the path from start to end.
 costfloat
Cost of the path. If geometric is False, the cost of the path is the sum of the values of
array
along the path. If geometric is True, a finer computation is made (see the documentation of the MCP_Geometric class).
See also
Examples
>>> import numpy as np >>> from skimage.graph import route_through_array >>> >>> image = np.array([[1, 3], [10, 12]]) >>> image array([[ 1, 3], [10, 12]]) >>> # Forbid diagonal steps >>> route_through_array(image, [0, 0], [1, 1], fully_connected=False) ([(0, 0), (0, 1), (1, 1)], 9.5) >>> # Now allow diagonal steps: the path goes directly from start to end >>> route_through_array(image, [0, 0], [1, 1]) ([(0, 0), (1, 1)], 9.19238815542512) >>> # Cost is the sum of array values along the path (16 = 1 + 3 + 12) >>> route_through_array(image, [0, 0], [1, 1], fully_connected=False, ... geometric=False) ([(0, 0), (0, 1), (1, 1)], 16.0) >>> # Larger array where we display the path that is selected >>> image = np.arange((36)).reshape((6, 6)) >>> image array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35]]) >>> # Find the path with lowest cost >>> indices, weight = route_through_array(image, (0, 0), (5, 5)) >>> indices = np.stack(indices, axis=1) >>> path = np.zeros_like(image) >>> path[indices[0], indices[1]] = 1 >>> path array([[1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1]])
shortest_path¶

skimage.graph.
shortest_path
(arr, reach=1, axis= 1, output_indexlist=False)[source]¶ Find the shortest path through an nd array from one side to another.
 Parameters
 arrndarray of float64
 reachint, optional
By default (
reach = 1
), the shortest path can only move one row up or down for every step it moves forward (i.e., the path gradient is limited to 1). reach defines the number of elements that can be skipped along each nonaxis dimension at each step. axisint, optional
The axis along which the path must always move forward (default 1)
 output_indexlistbool, optional
See return value p for explanation.
 Returns
 piterable of int
For each step along axis, the coordinate of the shortest path. If output_indexlist is True, then the path is returned as a list of nd tuples that index into arr. If False, then the path is returned as an array listing the coordinates of the path along the nonaxis dimensions for each step along the axis dimension. That is, p.shape == (arr.shape[axis], arr.ndim1) except that p is squeezed before returning so if arr.ndim == 2, then p.shape == (arr.shape[axis],)
 costfloat
Cost of path. This is the absolute sum of all the differences along the path.
MCP
¶

class
skimage.graph.
MCP
(costs, offsets=None, fully_connected=True, sampling=None)¶ Bases:
object
A class for finding the minimum cost path through a given nd costs array.
Given an nd costs array, this class can be used to find the minimumcost path through that array from any set of points to any other set of points. Basic usage is to initialize the class and call find_costs() with a one or more starting indices (and an optional list of end indices). After that, call traceback() one or more times to find the path from any given endposition to the closest starting index. New paths through the same costs array can be found by calling find_costs() repeatedly.
The cost of a path is calculated simply as the sum of the values of the costs array at each point on the path. The class MCP_Geometric, on the other hand, accounts for the fact that diagonal vs. axial moves are of different lengths, and weights the path cost accordingly.
Array elements with infinite or negative costs will simply be ignored, as will paths whose cumulative cost overflows to infinite.
 Parameters
 costsndarray
 offsetsiterable, optional
A list of offset tuples: each offset specifies a valid move from a given nd position. If not provided, offsets corresponding to a singly or fullyconnected nd neighborhood will be constructed with make_offsets(), using the fully_connected parameter value.
 fully_connectedbool, optional
If no
offsets
are provided, this determines the connectivity of the generated neighborhood. If true, the path may go along diagonals between elements of the costs array; otherwise only axial moves are permitted. samplingtuple, optional
For each dimension, specifies the distance between two cells/voxels. If not given or None, the distance is assumed unit.
 Attributes

__init__
(costs, offsets=None, fully_connected=True, sampling=None)¶ See class documentation.

find_costs
()¶ Find the minimumcost path from the given starting points.
This method finds the minimumcost path to the specified ending indices from any one of the specified starting indices. If no end positions are given, then the minimumcost path to every position in the costs array will be found.
 Parameters
 startsiterable
A list of nd starting indices (where n is the dimension of the costs array). The minimum cost path to the closest/cheapest starting point will be found.
 endsiterable, optional
A list of nd ending indices.
 find_all_endsbool, optional
If ‘True’ (default), the minimumcostpath to every specified endposition will be found; otherwise the algorithm will stop when a a path is found to any endposition. (If no ends were specified, then this parameter has no effect.)
 Returns
 cumulative_costsndarray
Same shape as the costs array; this array records the minimum cost path from the nearest/cheapest starting index to each index considered. (If ends were specified, not all elements in the array will necessarily be considered: positions not evaluated will have a cumulative cost of inf. If find_all_ends is ‘False’, only one of the specified endpositions will have a finite cumulative cost.)
 tracebackndarray
Same shape as the costs array; this array contains the offset to any given index from its predecessor index. The offset indices index into the
offsets
attribute, which is a array of nd offsets. In the 2d case, if offsets[traceback[x, y]] is (1, 1), that means that the predecessor of [x, y] in the minimum cost path to some start position is [x+1, y+1]. Note that if the offset_index is 1, then the given index was not considered.

goal_reached
()¶ int goal_reached(int index, float cumcost) This method is called each iteration after popping an index from the heap, before examining the neighbours.
This method can be overloaded to modify the behavior of the MCP algorithm. An example might be to stop the algorithm when a certain cumulative cost is reached, or when the front is a certain distance away from the seed point.
This method should return 1 if the algorithm should not check the current point’s neighbours and 2 if the algorithm is now done.

offsets
¶

traceback
(end)¶ Trace a minimum cost path through the precalculated traceback array.
This convenience function reconstructs the the minimum cost path to a given end position from one of the starting indices provided to find_costs(), which must have been called previously. This function can be called as many times as desired after find_costs() has been run.
 Parameters
 enditerable
An nd index into the costs array.
 Returns
 tracebacklist of nd tuples
A list of indices into the costs array, starting with one of the start positions passed to find_costs(), and ending with the given end index. These indices specify the minimumcost path from any given start index to the end index. (The total cost of that path can be read out from the cumulative_costs array returned by find_costs().)
MCP_Connect
¶

class
skimage.graph.
MCP_Connect
(costs, offsets=None, fully_connected=True)¶ Bases:
skimage.graph._mcp.MCP
Connect source points using the distanceweighted minimum cost function.
A front is grown from each seed point simultaneously, while the origin of the front is tracked as well. When two fronts meet, create_connection() is called. This method must be overloaded to deal with the found edges in a way that is appropriate for the application.

__init__
(*args, **kwargs)¶ Initialize self. See help(type(self)) for accurate signature.

create_connection
()¶ create_connection id1, id2, pos1, pos2, cost1, cost2)
Overload this method to keep track of the connections that are found during MCP processing. Note that a connection with the same ids can be found multiple times (but with different positions and costs).
At the time that this method is called, both points are “frozen” and will not be visited again by the MCP algorithm.
 Parameters
 id1int
The seed point id where the first neighbor originated from.
 id2int
The seed point id where the second neighbor originated from.
 pos1tuple
The index of of the first neighbour in the connection.
 pos2tuple
The index of of the second neighbour in the connection.
 cost1float
The cumulative cost at pos1.
 cost2float
The cumulative costs at pos2.

MCP_Flexible
¶

class
skimage.graph.
MCP_Flexible
(costs, offsets=None, fully_connected=True)¶ Bases:
skimage.graph._mcp.MCP
Find minimum cost paths through an Nd costs array.
See the documentation for MCP for full details. This class differs from MCP in that several methods can be overloaded (from pure Python) to modify the behavior of the algorithm and/or create custom algorithms based on MCP. Note that goal_reached can also be overloaded in the MCP class.

__init__
(costs, offsets=None, fully_connected=True, sampling=None)¶ See class documentation.

examine_neighbor
(index, new_index, offset_length)¶ This method is called once for every pair of neighboring nodes, as soon as both nodes are frozen.
This method can be overloaded to obtain information about neightboring nodes, and/or to modify the behavior of the MCP algorithm. One example is the MCP_Connect class, which checks for meeting fronts using this hook.

travel_cost
(old_cost, new_cost, offset_length)¶ This method calculates the travel cost for going from the current node to the next. The default implementation returns new_cost. Overload this method to adapt the behaviour of the algorithm.

update_node
(index, new_index, offset_length)¶ This method is called when a node is updated, right after new_index is pushed onto the heap and the traceback map is updated.
This method can be overloaded to keep track of other arrays that are used by a specific implementation of the algorithm. For instance the MCP_Connect class uses it to update an id map.

MCP_Geometric
¶

class
skimage.graph.
MCP_Geometric
(costs, offsets=None, fully_connected=True)¶ Bases:
skimage.graph._mcp.MCP
Find distanceweighted minimum cost paths through an nd costs array.
See the documentation for MCP for full details. This class differs from MCP in that the cost of a path is not simply the sum of the costs along that path.
This class instead assumes that the costs array contains at each position the “cost” of a unit distance of travel through that position. For example, a move (in 2d) from (1, 1) to (1, 2) is assumed to originate in the center of the pixel (1, 1) and terminate in the center of (1, 2). The entire move is of distance 1, half through (1, 1) and half through (1, 2); thus the cost of that move is (1/2)*costs[1,1] + (1/2)*costs[1,2].
On the other hand, a move from (1, 1) to (2, 2) is along the diagonal and is sqrt(2) in length. Half of this move is within the pixel (1, 1) and the other half in (2, 2), so the cost of this move is calculated as (sqrt(2)/2)*costs[1,1] + (sqrt(2)/2)*costs[2,2].
These calculations don’t make a lot of sense with offsets of magnitude greater than 1. Use the sampling argument in order to deal with anisotropic data.

__init__
(costs, offsets=None, fully_connected=True, sampling=None)¶ See class documentation.
