{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Trainable segmentation using local features and random forests\n\nA pixel-based segmentation is computed here using local features based on\nlocal intensity, edges and textures at different scales. A user-provided\nmask is used to identify different regions. The pixels of the mask are used\nto train a random-forest classifier [1]_ from scikit-learn. Unlabeled pixels\nare then labeled from the prediction of the classifier.\n\nThis segmentation algorithm is called trainable segmentation in other software\nsuch as ilastik [2]_ or ImageJ [3]_ (where it is also called \"weka\nsegmentation\").\n\n.. [1] https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html\n.. [2] https://www.ilastik.org/documentation/pixelclassification/pixelclassification\n.. [3] https://imagej.net/Trainable_Weka_Segmentation#Training_features_.282D.29\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage import data, segmentation, feature, future\nfrom sklearn.ensemble import RandomForestClassifier\nfrom functools import partial\n\nfull_img = data.skin()\n\nimg = full_img[:900, :900]\n\n# Build an array of labels for training the segmentation.\n# Here we use rectangles but visualization libraries such as plotly\n# (and napari?) can be used to draw a mask on the image.\ntraining_labels = np.zeros(img.shape[:2], dtype=np.uint8)\ntraining_labels[:130] = 1\ntraining_labels[:170, :400] = 1\ntraining_labels[600:900, 200:650] = 2\ntraining_labels[330:430, 210:320] = 3\ntraining_labels[260:340, 60:170] = 4\ntraining_labels[150:200, 720:860] = 4\n\nsigma_min = 1\nsigma_max = 16\nfeatures_func = partial(\n    feature.multiscale_basic_features,\n    intensity=True,\n    edges=False,\n    texture=True,\n    sigma_min=sigma_min,\n    sigma_max=sigma_max,\n    channel_axis=-1,\n)\nfeatures = features_func(img)\nclf = RandomForestClassifier(n_estimators=50, n_jobs=-1, max_depth=10, max_samples=0.05)\nclf = future.fit_segmenter(training_labels, features, clf)\nresult = future.predict_segmenter(features, clf)\n\nfig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(9, 4))\nax[0].imshow(segmentation.mark_boundaries(img, result, mode='thick'))\nax[0].contour(training_labels)\nax[0].set_title('Image, mask and segmentation boundaries')\nax[1].imshow(result)\nax[1].set_title('Segmentation')\nfig.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Feature importance\n\nWe inspect below the importance of the different features, as computed by\nscikit-learn. Intensity features have a much higher importance than texture\nfeatures. It can be tempting to use this information to reduce the number of\nfeatures given to the classifier, in order to reduce the computing time.\nHowever, this can lead to overfitting and a degraded result at the boundary\nbetween regions.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots(1, 2, figsize=(9, 4))\nl = len(clf.feature_importances_)\nfeature_importance = (\n    clf.feature_importances_[: l // 3],\n    clf.feature_importances_[l // 3 : 2 * l // 3],\n    clf.feature_importances_[2 * l // 3 :],\n)\nsigmas = np.logspace(\n    np.log2(sigma_min),\n    np.log2(sigma_max),\n    num=int(np.log2(sigma_max) - np.log2(sigma_min) + 1),\n    base=2,\n    endpoint=True,\n)\nfor ch, color in zip(range(3), ['r', 'g', 'b']):\n    ax[0].plot(sigmas, feature_importance[ch][::3], 'o', color=color)\n    ax[0].set_title(\"Intensity features\")\n    ax[0].set_xlabel(\"$\\\\sigma$\")\nfor ch, color in zip(range(3), ['r', 'g', 'b']):\n    ax[1].plot(sigmas, feature_importance[ch][1::3], 'o', color=color)\n    ax[1].plot(sigmas, feature_importance[ch][2::3], 's', color=color)\n    ax[1].set_title(\"Texture features\")\n    ax[1].set_xlabel(\"$\\\\sigma$\")\n\nfig.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Fitting new images\n\nIf you have several images of similar objects acquired in similar conditions,\nyou can use the classifier trained with `fit_segmenter` to segment other\nimages. In the example below we just use a different part of the image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "img_new = full_img[:700, 900:]\n\nfeatures_new = features_func(img_new)\nresult_new = future.predict_segmenter(features_new, clf)\nfig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(6, 4))\nax[0].imshow(segmentation.mark_boundaries(img_new, result_new, mode='thick'))\nax[0].set_title('Image')\nax[1].imshow(result_new)\nax[1].set_title('Segmentation')\nfig.tight_layout()\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
}