{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Use thin-plate splines for image warping\n\nTo warp an image, we start with a set of source and target coordinates.\nThe goal is to deform the image such that the source points move to the target\nlocations. Typically, we only know the target positions for a few, select\nsource points. To calculate the target positions for all other pixel positions,\nwe need a model. Various such models exist, such as [affine or projective\ntransformations](https://scikit-image.org/docs/stable/auto_examples/transform/plot_transform_types.html).\n\nMost transformations are linear (i.e., they preserve straight lines), but\nsometimes we need more flexibility. One model that represents a non-linear\ntransformation, i.e. one where lines can bend, is thin-plate splines [1]_ [2]_.\n\nThin-plate splines draw on the analogy of a metal sheet, which has inherent\nrigidity. Consider our source points: each has to move a certain distance, in\nboth the x and y directions, to land in its corresponding target position.\nFirst, examine only the x coordinates. Imagine placing a thin metal plate on\ntop of the image. Now bend it, such that at each source point, the plate's\nz offset is the distance, positive or negative, that that source point has to\ntravel in the x direction in order to land in its target position. The plate\nresists bending, and therefore remains smooth. We can read offsets for\ncoordinates other than source points from the position of the plate. The same\nprocedure can be repeated for the y coordinates.\n\nThis gives us our thin-plate spline model that maps any (x, y) coordinate to a\ntarget position.\n\n.. [1] Wikipedia, Thin plate spline\n       https://en.wikipedia.org/wiki/Thin_plate_spline\n\n.. [2] Bookstein, Fred L. \"Principal warps: Thin-plate splines and the\n       decomposition of deformations.\" IEEE Transactions on pattern analysis and\n       machine intelligence 11.6 (1989): 567\u2013585.\n       :DOI:`10.1109/34.24792`\n       https://user.engineering.uiowa.edu/~aip/papers/bookstein-89.pdf\n\n\n## Correct barrel distortion\n\nIn this example, we demonstrate how to correct barrel distortion [3]_ using\na thin-plate spline transform. Barrel distortion creates the characteristic fisheye\neffect, where image magnification decreases with distance from the image center.\n\nWe first generate an example dataset, by applying a fisheye warp to a checkboard\nimage, and thereafter apply the inverse corrective transform.\n\n.. [3] [https://en.wikipedia.org/wiki/Distortion_(optics)#Radial_distortion](https://en.wikipedia.org/wiki/Distortion_(optics)#Radial_distortion)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport skimage as ski\n\n\ndef radial_distortion(xy, k1=0.9, k2=0.5):\n    \"\"\"Distort coordinates `xy` symmetrically around their own center.\"\"\"\n    xy_c = xy.max(axis=0) / 2\n    xy = (xy - xy_c) / xy_c\n    radius = np.linalg.norm(xy, axis=1)\n    distortion_model = (1 + k1 * radius + k2 * radius**2) * k2\n    xy *= distortion_model.reshape(-1, 1)\n    xy = xy * xy_c + xy_c\n    return xy\n\n\nimage = ski.data.checkerboard()\nimage = ski.transform.warp(image, radial_distortion, cval=0.5)\n\n\n# Pick a few `src` points by hand, and move the corresponding `dst` points to their\n# expected positions.\n# fmt: off\nsrc = np.array([[22,  22], [100,  10], [177, 22], [190, 100], [177, 177], [100, 188],\n                [22, 177], [ 10, 100], [ 66, 66], [133,  66], [ 66, 133], [133, 133]])\ndst = np.array([[ 0,   0], [100,   0], [200,  0], [200, 100], [200, 200], [100, 200],\n                [ 0, 200], [  0, 100], [ 73, 73], [128,  73], [ 73, 128], [128, 128]])\n# fmt: on\n\n# Estimate the TPS transformation from these points and then warp the image.\n# We switch `src` and `dst` here because `skimage.transform.warp` requires the\n# inverse transformation!\ntps = ski.transform.ThinPlateSplineTransform.from_estimate(dst, src)\nwarped = ski.transform.warp(image, tps)\n\n\n# Plot the results\nfig, axs = plt.subplots(1, 2)\naxs[0].imshow(image, cmap='gray')\naxs[0].scatter(src[:, 0], src[:, 1], marker='x', color='cyan')\naxs[1].imshow(warped, cmap='gray', extent=(0, 200, 200, 0))\naxs[1].scatter(dst[:, 0], dst[:, 1], marker='x', color='cyan')\n\npoint_labels = [str(i) for i in range(len(src))]\nfor i, label in enumerate(point_labels):\n    axs[0].annotate(\n        label,\n        (src[:, 0][i], src[:, 1][i]),\n        textcoords=\"offset points\",\n        xytext=(0, 5),\n        ha='center',\n        color='red',\n    )\n    axs[1].annotate(\n        label,\n        (dst[:, 0][i], dst[:, 1][i]),\n        textcoords=\"offset points\",\n        xytext=(0, 5),\n        ha='center',\n        color='red',\n    )\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
}