{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Assemble images with simple image stitching\n\nThis example demonstrates how a set of images can be assembled under\nthe hypothesis of rigid body motions.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from matplotlib import pyplot as plt\nimport numpy as np\nfrom skimage import data, util, transform, feature, measure, filters, metrics\n\n\ndef match_locations(img0, img1, coords0, coords1, radius=5, sigma=3):\n    \"\"\"Match image locations using SSD minimization.\n\n    Areas from `img0` are matched with areas from `img1`. These areas\n    are defined as patches located around pixels with Gaussian\n    weights.\n\n    Parameters\n    ----------\n    img0, img1 : 2D array\n        Input images.\n    coords0 : (2, m) array_like\n        Centers of the reference patches in `img0`.\n    coords1 : (2, n) array_like\n        Centers of the candidate patches in `img1`.\n    radius : int\n        Radius of the considered patches.\n    sigma : float\n        Standard deviation of the Gaussian kernel centered over the patches.\n\n    Returns\n    -------\n    match_coords: (2, m) array\n        The points in `coords1` that are the closest corresponding matches to\n        those in `coords0` as determined by the (Gaussian weighted) sum of\n        squared differences between patches surrounding each point.\n    \"\"\"\n    y, x = np.mgrid[-radius : radius + 1, -radius : radius + 1]\n    weights = np.exp(-0.5 * (x**2 + y**2) / sigma**2)\n    weights /= 2 * np.pi * sigma * sigma\n\n    match_list = []\n    for r0, c0 in coords0:\n        roi0 = img0[r0 - radius : r0 + radius + 1, c0 - radius : c0 + radius + 1]\n        roi1_list = [\n            img1[r1 - radius : r1 + radius + 1, c1 - radius : c1 + radius + 1]\n            for r1, c1 in coords1\n        ]\n        # sum of squared differences\n        ssd_list = [np.sum(weights * (roi0 - roi1) ** 2) for roi1 in roi1_list]\n        match_list.append(coords1[np.argmin(ssd_list)])\n\n    return np.array(match_list)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Data generation\n\nFor this example, we generate a list of slightly tilted noisy images.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "img = data.moon()\n\nangle_list = [0, 5, 6, -2, 3, -4]\ncenter_list = [(0, 0), (10, 10), (5, 12), (11, 21), (21, 17), (43, 15)]\n\nimg_list = [\n    transform.rotate(img, angle=a, center=c)[40:240, 50:350]\n    for a, c in zip(angle_list, center_list)\n]\nref_img = img_list[0].copy()\n\nimg_list = [\n    util.random_noise(filters.gaussian(im, sigma=1.1), var=5e-4, rng=seed)\n    for seed, im in enumerate(img_list)\n]\n\npsnr_ref = metrics.peak_signal_noise_ratio(ref_img, img_list[0])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Image registration\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>This step is performed using the approach described in\n   `sphx_glr_auto_examples_transform_plot_matching.py`, but any other\n   method from the `sphx_glr_auto_examples_registration` section can be\n   applied, depending on your problem.</p></div>\n\nReference points are detected over all images in the list.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "min_dist = 5\ncorner_list = [\n    feature.corner_peaks(\n        feature.corner_harris(img), threshold_rel=0.001, min_distance=min_dist\n    )\n    for img in img_list\n]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The Harris corners detected in the first image are chosen as\nreferences. Then the detected points on the other images are\nmatched to the reference points.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "img0 = img_list[0]\ncoords0 = corner_list[0]\nmatching_corners = [\n    match_locations(img0, img1, coords0, coords1, min_dist)\n    for img1, coords1 in zip(img_list, corner_list)\n]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Once all the points are registered to the reference points, robust\nrelative affine transformations can be estimated using the RANSAC method.\n\n.. hint::\n   :func:`skimage.measure.ransac` uses random sampling to estimate a model's\n   parameters. Sometimes, the number of trials may not be enough to arrive\n   at a successful estimation. To make this example deterministic, we pass a\n   seed ``42`` to the parameter ``rng`` that is known to be successful.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "src = np.array(coords0)\ntrfm_list = [\n    measure.ransac(\n        (dst, src),\n        transform.EuclideanTransform,\n        min_samples=3,\n        residual_threshold=2,\n        max_trials=100,\n        rng=42,\n    )[0].params\n    for dst in matching_corners\n]\n\nfig, ax_list = plt.subplots(6, 2, figsize=(6, 9), sharex=True, sharey=True)\nfor idx, (im, trfm, (ax0, ax1)) in enumerate(zip(img_list, trfm_list, ax_list)):\n    ax0.imshow(im, cmap=\"gray\", vmin=0, vmax=1)\n    ax1.imshow(transform.warp(im, trfm), cmap=\"gray\", vmin=0, vmax=1)\n\n    if idx == 0:\n        ax0.set_title(\"Tilted images\")\n        ax0.set_ylabel(f\"Reference Image\\n(PSNR={psnr_ref:.2f})\")\n        ax1.set_title(\"Registered images\")\n\n    ax0.set(xticklabels=[], yticklabels=[], xticks=[], yticks=[])\n    ax1.set_axis_off()\n\nfig.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Image assembling\n\nA composite image can be obtained using the positions of the\nregistered images relative to the reference one. To do so, we define\na global domain around the reference image and position the other\nimages in this domain.\n\nA global transformation is defined to move the reference image in the\nglobal domain image via a simple translation:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "margin = 50\nheight, width = img_list[0].shape\nout_shape = height + 2 * margin, width + 2 * margin\nglob_trfm = np.eye(3)\nglob_trfm[:2, 2] = -margin, -margin"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally, the relative position of the other images in the global\ndomain are obtained by composing the global transformation with the\nrelative transformations:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "global_img_list = [\n    transform.warp(\n        img, trfm.dot(glob_trfm), output_shape=out_shape, mode=\"constant\", cval=np.nan\n    )\n    for img, trfm in zip(img_list, trfm_list)\n]\n\nall_nan_mask = np.all([np.isnan(img) for img in global_img_list], axis=0)\nglobal_img_list[0][all_nan_mask] = 1.0\n\ncomposite_img = np.nanmean(global_img_list, 0)\npsnr_composite = metrics.peak_signal_noise_ratio(\n    ref_img, composite_img[margin : margin + height, margin : margin + width]\n)\n\nfig, ax = plt.subplots(1, 1)\n\nax.imshow(composite_img, cmap=\"gray\", vmin=0, vmax=1)\nax.set_axis_off()\nax.set_title(f\"Reconstructed image (PSNR={psnr_composite:.2f})\")\nfig.tight_layout()\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
}