{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Fundamental matrix estimation\n\nThis example demonstrates how to robustly estimate\n`epipolar geometry <https://en.wikipedia.org/wiki/Epipolar_geometry>`\n(the geometry of stereo vision) between two views using sparse ORB feature\ncorrespondences.\n\nThe [fundamental matrix](https://en.wikipedia.org/wiki/Fundamental_matrix_(computer_vision))\nrelates corresponding points between a pair of\nuncalibrated images. The matrix transforms homogeneous image points in one image\nto epipolar lines in the other image.\n\nUncalibrated means that the intrinsic calibration (focal lengths, pixel skew,\nprincipal point) of the two cameras is not known. The fundamental matrix thus\nenables projective 3D reconstruction of the captured scene. If the calibration\nis known, estimating the essential matrix enables metric 3D reconstruction of\nthe captured scene.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nfrom skimage import data\nfrom skimage.color import rgb2gray\nfrom skimage.feature import match_descriptors, ORB, plot_matched_features\nfrom skimage.measure import ransac\nfrom skimage.transform import FundamentalMatrixTransform\nimport matplotlib.pyplot as plt\n\nimg_left, img_right, groundtruth_disp = data.stereo_motorcycle()\nimg_left, img_right = map(rgb2gray, (img_left, img_right))\n\n# Find sparse feature correspondences between left and right image.\n\ndescriptor_extractor = ORB()\n\ndescriptor_extractor.detect_and_extract(img_left)\nkeypoints_left = descriptor_extractor.keypoints\ndescriptors_left = descriptor_extractor.descriptors\n\ndescriptor_extractor.detect_and_extract(img_right)\nkeypoints_right = descriptor_extractor.keypoints\ndescriptors_right = descriptor_extractor.descriptors\n\nmatches = match_descriptors(descriptors_left, descriptors_right, cross_check=True)\n\nprint(f'Number of matches: {matches.shape[0]}')\n\n# Estimate the epipolar geometry between the left and right image.\nrandom_seed = 9\nrng = np.random.default_rng(random_seed)\n\nmodel, inliers = ransac(\n    (keypoints_left[matches[:, 0]], keypoints_right[matches[:, 1]]),\n    FundamentalMatrixTransform,\n    min_samples=8,\n    residual_threshold=1,\n    max_trials=5000,\n    rng=rng,\n)\n\ninlier_keypoints_left = keypoints_left[matches[inliers, 0]]\ninlier_keypoints_right = keypoints_right[matches[inliers, 1]]\n\nprint(f'Number of inliers: {inliers.sum()}')\n\n# Compare estimated sparse disparities to the dense ground-truth disparities.\n\ndisp = inlier_keypoints_left[:, 1] - inlier_keypoints_right[:, 1]\ndisp_coords = np.round(inlier_keypoints_left).astype(np.int64)\ndisp_idxs = np.ravel_multi_index(disp_coords.T, groundtruth_disp.shape)\ndisp_error = np.abs(groundtruth_disp.ravel()[disp_idxs] - disp)\ndisp_error = disp_error[np.isfinite(disp_error)]\n\n# Visualize the results.\n\nfig, ax = plt.subplots(nrows=2, ncols=1)\n\nplt.gray()\n\nplot_matched_features(\n    img_left,\n    img_right,\n    keypoints0=keypoints_left,\n    keypoints1=keypoints_right,\n    matches=matches[inliers],\n    ax=ax[0],\n    only_matches=True,\n)\nax[0].axis(\"off\")\nax[0].set_title(\"Inlier correspondences\")\n\nax[1].hist(disp_error)\nax[1].set_title(\"Histogram of disparity errors\")\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
}