{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Find the intersection of two segmentations\n\nWhen segmenting an image, you may want to combine multiple alternative\nsegmentations. The :py:func:`skimage.segmentation.join_segmentations`\nfunction computes the join of two segmentations, in which a pixel is\nplaced in the same segment if and only if it is in the same segment in\n*both* segmentations.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom skimage.filters import sobel\nfrom skimage.measure import label\nfrom skimage.segmentation import slic, join_segmentations, watershed\nfrom skimage.color import label2rgb\nfrom skimage import data\n\ncoins = data.coins()\n\n# Make segmentation using edge-detection and watershed.\nedges = sobel(coins)\n\n# Identify some background and foreground pixels from the intensity values.\n# These pixels are used as seeds for watershed.\nmarkers = np.zeros_like(coins)\nforeground, background = 1, 2\nmarkers[coins < 30.0] = background\nmarkers[coins > 150.0] = foreground\n\nws = watershed(edges, markers)\nseg1 = label(ws == foreground)\n\n# Make segmentation using SLIC superpixels.\nseg2 = slic(\n    coins,\n    n_segments=117,\n    max_num_iter=160,\n    sigma=1,\n    compactness=0.75,\n    channel_axis=None,\n    start_label=0,\n)\n\n# Combine the two.\nsegj = join_segmentations(seg1, seg2)\n\n# Show the segmentations.\nfig, axes = plt.subplots(ncols=2, nrows=2, figsize=(9, 5), sharex=True, sharey=True)\nax = axes.ravel()\nax[0].imshow(coins, cmap='gray')\nax[0].set_title('Image')\n\ncolor1 = label2rgb(seg1, image=coins, bg_label=0)\nax[1].imshow(color1)\nax[1].set_title('Sobel+Watershed')\n\ncolor2 = label2rgb(seg2, image=coins, image_alpha=0.5, bg_label=-1)\nax[2].imshow(color2)\nax[2].set_title('SLIC superpixels')\n\ncolor3 = label2rgb(segj, image=coins, image_alpha=0.5, bg_label=-1)\nax[3].imshow(color3)\nax[3].set_title('Join')\n\nfor a in ax:\n    a.axis('off')\nfig.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
}