{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Use rolling-ball algorithm for estimating background intensity\n\nThe rolling-ball algorithm estimates the background intensity of a grayscale\nimage. It comes in useful, for instance, in case of uneven exposure, when\nsubtracting the background is desirable. It is frequently used in biomedical\nimage processing and was first proposed by Stanley R. Sternberg in\n1983 [1]_.\n\nThe algorithm works as a filter: Think of the image\nas a surface that has unit-sized blocks stacked on top of each other in place\nof each pixel. The number of blocks, and hence surface height, is determined\nby the intensity of the pixel. To get the intensity of the background at a\ndesired (pixel) position, we imagine submerging a ball under the surface at the\ndesired position. Once it is completely covered by the blocks, the apex of\nthe ball determines the intensity of the background at that position. We can\nthen 'roll' this ball around below the surface to get the background values for\nthe entire image. The larger the ball, the smoother the background.\n\nscikit-image implements a generalized version of this rolling-ball algorithm,\nallowing you to work with n-dimensional images and to use not only balls, but\nother kernels as well. This way, you may directly filter RGB images or\nimage stacks along any (or all) spatial dimensions.\n\n.. [1] Sternberg, Stanley R. \"Biomedical image processing.\" Computer 1 (1983):\n    22-34. :DOI:`10.1109/MC.1983.1654163`\n\n\n## Classic rolling ball\n\nIn scikit-image, the implementation assumes that your image background has\nlow intensity (dark), whereas the features have high intensity (bright). If\nthis is not your case, you first have to invert the image\u2014we give an example\nof that further on.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport pywt\nimport skimage as ski\n\n\ndef plot_result(image, background):\n    fig, ax = plt.subplots(ncols=3)\n\n    ax[0].imshow(image, cmap='gray')\n    ax[0].set_title('Original image')\n    ax[0].axis('off')\n\n    ax[1].imshow(background, cmap='gray')\n    ax[1].set_title('Background')\n    ax[1].axis('off')\n\n    ax[2].imshow(image - background, cmap='gray')\n    ax[2].set_title('Result')\n    ax[2].axis('off')\n\n    fig.tight_layout()\n\n\nimage = ski.data.coins()\n\nbackground = ski.restoration.rolling_ball(image)\n\nplot_result(image, background)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Bright background\n\nIf you have dark features on a bright background, you need to invert\nthe image before passing it to the rolling-ball filter, and then invert the\nresult. This can be accomplished as follows:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.data.page()\nimage_inverted = ski.util.invert(image)\n\nbackground_inverted = ski.restoration.rolling_ball(image_inverted, radius=45)\nfiltered_image_inverted = image_inverted - background_inverted\nfiltered_image = ski.util.invert(filtered_image_inverted)\nbackground = ski.util.invert(background_inverted)\n\nfig, ax = plt.subplots(ncols=3)\n\nax[0].imshow(image, cmap='gray')\nax[0].set_title('Original image')\nax[0].axis('off')\n\nax[1].imshow(background, cmap='gray')\nax[1].set_title('Background')\nax[1].axis('off')\n\nax[2].imshow(filtered_image, cmap='gray')\nax[2].set_title('Result')\nax[2].axis('off')\n\nfig.tight_layout()\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Be careful not to fall victim to an integer underflow when subtracting\na bright background. For example, this code looks correct, but may\nsuffer from an underflow leading to unwanted artifacts. You can see\nthis in the top right corner of the visualization.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.data.page()\nimage_inverted = ski.util.invert(image)\n\nbackground_inverted = ski.restoration.rolling_ball(image_inverted, radius=45)\nbackground = ski.util.invert(background_inverted)\nunderflow_image = image - background  # integer underflow occurs here\n\n# correct subtraction\ncorrect_image = ski.util.invert(image_inverted - background_inverted)\n\nfig, ax = plt.subplots(ncols=2)\n\nax[0].imshow(underflow_image, cmap='gray')\nax[0].set_title('Background Removal with Underflow')\nax[0].axis('off')\n\nax[1].imshow(correct_image, cmap='gray')\nax[1].set_title('Correct Background Removal')\nax[1].axis('off')\n\nfig.tight_layout()\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Image Datatypes\n\n``rolling_ball`` can handle datatypes other than `np.uint8`. You can\npass them into the function in the same way.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.data.coins()[:200, :200].astype(np.uint16)\n\nbackground = ski.restoration.rolling_ball(image, radius=70.5)\nplot_result(image, background)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "However, you need to be careful if you use floating point images\nthat have been normalized to ``[0, 1]``. In this case the ball will\nbe much larger than the image intensity, which can lead to\nunexpected results.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.util.img_as_float(ski.data.coins()[:200, :200])\n\nbackground = ski.restoration.rolling_ball(image, radius=70.5)\nplot_result(image, background)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Because ``radius=70.5`` is much larger than the maximum intensity of\nthe image, the effective kernel size is reduced significantly, i.e.,\nonly a small cap (approximately ``radius=10``) of the ball is rolled\naround in the image. You can find a reproduction of this strange\neffect in the ``Advanced Shapes`` section below.\n\nTo get the expected result, you need to reduce the intensity of the\nkernel. This is done by specifying the kernel manually using the\n``kernel`` argument.\n\nNote: The radius is equal to the length of a semi-axis of an\nellipsis, which is *half* a full axis. Hence, the kernel shape is\nmultiplied by two.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "normalized_radius = 70.5 / 255\nimage = ski.util.img_as_float(ski.data.coins())\nkernel = ski.restoration.ellipsoid_kernel((70.5 * 2, 70.5 * 2), normalized_radius * 2)\n\nbackground = ski.restoration.rolling_ball(image, kernel=kernel)\nplot_result(image, background)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Advanced Shapes\n\nBy default, :func:`skimage.restoration.rolling_ball` uses a ball-shaped\nkernel (surprise).\nSometimes, though, this can be too limiting---as in the example above,\nbecause the intensity dimension has a different scale compared to\nthe spatial dimensions, or because the image dimensions may have\ndifferent meanings (e.g., one could be a stack counter in an image stack).\n\nTo account for this, :func:`skimage.restoration.rolling_ball` has a `kernel`\nargument which allows you to specify the kernel to be used. A kernel must\nhave the same dimensionality as the image (i.e., the same number of\ndimensions/axes).\nTo help with its creation, two kernel implementations are provided:\n:func:`skimage.restoration.ball_kernel` specifies a ball-shaped kernel and\nis used as the default kernel; :func:`skimage.restoration.ellipsoid_kernel`\nspecifies an ellipsoid-shaped kernel.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.data.coins()\nkernel = ski.restoration.ellipsoid_kernel((70.5 * 2, 70.5 * 2), 70.5 * 2)\n\nbackground = ski.restoration.rolling_ball(image, kernel=kernel)\nplot_result(image, background)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "You can also use :func:`skimage.restoration.ellipsoid_kernel` to recreate\nthe previous, unexpected result and see that the effective (spatial) filter\nsize was reduced.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.data.coins()\nkernel = ski.restoration.ellipsoid_kernel((10 * 2, 10 * 2), 255 * 2)\n\nbackground = ski.restoration.rolling_ball(image, kernel=kernel)\nplot_result(image, background)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Higher Dimensions\n\nAnother interesting feature of :func:`skimage.restoration.rolling_ball` is\nthat you can directly apply it to higher-dimensional images, e.g., a Z-stack\nof images obtained in confocal microscopy. The number of kernel dimensions\nmust match that of image dimensions; in this case, the kernel is thus\n3-dimensional.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.data.cells3d()[:, 1, ...]\nkernel = ski.restoration.ellipsoid_kernel((1, 21, 21), 0.1)\n\nbackground = ski.restoration.rolling_ball(image, kernel=kernel)\n\nplot_result(image[30, ...], background[30, ...])\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The above filter is actually applied to each image in the stack\n*individually*, since the kernel has size 1 along the Z axis.\n\nTo filter along all 3 dimensions at the same time, you must use sizes\ngreater than 1 along all 3 dimensions.\n\n  .. code-block:: python\n     :caption: Change the first line in the above code block.\n\n      kernel = ski.restoration.ellipsoid_kernel((5, 21, 21), 0.1)\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Another possibility is to filter individual pixels *only* along the\nplanar (Z) axis.\n\n  .. code-block:: python\n     :caption: This change here will show a lot more clearly in the result.\n\n      kernel = ski.restoration.ellipsoid_kernel((100, 1, 1), 0.1)\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1D Signal Filtering\n\nAs another example of the n-dimensional feature of\n``rolling_ball``, we show an implementation for 1D data. Here,\nwe are interested in removing the background signal of an ECG waveform\nto detect prominent peaks (higher values than the local baseline).\nSmoother peaks can be removed with smaller values of the radius.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "x = pywt.data.ecg()\nbackground = ski.restoration.rolling_ball(x, radius=80)\nbackground2 = ski.restoration.rolling_ball(x, radius=10)\nplt.figure()\nplt.plot(x, label='original')\nplt.plot(x - background, label='radius=80')\nplt.plot(x - background2, label='radius=10')\nplt.legend()\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
}