{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Evaluating segmentation metrics\n\nWhen trying out different segmentation methods, how do you know which one is\nbest? If you have a *ground truth* or *gold standard* segmentation, you can use\nvarious metrics to check how close each automated method comes to the truth.\nIn this example we use an easy-to-segment image as an example of how to\ninterpret various segmentation metrics. We will use the adapted Rand error\nand the variation of information as example metrics, and see how\n*oversegmentation* (splitting of true segments into too many sub-segments) and\n*undersegmentation* (merging of different true segments into a single segment)\naffect the different scores.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import ndimage as ndi\nimport skimage as ski\n\n\nimage = ski.data.coins()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "First, we generate the true segmentation. For this simple image, we know\nexact functions and parameters that will produce a perfect segmentation. In\na real scenario, typically you would generate ground truth by manual\nannotation or \"painting\" of a segmentation.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "elevation_map = ski.filters.sobel(image)\nmarkers = np.zeros_like(image)\nmarkers[image < 30] = 1\nmarkers[image > 150] = 2\nim_true = ski.segmentation.watershed(elevation_map, markers)\nim_true = ndi.label(ndi.binary_fill_holes(im_true - 1))[0]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Next, we create three different segmentations with different characteristics.\nThe first one uses :func:`skimage.segmentation.watershed` with\n*compactness*, which is a useful initial segmentation but too fine as a\nfinal result. We will see how this causes the oversegmentation metrics to\nshoot up.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "edges = ski.filters.sobel(image)\nim_test1 = ski.segmentation.watershed(edges, markers=468, compactness=0.001)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The next approach uses the Canny edge filter, :func:`skimage.feature.canny`.\nThis is a very good edge finder, and gives balanced results.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "edges = ski.feature.canny(image)\nfill_coins = ndi.binary_fill_holes(edges)\nim_test2 = ndi.label(ski.morphology.remove_small_objects(fill_coins, max_size=20))[0]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally, we use morphological geodesic active contours,\n:func:`skimage.segmentation.morphological_geodesic_active_contour`, a method\nthat generally produces good results, but requires a long time to converge on\na good answer. We purposefully cut short the procedure at 100 iterations, so\nthat the final result is *undersegmented*, meaning that many regions are\nmerged into one segment. We will see the corresponding effect on the\nsegmentation metrics.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.util.img_as_float(image)\ngradient = ski.segmentation.inverse_gaussian_gradient(image)\ninit_ls = np.zeros(image.shape, dtype=np.int8)\ninit_ls[10:-10, 10:-10] = 1\nim_test3 = ski.segmentation.morphological_geodesic_active_contour(\n    gradient,\n    num_iter=100,\n    init_level_set=init_ls,\n    smoothing=1,\n    balloon=-1,\n    threshold=0.69,\n)\nim_test3 = ski.measure.label(im_test3)\n\nmethod_names = [\n    'Compact watershed',\n    'Canny filter',\n    'Morphological Geodesic Active Contours',\n]\nshort_method_names = ['Compact WS', 'Canny', 'GAC']\n\nprecision_list = []\nrecall_list = []\nsplit_list = []\nmerge_list = []\nfor name, im_test in zip(method_names, [im_test1, im_test2, im_test3]):\n    error, precision, recall = ski.metrics.adapted_rand_error(im_true, im_test)\n    splits, merges = ski.metrics.variation_of_information(im_true, im_test)\n    split_list.append(splits)\n    merge_list.append(merges)\n    precision_list.append(precision)\n    recall_list.append(recall)\n    print(f'\\n## Method: {name}')\n    print(f'Adapted Rand error: {error}')\n    print(f'Adapted Rand precision: {precision}')\n    print(f'Adapted Rand recall: {recall}')\n    print(f'False Splits: {splits}')\n    print(f'False Merges: {merges}')\n\nfig, axes = plt.subplots(2, 3, figsize=(9, 6), constrained_layout=True)\nax = axes.ravel()\n\nax[0].scatter(merge_list, split_list)\nfor i, txt in enumerate(short_method_names):\n    ax[0].annotate(txt, (merge_list[i], split_list[i]), verticalalignment='center')\nax[0].set_xlabel('False Merges (bits)')\nax[0].set_ylabel('False Splits (bits)')\nax[0].set_title('Split Variation of Information')\n\nax[1].scatter(precision_list, recall_list)\nfor i, txt in enumerate(short_method_names):\n    ax[1].annotate(txt, (precision_list[i], recall_list[i]), verticalalignment='center')\nax[1].set_xlabel('Precision')\nax[1].set_ylabel('Recall')\nax[1].set_title('Adapted Rand precision vs. recall')\nax[1].set_xlim(0, 1)\nax[1].set_ylim(0, 1)\n\nax[2].imshow(ski.segmentation.mark_boundaries(image, im_true))\nax[2].set_title('True Segmentation')\nax[2].set_axis_off()\n\nax[3].imshow(ski.segmentation.mark_boundaries(image, im_test1))\nax[3].set_title('Compact Watershed')\nax[3].set_axis_off()\n\nax[4].imshow(ski.segmentation.mark_boundaries(image, im_test2))\nax[4].set_title('Edge Detection')\nax[4].set_axis_off()\n\nax[5].imshow(ski.segmentation.mark_boundaries(image, im_test3))\nax[5].set_title('Morphological GAC')\nax[5].set_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
}