{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Hierarchical Merging of Region Boundary RAGs\n\nThis example demonstrates how to perform hierarchical merging on region\nboundary Region Adjacency Graphs (RAGs). Region boundary RAGs can be\nconstructed with the :py:func:`skimage.graph.rag_boundary` function.\nThe regions with the lowest edge weights are successively merged until there\nis no edge with weight less than ``thresh``. The hierarchical merging is done\nthrough the :py:func:`skimage.graph.merge_hierarchical` function.\nFor an example of how to construct region boundary based RAGs, see\n:any:`plot_rag_boundary`.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from skimage import data, segmentation, filters, color\nfrom skimage import graph\nfrom matplotlib import pyplot as plt\n\n\ndef weight_boundary(graph, src, dst, n):\n    \"\"\"\n    Handle merging of nodes of a region boundary region adjacency graph.\n\n    This function computes the `\"weight\"` and the count `\"count\"`\n    attributes of the edge between `n` and the node formed after\n    merging `src` and `dst`.\n\n\n    Parameters\n    ----------\n    graph : RAG\n        The graph under consideration.\n    src, dst : int\n        The vertices in `graph` to be merged.\n    n : int\n        A neighbor of `src` or `dst` or both.\n\n    Returns\n    -------\n    data : dict\n        A dictionary with the \"weight\" and \"count\" attributes to be\n        assigned for the merged node.\n\n    \"\"\"\n    default = {'weight': 0.0, 'count': 0}\n\n    count_src = graph[src].get(n, default)['count']\n    count_dst = graph[dst].get(n, default)['count']\n\n    weight_src = graph[src].get(n, default)['weight']\n    weight_dst = graph[dst].get(n, default)['weight']\n\n    count = count_src + count_dst\n    return {\n        'count': count,\n        'weight': (count_src * weight_src + count_dst * weight_dst) / count,\n    }\n\n\ndef merge_boundary(graph, src, dst):\n    \"\"\"Call back called before merging 2 nodes.\n\n    In this case we don't need to do any computation here.\n    \"\"\"\n    pass\n\n\nimg = data.coffee()\nedges = filters.sobel(color.rgb2gray(img))\nlabels = segmentation.slic(img, compactness=30, n_segments=400, start_label=1)\ng = graph.rag_boundary(labels, edges)\n\nfig, axes = plt.subplots(nrows=2, ncols=2)\n\ngraph.show_rag(labels, g, img, ax=axes[0, 0])\naxes[0, 0].set_title('Initial RAG')\n\nlabels2 = graph.merge_hierarchical(\n    labels,\n    g,\n    thresh=0.08,\n    rag_copy=False,\n    in_place_merge=True,\n    merge_func=merge_boundary,\n    weight_func=weight_boundary,\n)\n\ngraph.show_rag(labels, g, img, ax=axes[0, 1])\naxes[0, 1].set_title('RAG after hierarchical merging')\n\nout = color.label2rgb(labels2, img, kind='avg', bg_label=0)\naxes[1, 0].imshow(out)\naxes[1, 0].set_title('Final segmentation')\n\naxes[1, 1].axis('off')\n\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}