{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Robust line model estimation using RANSAC\n\nIn this example we see how to robustly fit a line model to faulty data using\nthe RANSAC (random sample consensus) algorithm.\n\nFirstly the data are generated by adding a gaussian noise to a linear function.\nThen, the outlier points are added to the data set.\n\nRANSAC iteratively estimates the parameters from the data set.\nAt each iteration the following steps are performed:\n\n1. Select ``min_samples`` random samples from the original data and check\n   whether the set of data is valid (see ``is_data_valid`` option).\n2. Estimate a model on the random subset\n   (``model_cls.from_estimate(*data[random_subset]``) and check whether the\n   estimated model is valid (see ``is_model_valid`` option).\n3. Classify all the data points as either inliers or outliers by calculating\n   the residuals using the estimated model (``model_cls.residuals(*data)``) -\n   all data samples with residuals smaller than the ``residual_threshold``\n   are considered as inliers.\n4. If the number of the inlier samples is greater than ever before,\n   save the estimated model as the best model. In case the current estimated\n   model has the same number of inliers, it is considered as the best model\n   only if the sum of residuals is lower.\n\nThese steps are performed either a maximum number of times or until one of\nthe special stop criteria are met. The final model is estimated using all the\ninlier samples of the previously determined best model.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom skimage.measure import LineModelND, ransac\n\nrng = np.random.default_rng()\n\n# generate coordinates of line\nx = np.arange(-200, 200)\ny = 0.2 * x + 20\ndata = np.column_stack([x, y])\n\n# add gaussian noise to coordinates\nnoise = rng.normal(size=data.shape)\ndata += 0.5 * noise\ndata[::2] += 5 * noise[::2]\ndata[::4] += 20 * noise[::4]\n\n# add faulty data\nfaulty = np.array(30 * [(180.0, -100)])\nfaulty += 10 * rng.normal(size=faulty.shape)\ndata[: faulty.shape[0]] = faulty\n\n# fit line using all data\nmodel = LineModelND.from_estimate(data)\n\n# robustly fit line only using inlier data with RANSAC algorithm\nmodel_robust, inliers = ransac(\n    data, LineModelND, min_samples=2, residual_threshold=1, max_trials=1000\n)\noutliers = inliers == False\n\n# generate coordinates of estimated models\nline_x = np.arange(-250, 250)\nline_y = model.predict_y(line_x)\nline_y_robust = model_robust.predict_y(line_x)\n\nfig, ax = plt.subplots()\nax.plot(data[inliers, 0], data[inliers, 1], '.b', alpha=0.6, label='Inlier data')\nax.plot(data[outliers, 0], data[outliers, 1], '.r', alpha=0.6, label='Outlier data')\nax.plot(line_x, line_y, '-k', label='Line model from all data')\nax.plot(line_x, line_y_robust, '-b', label='Robust line model')\nax.legend(loc='lower left')\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now, we generalize this example to 3D points.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nfrom matplotlib import pyplot as plt\nfrom skimage.measure import LineModelND, ransac\n\n\n# generate coordinates of line\npoint = np.array([0, 0, 0], dtype='float')\ndirection = np.array([1, 1, 1], dtype='float') / np.sqrt(3)\nxyz = point + 10 * np.arange(-100, 100)[..., np.newaxis] * direction\n\n# add gaussian noise to coordinates\nnoise = rng.normal(size=xyz.shape)\nxyz += 0.5 * noise\nxyz[::2] += 20 * noise[::2]\nxyz[::4] += 100 * noise[::4]\n\n# robustly fit line only using inlier data with RANSAC algorithm\nmodel_robust, inliers = ransac(\n    xyz, LineModelND, min_samples=2, residual_threshold=1, max_trials=1000\n)\noutliers = inliers == False\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.scatter(\n    xyz[inliers][:, 0],\n    xyz[inliers][:, 1],\n    xyz[inliers][:, 2],\n    c='b',\n    marker='o',\n    label='Inlier data',\n)\nax.scatter(\n    xyz[outliers][:, 0],\n    xyz[outliers][:, 1],\n    xyz[outliers][:, 2],\n    c='r',\n    marker='o',\n    label='Outlier data',\n)\nax.legend(loc='lower left')\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
}