{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Using geometric transformations\n\nIn this example, we will see how to use geometric transformations in the context\nof image processing.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom skimage import data\nfrom skimage import transform"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Basics\n\nSeveral different geometric transformation types are supported: similarity,\naffine, projective and polynomial. For a tutorial on the available types of\ntransformations, see `sphx_glr_auto_examples_transform_plot_transform_types.py`.\n\nGeometric transformations can either be created using the explicit\nparameters (e.g. scale, shear, rotation and translation) or the\ntransformation matrix.\n\nFirst we create a transformation using explicit parameters:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "tform = transform.SimilarityTransform(scale=1, rotation=math.pi / 2, translation=(0, 1))\nprint(tform.params)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Alternatively you can define a transformation by the transformation matrix\nitself:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "matrix = tform.params.copy()\nmatrix[1, 2] = 2\ntform2 = transform.SimilarityTransform(matrix)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "These transformation objects can then be used to apply forward and inverse\ncoordinate transformations between the source and destination coordinate\nsystems:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "coord = [1, 0]\nprint(tform2(coord))\nprint(tform2.inverse(tform(coord)))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Image warping\n\nGeometric transformations can also be used to warp images:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "text = data.text()\n\ntform = transform.SimilarityTransform(\n    scale=1, rotation=math.pi / 4, translation=(text.shape[0] / 2, -100)\n)\n\nrotated = transform.warp(text, tform)\nback_rotated = transform.warp(rotated, tform.inverse)\n\nfig, ax = plt.subplots(nrows=3)\n\nax[0].imshow(text, cmap=plt.cm.gray)\nax[1].imshow(rotated, cmap=plt.cm.gray)\nax[2].imshow(back_rotated, cmap=plt.cm.gray)\n\nfor a in ax:\n    a.axis('off')\n\nplt.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Parameter estimation\n\nIn addition to the basic functionality mentioned above you can also\ngenerate a transform by estimating the parameters of a geometric\ntransformation using the least squares method.\n\nThis can amongst other things be used for image registration or\nrectification, where you have a set of control points or\nhomologous/corresponding points in two images.\n\nLet's assume we want to recognize letters on a photograph which was not\ntaken from the front but at a certain angle. In the simplest case of a\nplane paper surface the letters are projectively distorted. Simple matching\nalgorithms would not be able to match such symbols. One solution to this\nproblem would be to warp the image so that the distortion is removed and\nthen apply a matching algorithm:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "text = data.text()\n\nsrc = np.array([[0, 0], [0, 50], [300, 50], [300, 0]])\ndst = np.array([[155, 15], [65, 40], [260, 130], [360, 95]])\n\ntform3 = transform.ProjectiveTransform.from_estimate(src, dst)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div class=\"alert alert-info\"><h4>Note</h4><p>For many transform types, including the ``ProjectiveTransform``, it is\n   possible for the estimation to fail.  If this is the case,\n   ``from_estimate`` returns a special object of type ``FailedEstimation``.\n   This object describes the reason for the failure and can be tested for.\n   The following is a typical pattern to handle failed estimations\n   explicitly:\n\n```python\nif not tform3:  # If result is *falsey*, we have a failed estimation.\n    raise RuntimeError(f'Failed estimation: {tform3}')\n```\n   See `failed-estimation` below for more details.</p></div>\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "warped = transform.warp(text, tform3, output_shape=(50, 300))\n\nfig, ax = plt.subplots(nrows=2, figsize=(8, 3))\n\nax[0].imshow(text, cmap=plt.cm.gray)\nax[0].plot(dst[:, 0], dst[:, 1], '.r')\nax[1].imshow(warped, cmap=plt.cm.gray)\n\nfor a in ax:\n    a.axis('off')\n\nplt.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The above estimation relies on accurate knowledge of the location of points\nand an accurate selection of their correspondence. If point locations have\nan uncertainty associated with them, then weighting can be provided so that\nthe resulting transform prioritises an accurate fit to those points with the\nhighest weighting.\nAn alternative approach called the\n[RANSAC algorithm](https://en.wikipedia.org/wiki/Random_sample_consensus)\nis useful when the correspondence points are not perfectly accurate.\nSee the `sphx_glr_auto_examples_transform_plot_matching.py` tutorial\nfor an in-depth description of how to use this approach in scikit-image.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n## Failed estimation\n\nThere are situations where transform classes can fail to estimate a valid\ntransformation, and we recommend that you always check for this possible\ncase.\n\nIf estimation succeeds, the result you get back will be a valid estimated\ntransform.  You can check if you have a valid transform by truth testing.\nE.g., the estimation from the previous section ``tform3`` is valid and *truthy*:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "bool(tform3)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "However, if estimation failed, the ``from_estimate`` method returns a\nspecial object of type ``FailedEstimation``.  Here is an example of a failed\nestimation, where all the input points are the same:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Repeat last point 4 times, for four identical points.\nbad_src = np.tile(src[-1, :], (4, 1))\nbad_tform = transform.ProjectiveTransform.from_estimate(bad_src, dst)\nbad_tform"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This object type is *falsey*---meaning that:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "bool(bad_tform)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "You can access the raw message string of the failure with\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "str(bad_tform)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We recommend that you put in a routine check to confirm the estimation\nsucceeded:\n\n```python\nif not bad_tform:\n    raise RuntimeError(f'Failed estimation: {bad_tform}')\n```\nOf course, there may be times, where you did not check the *truthiness* of\nthe estimation, and you nevertheless try to use the returned estimate.  In\nthis case, you'll get a :class:`~.FailedEstimationAccessError`---a custom\nsubclass of a :class:`AttributeError`.\n\n"
      ]
    }
  ],
  "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
}