{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Affine Registration in 3D\n\nThis example explains how to compute an affine transformation to register two\n3D volumes by maximization of their Mutual Information [Mattes03]_. The\noptimization strategy is similar to that implemented in ANTS [Avants11]_.\n\nWe will do this twice. The first part of this tutorial will walk through the\ndetails of the process with the object-oriented interface implemented in\nthe ``dipy.align`` module. The second part will use a simplified functional\ninterface.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from os.path import join as pjoin\nimport numpy as np\nfrom dipy.viz import regtools\nfrom dipy.data import fetch_stanford_hardi\nfrom dipy.data.fetcher import fetch_syn_data\nfrom dipy.io.image import load_nifti\nfrom dipy.align.imaffine import (transform_centers_of_mass,\n AffineMap,\n MutualInformationMetric,\n AffineRegistration)\nfrom dipy.align.transforms import (TranslationTransform3D,\n RigidTransform3D,\n AffineTransform3D)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's fetch two b0 volumes, the static image will be the b0 from the Stanford\nHARDI dataset\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "files, folder = fetch_stanford_hardi()\nstatic_data, static_affine, static_img = load_nifti(\n pjoin(folder, 'HARDI150.nii.gz'),\n return_img=True)\nstatic = np.squeeze(static_data)[..., 0]\nstatic_grid2world = static_affine" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now the moving image\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "files, folder2 = fetch_syn_data()\nmoving_data, moving_affine, moving_img = load_nifti(\n pjoin(folder2, 'b0.nii.gz'),\n return_img=True)\nmoving = moving_data\nmoving_grid2world = moving_affine" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see that the images are far from aligned by drawing one on top of\nthe other. The images don't even have the same number of voxels, so in order\nto draw one on top of the other we need to resample the moving image on a grid\nof the same dimensions as the static image, we can do this by \"transforming\"\nthe moving image using an identity transform\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "identity = np.eye(4)\naffine_map = AffineMap(identity,\n static.shape, static_grid2world,\n moving.shape, moving_grid2world)\nresampled = affine_map.transform(moving)\nregtools.overlay_slices(static, resampled, None, 0,\n \"Static\", \"Moving\", \"resampled_0.png\")\nregtools.overlay_slices(static, resampled, None, 1,\n \"Static\", \"Moving\", \"resampled_1.png\")\nregtools.overlay_slices(static, resampled, None, 2,\n \"Static\", \"Moving\", \"resampled_2.png\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. figure:: resampled_0.png\n :align: center\n.. figure:: resampled_1.png\n :align: center\n.. figure:: resampled_2.png\n :align: center\n\n Input images before alignment.\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can obtain a very rough (and fast) registration by just aligning the centers\nof mass of the two images\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "c_of_mass = transform_centers_of_mass(static, static_grid2world,\n moving, moving_grid2world)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now transform the moving image and draw it on top of the static image,\nregistration is not likely to be good, but at least they will occupy roughly\nthe same space\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "transformed = c_of_mass.transform(moving)\nregtools.overlay_slices(static, transformed, None, 0,\n \"Static\", \"Transformed\", \"transformed_com_0.png\")\nregtools.overlay_slices(static, transformed, None, 1,\n \"Static\", \"Transformed\", \"transformed_com_1.png\")\nregtools.overlay_slices(static, transformed, None, 2,\n \"Static\", \"Transformed\", \"transformed_com_2.png\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. figure:: transformed_com_0.png\n :align: center\n.. figure:: transformed_com_1.png\n :align: center\n.. figure:: transformed_com_2.png\n :align: center\n\n Registration result by aligning the centers of mass of the images.\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This was just a translation of the moving image towards the static image, now\nwe will refine it by looking for an affine transform. We first create the\nsimilarity metric (Mutual Information) to be used. We need to specify the\nnumber of bins to be used to discretize the joint and marginal probability\ndistribution functions (PDF), a typical value is 32. We also need to specify\nthe percentage (an integer in (0, 100]) of voxels to be used for computing the\nPDFs, the most accurate registration will be obtained by using all voxels, but\nit is also the most time-consuming choice. We specify full sampling by passing\nNone instead of an integer\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "nbins = 32\nsampling_prop = None\nmetric = MutualInformationMetric(nbins, sampling_prop)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To avoid getting stuck at local optima, and to accelerate convergence, we use a\nmulti-resolution strategy (similar to ANTS [Avants11]_) by building a Gaussian\nPyramid. To have as much flexibility as possible, the user can specify how this\nGaussian Pyramid is built. First of all, we need to specify how many\nresolutions we want to use. This is indirectly specified by just providing a\nlist of the number of iterations we want to perform at each resolution. Here we\nwill just specify 3 resolutions and a large number of iterations, 10000 at the\ncoarsest resolution, 1000 at the medium resolution and 100 at the finest. These\nare the default settings\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "level_iters = [10000, 1000, 100]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To compute the Gaussian pyramid, the original image is first smoothed at each\nlevel of the pyramid using a Gaussian kernel with the requested sigma. A good\ninitial choice is [3.0, 1.0, 0.0], this is the default\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "sigmas = [3.0, 1.0, 0.0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we specify the sub-sampling factors. A good configuration is [4, 2, 1],\nwhich means that, if the original image shape was (nx, ny, nz) voxels, then the\nshape of the coarsest image will be about (nx//4, ny//4, nz//4), the shape in\nthe middle resolution will be about (nx//2, ny//2, nz//2) and the image at the\nfinest scale has the same size as the original image. This set of factors is\nthe default\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "factors = [4, 2, 1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we go ahead and instantiate the registration class with the configuration\nwe just prepared\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "affreg = AffineRegistration(metric=metric,\n level_iters=level_iters,\n sigmas=sigmas,\n factors=factors)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using AffineRegistration we can register our images in as many stages as we\nwant, providing previous results as initialization for the next (the same logic\nas in ANTS). The reason why it is useful is that registration is a non-convex\noptimization problem (it may have more than one local optima), which means that\nit is very important to initialize as close to the solution as possible. For\nexample, let's start with our (previously computed) rough transformation\naligning the centers of mass of our images, and then refine it in three stages.\nFirst look for an optimal translation. The dictionary regtransforms contains\nall available transforms, we obtain one of them by providing its name and the\ndimension (either 2 or 3) of the image we are working with (since we are\naligning volumes, the dimension is 3)\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "transform = TranslationTransform3D()\nparams0 = None\nstarting_affine = c_of_mass.affine\ntranslation = affreg.optimize(static, moving, transform, params0,\n static_grid2world, moving_grid2world,\n starting_affine=starting_affine)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we look at the result, we can see that this translation is much better than\nsimply aligning the centers of mass\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "transformed = translation.transform(moving)\nregtools.overlay_slices(static, transformed, None, 0,\n \"Static\", \"Transformed\", \"transformed_trans_0.png\")\nregtools.overlay_slices(static, transformed, None, 1,\n \"Static\", \"Transformed\", \"transformed_trans_1.png\")\nregtools.overlay_slices(static, transformed, None, 2,\n \"Static\", \"Transformed\", \"transformed_trans_2.png\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. figure:: transformed_trans_0.png\n :align: center\n.. figure:: transformed_trans_1.png\n :align: center\n.. figure:: transformed_trans_2.png\n :align: center\n\n Registration result by translating the moving image, using\n Mutual Information.\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's refine with a rigid transform (this may even modify our previously\nfound optimal translation)\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "transform = RigidTransform3D()\nparams0 = None\nstarting_affine = translation.affine\nrigid = affreg.optimize(static, moving, transform, params0,\n static_grid2world, moving_grid2world,\n starting_affine=starting_affine)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This produces a slight rotation, and the images are now better aligned\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "transformed = rigid.transform(moving)\nregtools.overlay_slices(static, transformed, None, 0,\n \"Static\", \"Transformed\", \"transformed_rigid_0.png\")\nregtools.overlay_slices(static, transformed, None, 1,\n \"Static\", \"Transformed\", \"transformed_rigid_1.png\")\nregtools.overlay_slices(static, transformed, None, 2,\n \"Static\", \"Transformed\", \"transformed_rigid_2.png\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. figure:: transformed_rigid_0.png\n :align: center\n.. figure:: transformed_rigid_1.png\n :align: center\n.. figure:: transformed_rigid_2.png\n :align: center\n\n Registration result with a rigid transform, using Mutual Information.\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, let's refine with a full affine transform (translation, rotation, scale\nand shear), it is safer to fit more degrees of freedom now since we must be\nvery close to the optimal transform\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "transform = AffineTransform3D()\nparams0 = None\nstarting_affine = rigid.affine\naffine = affreg.optimize(static, moving, transform, params0,\n static_grid2world, moving_grid2world,\n starting_affine=starting_affine)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This results in a slight shear and scale\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "transformed = affine.transform(moving)\nregtools.overlay_slices(static, transformed, None, 0,\n \"Static\", \"Transformed\", \"transformed_affine_0.png\")\nregtools.overlay_slices(static, transformed, None, 1,\n \"Static\", \"Transformed\", \"transformed_affine_1.png\")\nregtools.overlay_slices(static, transformed, None, 2,\n \"Static\", \"Transformed\", \"transformed_affine_2.png\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. figure:: transformed_affine_0.png\n :align: center\n.. figure:: transformed_affine_1.png\n :align: center\n.. figure:: transformed_affine_2.png\n :align: center\n\n Registration result with an affine transform, using Mutual Information.\n\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, let's repeat this process with a simplified functional interface:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from dipy.align import affine_registration, register_dwi_to_template" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This interface constructs a pipeline of operations from a given list of\ntransformations.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "pipeline = [\"center_of_mass\", \"translation\", \"rigid\", \"affine\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And then applies the transformations in the pipeline on the input (from left to\nright) with a call to an `affine_registration` function, which takes optional\nsettings for things like the iterations, sigmas and factors. The pipeline must\nbe a list of strings with one or more of the following transformations:\ncenter_of_mass, translation, rigid, rigid_isoscaling, rigid_scaling and affine.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "xformed_img, reg_affine = affine_registration(\n moving,\n static,\n moving_affine=moving_affine,\n static_affine=static_affine,\n nbins=32,\n metric='MI',\n pipeline=pipeline,\n level_iters=level_iters,\n sigmas=sigmas,\n factors=factors)\n\nregtools.overlay_slices(static, xformed_img, None, 0,\n \"Static\", \"Transformed\", \"xformed_affine_0.png\")\nregtools.overlay_slices(static, xformed_img, None, 1,\n \"Static\", \"Transformed\", \"xformed_affine_1.png\")\nregtools.overlay_slices(static, xformed_img, None, 2,\n \"Static\", \"Transformed\", \"xformed_affine_2.png\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. figure:: xformed_affine_0.png\n :align: center\n.. figure:: xformed_affine_1.png\n :align: center\n.. figure:: xformed_affine_2.png\n :align: center\n\n Registration result with an affine transform, using functional interface.\n\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, you can also use the `register_dwi_to_template` function that\nneeds to also know about the gradient table of the DWI data, provided as a\ntuple of (bvals_file, bvecs_file). In this case, we are going to move the\ndiffusion data to the B0 image (the opposite of the previous examples), which\nreverses what is the \"moving\" image and what is \"static\".\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "xformed_dwi, reg_affine = register_dwi_to_template(\n dwi=static_img,\n gtab=(pjoin(folder, 'HARDI150.bval'),\n pjoin(folder, 'HARDI150.bvec')),\n template=moving_img,\n reg_method=\"aff\",\n nbins=32,\n metric='MI',\n pipeline=pipeline,\n level_iters=level_iters,\n sigmas=sigmas,\n factors=factors)\n\nregtools.overlay_slices(moving, xformed_dwi, None, 0,\n \"Static\", \"Transformed\", \"xformed_dwi_0.png\")\nregtools.overlay_slices(moving, xformed_dwi, None, 1,\n \"Static\", \"Transformed\", \"xformed_dwi_1.png\")\nregtools.overlay_slices(moving, xformed_dwi, None, 2,\n \"Static\", \"Transformed\", \"xformed_dwi_2.png\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. figure:: xformed_dwi_0.png\n :align: center\n.. figure:: xformed_dwi_1.png\n :align: center\n.. figure:: xformed_dwi_2.png\n :align: center\n\n Same again, using the `dwi_to_template` functional interface.\n\n\n.. [Mattes03] Mattes, D., Haynor, D. R., Vesselle, H., Lewellen, T. K.,\n Eubank, W. (2003). PET-CT image registration in the chest using\n free-form deformations. IEEE Transactions on Medical Imaging,\n 22(1), 120-8.\n.. [Avants11] Avants, B. B., Tustison, N., & Song, G. (2011). Advanced\n Normalization Tools (ANTS), 1-35.\n\n.. include:: ../links_names.inc\n\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.9.13" } }, "nbformat": 4, "nbformat_minor": 0 }