{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Region adjacency graph (RAG) Merging\n\nThis example constructs a Region Adjacency Graph (RAG) and progressively merges\nregions that are similar in color. Merging two adjacent regions produces\na new region with all the pixels from the merged regions. Regions are merged\nuntil no highly similar region pairs remain.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from skimage import data, segmentation, color\nfrom skimage import graph\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef _weight_mean_color(graph, src, dst, n):\n    \"\"\"Callback to handle merging nodes by recomputing mean color.\n\n    The method expects that the mean color of `dst` is already computed.\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\"` attribute set as the absolute\n        difference of the mean color between node `dst` and `n`.\n    \"\"\"\n\n    diff = graph.nodes[dst]['mean color'] - graph.nodes[n]['mean color']\n    diff = np.linalg.norm(diff)\n    return {'weight': diff}\n\n\ndef merge_mean_color(graph, src, dst):\n    \"\"\"Callback called before merging two nodes of a mean color distance graph.\n\n    This method computes the mean color of `dst`.\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    graph.nodes[dst]['total color'] += graph.nodes[src]['total color']\n    graph.nodes[dst]['pixel count'] += graph.nodes[src]['pixel count']\n    graph.nodes[dst]['mean color'] = (\n        graph.nodes[dst]['total color'] / graph.nodes[dst]['pixel count']\n    )\n\n\nimg = data.coffee()\nlabels = segmentation.slic(img, compactness=30, n_segments=400, start_label=1)\ng = graph.rag_mean_color(img, labels)\n\nlabels2 = graph.merge_hierarchical(\n    labels,\n    g,\n    thresh=35,\n    rag_copy=False,\n    in_place_merge=True,\n    merge_func=merge_mean_color,\n    weight_func=_weight_mean_color,\n)\n\nout = color.label2rgb(labels2, img, kind='avg', bg_label=0)\nout = segmentation.mark_boundaries(out, labels2, (0, 0, 0))\n\nfig, ax = plt.subplots()\nax.imshow(out)\nplt.tight_layout()\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
}