diff --git a/skimage/graph/graph_merge.py b/skimage/graph/graph_merge.py index 379f11fc..69aa94f1 100644 --- a/skimage/graph/graph_merge.py +++ b/skimage/graph/graph_merge.py @@ -2,18 +2,62 @@ import numpy as np def _hmerge(rag, x, y, n): + """Callback to handle merging nodes by recomputing mean color. + + The method expects that the mean color of `y` is already computed. + + Parameters + ---------- + graph : RAG + The graph under consideration. + src, dst : int + The verices in `graph` to be merged. + n : int + A neighbor of `src` or `dst` or both. + + Returns + ------- + weight : float + The absolute difference of the mean color between node `y` and `n`. + """ diff = rag.node[y]['mean color'] - rag.node[n]['mean color'] diff = np.linalg.norm(diff) return diff -def merge_hierarchical(rag, labels, thresh): +def merge_hierarchical(labels, rag, thresh): + """Perform hierarchical merging of a RAG. + Given an image's labels and its RAG, the method merges the similar nodes + until the weight between every two nodes is more than `thresh`. + + Parameters + ---------- + labels : ndarray + The array of labels. + rag : RAG + The Region Adjacency Graph. + thresh : float + The threshold. Nodes are merged until the minimum edge weight in the + graph exceeds `thresh`. + + Returns + ------- + out : ndarray + The new labelled array. + + Examples + -------- + >>> from skimage import data, graph, segmentation + >>> img = data.coffee() + >>> labels = segmentation.slic(img) + >>> rag = graph.rag_mean_color(img, labels) + >>> new_labels = graph.merge_hierarchical(labels, rag, 40) + """ min_wt = 0 while min_wt < thresh: - valid_edges = ((x, y, d) - for x, y, d in rag.edges(data=True) if x != y) + valid_edges = ((x, y, d) for x, y, d in rag.edges(data=True) if x != y) x, y, d = min(valid_edges, key=lambda x: x[2]['weight']) min_wt = d['weight']