├── test ├── __init__.py ├── README.md ├── test_base_transformation.py ├── test_base_interpolation.py ├── test_utils.py ├── test_linear_transformation.py ├── test_bspline_interpolation.py ├── test_translation_transformation.py ├── test_isotropic_scaling_transformation.py ├── test_anisotropic_scaling_transformation.py ├── test_grid.py ├── test_composed_transformation.py ├── test_bspline_transformation.py ├── test_bspline_cuda_transformation.py ├── test_linear_interpolation.py ├── test_bspline_cuda_interpolation.py ├── test_multichannel_interpolation.py └── test_affine_transformation.py ├── examples.png ├── grid_examples.png ├── notebooks ├── lung_ct.png ├── cupy_interpolation.png ├── cupy_transformation.png └── gpu_support.ipynb ├── gryds ├── config.py ├── __init__.py ├── interpolators │ ├── __init__.py │ ├── base.py │ ├── cuda.py │ ├── linear.py │ ├── grid.py │ ├── color.py │ └── bspline.py ├── transformers │ ├── __init__.py │ ├── translation.py │ ├── linear.py │ ├── composed.py │ ├── cuda.py │ ├── bspline.py │ ├── base.py │ └── affine.py └── utils.py ├── profiling ├── comp.py ├── graphs_interpolation.py ├── graphs_transformation.py ├── graphs_multiple_transformations.py └── README.md ├── setup.py ├── .gitignore ├── README.md └── LICENSE /test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tueimage/gryds/HEAD/examples.png -------------------------------------------------------------------------------- /grid_examples.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tueimage/gryds/HEAD/grid_examples.png -------------------------------------------------------------------------------- /notebooks/lung_ct.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tueimage/gryds/HEAD/notebooks/lung_ct.png -------------------------------------------------------------------------------- /notebooks/cupy_interpolation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tueimage/gryds/HEAD/notebooks/cupy_interpolation.png -------------------------------------------------------------------------------- /notebooks/cupy_transformation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tueimage/gryds/HEAD/notebooks/cupy_transformation.png -------------------------------------------------------------------------------- /gryds/config.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Config file 4 | 5 | 6 | import numpy 7 | DTYPE = numpy.float32 8 | -------------------------------------------------------------------------------- /gryds/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Implement transformations of images, grids, and points 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | from .transformers import * 9 | from .interpolators import * 10 | from .utils import dvf_show, dvf_opts 11 | from .config import DTYPE 12 | -------------------------------------------------------------------------------- /test/README.md: -------------------------------------------------------------------------------- 1 | # Testing 2 | 3 | To run the test methods, run the following from this folder: 4 | 5 | ``` 6 | python -m unittest discover 7 | ``` 8 | 9 | This will show the outcome of all tests. 10 | 11 | 12 | To assess test coverage of the codebase, use: 13 | 14 | ``` 15 | pytest --cov gryds --cov-report=test 16 | ``` 17 | 18 | to show in terminal or 19 | 20 | ``` 21 | pytest --cov gryds --cov-report=html 22 | ``` 23 | 24 | to create an interactive html-based test coverage report. 25 | -------------------------------------------------------------------------------- /gryds/interpolators/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Interpolation code 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | from .grid import Grid 9 | from .bspline import BSplineInterpolator 10 | from .linear import LinearInterpolator 11 | from .color import MultiChannelInterpolator 12 | 13 | try: 14 | from .cuda import BSplineInterpolatorCuda 15 | except ImportError: 16 | pass 17 | 18 | Interpolator = BSplineInterpolator # Default interpolator 19 | -------------------------------------------------------------------------------- /gryds/transformers/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Transformations of points and grids of points 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | from .composed import ComposedTransformation 9 | from .translation import TranslationTransformation 10 | from .linear import LinearTransformation 11 | from .affine import AffineTransformation 12 | from .bspline import BSplineTransformation 13 | from .base import Transformation 14 | 15 | try: 16 | from .cuda import BSplineTransformationCuda 17 | except ImportError: 18 | pass 19 | -------------------------------------------------------------------------------- /profiling/comp.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | sys.path.append(os.path.abspath('..')) 4 | import gryds 5 | import numpy as np 6 | from cProfile import Profile 7 | from pstats import Stats 8 | import time 9 | from gryds.interpolators import cuda 10 | import matplotlib.pyplot as plt 11 | import seaborn as sns 12 | 13 | 14 | bsp = gryds.BSplineTransformation(0.01 * (np.random.rand(2, 32, 32) - 0.5), order=1) 15 | # bsp = gryds.TranslationTransformation([0.1, 0.3]) 16 | 17 | image = np.zeros((128, 128)) 18 | image[32:-32] = 0.5 19 | image[:, 32:-32] += 0.5 20 | intp_cpu = gryds.BSplineInterpolator(image, order=1).transform(bsp) 21 | intp_gpu = cuda.BSplineInterpolatorCuda(image).transform(bsp) 22 | 23 | fig, ax = plt.subplots(1, 3) 24 | ax[0].imshow(intp_cpu, vmin=0, vmax=1) 25 | ax[1].imshow(intp_gpu, vmin=0, vmax=1) 26 | ax[2].imshow(intp_cpu - intp_gpu, vmin=-1, vmax=1) 27 | plt.show() 28 | 29 | 30 | -------------------------------------------------------------------------------- /test/test_base_transformation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestBaseTransformation(TestCase): 15 | 16 | def test_wrong_format_for_points(self): 17 | 18 | t = gryds.transformers.base.Transformation(ndim=3, parameters=[]) 19 | points = np.random.rand(2, 10) # incompatible with t.ndim=3 20 | self.assertRaises(ValueError, t._dimension_check, points) 21 | 22 | points = np.random.rand(2, 3, 10) # not a list of points 23 | self.assertRaises(ValueError, t._dimension_check, points) 24 | 25 | def test_base_transformation_transform(self): 26 | 27 | t = gryds.transformers.base.Transformation(ndim=3, parameters=[]) 28 | points = np.random.rand(2, 10) # incompatible with t.ndim=3 29 | self.assertRaises(NotImplementedError, t._transform_points, points) 30 | -------------------------------------------------------------------------------- /gryds/transformers/translation.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Translation transformation 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | import numpy as np 9 | from ..config import DTYPE 10 | from .base import Transformation 11 | 12 | 13 | class TranslationTransformation(Transformation): 14 | """Translation of points. 15 | 16 | Attributes: 17 | ndim (int): The number of dimensions. 18 | parameters (np.ndarray): Translation vector. 19 | """ 20 | 21 | def __init__(self, translation): 22 | """ 23 | Args: 24 | translation (np.array): Translation vector. 25 | """ 26 | super(TranslationTransformation, self).__init__( 27 | ndim=len(translation), 28 | parameters=np.array(translation) 29 | ) 30 | 31 | def __repr__(self): 32 | return '{}({}D, t={})'.format(self.__class__.__name__, self.ndim, self.parameters) 33 | 34 | def _transform_points(self, points): 35 | result = (points + self.parameters[:, None]) 36 | return result 37 | -------------------------------------------------------------------------------- /gryds/interpolators/base.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Transformation base class 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | from .grid import Grid 9 | from ..config import DTYPE 10 | 11 | 12 | class Interpolator(object): 13 | """Base class for interpolators, that implements the minimum requirements 14 | for sampling on grids in new images. 15 | 16 | Attributes: 17 | self.image (np.ndarray): The wrapped ND image. 18 | self.grid (Grid): The image's default sampling grid. 19 | """ 20 | 21 | def __init__(self, image): 22 | """ 23 | Args: 24 | image (np.ndarray): An ND image array. 25 | """ 26 | self.image = image 27 | self.grid = Grid(shape=self.image.shape) 28 | 29 | def __repr__(self): 30 | return '{}({}D)'.format(self.__class__.__name__, self.image.ndim) 31 | 32 | @property 33 | def shape(self): 34 | return self.image.shape 35 | 36 | def sample(self, points, **kwargs): 37 | raise NotImplementedError() 38 | 39 | def resample(self, points, **kwargs): 40 | raise NotImplementedError() 41 | 42 | def transform(self, *transforms, **kwargs): 43 | transformed_grid = self.grid.transform(*transforms) 44 | new_image = self.resample(transformed_grid, **kwargs) 45 | return new_image.astype(DTYPE) 46 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | 4 | setuptools.setup( 5 | name="gryds", 6 | version="0.0.1", 7 | author="Koen A. J. Eppenhof", 8 | author_email="k.a.j.eppenhof@tue.nl", 9 | description="Gryds: a Python package for geometric transformations of images for data augmentation in deep learning", 10 | long_description=""" 11 | Gryds enables you to make fast geometric transformations of images for the purpose of data augmentation in deep learning. 12 | The supported geometric transformations include translations, rigid transformations (translation + rotation), 13 | similarity transformations (translation + rotation + isotropic scaling), 14 | affine transformations (translation + rotation + arbitrary scaling + shearing), 15 | and deformable transformations (modeled as B-splines). It is also possible to apply the transformations to 16 | coordinates in the image domain, and to inspect the deformation vector field.""", 17 | long_description_content_type="text/markdown", 18 | url="https://github.com/tueimage/gryds", 19 | packages=setuptools.find_packages(), 20 | classifiers=[ 21 | "Programming Language :: Python :: 2.6", 22 | "Programming Language :: Python :: 2.7", 23 | "Programming Language :: Python :: 3", 24 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 25 | "Operating System :: OS Independent", 26 | ], 27 | ) 28 | -------------------------------------------------------------------------------- /test/test_base_interpolation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestBaseInterpolator(TestCase): 15 | """Tests grid initialization and scaling.""" 16 | 17 | def test_base_interpolator_shape(self): 18 | im = np.random.rand(10, 10, 10, 10) 19 | intp = gryds.base.Interpolator(im) 20 | np.testing.assert_equal(intp.shape, (10, 10, 10, 10)) 21 | 22 | def test_base_interpolator_sample(self): 23 | im = np.random.rand(10, 10, 10, 10) 24 | intp = gryds.base.Interpolator(im) 25 | self.assertRaises(NotImplementedError, intp.sample, 0) 26 | 27 | def test_base_interpolator_resample(self): 28 | im = np.random.rand(10, 10, 10, 10) 29 | intp = gryds.base.Interpolator(im) 30 | self.assertRaises(NotImplementedError, intp.resample, 0) 31 | 32 | def test_base_interpolator_transform(self): 33 | trf = gryds.TranslationTransformation([1, 2, 3, 4, 5]) 34 | im = np.random.rand(10, 10, 10, 10, 10) 35 | intp = gryds.base.Interpolator(im) 36 | self.assertRaises(NotImplementedError, intp.transform, trf) 37 | 38 | def test_repr(self): 39 | self.assertEqual( 40 | str(gryds.base.Interpolator(np.random.rand(20, 20))), 41 | 'Interpolator(2D)' 42 | ) 43 | -------------------------------------------------------------------------------- /test/test_utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestUtils(TestCase): 15 | 16 | def test_dvf_opts(self): 17 | self.assertEqual( 18 | gryds.dvf_opts(np.array([1, 2, 3])), 19 | { 20 | 'cmap': 'bwr', 21 | 'vmin': -3, 22 | 'vmax': 3 23 | } 24 | ) 25 | 26 | def test_dvf_show(self): 27 | dvf = np.array([1, 2, 3]) 28 | self.assertDictEqual( 29 | gryds.dvf_show(dvf), 30 | { 31 | 'X': dvf, 32 | 'cmap': 'bwr', 33 | 'vmin': -3, 34 | 'vmax': 3 35 | } 36 | ) 37 | 38 | def test_max_no_fold(self): 39 | np.random.seed(0) 40 | random_grid = gryds.utils.max_no_fold((2, 200, 300)) 41 | print(random_grid.max()) 42 | self.assertTrue( 43 | np.all(random_grid <= .000628141) 44 | ) 45 | self.assertTrue( 46 | np.all(random_grid >= -.000628141) 47 | ) 48 | 49 | 50 | def test_phantom(self): 51 | phantom = gryds.utils.phantom_image((3, 10), spacing=4) 52 | 53 | np.testing.assert_equal(phantom[0], 1) 54 | np.testing.assert_equal(phantom[1], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0]) 55 | np.testing.assert_equal(phantom[2], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0]) 56 | 57 | -------------------------------------------------------------------------------- /gryds/transformers/linear.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Linear transformations 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | import numpy as np 9 | from ..config import DTYPE 10 | from .base import Transformation 11 | 12 | 13 | class LinearTransformation(Transformation): 14 | """Linear transformation for 2D or 3D augmented coordinates. 15 | 16 | Attributes: 17 | ndim (int): The number of dimensions. 18 | parameters (np.ndarray): The (ndim) x (ndim + 1) transformation matrix. 19 | """ 20 | 21 | def __init__(self, matrix): 22 | """ 23 | Args: 24 | matrix (np.array): An (ndim ) x (ndim + 1) array 25 | representing the augmented affine matrix. 26 | Raises: 27 | ValueError: If the matrix is not shaped correctly. 28 | """ 29 | matrix = np.array(matrix, dtype=DTYPE) 30 | 31 | if matrix.shape[0] != matrix.shape[1] - 1: 32 | raise ValueError( 33 | 'Incorrect matrix shape, should be (ndim) x (ndim + 1),' 34 | 'is {}.'.format(matrix.shape)) 35 | 36 | super(LinearTransformation, self).__init__(len(matrix), matrix) 37 | 38 | def _transform_points(self, points): 39 | augmented_points = np.ones((self.ndim + 1, points.shape[1]), 40 | dtype=DTYPE) 41 | augmented_points[:self.ndim] = points 42 | 43 | transformed_points = np.dot(self.parameters, augmented_points) 44 | result = transformed_points[:self.ndim, :] 45 | 46 | assert result.dtype == DTYPE 47 | return result 48 | -------------------------------------------------------------------------------- /profiling/graphs_interpolation.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | sys.path.append(os.path.abspath('..')) 4 | import gryds 5 | import numpy as np 6 | from cProfile import Profile 7 | from pstats import Stats 8 | import time 9 | import matplotlib.pyplot as plt 10 | import seaborn as sns 11 | 12 | 13 | # bsp = gryds.BSplineTransformation(np.random.rand(3, 32, 32, 32), order=1) 14 | bsp = gryds.TranslationTransformation([0.1, 0.2, 0.3]) 15 | N = 1 16 | 17 | Ns = range(0, 151, 1) 18 | M = 10 19 | 20 | image = np.random.rand(N, 128, 128) 21 | intp = gryds.BSplineInterpolatorCuda(image) 22 | intp.transform(bsp) 23 | 24 | times = [] 25 | for i in range(M): 26 | ts = [] 27 | for N in Ns: 28 | print(i, N) 29 | image = np.random.rand(N, 128, 128) 30 | intp = gryds.Interpolator(image, order=1) 31 | t0 = time.time() 32 | intp.transform(bsp) 33 | ts.append(time.time() - t0) 34 | times.append(ts) 35 | times = np.median(times, axis=0) 36 | 37 | times_cuda = [] 38 | for i in range(M): 39 | ts = [] 40 | for N in Ns: 41 | print(i, N) 42 | image = np.random.rand(N, 128, 128) 43 | intp = gryds.BSplineInterpolatorCuda(image, order=1) 44 | t0 = time.time() 45 | intp.transform(bsp) 46 | ts.append(time.time() - t0) 47 | times_cuda.append(ts) 48 | times_cuda = np.median(times_cuda, axis=0) 49 | 50 | 51 | plt.plot(Ns, times, '-') 52 | plt.plot(Ns, times_cuda, '-') 53 | plt.xlabel('Number of slices (volume = N x 128 x 128)') 54 | plt.ylabel('Seconds') 55 | plt.title('Time of interpolation as function of image size\nTiming is median of 10 trials') 56 | plt.legend(['CPU', 'GPU']) 57 | plt.grid() 58 | plt.show() 59 | -------------------------------------------------------------------------------- /profiling/graphs_transformation.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | sys.path.append(os.path.abspath('..')) 4 | import gryds 5 | import numpy as np 6 | from cProfile import Profile 7 | from pstats import Stats 8 | import time 9 | import matplotlib.pyplot as plt 10 | import seaborn as sns 11 | 12 | 13 | bsp = gryds.BSplineTransformation(0.01 * (np.random.rand(3, 2, 2, 2) - 0.5), order=1) 14 | bsp_cuda = gryds.BSplineTransformationCuda(0.01 * (np.random.rand(3, 2, 2, 2) - 0.5), order=1) 15 | N = 1 16 | 17 | Ns = range(0, 151, 1) 18 | M = 2 19 | 20 | image = np.random.rand(N, 128, 128) 21 | intp = gryds.BSplineInterpolatorCuda(image) 22 | intp.transform(bsp) 23 | 24 | times = [] 25 | for i in range(M): 26 | ts = [] 27 | for N in Ns: 28 | print(i, N) 29 | image = np.random.rand(N, 128, 128) 30 | intp = gryds.Interpolator(image, order=1) 31 | t0 = time.time() 32 | intp.transform(bsp) 33 | ts.append(time.time() - t0) 34 | times.append(ts) 35 | times = np.median(times, axis=0) 36 | 37 | times_cuda = [] 38 | for i in range(M): 39 | ts = [] 40 | for N in Ns: 41 | print(i, N) 42 | image = np.random.rand(N, 128, 128) 43 | intp = gryds.BSplineInterpolatorCuda(image, order=1) 44 | t0 = time.time() 45 | intp.transform(bsp_cuda) 46 | ts.append(time.time() - t0) 47 | times_cuda.append(ts) 48 | times_cuda = np.median(times_cuda, axis=0) 49 | 50 | 51 | plt.plot(Ns, times, '-') 52 | plt.plot(Ns, times_cuda, '-') 53 | plt.xlabel('Number of slices (volume = N x 128 x 128)') 54 | plt.ylabel('Seconds') 55 | plt.title('Time of B-spline transformation as function of image size\nTiming is median of 10 trials') 56 | plt.legend(['CPU', 'GPU']) 57 | plt.grid() 58 | plt.show() 59 | -------------------------------------------------------------------------------- /test/test_linear_transformation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestLinear(TestCase): 15 | """Tests rotation, and associated effect on grids and Jacobians""" 16 | 17 | def test_2d_translation(self): 18 | matrix = np.zeros((2, 3)) 19 | matrix[0, 0] = 1 20 | matrix[1, 1] = 1 21 | matrix[0, 2] = 0.1 22 | trf = gryds.LinearTransformation(matrix) # move grid 10% downwards (moves image 10% upwards) 23 | 24 | grid = gryds.Grid((10, 20)) 25 | new_grid = grid.transform(trf) 26 | 27 | # The original grid runs from 0 to 0.9 for the i-coordinates 28 | # The transformed grid should run from 0.1 to 1 29 | np.testing.assert_equal(new_grid.grid[0, 0], np.array(0.1, DTYPE)) 30 | np.testing.assert_equal(new_grid.grid[0, 9], np.array(1.0, DTYPE)) 31 | 32 | # The jacobian of this transformation should be 1 everywhere, i.e. no 33 | # scaling should have happened 34 | np.testing.assert_almost_equal( 35 | grid.jacobian_det(trf), 36 | np.array(1, DTYPE), 37 | decimal=4) 38 | 39 | def test_incorrect_matrix_size(self): 40 | matrix = np.zeros((3, 3)) 41 | self.assertRaises(ValueError, gryds.LinearTransformation, matrix) 42 | 43 | matrix = np.zeros((2, 2)) 44 | self.assertRaises(ValueError, gryds.LinearTransformation, matrix) 45 | 46 | matrix = np.zeros((3, 30)) 47 | self.assertRaises(ValueError, gryds.LinearTransformation, matrix) 48 | 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /profiling/graphs_multiple_transformations.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | sys.path.append(os.path.abspath('..')) 4 | import gryds 5 | import numpy as np 6 | from cProfile import Profile 7 | from pstats import Stats 8 | import time 9 | import matplotlib.pyplot as plt 10 | import seaborn as sns 11 | 12 | bsp = gryds.BSplineTransformation(0.01 * (np.random.rand(3, 32, 32, 32) - 0.5), order=1) 13 | bsp_cuda = gryds.BSplineTransformationCuda(0.01 * (np.random.rand(3, 32, 32, 32) - 0.5), order=1) 14 | N = 1 15 | 16 | Ns = range(0, 15, 1) 17 | M = 2 18 | 19 | image = np.random.rand(N, 128, 128) 20 | intp = gryds.BSplineInterpolatorCuda(image) 21 | intp.transform(bsp) 22 | 23 | times = [] 24 | for i in range(M): 25 | ts = [] 26 | for N in Ns: 27 | print(i, N) 28 | image = np.random.rand(N, 128, 128) 29 | intp = gryds.Interpolator(image, order=1) 30 | t0 = time.time() 31 | intp.transform(bsp, bsp, bsp) 32 | ts.append(time.time() - t0) 33 | times.append(ts) 34 | times = np.median(times, axis=0) 35 | 36 | times_cuda = [] 37 | for i in range(M): 38 | ts = [] 39 | for N in Ns: 40 | print(i, N) 41 | image = np.random.rand(N, 128, 128) 42 | intp = gryds.BSplineInterpolatorCuda(image, order=1) 43 | t0 = time.time() 44 | intp.transform(bsp_cuda, bsp_cuda, bsp_cuda) 45 | ts.append(time.time() - t0) 46 | times_cuda.append(ts) 47 | times_cuda = np.median(times_cuda, axis=0) 48 | 49 | 50 | plt.plot(Ns, times, '-') 51 | plt.plot(Ns, times_cuda, '-') 52 | plt.xlabel('Number of slices (volume = N x 128 x 128)') 53 | plt.ylabel('Seconds') 54 | plt.title('Time of B-spline transformation as function of image size\nTiming is median of 10 trials') 55 | plt.legend(['CPU', 'GPU']) 56 | plt.grid() 57 | plt.show() 58 | -------------------------------------------------------------------------------- /gryds/utils.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Utils file 4 | 5 | 6 | import numpy as np 7 | 8 | 9 | def dvf_opts(dvf): 10 | """plt.imshow kwargs to show a 2D deformation field as a normalized 11 | blue-white-red map. 12 | 13 | Example usage: plt.imshow(dvf, **dvf_opts(dvf)) 14 | """ 15 | return { 16 | 'cmap': 'bwr', 17 | 'vmin': -np.abs(max(dvf.min(), dvf.max())), 18 | 'vmax': np.abs(max(dvf.min(), dvf.max())) 19 | } 20 | 21 | 22 | def dvf_show(dvf): 23 | """Plot a 2D deformation field as a normalized blue-white-red map. 24 | 25 | Example usage: plt.imshow(**dvf_show(dvf)) 26 | """ 27 | return { 28 | 'X': dvf, 29 | 'cmap': 'bwr', 30 | 'vmin': -max(dvf.min(), dvf.max()), 31 | 'vmax': max(dvf.min(), dvf.max()) 32 | } 33 | 34 | 35 | def max_no_fold(size): 36 | """Find a B-spline grid with maximal range without folding.""" 37 | scale = [0.5 * 1. / (4 * (x - 1)) for x in size[1:]] 38 | return unif(scale, size) 39 | 40 | 41 | def unif(scale, size): 42 | """Returns a uniformly distributed grid of given size 43 | and displacement scale""" 44 | 45 | size = np.array([size]).flatten() 46 | # return scale * 2 * (np.random.rand(*size) - 0.5) 47 | return np.array([ 48 | x * y for x, y in zip(scale, 2 * (np.random.rand(*size) - 0.5))]) 49 | 50 | 51 | def phantom_image(size, spacing=4, thickness=1, offset=0): 52 | """Returns a 3D grid image of given size, with certain grid spacing.""" 53 | im = np.zeros(size) 54 | N = spacing 55 | 56 | for i in range(thickness): 57 | sl = slice(offset + i, None, N) 58 | for axis in range(im.ndim): 59 | id = [slice(None)] * im.ndim 60 | id[axis] = sl 61 | im[tuple(id)] = 1 62 | 63 | return im 64 | -------------------------------------------------------------------------------- /test/test_bspline_interpolation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestBSplineInterpolator(TestCase): 15 | 16 | def test_2d_bspline_interpolator_90_deg_rotation(self): 17 | image = np.array([ 18 | [0, 0, 1, 0, 0], 19 | [0, 0, 1, 0, 0], 20 | [1, 1, 1, 1, 1], 21 | [0, 0, 1, 0, 0], 22 | [0, 0, 1, 0, 0] 23 | ], dtype=DTYPE) 24 | intp = gryds.Interpolator(image) 25 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 26 | new_image = intp.transform(trf, mode='mirror').astype(DTYPE) 27 | np.testing.assert_almost_equal(image, new_image, decimal=4) 28 | 29 | def test_2d_bspline_interpolator_45_deg_rotation(self): 30 | image = np.array([ 31 | [0, 0, 1, 0, 0], 32 | [0, 0, 1, 0, 0], 33 | [1, 1, 1, 1, 1], 34 | [0, 0, 1, 0, 0], 35 | [0, 0, 1, 0, 0] 36 | ], dtype=DTYPE) 37 | expected = np.array([ 38 | [1., 0.2929, 0., 0.2929, 1.], 39 | [0.2929, 1., 0.5, 1., 0.2929], 40 | [0., 0.5, 1., 0.5, 0.], 41 | [0.2929, 1., 0.5, 1., 0.2929], 42 | [1., 0.2929, 0., 0.2929, 1.] 43 | ], dtype=DTYPE) 44 | intp = gryds.Interpolator(image, order=1, mode='mirror') 45 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/4.], center=[0.4, 0.4]) 46 | new_image = intp.transform(trf).astype(DTYPE) 47 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 48 | 49 | def test_repr(self): 50 | self.assertEqual(str(gryds.BSplineTransformation(np.random.rand(2, 5, 7))), 'BSplineTransformation(2D, 5x7)') 51 | -------------------------------------------------------------------------------- /test/test_translation_transformation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestTranslation(TestCase): 15 | """Tests translation, and associated effect on grids and Jacobians""" 16 | 17 | def test_2d_translation(self): 18 | trf = gryds.TranslationTransformation([0.1, 0]) # move grid 10% downwards (moves image 10% upwards) 19 | 20 | grid = gryds.Grid((10, 20)) 21 | new_grid = grid.transform(trf) 22 | 23 | # The original grid runs from 0 to 0.9 for the i-coordinates 24 | # The transformed grid should run from 0.1 to 1 25 | np.testing.assert_equal(new_grid.grid[0, 0], np.array(0.1, DTYPE)) 26 | np.testing.assert_equal(new_grid.grid[0, 9], np.array(1.0, DTYPE)) 27 | 28 | # The jacobian of this transformation should be 1 everywhere, i.e. no 29 | # scaling should have happened 30 | np.testing.assert_almost_equal( 31 | grid.jacobian_det(trf), 32 | np.array(1, DTYPE), 33 | decimal=4) 34 | 35 | def test_5d_translation(self): 36 | trf = gryds.TranslationTransformation([0, 0, 0.1, 0, 0]) 37 | 38 | grid = gryds.Grid((10, 10, 10, 10, 10)) 39 | new_grid = grid.transform(trf) 40 | 41 | # The original grid runs from 0 to 0.9 42 | # The transformed grid should run from 0.1 to 1 43 | self.assertTrue(np.all(new_grid.grid[2, :, :, 0] == np.array(0.1, DTYPE))) 44 | self.assertTrue(np.all(new_grid.grid[2, :, :, 9] == np.array(1.0, DTYPE))) 45 | 46 | # The jacobian of this transformation should be 1 everywhere, i.e. no 47 | # scaling should have happened 48 | np.testing.assert_almost_equal( 49 | grid.jacobian_det(trf), 50 | np.array(1, DTYPE), 51 | decimal=4) 52 | 53 | def test_repr(self): 54 | self.assertEqual(str(gryds.TranslationTransformation([3, 4])), 'TranslationTransformation(2D, t=[3 4])') 55 | -------------------------------------------------------------------------------- /test/test_isotropic_scaling_transformation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestIsotropic(TestCase): 15 | """Tests isotropic scaling, and associated effect on grids and Jacobians""" 16 | 17 | def test_2d_downscaling(self): 18 | trf = gryds.AffineTransformation(ndim=2, scaling=[1.5, 1.5]) # scale grid by 150% isotropically 19 | 20 | grid = gryds.Grid((10, 20)) 21 | new_grid = grid.transform(trf) 22 | 23 | # The original grid runs from 0 to 0.9 for the i-coordinates 24 | # The transformed grid should run from 0 to 1.35 25 | np.testing.assert_equal(new_grid.grid[0, 0], np.array(0, DTYPE)) 26 | np.testing.assert_almost_equal( 27 | new_grid.grid[0, 9], 28 | np.array(1.35, DTYPE), 29 | decimal=6 30 | ) 31 | 32 | # The jacobian of this transformation should be 1 everywhere, i.e. no 33 | # scaling should have happened 34 | np.testing.assert_almost_equal( 35 | grid.jacobian_det(trf), 36 | np.array(2.25, DTYPE), # i.e. 1.5*1.5 37 | decimal=4) 38 | 39 | def test_5d_scaling(self): 40 | matrix = np.zeros((5, 6)) 41 | for i in range(5): 42 | matrix[i, i] = 1.5 43 | trf = gryds.LinearTransformation(matrix) # scale grid by 150$ isotropically 44 | 45 | grid = gryds.Grid((2, 3, 4, 5, 6)) 46 | new_grid = grid.transform(trf) 47 | 48 | # The original grid runs from 0 to 0.9 49 | # The transformed grid should run from 0 to 1.35 50 | np.testing.assert_equal(new_grid.grid[0, 0], np.array(0, DTYPE)) 51 | np.testing.assert_almost_equal( 52 | new_grid.grid[2, :, :, 3], 53 | np.array(1.125, DTYPE), # 1.5 * 0.75 54 | decimal=6 55 | ) 56 | 57 | # The jacobian of this transformation should be 1 everywhere, i.e. no 58 | # scaling should have happened 59 | np.testing.assert_almost_equal( 60 | grid.jacobian_det(trf), 61 | np.array(7.59375, DTYPE), # i.e. 1.5^5 62 | decimal=4) 63 | -------------------------------------------------------------------------------- /test/test_anisotropic_scaling_transformation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestAnisotropic(TestCase): 15 | """Tests anisotropic scaling, and associated effect on grids and Jacobians""" 16 | 17 | def test_2d_downscaling(self): 18 | trf = gryds.AffineTransformation(ndim=2, scaling=[1.5, 1]) # scale grid by 150% isotropically 19 | 20 | grid = gryds.Grid((10, 20)) 21 | new_grid = grid.transform(trf) 22 | 23 | # The original grid runs from 0 to 0.9 for the i-coordinates 24 | # The transformed grid should run from 0 to 1.35 25 | np.testing.assert_equal(new_grid.grid[0, 0], np.array(0, DTYPE)) 26 | np.testing.assert_almost_equal( 27 | new_grid.grid[0, 9], 28 | np.array(1.35, DTYPE), 29 | decimal=6 30 | ) 31 | 32 | # The jacobian of this transformation should be 1 everywhere, i.e. no 33 | # scaling should have happened 34 | np.testing.assert_almost_equal( 35 | grid.jacobian_det(trf), 36 | np.array(1.5, DTYPE), # i.e. 1.5*1.5 37 | decimal=4) 38 | 39 | def test_5d_downscaling(self): 40 | matrix = np.zeros((5, 6)) 41 | for i in range(5): 42 | matrix[i, i] = 1 43 | matrix[2, 2] = 1.5 44 | 45 | trf = gryds.LinearTransformation(matrix) # scale grid by 150$ isotropically 46 | 47 | grid = gryds.Grid((2, 3, 4, 5, 6)) 48 | new_grid = grid.transform(trf) 49 | 50 | # The original grid runs from 0 to 0.9 51 | # The transformed grid should run from 0 to 1.35 52 | np.testing.assert_equal(new_grid.grid[0, 0], np.array(0, DTYPE)) 53 | np.testing.assert_almost_equal( 54 | new_grid.grid[2, :, :, 3], 55 | np.array(1.125, DTYPE), # 1.5 * 0.75 56 | decimal=6 57 | ) 58 | 59 | # The jacobian of this transformation should be 1 everywhere, i.e. no 60 | # scaling should have happened 61 | np.testing.assert_almost_equal( 62 | grid.jacobian_det(trf), 63 | np.array(1.5, DTYPE), # i.e. 1.5^5 64 | decimal=4) 65 | -------------------------------------------------------------------------------- /gryds/transformers/composed.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # Composed transformations combine multiple transform objects into one 5 | 6 | 7 | from __future__ import division, print_function, absolute_import 8 | 9 | import numpy as np 10 | from ..config import DTYPE 11 | from .base import Transformation 12 | 13 | 14 | class ComposedTransformation(Transformation): 15 | """Composed transform that turns multiple Transform objects into a net 16 | tranform through composition. 17 | 18 | Given two transformations t1 and t2, and a points x0, the following result 19 | in the same transformed points x2: 20 | 21 | >>> # Manual composition 22 | >>> x1 = t1.transform(x0) 23 | >>> x2 = t2.transform(x1) 24 | 25 | >>> # With ComposedTransform 26 | >>> t12 = ComposedTransform(t1, t2) 27 | >>> x2 = t12.transform(x0) 28 | 29 | Attributes: 30 | ndim (int): The number of dimensions. 31 | parameters (np.ndarray): Left empty 32 | transformations (Iterable): A sequence of Transformation objects 33 | """ 34 | 35 | def __init__(self, *transformations): 36 | """ 37 | Args: 38 | transformations (iterable): A sequence (list, tuple) of transformations. 39 | Raises: 40 | ValueError: If the number of dimenions the transformations operate 41 | on are not the same. 42 | ValueError: If transformations is empty. 43 | """ 44 | if not transformations or len(transformations) == 0: 45 | raise ValueError('No transformations supplied.') 46 | ndims = [x.ndim for x in transformations] 47 | if not np.all(np.array(ndims) == ndims[0]): 48 | raise ValueError('Number of dimensions for transformations {} do not ' 49 | ' match: {}.'.format(', '.join( 50 | tuple([x.__class__.__name__ for x in transformations]) 51 | ), ndims)) 52 | self.ndim = ndims[0] 53 | self.transformations = transformations 54 | 55 | def __repr__(self): 56 | return '{}({}D, {})'.format(self.__class__.__name__, self.ndim, 57 | '∘'.join([str(x) for x in self.transformations])) 58 | 59 | def _transform_points(self, points): 60 | points_copy = points.copy() 61 | for transform in self.transformations: 62 | points_copy = transform.transform(points_copy) 63 | assert points_copy.dtype == DTYPE 64 | return points_copy 65 | -------------------------------------------------------------------------------- /test/test_grid.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestGrid(TestCase): 15 | """Tests grid initialization and scaling.""" 16 | 17 | def test_2d_grid_ranges(self): 18 | a_grid = gryds.Grid((10, 20)) 19 | 20 | self.assertEqual( 21 | a_grid.grid[0, 9, 0], 22 | np.array(0.9, dtype=DTYPE) 23 | ) 24 | self.assertEqual( 25 | a_grid.grid[1, 0, 19], 26 | np.array(0.95, dtype=DTYPE) 27 | ) 28 | 29 | def test_2d_grid_scaling(self): 30 | a_grid = gryds.Grid((10, 20)) 31 | 32 | new_grid = a_grid.scaled_to((3, 4)) 33 | self.assertAlmostEqual( 34 | new_grid.grid[0, 9, 0], 35 | np.array(2.7, dtype=DTYPE), 36 | places=6 37 | ) 38 | self.assertAlmostEqual( 39 | new_grid.grid[1, 0, 19], 40 | np.array(3.8, dtype=DTYPE), 41 | places=6 42 | ) 43 | 44 | def test_5d_grid_range(self): 45 | a_grid = gryds.Grid((10, 10, 10, 10, 10)) 46 | 47 | self.assertEqual( 48 | a_grid.grid[0, 9, 0, 0, 0, 0], 49 | np.array(0.9, dtype=DTYPE) 50 | ) 51 | self.assertEqual( 52 | a_grid.grid[4, 0, 0, 0, 0, 9], 53 | np.array(0.9, dtype=DTYPE) 54 | ) 55 | 56 | def test_5d_grid_scaling(self): 57 | a_grid = gryds.Grid((10, 10, 10, 10, 10)) 58 | 59 | new_grid = a_grid.scaled_to((3, 4, 5, 6, 7)) 60 | 61 | self.assertAlmostEqual( 62 | new_grid.grid[0, 9, 0, 0, 0, 0], 63 | np.array(2.7, dtype=DTYPE), # 3 x 9 / 10 64 | places=6 65 | ) 66 | self.assertAlmostEqual( 67 | new_grid.grid[4, 0, 0, 0, 0, 9], 68 | np.array(6.3, dtype=DTYPE), # 7 x 9 / 10 69 | places=6 70 | ) 71 | 72 | def test_grid_repr(self): 73 | a_grid = gryds.Grid((2, 2)) 74 | self.assertEqual(str(a_grid), 'Grid(2D, 2x2)') 75 | 76 | def test_grid_init(self): 77 | gryds.Grid(grid=np.zeros((2, 10, 10))) 78 | 79 | def test_grid_wrong_scale_shape(self): 80 | a_grid = gryds.Grid((2, 2)) 81 | self.assertRaises(ValueError, a_grid.scaled_to, [1, 2, 3]) 82 | 83 | def test_no_grid_no_shape(self): 84 | self.assertRaises(ValueError, gryds.Grid) 85 | -------------------------------------------------------------------------------- /profiling/README.md: -------------------------------------------------------------------------------- 1 | # Profiling of B-spline code 2 | 3 | The code in this folder profiles third-order B-spline interpolation and transformation. 4 | 5 | Currently, the profiling tool has the following output: 6 | 7 | ```python 8 | ncalls tottime percall cumtime percall filename:lineno(function) 9 | 1 0.076 0.076 29.532 29.532 bspline.py:101(transform) 10 | 4 0.000 0.000 27.591 6.898 interpolation.py:266(map_coordinates) 11 | 4 26.314 6.578 26.314 6.578 {built-in method scipy.ndimage._nd_image.geometric_transform} 12 | 1 0.000 0.000 24.299 24.299 grid.py:69(transform) 13 | 1 0.064 0.064 24.066 24.066 base.py:88(__call__) 14 | 1 0.429 0.429 24.002 24.002 base.py:64(transform) 15 | 1 0.204 0.204 23.256 23.256 bspline.py:60(_transform_points) 16 | 1 0.011 0.011 5.144 5.144 bspline.py:76(resample) 17 | 1 0.010 0.010 4.794 4.794 bspline.py:48(sample) 18 | 4 0.000 0.000 1.277 0.319 interpolation.py:108(spline_filter) 19 | 12 0.000 0.000 1.272 0.106 interpolation.py:54(spline_filter1d) 20 | 12 1.272 0.106 1.272 0.106 {built-in method scipy.ndimage._nd_image.spline_filter1d} 21 | 7 0.482 0.069 0.482 0.069 {method 'astype' of 'numpy.ndarray' objects} 22 | 30 0.457 0.015 0.457 0.015 {built-in method numpy.core.multiarray.array} 23 | 1 0.039 0.039 0.327 0.327 grid.py:43(scaled_to) 24 | 2 0.000 0.000 0.231 0.116 grid.py:19(__init__) 25 | 1 0.120 0.120 0.120 0.120 {method 'copy' of 'numpy.ndarray' objects} 26 | 1 0.049 0.049 0.049 0.049 grid.py:65() 27 | 20 0.000 0.000 0.005 0.000 _ni_support.py:71(_get_output) 28 | 24 0.005 0.000 0.005 0.000 {built-in method numpy.core.multiarray.zeros} 29 | 24 0.000 0.000 0.000 0.000 type_check.py:250(iscomplexobj) 30 | 24 0.000 0.000 0.000 0.000 numeric.py:433(asarray) 31 | 2 0.000 0.000 0.000 0.000 {method 'reshape' of 'numpy.ndarray' objects} 32 | 24 0.000 0.000 0.000 0.000 {built-in method builtins.issubclass} 33 | 16 0.000 0.000 0.000 0.000 _ni_support.py:38(_extend_mode_to_code) 34 | 12 0.000 0.000 0.000 0.000 {built-in method builtins.isinstance} 35 | 1 0.000 0.000 0.000 0.000 base.py:42(_dimension_check) 36 | 12 0.000 0.000 0.000 0.000 _ni_support.py:86(_check_axis) 37 | 3 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 38 | 6 0.000 0.000 0.000 0.000 {built-in method builtins.len} 39 | 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 40 | ``` 41 | 42 | Because B-splines are used for the transformation and the interpolation, there are four calls (three dimensions + interpolation) to `scipy.ndimage.map_coordinates`, which takes up about 93% of the time required for the full script. Accelerating this function would therefore be the best way to improve speed, however, it is already very much optimized: `map_coordinates` calls compiled C-code. 43 | -------------------------------------------------------------------------------- /test/test_composed_transformation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import absolute_import 5 | 6 | import sys 7 | import os 8 | 9 | sys.path.append(os.path.abspath('../gryds')) 10 | 11 | from unittest import TestCase 12 | import numpy as np 13 | import gryds 14 | DTYPE = gryds.DTYPE 15 | 16 | 17 | class TestComposition(TestCase): 18 | """Tests composed transformations by applying inverse transformations""" 19 | 20 | def test_translation(self): 21 | image = np.array([ 22 | [0, 0, 1, 0, 0], 23 | [0, 0, 1, 0, 0], 24 | [1, 1, 1, 1, 1], 25 | [0, 0, 1, 0, 0], 26 | [0, 0, 1, 0, 0] 27 | ], dtype=DTYPE) 28 | intp = gryds.Interpolator(image, mode='mirror') 29 | 30 | trf1 = gryds.TranslationTransformation([0.1, 0]) 31 | trf2 = gryds.TranslationTransformation([-0.1, 0]) 32 | 33 | trf = gryds.ComposedTransformation(trf2, trf1) 34 | 35 | new_image = intp.transform(trf) 36 | np.testing.assert_almost_equal(image, new_image) 37 | 38 | def test_rotation(self): 39 | image = np.array([ 40 | [0, 0, 1, 0, 0], 41 | [0, 0, 1, 0, 0], 42 | [1, 1, 1, 1, 1], 43 | [0, 0, 1, 0, 0], 44 | [0, 0, 1, 0, 0] 45 | ], dtype=DTYPE) 46 | intp = gryds.Interpolator(image, mode='mirror') 47 | 48 | trf1 = gryds.AffineTransformation(ndim=2, angles=[0.1]) 49 | trf2 = gryds.AffineTransformation(ndim=2, angles=[-0.1]) 50 | 51 | trf = gryds.ComposedTransformation(trf2, trf1) 52 | 53 | new_image = intp.transform(trf) 54 | np.testing.assert_almost_equal(image, new_image, decimal=6) 55 | 56 | def test_rotation_translation(self): 57 | image = np.array([ 58 | [0, 0, 1, 0, 0], 59 | [0, 0, 1, 0, 0], 60 | [1, 1, 1, 1, 1], 61 | [0, 0, 1, 0, 0], 62 | [0, 0, 1, 0, 0] 63 | ], dtype=DTYPE) 64 | intp = gryds.Interpolator(image, mode='mirror') 65 | 66 | trf1 = gryds.TranslationTransformation([0.1, 0]) 67 | trf2 = gryds.AffineTransformation(ndim=2, angles=[0.1]) 68 | trf3 = gryds.AffineTransformation(ndim=2, angles=[-0.1]) 69 | trf4 = gryds.TranslationTransformation([-0.1, 0]) 70 | 71 | trf = gryds.ComposedTransformation(trf1, trf2, trf3, trf4) 72 | 73 | new_image = intp.transform(trf) 74 | np.testing.assert_almost_equal(image, new_image, decimal=6) 75 | 76 | def test_incompatible_error(self): 77 | trf1 = gryds.TranslationTransformation([0.1, 0, 0]) 78 | trf2 = gryds.TranslationTransformation([-0.1, 0]) 79 | 80 | self.assertRaises(ValueError, gryds.ComposedTransformation, trf2, trf1) 81 | 82 | def test_repr(self): 83 | bsp = gryds.BSplineTransformation(np.random.rand(2, 3, 4)) 84 | self.assertEqual(str(gryds.ComposedTransformation(bsp, bsp)), 85 | 'ComposedTransformation(2D, BSplineTransformation(2D, 3x4)∘BSplineTransformation(2D, 3x4))' 86 | ) 87 | 88 | def test_no_transformations_supplied(self): 89 | self.assertRaises(ValueError, gryds.ComposedTransformation) 90 | -------------------------------------------------------------------------------- /gryds/transformers/cuda.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # BSpline transformation 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | import numpy as np 9 | import cupy as cp 10 | import cupyx.scipy.ndimage as nd 11 | from ..config import DTYPE 12 | from .base import Transformation 13 | from .bspline import BSplineTransformation 14 | 15 | 16 | class BSplineTransformationCuda(BSplineTransformation): 17 | """BSpline transformation of points. 18 | 19 | Attributes: 20 | ndim (int): The number of dimensions. 21 | parameters (np.ndarray): The control point grid in 22 | ndim x Ni x Nj x ... x Nndim format. 23 | bspline_order (int): The order of the B-spline. 24 | mode (str): How edges of image domain should be treated when transformed. 25 | cval (numeric): Constant value for mode='constant' 26 | """ 27 | 28 | def __init__(self, grid, order=1, mode='mirror', cval=0): 29 | """ 30 | Args: 31 | grid (np.array): An (ndim x N1 x N2 x ... Nndim) sized array of 32 | displacements for grid points. 33 | order (int): B-Spline order. Currently, only 0 and 1 are 34 | supported. 35 | mode (str): How edges of image domain should be treated when 36 | transformed. One of 'constant', 'nearest', 'mirror', 'reflect', 37 | 'wrap'. Default is 'constant'. See https://docs.scipy.org/doc/ 38 | scipy-0.14.0/reference/generated/ 39 | scipy.ndimage.interpolation.map_coordinates.html for more 40 | information about modes. 41 | cval (numeric): Constant value for mode='constant' 42 | Raises: 43 | ValueError: If grid.shape[0] is not equal to grid.ndim -1 44 | """ 45 | super(BSplineTransformationCuda, self).__init__( 46 | grid=grid, 47 | order=order, 48 | mode=mode, 49 | cval=cval 50 | ) 51 | 52 | def _transform_points(self, points): 53 | assert points.dtype == DTYPE 54 | # Empty list for the interpolated B-spline grid's components. 55 | displacement = [] 56 | 57 | # Reshape points for the cupy map_coordinates function to 58 | # receive coordinates in the expected shape 59 | points_gpu = points.reshape(self.ndim, -1) 60 | 61 | # Points is in the [0, 1)^ndim domain. Here it is scaled to the 62 | # B-spline grid's size. 63 | scaled_points = points_gpu * ( 64 | np.array(self.parameters.shape[1:], dtype=DTYPE) - 1)[:, None] 65 | 66 | # Every component (e.g. Tx, Ty, Tz in 3D) of the B-spline grid is 67 | # interpolated at the scaled point's positions. 68 | for bspline_component in self.parameters: 69 | displacement.append( 70 | cp.asnumpy( 71 | nd.map_coordinates(input=cp.array(bspline_component), 72 | coordinates=cp.array(scaled_points), 73 | order=self.bspline_order, 74 | mode=self.mode, 75 | cval=self.cval) 76 | ) 77 | ) 78 | result = points + np.array(displacement).reshape(points.shape) 79 | 80 | assert result.dtype == DTYPE 81 | return result 82 | -------------------------------------------------------------------------------- /gryds/transformers/bspline.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # BSpline transformation 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | import numpy as np 9 | import scipy.ndimage as nd 10 | from ..config import DTYPE 11 | from .base import Transformation 12 | from .affine import _center_of 13 | 14 | 15 | class BSplineTransformation(Transformation): 16 | """BSpline transformation of points. 17 | 18 | Attributes: 19 | ndim (int): The number of dimensions. 20 | parameters (np.ndarray): The control point grid in 21 | ndim x Ni x Nj x ... x Nndim format. 22 | bspline_order (int): The order of the B-spline. 23 | mode (str): How edges of image domain should be treated when transformed. 24 | cval (numeric): Constant value for mode='constant' 25 | """ 26 | 27 | def __init__(self, grid, order=3, mode='mirror', cval=0): 28 | """ 29 | Args: 30 | grid (np.array): An (ndim x N1 x N2 x ... Nndim) sized array of 31 | displacements for grid points. 32 | order (int): The order of the B-spline. Default is 3. Use 0 for 33 | binary images. Use 1 for normal linear interpolation. 34 | mode (str): How edges of image domain should be treated when 35 | transformed. One of 'constant', 'nearest', 'mirror', 'reflect', 36 | 'wrap'. Default is 'constant'. See https://docs.scipy.org/doc/ 37 | scipy-0.14.0/reference/generated/ 38 | scipy.ndimage.interpolation.map_coordinates.html for more 39 | information about modes. 40 | cval (numeric): Constant value for mode='constant' 41 | Raises: 42 | ValueError: If grid.shape[0] is not equal to grid.ndim -1 43 | """ 44 | grid = np.array(grid, dtype=DTYPE) 45 | if grid.shape[0] is not grid.ndim - 1: 46 | raise ValueError('First axis of grid should be equal to ' 47 | 'transform\'s ndim {}.'.format(grid.ndim - 1)) 48 | self.bspline_order = order 49 | self.mode = mode 50 | self.cval = cval 51 | super(BSplineTransformation, self).__init__( 52 | ndim=len(grid), 53 | parameters=grid 54 | ) 55 | 56 | def __repr__(self): 57 | return '{}({}D, {})'.format( 58 | self.__class__.__name__, 59 | self.ndim, 60 | 'x'.join([str(x) for x in self.parameters.shape[1:]]) 61 | ) 62 | 63 | def _transform_points(self, points): 64 | assert points.dtype == DTYPE 65 | # Empty list for the interpolated B-spline grid's components. 66 | displacement = [] 67 | 68 | # Points is in the [0, 1)^ndim domain. Here it is scaled to the 69 | # B-spline grid's size. 70 | scaled_points = points * ( 71 | np.array(self.parameters.shape[1:], dtype=DTYPE) - 1)[:, None] 72 | 73 | # Every component (e.g. Tx, Ty, Tz in 3D) of the B-spline grid is 74 | # interpolated at the scaled point's positions. 75 | for bspline_component in self.parameters: 76 | displacement.append( 77 | nd.map_coordinates(bspline_component, scaled_points, 78 | order=self.bspline_order, 79 | mode=self.mode, 80 | cval=self.cval) 81 | ) 82 | result = (points + np.array(displacement)) 83 | assert result.dtype == DTYPE 84 | return result 85 | -------------------------------------------------------------------------------- /test/test_bspline_transformation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestBSplineTransformation(TestCase): 15 | """Tests BSpline transformations, and associated effect on grids and Jacobians""" 16 | 17 | def test_translation_bspline_2d(self): 18 | bspline_grid = np.ones((2, 2, 2)) 19 | trf = gryds.BSplineTransformation(bspline_grid) 20 | 21 | grid = gryds.Grid((10, 20)) 22 | new_grid = grid.transform(trf) 23 | 24 | # The grid runs from 0 to 0.9 on the i-axis 25 | # Translation by 100% will mean that the i-axis will now run from 1 to 1.9 26 | np.testing.assert_equal(new_grid.grid[0, 0, 0], np.array(1, DTYPE)) 27 | np.testing.assert_equal(new_grid.grid[0, -1, 0], np.array(1.9, DTYPE)) 28 | 29 | # The jacobian of this transformation should be 1 everywhere, i.e. no 30 | # scaling should have happened 31 | np.testing.assert_almost_equal( 32 | grid.jacobian_det(trf), 33 | np.array(1, DTYPE), 34 | decimal=4) 35 | 36 | def test_translation_bspline_5d(self): 37 | bspline_grid = np.ones((5, 2, 2, 2, 2, 2)) 38 | trf = gryds.BSplineTransformation(bspline_grid) 39 | 40 | grid = gryds.Grid((3, 3, 3, 3, 3)) 41 | new_grid = grid.transform(trf) 42 | 43 | # The grid runs from 0 to 0.9 on the i-axis 44 | # Translation by 100% will mean that the i-axis will now run from 1 to 1.9 45 | np.testing.assert_equal(new_grid.grid[0, 0, 0, 0, 0], np.array(1, DTYPE)) 46 | np.testing.assert_almost_equal(new_grid.grid[0, -1, 0, 0, 0], np.array(1.6666667, DTYPE)) 47 | 48 | # The jacobian of this transformation should be 1 everywhere, i.e. no 49 | # scaling should have happened 50 | np.testing.assert_almost_equal( 51 | grid.jacobian_det(trf), 52 | np.array(1, DTYPE), 53 | decimal=4) 54 | 55 | def test_bspline_2d(self): 56 | bspline_grid = np.array([ 57 | [[0.1, 0], [0, 0]], 58 | [[0, 0], [0, 0]] 59 | ]) 60 | trf = gryds.BSplineTransformation(bspline_grid) 61 | 62 | grid = gryds.Grid((10, 20)) 63 | new_grid = grid.transform(trf) 64 | 65 | # The top left has been displaced by 10% or 0.1 pixels in the i-direction 66 | np.testing.assert_almost_equal(new_grid.grid[0, 0, 0], np.array(0.1, DTYPE)) 67 | 68 | # The jacobian of this transformation should NOT be 1 everywhere, i.e. 69 | # scaling should have happened, and the new volume should be smaller 70 | # as the top left has been folded in 71 | self.assertTrue(np.all(grid.jacobian_det(trf) < np.array(1, DTYPE))) 72 | 73 | def test_bspline_2d_folding(self): 74 | bspline_grid = np.array([ 75 | [[0.51, 0.51], [-0.5, -0.5]], # Folds the top half of the image slightly over the bottom half. 76 | [[0, 0], [0, 0]] 77 | ]) 78 | trf = gryds.BSplineTransformation(bspline_grid, order=1) 79 | 80 | grid = gryds.Grid((100, 20)) 81 | 82 | # The jacobian of this transformation should be below 0 everywhere 83 | self.assertTrue(np.all(grid.jacobian_det(trf) < 0)) 84 | 85 | def test_bspline_wrong_grid_size(self): 86 | bspline_grid = np.random.rand(3, 10, 10) 87 | self.assertRaises(ValueError, gryds.BSplineTransformation, bspline_grid) 88 | -------------------------------------------------------------------------------- /notebooks/gpu_support.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Faster interpolation and transformation using the GPU\n", 8 | "\n", 9 | "Gryds has GPU support for the interpolation and deformable transformations. From our own testing, we know that this can give a significant speed improvement for 3D images.\n", 10 | "\n", 11 | "By executing the interpolation on the GPU, we obtain a 2-3 times speed-up. Shown below is a curve for the number of seconds of GPU vs CPU linear interpolation as a function of image size.\n", 12 | "\n", 13 | "The GPU execution has some overhead, that means that for smaller images (i.e. 2D images) the CPU implementation is still faster. Starting from an image size of 6 x 128 x 128 the GPU version is significantly faster.\n", 14 | "\n", 15 | "![](cupy_interpolation.png)\n", 16 | "\n", 17 | "If we also run the *transformation* on the GPU, the speed-up is even larger: about seven times faster.\n", 18 | "\n", 19 | "![](cupy_transformation.png)\n" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "## Using GPU acceleration\n", 27 | "\n", 28 | "The GPU versions of the interpolation and transformations are called `BSplineInterpolatorCuda` and `BSplineTransformationCuda`. Currently, only zero and first-order B-splines are supported on the GPU.\n", 29 | "\n", 30 | "Except for a CUDA installation and an Nvidia GPU, there is one extra requirement: a package called `cupy`. `cupy` can be installed using `pip` by typing `pip install cupy`. Once installed, Gryds will automatically import the `BSplineInterpolatorCuda` and `BSplineTransformationCuda` classes, that you can use exactly like the normal `BSplineInterpolator` and `BSplineTransformationCuda` classes. I.e., to turn this CPU-only code\n", 31 | "\n", 32 | "```python\n", 33 | "image = np.random.rand(128, 128, 128)\n", 34 | "tf = gryds.BSplineTransformation(0.01 * (np.random.rand(3, 32, 32, 32) - 0.5), order=1)\n", 35 | "intp = gryds.BSplineInterpolator(image, order=1)\n", 36 | "output = intp.transform(tf)\n", 37 | "```\n", 38 | "\n", 39 | "into GPU code, you just append `Cuda` to the class names:\n", 40 | "\n", 41 | "```python\n", 42 | "image = np.random.rand(128, 128, 128)\n", 43 | "tf = gryds.BSplineTransformationCuda(0.01 * (np.random.rand(3, 32, 32, 32) - 0.5), order=1)\n", 44 | "intp = gryds.BSplineInterpolatorCuda(image, order=1)\n", 45 | "output = intp.transform(tf)\n", 46 | "```" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "metadata": {}, 52 | "source": [ 53 | "## Implementation details\n", 54 | "\n", 55 | "These GPU versions of the interpolator and transformer use CUDA implementations of the `scipy.ndimage.map_coordinates()` function, which is called `cupyx.scipy.ndimage.map_coordinates()`. At the time of writing, this function only support zero and first-order B-spline interpolation, but future versions could also include higher-orders. Documentation on `cupy` can be found [here](https://docs-cupy.chainer.org/en/stable/reference/generated/cupyx.scipy.ndimage.map_coordinates.html#cupyx.scipy.ndimage.map_coordinates)." 56 | ] 57 | } 58 | ], 59 | "metadata": { 60 | "kernelspec": { 61 | "display_name": "Python 3", 62 | "language": "python", 63 | "name": "python3" 64 | }, 65 | "language_info": { 66 | "codemirror_mode": { 67 | "name": "ipython", 68 | "version": 3 69 | }, 70 | "file_extension": ".py", 71 | "mimetype": "text/x-python", 72 | "name": "python", 73 | "nbconvert_exporter": "python", 74 | "pygments_lexer": "ipython3", 75 | "version": "3.6.8" 76 | } 77 | }, 78 | "nbformat": 4, 79 | "nbformat_minor": 2 80 | } 81 | -------------------------------------------------------------------------------- /gryds/interpolators/cuda.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Resample images on a new Grid instance using B-spline interplation 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | import numpy as np 9 | import cupyx.scipy.ndimage as nd 10 | import cupy as cp 11 | from ..config import DTYPE 12 | from .grid import Grid 13 | from .base import Interpolator 14 | from .bspline import BSplineInterpolator 15 | 16 | 17 | class BSplineInterpolatorCuda(BSplineInterpolator): 18 | """An interpolator for an image that can resample an image on a new grid, 19 | or transform an image. 20 | 21 | Attributes: 22 | image (np.ndarray): The wrapped ND image. 23 | grid (Grid): The image's default sampling grid. 24 | default_mode (str): Determines how edges are treated. 25 | default_order (int): B-Spline order. Currently, only 0 and 1 are 26 | supported. 27 | default_cval (numeric): Constant value for mode='constant'. 28 | """ 29 | 30 | def __init__(self, image, mode='constant', order=1, cval=0): 31 | """ 32 | Args: 33 | image (np.array): An image array. 34 | order (int): The order of the B-spline. Default is 1. Use 0 for 35 | binary images. Use 1 for normal linear interpolation. 36 | mode (str): How edges of image domain should be treated when 37 | transformed of 'constant', 'nearest', 'mirror', 'reflect', 38 | 'wrap'. Default is 'constant'. See https://docs.scipy.org/doc/ 39 | scipy-0.14.0/reference/generated/ 40 | scipy.ndimage.interpolation.map_coordinates.html for more 41 | information about modes. 42 | cval (numeric): Constant value for mode='constant'. 43 | """ 44 | super(BSplineInterpolatorCuda, self).__init__( 45 | image, mode=mode, order=order, cval=cval 46 | ) 47 | 48 | def sample(self, points, mode=None, order=None, cval=None): 49 | """ 50 | Samples the image at given points. 51 | 52 | Args: 53 | points (np.array): An N x ndims array of points. 54 | order (int): The order of the B-spline. Default is 3. Use 0 for 55 | binary images. Use 1 for normal linear interpolation. 56 | mode (str): How edges of image domain should be treated when 57 | transformed of 'constant', 'nearest', 'mirror', 'reflect', 58 | 'wrap'. Default is 'constant'. See https://docs.scipy.org/doc/ 59 | scipy-0.14.0/reference/generated/ 60 | scipy.ndimage.interpolation.map_coordinates.html for more 61 | information about modes. 62 | cval (numeric): Constant value for mode='constant' 63 | Returns: 64 | np.array: N-shaped array of intensities at the points. 65 | """ 66 | new_mode = mode if mode else self.default_mode 67 | new_order = order if order else self.default_order 68 | new_cval = cval if cval else self.default_cval 69 | 70 | # Reshape points for the cupy map_coordinates function to 71 | # receive coordinates in the expected shape 72 | points_gpu = points.reshape(self.image.ndim, -1) 73 | sample_gpu = nd.map_coordinates(input=cp.array(self.image), 74 | coordinates=cp.array(points_gpu), 75 | mode=new_mode, 76 | order=new_order, 77 | cval=new_cval) 78 | 79 | # Convert back to CPU array and reshape to original shape 80 | sample_cpu = cp.asnumpy(sample_gpu) 81 | sample = sample_cpu.transpose().reshape(points.shape[1:]) 82 | return np.array(sample.astype(DTYPE)) 83 | 84 | -------------------------------------------------------------------------------- /gryds/transformers/base.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Transformation base class 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | import numpy as np 9 | from ..config import DTYPE 10 | 11 | 12 | class Transformation(object): 13 | """Base class for transformations, i.e. maps from *points* in one spatial 14 | domain to points in another spatial domain. This base class enforces checks 15 | of the number of points against the number of dimensions of the transform, 16 | i.e. an error is thrown if self.ndim does not match the number of dimensions 17 | in the points. 18 | 19 | All transformations are applied to relative coordinates, i.e. coordinates in 20 | the [0, 1)^ndim domain. The base class scales the points if necessary to 21 | this domain using the scale parameter of the transform function supplied by 22 | the user. 23 | 24 | Attributes: 25 | ndim (int): The number of dimensions. 26 | parameters (iterable/array): Some array-like representation of the 27 | transformation parameters, dependant on kind of transformation. 28 | """ 29 | 30 | def __init__(self, ndim, parameters): 31 | """ 32 | Args: 33 | ndim (int): Number of dimensions of the transformation, used for 34 | checking the dimensions of points to be transformed. 35 | """ 36 | self.ndim = ndim 37 | self.parameters = parameters 38 | 39 | def __repr__(self): 40 | return '{}({}D)'.format(self.__class__.__name__, self.ndim) 41 | 42 | def _dimension_check(self, points): 43 | """Checks if the points are compatible with the number of dimensions 44 | in the transformation. 45 | 46 | Args: 47 | points (np.array): A (self.ndim x N) array of N points. 48 | scale (np.array): An array of self.ndim scaling factors. 49 | Raises: 50 | ValueError: If the points and self.ndim are not compatible 51 | """ 52 | if points.ndim != 2: 53 | raise ValueError( 54 | 'Points should be expressed as an (ndim x N) matrix.') 55 | if self.ndim != points.shape[0]: 56 | raise ValueError( 57 | 'Dimensions not compatible: {}D point cannot be transformed' 58 | ' by {}D transformer.'.format(points.shape[0], self.ndim)) 59 | 60 | def _transform_points(self, points): 61 | """Template for transformer function.""" 62 | raise NotImplementedError 63 | 64 | def transform(self, points, scale=None): 65 | """Calling the _transform_points function with dimension checks. 66 | 67 | Args: 68 | points (np.array): A (self.ndim x N) array of N points. 69 | scale (np.array): An array of self.ndim scaling factors. 70 | Returns: 71 | (np.array): The (self.ndim x N) array of N transformed points. 72 | Raises: 73 | ValueError: If the points and self.ndim are not compatible. 74 | """ 75 | points = np.array(points, dtype=DTYPE) 76 | 77 | if not scale: 78 | scale = [1] 79 | 80 | scale = np.array(scale, dtype=DTYPE)[:, None] 81 | scaled_points = points / scale 82 | 83 | self._dimension_check(scaled_points) 84 | result = self._transform_points(scaled_points).astype('float32') * scale 85 | 86 | return result.astype(DTYPE) 87 | 88 | def __call__(self, points, scale=None): 89 | """Calling the transformation as a function invokes the `transform` 90 | function. 91 | 92 | Args: 93 | points (np.array): A (self.ndim x N) array of N points. 94 | scale (np.array): An array of self.ndim scaling factors. 95 | Returns: 96 | (np.array): The (self.ndim x N) array of N transformed points. 97 | Raises: 98 | ValueError: If the points and self.ndim are not compatible. 99 | """ 100 | return self.transform(points, scale) 101 | -------------------------------------------------------------------------------- /test/test_bspline_cuda_transformation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | try: 15 | gryds.BSplineTransformationCuda 16 | except AttributeError: 17 | print('Cuda tests not run because Cupy was not installed.') 18 | else: 19 | class TestBSplineCudaTransformation(TestCase): 20 | """Tests BSpline transformations, and associated effect on grids and Jacobians""" 21 | 22 | def test_translation_bspline_2d(self): 23 | bspline_grid = np.ones((2, 2, 2)) 24 | trf = gryds.BSplineTransformationCuda(bspline_grid) 25 | 26 | grid = gryds.Grid((10, 20)) 27 | new_grid = grid.transform(trf) 28 | 29 | # The grid runs from 0 to 0.9 on the i-axis 30 | # Translation by 100% will mean that the i-axis will now run from 1 to 1.9 31 | np.testing.assert_equal(new_grid.grid[0, 0, 0], np.array(1, DTYPE)) 32 | np.testing.assert_equal( 33 | new_grid.grid[0, -1, 0], np.array(1.9, DTYPE)) 34 | 35 | # The jacobian of this transformation should be 1 everywhere, i.e. no 36 | # scaling should have happened 37 | np.testing.assert_almost_equal( 38 | grid.jacobian_det(trf), 39 | np.array(1, DTYPE), 40 | decimal=4) 41 | 42 | def test_translation_bspline_5d(self): 43 | bspline_grid = np.ones((5, 2, 2, 2, 2, 2)) 44 | trf = gryds.BSplineTransformationCuda(bspline_grid) 45 | 46 | grid = gryds.Grid((3, 3, 3, 3, 3)) 47 | new_grid = grid.transform(trf) 48 | 49 | # The grid runs from 0 to 0.9 on the i-axis 50 | # Translation by 100% will mean that the i-axis will now run from 1 to 1.9 51 | np.testing.assert_equal( 52 | new_grid.grid[0, 0, 0, 0, 0], np.array(1, DTYPE)) 53 | np.testing.assert_almost_equal( 54 | new_grid.grid[0, -1, 0, 0, 0], np.array(1.6666667, DTYPE)) 55 | 56 | # The jacobian of this transformation should be 1 everywhere, i.e. no 57 | # scaling should have happened 58 | np.testing.assert_almost_equal( 59 | grid.jacobian_det(trf), 60 | np.array(1, DTYPE), 61 | decimal=4) 62 | 63 | def test_bspline_2d(self): 64 | bspline_grid = np.array([ 65 | [[0.1, 0], [0, 0]], 66 | [[0, 0], [0, 0]] 67 | ]) 68 | trf = gryds.BSplineTransformationCuda(bspline_grid) 69 | 70 | grid = gryds.Grid((10, 20)) 71 | new_grid = grid.transform(trf) 72 | 73 | # The top left has been displaced by 10% or 0.1 pixels in the i-direction 74 | np.testing.assert_almost_equal( 75 | new_grid.grid[0, 0, 0], np.array(0.1, DTYPE)) 76 | 77 | # The jacobian of this transformation should NOT be 1 everywhere, i.e. 78 | # scaling should have happened, and the new volume should be smaller 79 | # as the top left has been folded in 80 | self.assertTrue( 81 | np.all(grid.jacobian_det(trf) < np.array(1, DTYPE))) 82 | 83 | def test_bspline_2d_folding(self): 84 | bspline_grid = np.array([ 85 | # Folds the top half of the image slightly over the bottom half. 86 | [[0.51, 0.51], [-0.5, -0.5]], 87 | [[0, 0], [0, 0]] 88 | ]) 89 | trf = gryds.BSplineTransformationCuda(bspline_grid, order=1) 90 | 91 | grid = gryds.Grid((100, 20)) 92 | 93 | # The jacobian of this transformation should be below 0 everywhere 94 | self.assertTrue(np.all(grid.jacobian_det(trf) < 0)) 95 | 96 | def test_bspline_wrong_grid_size(self): 97 | bspline_grid = np.random.rand(3, 10, 10) 98 | self.assertRaises( 99 | ValueError, gryds.BSplineTransformationCuda, bspline_grid) 100 | -------------------------------------------------------------------------------- /gryds/interpolators/linear.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Resample images on a new Grid instance using linear interplation. 4 | # This class is mostly here to test pure Numpy implementations of 5 | # linear interpolation but can be mostly ignored for standard code. 6 | 7 | 8 | from __future__ import division, print_function, absolute_import 9 | 10 | import numpy as np 11 | from ..config import DTYPE 12 | from .grid import Grid 13 | from .base import Interpolator 14 | 15 | 16 | class LinearInterpolator(Interpolator): 17 | """A pure Numpy implementation of linear interpolation. 18 | 19 | Attributes: 20 | self.image (np.ndarray): The wrapped ND image. 21 | self.grid (Grid): The image's default sampling grid. 22 | """ 23 | def __init__(self, image, **kwargs): 24 | """ 25 | Args: 26 | image (np.array): A 2D or 3D image array. 27 | """ 28 | super(LinearInterpolator, self).__init__( 29 | image 30 | ) 31 | if kwargs: 32 | print('WARNING: ignored options: {}'.format(kwargs)) 33 | if image.ndim == 2: 34 | self._sample = self.__sample2 35 | elif image.ndim == 3: 36 | self._sample = self.__sample3 37 | else: 38 | raise ValueError('Image should be 2D or 3D array.') 39 | 40 | def sample(self, points, **kwargs): 41 | """ 42 | Samples the image at given points. 43 | 44 | Args: 45 | points (np.array): An N x ndims array of points. 46 | **kwargs (dict): ignored 47 | Returns: 48 | np.array: N-shaped array of intensities at the points. 49 | """ 50 | if kwargs: 51 | print('WARNING: ignored options: {}'.format(kwargs)) 52 | p = np.array(points) 53 | return self._sample(*p) 54 | 55 | def resample(self, grid, **kwargs): 56 | """ 57 | Reamples the image at a given grid. 58 | 59 | Args: 60 | grid (Grid): The new grid. 61 | **kwargs (dict): ignored 62 | Returns: 63 | np.array: The resampled image at the new grid. 64 | """ 65 | if kwargs: 66 | print('WARNING: ignored options: {}'.format(kwargs)) 67 | g = grid.scaled_to(self.image.shape).grid 68 | return self._sample(*g) 69 | 70 | def __sample2(self, X, Y): 71 | X0 = np.floor(X).astype('int') 72 | Y0 = np.floor(Y).astype('int') 73 | X1 = X0 + 1 74 | Y1 = Y0 + 1 75 | 76 | X0 = np.clip(X0, 0, self.image.shape[0] - 1) 77 | X1 = np.clip(X1, 0, self.image.shape[0] - 1) 78 | Y0 = np.clip(Y0, 0, self.image.shape[1] - 1) 79 | Y1 = np.clip(Y1, 0, self.image.shape[1] - 1) 80 | 81 | b_x0y0 = self.image[X0, Y0] 82 | b_x1y0 = self.image[X1, Y0] 83 | b_x0y1 = self.image[X0, Y1] 84 | b_x1y1 = self.image[X1, Y1] 85 | 86 | b = (X1 - X) * (Y1 - Y) * b_x0y0 + \ 87 | (X - X0) * (Y1 - Y) * b_x1y0 + \ 88 | (X1 - X) * (Y - Y0) * b_x0y1 + \ 89 | (X - X0) * (Y - Y0) * b_x1y1 90 | return b 91 | 92 | def __sample3(self, X, Y, Z): 93 | X0 = np.floor(X).astype('int64') 94 | Y0 = np.floor(Y).astype('int64') 95 | Z0 = np.floor(Z).astype('int64') 96 | X1 = X0 + 1 97 | Y1 = Y0 + 1 98 | Z1 = Z0 + 1 99 | 100 | X0 = np.clip(X0, 0, self.image.shape[0] - 1) 101 | X1 = np.clip(X1, 0, self.image.shape[0] - 1) 102 | Y0 = np.clip(Y0, 0, self.image.shape[1] - 1) 103 | Y1 = np.clip(Y1, 0, self.image.shape[1] - 1) 104 | Z0 = np.clip(Z0, 0, self.image.shape[2] - 1) 105 | Z1 = np.clip(Z1, 0, self.image.shape[2] - 1) 106 | 107 | b_x0y0z0 = self.image[X0, Y0, Z0] 108 | b_x1y0z0 = self.image[X1, Y0, Z0] 109 | b_x0y1z0 = self.image[X0, Y1, Z0] 110 | b_x1y1z0 = self.image[X1, Y1, Z0] 111 | b_x0y0z1 = self.image[X0, Y0, Z1] 112 | b_x1y0z1 = self.image[X1, Y0, Z1] 113 | b_x0y1z1 = self.image[X0, Y1, Z1] 114 | b_x1y1z1 = self.image[X1, Y1, Z1] 115 | 116 | b = (X1 - X) * (Y1 - Y) * (Z1 - Z) * b_x0y0z0 + \ 117 | (X - X0) * (Y1 - Y) * (Z1 - Z) * b_x1y0z0 + \ 118 | (X1 - X) * (Y - Y0) * (Z1 - Z) * b_x0y1z0 + \ 119 | (X - X0) * (Y - Y0) * (Z1 - Z) * b_x1y1z0 + \ 120 | (X1 - X) * (Y1 - Y) * (Z - Z0) * b_x0y0z1 + \ 121 | (X - X0) * (Y1 - Y) * (Z - Z0) * b_x1y0z1 + \ 122 | (X1 - X) * (Y - Y0) * (Z - Z0) * b_x0y1z1 + \ 123 | (X - X0) * (Y - Y0) * (Z - Z0) * b_x1y1z1 124 | return b 125 | -------------------------------------------------------------------------------- /test/test_linear_interpolation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestLinearInterpolator(TestCase): 15 | """Tests grid initialization and scaling.""" 16 | 17 | def test_2d_linear_interpolator_90_deg_rotation(self): 18 | image = np.array([ 19 | [0, 0, 1, 0, 0], 20 | [0, 0, 1, 0, 0], 21 | [1, 1, 1, 1, 1], 22 | [0, 0, 1, 0, 0], 23 | [0, 0, 1, 0, 0] 24 | ], dtype=DTYPE) 25 | expected = np.array([ 26 | [0, 0, 1, 0, 0], 27 | [0, 0, 1, 0, 0], 28 | [0, 1, 1, 1, 1], 29 | [0, 0, 1, 0, 0], 30 | [0, 0, 0, 0, 0] 31 | ], dtype=DTYPE) # Borders will be zero due to being outside of image domain 32 | intp = gryds.LinearInterpolator(image) 33 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 34 | new_image = intp.transform(trf).astype(DTYPE) 35 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 36 | 37 | def test_2d_linear_interpolator_45_deg_rotation(self): 38 | image = np.array([ 39 | [0, 0, 1, 0, 0], 40 | [0, 0, 1, 0, 0], 41 | [1, 1, 1, 1, 1], 42 | [0, 0, 1, 0, 0], 43 | [0, 0, 1, 0, 0] 44 | ], dtype=DTYPE) 45 | expected = np.array([ 46 | [0, 0, 0., 0, 0], 47 | [0., 1., 0.5, 1., 0.], 48 | [0., 0.5, 1., 0.5, 0.], 49 | [0., 1., 0.5, 1., 0.], 50 | [0., 0., 0., 0., 0.] 51 | ], dtype=DTYPE) # Borders will be zero due to being outside of image domain 52 | intp = gryds.LinearInterpolator(image, mode='mirror') 53 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/4.], center=[0.4, 0.4]) 54 | new_image = intp.transform(trf).astype(DTYPE) 55 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 56 | 57 | def test_3d_linear_interpolator_90_deg_rotation(self): 58 | image = np.zeros((2, 5, 5)) 59 | image[1] = np.array([[ 60 | [0, 0, 1, 0, 0], 61 | [0, 0, 1, 0, 0], 62 | [1, 1, 1, 1, 1], 63 | [0, 0, 1, 0, 0], 64 | [0, 0, 1, 0, 0] 65 | ]], dtype=DTYPE) 66 | image[0] = image[1] 67 | expected = np.zeros((2, 5, 5)) 68 | expected[0] = np.array([ 69 | [0, 0, 1, 0, 0], 70 | [0, 0, 1, 0, 0], 71 | [0, 1, 1, 1, 1], 72 | [0, 0, 1, 0, 0], 73 | [0, 0, 0, 0, 0] 74 | ], dtype=DTYPE) # Borders will be zero due to being outside of image domain 75 | intp = gryds.LinearInterpolator(image) 76 | trf = gryds.AffineTransformation(ndim=3, angles=[np.pi/2., 0, 0], center=[0.4, 0.4, 0.4]) 77 | new_image = intp.transform(trf).astype(DTYPE) 78 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 79 | 80 | def test_3d_linear_interpolator_45_deg_rotation(self): 81 | image = np.array([ 82 | [0, 0, 1, 0, 0], 83 | [0, 0, 1, 0, 0], 84 | [1, 1, 1, 1, 1], 85 | [0, 0, 1, 0, 0], 86 | [0, 0, 1, 0, 0] 87 | ], dtype=DTYPE) 88 | expected = np.array([ 89 | [0, 0, 0., 0, 0], 90 | [0., 1., 0.5, 1., 0.], 91 | [0., 0.5, 1., 0.5, 0.], 92 | [0., 1., 0.5, 1., 0.], 93 | [0., 0., 0., 0., 0.] 94 | ], dtype=DTYPE) # Borders will be zero due to being outside of image domain 95 | intp = gryds.LinearInterpolator(image) 96 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/4.], center=[0.4, 0.4]) 97 | new_image = intp.transform(trf).astype(DTYPE) 98 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 99 | 100 | def test_linear_interpolator_sampling(self): 101 | 102 | image = np.array([ 103 | [0, 0, 1, 0, 0], 104 | [0, 0, 1, 0, 0], 105 | [1, 1, 1, 1, 1], 106 | [0, 0, 1, 0, 0], 107 | [0, 0, 1, 0, 0] 108 | ], dtype=DTYPE) 109 | intp = gryds.LinearInterpolator(image) 110 | 111 | np.testing.assert_equal(intp.sample([0, 2.5]), 0.5) 112 | 113 | 114 | def test_linear_interpolator_error(self): 115 | 116 | image = np.random.rand(3, 3, 3, 3) 117 | self.assertRaises(ValueError, gryds.LinearInterpolator, image) 118 | 119 | 120 | def test_linear_interpolator_warning(self): 121 | image = np.random.rand(3, 3, 3) 122 | grid = gryds.Grid(image.shape) 123 | gryds.LinearInterpolator(image).resample(grid, some_kwarg=42) 124 | 125 | -------------------------------------------------------------------------------- /gryds/interpolators/grid.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Implementation of sampling grids 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | import numpy as np 9 | from ..config import DTYPE 10 | 11 | 12 | class Grid(object): 13 | """Sampling grid that can be transformed. 14 | 15 | Attributes: 16 | self.grid (nd.array): The grid as an ndim x Ni x Nj x ... x Nndim array 17 | """ 18 | 19 | def __init__(self, shape=None, grid=None): 20 | """ 21 | Args: 22 | shape (iterable): an interable of length ndim for the shape of the 23 | grid. 24 | grid (np.ndarray): a pre-defined grid as an ndim x Ni x Nj x ... x Nndim array 25 | 26 | Raises: 27 | ValueError: when neither the shape or the grid are defined. 28 | """ 29 | if grid is not None and shape is None: 30 | self.grid = grid.astype(DTYPE) 31 | elif shape is not None and grid is None: 32 | self.grid = np.array(np.meshgrid( 33 | *[np.arange(d) / d for d in shape], 34 | indexing='ij' 35 | ), dtype=DTYPE) 36 | else: 37 | raise ValueError('Either the shape or the grid parameters should be defined') 38 | 39 | def __repr__(self): 40 | return '{}({}D, {})'.format(self.__class__.__name__, self.grid.shape[0], 41 | 'x'.join([str(x) for x in self.grid.shape[1:]])) 42 | 43 | def scaled_to(self, size): 44 | """ 45 | Scale the grid to the given size, for example to fit an image size. 46 | 47 | Args: 48 | size (iterable): An iterable of length ndim for the shape of the 49 | grid. 50 | Raises: 51 | ValueError: when the number of dimensions and size parameters 52 | do not match. 53 | Returns: 54 | Grid: A scaled version of the grid. 55 | """ 56 | if len(size) != len(self.grid): 57 | raise ValueError( 58 | 'Number of dimensions in size ({}) and grid ({}), do not' 59 | ' match'.format( 60 | len(size), len(self.grid)) 61 | ) 62 | size = np.array(size) 63 | 64 | new_grid_instance = Grid(grid=np.array( 65 | [x * y for x, y in zip(size, self.grid)], dtype=DTYPE 66 | )) 67 | return new_grid_instance 68 | 69 | def transform(self, *transforms): 70 | """ 71 | Transform the grid with a one or multiple transforms. 72 | 73 | Args: 74 | transforms (*list): A list of Transform objects. 75 | Returns: 76 | Grid: a new grid instance with a transformed version of the points. 77 | """ 78 | org_shape = self.grid.shape 79 | new_grid = self.grid.copy() 80 | 81 | for transform in transforms: 82 | rshp_grid = new_grid.reshape(self.grid.shape[0], -1) 83 | new_grid = transform(rshp_grid) 84 | 85 | new_grid_instance = Grid(grid=new_grid.reshape(org_shape)) 86 | 87 | return new_grid_instance 88 | 89 | def jacobian(self, *transforms): 90 | """ 91 | Calculate the Jacobian for the points on the grid after the transforms 92 | have been applied. 93 | 94 | Args: 95 | transforms (*list): A list of Transform objects. 96 | Returns: 97 | np.array: An array of the size of the grid with the Jacobian 98 | vectors, (i.e. ndim x Na x Nb x ... x ND) 99 | """ 100 | diff_grid = self.transform(*transforms).scaled_to(self.grid.shape[1:]).grid 101 | # scaled_grid = new_grid.scaled_to(self.grid.shape[1:]) 102 | jacobian = np.zeros( 103 | (self.grid.shape[0], self.grid.shape[0]) + self.grid.shape[1:] 104 | ) 105 | for i in range(jacobian.shape[0]): 106 | for j in range(jacobian.shape[1]): 107 | padding = self.grid.shape[0] * [(0, 0)] 108 | padding[j] = (0, 1) 109 | jacobian[i, j] = np.pad( 110 | np.diff(diff_grid[i], axis=j), 111 | padding, mode='edge') 112 | 113 | return jacobian.astype(DTYPE) 114 | 115 | def jacobian_det(self, *transforms): 116 | """ 117 | Calculate the Jacobian determinant for the points on the grid after the 118 | transforms have been applied. 119 | 120 | Args: 121 | *transforms (list): A list of Transform objects. 122 | Returns: 123 | np.array: An array of the size of the grid with the Jacobian 124 | determinant, (i.e. Na x ... x ND) 125 | """ 126 | jac = self.jacobian(*transforms) 127 | jac = np.transpose(jac, list(range(2, jac.ndim)) + [0, 1]) 128 | 129 | jacdet = np.linalg.det(jac) 130 | 131 | return jacdet.astype(DTYPE) 132 | -------------------------------------------------------------------------------- /test/test_bspline_cuda_interpolation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | try: 15 | gryds.BSplineInterpolatorCuda 16 | except AttributeError: 17 | print('Cuda tests not run because Cupy was not installed.') 18 | else: 19 | class TestBSplineCudaInterpolator(TestCase): 20 | """Tests grid initialization and scaling.""" 21 | 22 | def test_2d_cuda_interpolator_90_deg_rotation(self): 23 | image = np.array([ 24 | [0, 0, 1, 0, 0], 25 | [0, 0, 1, 0, 0], 26 | [1, 1, 1, 1, 1], 27 | [0, 0, 1, 0, 0], 28 | [0, 0, 1, 0, 0] 29 | ], dtype=DTYPE) 30 | expected = np.array([ 31 | [0, 0, 1, 0, 0], 32 | [0, 0, 1, 0, 0], 33 | [0, 1, 1, 1, 1], 34 | [0, 0, 1, 0, 0], 35 | [0, 0, 1, 0, 0] 36 | ], dtype=DTYPE) # Borders will be zero due to being outside of image domain 37 | intp = gryds.BSplineInterpolatorCuda(image) 38 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 39 | new_image = intp.transform(trf).astype(DTYPE) 40 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 41 | 42 | def test_2d_cuda_interpolator_45_deg_rotation(self): 43 | image = np.array([ 44 | [0, 0, 1, 0, 0], 45 | [0, 0, 1, 0, 0], 46 | [1, 1, 1, 1, 1], 47 | [0, 0, 1, 0, 0], 48 | [0, 0, 1, 0, 0] 49 | ], dtype=DTYPE) 50 | expected = np.array([ 51 | [0, 0, 0, 0, 0], 52 | [0, 1., 0.5, 1., 0], 53 | [0., 0.5, 1., 0.5, 0.], 54 | [0, 1., 0.5, 1., 0], 55 | [0, 0, 0, 0, 0] 56 | ], dtype=DTYPE) # Borders will be zero due to being outside of image domain 57 | intp = gryds.BSplineInterpolatorCuda(image) 58 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/4.], center=[0.4, 0.4]) 59 | new_image = intp.transform(trf).astype(DTYPE) 60 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 61 | 62 | def test_3d_cuda_interpolator_90_deg_rotation(self): 63 | image = np.zeros((2, 5, 5)) 64 | image[1] = np.array([[ 65 | [0, 0, 1, 0, 0], 66 | [0, 0, 1, 0, 0], 67 | [1, 1, 1, 1, 1], 68 | [0, 0, 1, 0, 0], 69 | [0, 0, 1, 0, 0] 70 | ]], dtype=DTYPE) 71 | image[0] = image[1] 72 | expected = np.zeros((2, 5, 5)) 73 | expected[0] = np.array([ 74 | [0, 0, 1, 0, 0], 75 | [0, 0, 1, 0, 0], 76 | [0, 1, 1, 1, 1], 77 | [0, 0, 1, 0, 0], 78 | [0, 0, 1, 0, 0] 79 | ], dtype=DTYPE) # Borders will be zero due to being outside of image domain 80 | expected[1] = expected[0] 81 | intp = gryds.BSplineInterpolatorCuda(image) 82 | trf = gryds.AffineTransformation(ndim=3, angles=[np.pi/2., 0, 0], center=[0.4, 0.4, 0.4]) 83 | new_image = intp.transform(trf).astype(DTYPE) 84 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 85 | 86 | def test_3d_cuda_interpolator_45_deg_rotation(self): 87 | image = np.array([ 88 | [0, 0, 1, 0, 0], 89 | [0, 0, 1, 0, 0], 90 | [1, 1, 1, 1, 1], 91 | [0, 0, 1, 0, 0], 92 | [0, 0, 1, 0, 0] 93 | ], dtype=DTYPE) 94 | expected = np.array([ 95 | [0, 0, 0., 0, 0], 96 | [0., 1., 0.5, 1., 0.], 97 | [0., 0.5, 1., 0.5, 0.], 98 | [0., 1., 0.5, 1., 0.], 99 | [0., 0., 0., 0., 0.] 100 | ], dtype=DTYPE) # Borders will be zero due to being outside of image domain 101 | intp = gryds.BSplineInterpolatorCuda(image) 102 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/4.], center=[0.4, 0.4]) 103 | new_image = intp.transform(trf).astype(DTYPE) 104 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 105 | 106 | def test_normal_bspline_equal(self): 107 | bsp = gryds.BSplineTransformation(0.01 * (np.random.rand(2, 32, 32) - 0.5), order=1) 108 | image = np.zeros((128, 128)) 109 | image[32:-32] = 0.5 110 | image[:, 32:-32] += 0.5 111 | intp_cpu = gryds.BSplineInterpolator(image, order=1).transform(bsp) 112 | intp_gpu = gryds.BSplineInterpolatorCuda(image).transform(bsp) 113 | np.testing.assert_equal(intp_cpu, intp_gpu) 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gryds: a Python package for geometric transformations of images for data augmentation in deep learning 2 | 3 | This package enables you to make fast geometric transformations of images for the purpose of data augmentation in deep learning. The supported geometric transformations are 4 | 5 | * Translations 6 | * Rigid transformations (translation + rotation) 7 | * Similarity transformations (translation + rotation + isotropic scaling) 8 | * Affine transformations (translation + rotation + arbitrary scaling + shearing) 9 | * Deformable transformations (modeled as B-splines) 10 | 11 | These transformations can be applied to points, sampling grids (hence the name), or interpolator objects that wrap an image. The package has been designed such that images of arbitrary dimensions can be used, but it has only been extensively tested on 2D and 3D images. 12 | 13 | The package works with both Python versions 2 (2.6 or higher) and 3. To get a full overview of this package, you can follow the code in the tutorial notebook. 14 | 15 | 16 | ### Citation 17 | 18 | If you use this package in academic research, please cite the following paper: 19 | 20 | *[K.A.J. Eppenhof and J.P.W. Pluim, Plumonary CT Registration through Supervised Learning with Convolutional Neural Networks, IEEE Transactions on Medical Imaging, 2019](https://www.doi.org/10.1109/TMI.2018.2878316)* 21 | 22 | ```bibtex 23 | @article{EppenhofPluimTMI2019, 24 | author={K. A. J. Eppenhof and J. P. W. Pluim}, 25 | journal={IEEE Transactions on Medical Imaging}, 26 | title={Pulmonary CT Registration through Supervised Learning with Convolutional Neural Networks}, 27 | year={2019}, 28 | volume={38}, 29 | number={5}, 30 | pages={1097-1105}, 31 | doi={10.1109/TMI.2018.2878316}, 32 | } 33 | ``` 34 | 35 | For this paper, we used the code in this repository to create the training set of images. 36 | 37 | ### Installation 38 | 39 | Using `pip`, you can install from this repository: 40 | 41 | `pip install git+https://github.com/tueimage/gryds` 42 | 43 | The package requires `numpy` and `scipy`. It has been tested on Python 2 with `numpy 1.13.3` and `scipy 0.19.1`, and on Python 3 with `numpy 1.15.4` and `scipy 1.2.0`. 44 | 45 | ### Tutorial 46 | 47 | A Jupyter notebook that covers most of the available transformations and interpolations is available [here](https://nbviewer.jupyter.org/github/tueimage/gryds/blob/master/notebooks/tutorial.ipynb). 48 | 49 | ### A minimal working example for randomly warping an image 50 | 51 | Assuming you have a 2D image in the `image` variable: 52 | 53 | ```python 54 | import numpy as np 55 | import gryds 56 | 57 | # Define a random 3x3 B-spline grid for a 2D image: 58 | random_grid = np.random.rand(2, 3, 3) 59 | random_grid -= 0.5 60 | random_grid /= 5 61 | 62 | # Define a B-spline transformation object 63 | bspline = gryds.BSplineTransformation(random_grid) 64 | 65 | # Define an interpolator object for the image: 66 | interpolator = gryds.Interpolator(image) 67 | 68 | # Transform the image using the B-spline transformation 69 | transformed_image = interpolator.transform(bspline) 70 | ``` 71 | 72 | ### Combining multiple transformations 73 | 74 | Simply add more transformations in the `transform()` method of the interpolator. 75 | Note that the transformations are applied to the grid, and that the order of the 76 | transformations therefore is reversed when reasoned from the image. 77 | 78 | ```python 79 | import numpy as np 80 | import gryds 81 | 82 | # Define a scaling transformation object 83 | affine = gryds.AffineTransformation( 84 | ndim=2, 85 | angles=[np.pi/4.], # List of angles (for 3D transformations you need a list of 3 angles). 86 | center=[0.5, 0.5] # Center of rotation. 87 | ) 88 | 89 | # Define a random 3x3 B-spline grid for a 2D image: 90 | random_grid = np.random.rand(2, 3, 3) 91 | random_grid -= 0.5 92 | random_grid /= 5 93 | 94 | # Define a B-spline transformation object 95 | bspline = gryds.BSplineTransformation(random_grid) 96 | 97 | # Define an interpolator object for the image: 98 | interpolator = gryds.Interpolator(image) 99 | 100 | # Transform the image using both transformations. The B-spline is applied to the 101 | # sampling grid first, and the affine transformation second. From the 102 | # perspective of the image itself, the order will seem reversed (!). See the 103 | # tutorial notebook for details. 104 | transformed_image = interpolator.transform(bspline, affine) 105 | ``` 106 | 107 | ### GPU acceleration 108 | 109 | Gryds supports GPU acceleration for B-spline interpolation and B-spline transformations. For details, we refer to the GPU-support notebook [here](https://nbviewer.jupyter.org/github/tueimage/gryds/blob/master/notebooks/gpu_support.ipynb). 110 | 111 | ### Why does Gryds apply the inverse transformation to my images? 112 | 113 | Gryds applies the transformation to sampling grids (hence the name) that 114 | are super-imposed on the image. When you apply a transformation to an `Interpolation` 115 | object with the `transform()` method, the *image grid is transformed*. The transformed grid is then used to interpolate the resulting image. For example, if a transformation rotates a grid to anti-clockwise by 45°, the image will be rotated 45° clockwise. The follow example clarifies this: 116 | 117 | ![](grid_examples.png) 118 | -------------------------------------------------------------------------------- /test/test_multichannel_interpolation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestMultiChannelInterpolator(TestCase): 15 | 16 | def test_bspline_channels_first(self): 17 | image = np.array(3 * [[ 18 | [0, 0, 1, 0, 0], 19 | [0, 0, 1, 0, 0], 20 | [1, 1, 1, 1, 1], 21 | [0, 0, 1, 0, 0], 22 | [0, 0, 1, 0, 0] 23 | ]], dtype=DTYPE) 24 | 25 | intp = gryds.MultiChannelInterpolator(image, data_format='channels_first', cval=[0, 0, 0]) 26 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 27 | new_image = intp.transform(trf, mode='mirror').astype(DTYPE) 28 | np.testing.assert_almost_equal(image, new_image, decimal=4) 29 | 30 | intp = gryds.MultiChannelInterpolator(image, data_format='channels_first') 31 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 32 | new_image = intp.transform(trf, mode='mirror').astype(DTYPE) 33 | np.testing.assert_almost_equal(image, new_image, decimal=4) 34 | 35 | def test_bspline_channels_last(self): 36 | image = np.array(3 * [[ 37 | [0, 0, 1, 0, 0], 38 | [0, 0, 1, 0, 0], 39 | [1, 1, 1, 1, 1], 40 | [0, 0, 1, 0, 0], 41 | [0, 0, 1, 0, 0] 42 | ]], dtype=DTYPE).transpose(1, 2, 0) 43 | 44 | intp = gryds.MultiChannelInterpolator(image, data_format='channels_last', cval=[0, 0, 0]) 45 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 46 | new_image = intp.transform(trf, mode='mirror').astype(DTYPE) 47 | np.testing.assert_almost_equal(image, new_image, decimal=4) 48 | 49 | intp = gryds.MultiChannelInterpolator(image, data_format='channels_last') 50 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 51 | new_image = intp.transform(trf, mode='mirror').astype(DTYPE) 52 | np.testing.assert_almost_equal(image, new_image, decimal=4) 53 | 54 | def test_linear_channels_first(self): 55 | image = np.array(3 * [[ 56 | [0, 0, 1, 0, 0], 57 | [0, 0, 1, 0, 0], 58 | [1, 1, 1, 1, 1], 59 | [0, 0, 1, 0, 0], 60 | [0, 0, 1, 0, 0] 61 | ]], dtype=DTYPE) 62 | 63 | expected = np.array(3 * [[ 64 | [0, 0, 1, 0, 0], 65 | [0, 0, 1, 0, 0], 66 | [0, 1, 1, 1, 1], 67 | [0, 0, 1, 0, 0], 68 | [0, 0, 0, 0, 0] 69 | ]], dtype=DTYPE) 70 | 71 | intp = gryds.MultiChannelInterpolator(image, gryds.LinearInterpolator, data_format='channels_first', cval=[0, 0, 0]) 72 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 73 | new_image = intp.transform(trf).astype(DTYPE) 74 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 75 | 76 | intp = gryds.MultiChannelInterpolator(image, gryds.LinearInterpolator, data_format='channels_first') 77 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 78 | new_image = intp.transform(trf).astype(DTYPE) 79 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 80 | 81 | def test_linear_channels_last(self): 82 | image = np.array(3 * [[ 83 | [0, 0, 1, 0, 0], 84 | [0, 0, 1, 0, 0], 85 | [1, 1, 1, 1, 1], 86 | [0, 0, 1, 0, 0], 87 | [0, 0, 1, 0, 0] 88 | ]], dtype=DTYPE).transpose(1, 2, 0) 89 | 90 | expected = np.array(3 * [[ 91 | [0, 0, 1, 0, 0], 92 | [0, 0, 1, 0, 0], 93 | [0, 1, 1, 1, 1], 94 | [0, 0, 1, 0, 0], 95 | [0, 0, 0, 0, 0] 96 | ]], dtype=DTYPE).transpose(1, 2, 0) 97 | 98 | intp = gryds.MultiChannelInterpolator(image, gryds.LinearInterpolator, data_format='channels_last', cval=[0, 0, 0]) 99 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 100 | new_image = intp.transform(trf).astype(DTYPE) 101 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 102 | 103 | intp = gryds.MultiChannelInterpolator(image, gryds.LinearInterpolator, data_format='channels_last') 104 | trf = gryds.AffineTransformation(ndim=2, angles=[np.pi/2.], center=[0.4, 0.4]) 105 | new_image = intp.transform(trf).astype(DTYPE) 106 | np.testing.assert_almost_equal(expected, new_image, decimal=4) 107 | 108 | def test_data_format_error(self): 109 | # Test if data_format error is raised 110 | self.assertRaises(ValueError, 111 | gryds.MultiChannelInterpolator, np.array([]), data_format='channels_second') 112 | 113 | def test_shape_prop(self): 114 | image = np.array(3 * [[ 115 | [0, 0, 1, 0, 0], 116 | [0, 0, 1, 0, 0], 117 | [1, 1, 1, 1, 1], 118 | [0, 0, 1, 0, 0], 119 | [0, 0, 1, 0, 0] 120 | ]], dtype=DTYPE).transpose(1, 2, 0) 121 | intp = gryds.MultiChannelInterpolator(image, gryds.LinearInterpolator, data_format='channels_last', cval=[0, 0, 0]) 122 | self.assertEqual(intp.shape, (5, 5, 3)) 123 | 124 | def test_repr(self): 125 | self.assertEqual( 126 | str(gryds.MultiChannelInterpolator(np.random.rand(3, 20, 20))), 127 | 'MultiChannelInterpolator(2D, channels_last)') 128 | -------------------------------------------------------------------------------- /test/test_affine_transformation.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import sys 4 | import os 5 | 6 | sys.path.append(os.path.abspath('../gryds')) 7 | 8 | from unittest import TestCase 9 | import numpy as np 10 | import gryds 11 | DTYPE = gryds.DTYPE 12 | 13 | 14 | class TestRotation(TestCase): 15 | """Tests rotation, and associated effect on grids and Jacobians""" 16 | 17 | def test_2d_90_deg_rotation(self): 18 | trf = gryds.AffineTransformation(ndim=2, angles=[0.5 * np.pi]) # rotate grid 90 degrees clockwise 19 | 20 | grid = gryds.Grid((10, 20)) 21 | new_grid = grid.transform(trf) 22 | 23 | # The grid runs from 0 to 0.95 on the j-axis 24 | # 90 deg rot means the i-axis will run from 0 to -0.95 25 | np.testing.assert_equal(new_grid.grid[0, 0, 0], np.array(0, DTYPE)) 26 | np.testing.assert_equal(new_grid.grid[0, 0, -1], np.array(-0.95, DTYPE)) 27 | 28 | # The jacobian of this transformation should be 1 everywhere, i.e. no 29 | # scaling should have happened 30 | np.testing.assert_almost_equal( 31 | grid.jacobian_det(trf), 32 | np.array(1, DTYPE), 33 | decimal=4) 34 | 35 | def test_2d_45_deg_rotation(self): 36 | trf = gryds.AffineTransformation(ndim=2, angles=[0.25 * np.pi]) # rotate grid 90 degrees anticlockwise 37 | 38 | grid = gryds.Grid((10, 20)) 39 | new_grid = grid.transform(trf) 40 | 41 | # The grid runs from 0 to 0.95 on the j-axis 42 | # 90 deg rot means the i-axis will run from 0 to -0.95 43 | np.testing.assert_equal(new_grid.grid[0, 0, 0], np.array(0, DTYPE)) 44 | np.testing.assert_almost_equal( 45 | new_grid.grid[0, 0, -1], 46 | np.array(-0.671751442, DTYPE), # 0.95 / sqrt(2) 47 | decimal=6) 48 | 49 | # The jacobian of this transformation should be 1 everywhere, i.e. no 50 | # scaling should have happened 51 | np.testing.assert_almost_equal( 52 | grid.jacobian_det(trf), 53 | np.array(1, DTYPE), 54 | decimal=5) 55 | 56 | def test_3d_90_deg_rotation(self): 57 | trf = gryds.AffineTransformation(ndim=3, angles=[0, 0.5 * np.pi, 0]) # rotate grid 90 degrees anticlockwise 58 | 59 | grid = gryds.Grid((10, 20, 20)) 60 | new_grid = grid.transform(trf) 61 | 62 | # The grid runs from 0 to 0.95 on the j-axis 63 | # 90 deg rot means the i-axis will run from 0 to -0.95 64 | np.testing.assert_equal(new_grid.grid[0, 0, 0, 0], np.array(0, DTYPE)) 65 | 66 | np.testing.assert_almost_equal( 67 | new_grid.grid[0, 0, 0, -1], 68 | np.array(0.95, DTYPE), 69 | decimal=6) 70 | 71 | # The jacobian of this transformation should be 1 everywhere, i.e. no 72 | # scaling should have happened 73 | np.testing.assert_almost_equal( 74 | grid.jacobian_det(trf), 75 | np.array(1, DTYPE), 76 | decimal=5) 77 | 78 | def test_3d_45_deg_rotation(self): 79 | trf = gryds.AffineTransformation(ndim=3, angles=[0, 0.25 * np.pi, 0]) # rotate grid 45 degrees anticlockwise 80 | 81 | grid = gryds.Grid((10, 20, 20)) 82 | new_grid = grid.transform(trf) 83 | 84 | # The grid runs from 0 to 0.95 on the j-axis 85 | # 90 deg rot means the i-axis will run from 0 to -0.95 86 | np.testing.assert_equal(new_grid.grid[0, 0, 0, 0], np.array(0, DTYPE)) 87 | 88 | np.testing.assert_almost_equal( 89 | new_grid.grid[0, 0, 0, -1], 90 | np.array(0.671751442, DTYPE), 91 | decimal=6) 92 | 93 | # The jacobian of this transformation should be 1 everywhere, i.e. no 94 | # scaling should have happened 95 | np.testing.assert_almost_equal( 96 | grid.jacobian_det(trf), 97 | np.array(1, DTYPE), 98 | decimal=5) 99 | 100 | 101 | def test_3d_45_deg_rotation_with_center(self): 102 | trf = gryds.AffineTransformation( 103 | ndim=3, 104 | angles=[0, 0.25 * np.pi, 0], 105 | center_of=np.zeros((10, 20, 20)) 106 | ) # rotate grid 45 degrees anticlockwise 107 | 108 | grid = gryds.Grid((10, 20, 20)) 109 | 110 | # The jacobian of this transformation should be 1 everywhere, i.e. no 111 | # scaling should have happened 112 | np.testing.assert_almost_equal( 113 | grid.jacobian_det(trf), 114 | np.array(1, DTYPE), 115 | decimal=5) 116 | 117 | def test_affine_errors(self): 118 | self.assertRaises(ValueError, gryds.AffineTransformation, ndim=2, angles=[1, 2, 3, 4]) 119 | # Should raise a ValueError for number of angles not supported 120 | 121 | self.assertRaises(ValueError, gryds.AffineTransformation, ndim=2, shear_matrix=[[1]]) 122 | # Should raise a ValueError for shear_matrix not being ndim x ndim shaped 123 | 124 | gryds.AffineTransformation(ndim=2, shear_matrix=[[1, 1], [1, 1]]) 125 | # Should print a Warning that the shear matrix contains scaling 126 | 127 | self.assertRaises(ValueError, gryds.AffineTransformation, ndim=2, scaling=[1, 2, 3]) 128 | # Should raise a ValueError for number of scaling components not agreeing with ndim 129 | 130 | self.assertRaises(ValueError, gryds.AffineTransformation, ndim=2, translation=[1, 2, 3]) 131 | # Should raise a ValueError for number of translation components not agreeing with ndim 132 | 133 | def test_repr(self): 134 | self.assertEqual(str(gryds.AffineTransformation(2, angles=[0.4])), 'AffineTransformation(2D)') 135 | 136 | -------------------------------------------------------------------------------- /gryds/interpolators/color.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Resample multi-channel images on a new Grid 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | import numpy as np 9 | from ..config import DTYPE 10 | from .grid import Grid 11 | from .bspline import BSplineInterpolator 12 | 13 | 14 | class MultiChannelInterpolator: 15 | """Wrapper for an interpolator that is applied to each channel of a 16 | multi-channel (e.g. color) image. 17 | 18 | Attributes: 19 | image (np.ndarray): The wrapped ND image. 20 | grid (Grid): The image's default sampling grid. 21 | default_mode (str): Determines how edges are treated. 22 | default_order (int): B-Spline order. 23 | default_cval (numeric): Constant value for mode='constant'. 24 | """ 25 | 26 | def __init__(self, image, interpolator=BSplineInterpolator, 27 | data_format='channels_last', cval=None, **kwargs): 28 | """ 29 | Args: 30 | image (np.array): An image array. 31 | interpolator (Interpolator): The interpolator that will be applied. 32 | data_format (str): The format of the multi-channel image. Options 33 | are 'channels_last' (for [[[R,G,B]]] images) 34 | and 'channels_first' (for [[[R]], [[G]], [[B]]] images). 35 | cval (numeric): Constant value for mode='constant' if the wrapped 36 | Interpolator class supports it. 37 | **kwargs (dict): Options for the wrapped Interpolator class. 38 | Raises: 39 | ValueError: when the data_format is something other than 40 | 'channels_first' or 'channels_last'. 41 | """ 42 | self.image = image 43 | self.data_format = data_format 44 | 45 | self.nchan = image.shape[-1] if data_format == 'channels_last' \ 46 | else image.shape[0] 47 | if cval is not None: 48 | assert len(cval) == self.nchan 49 | else: 50 | cval = self.nchan * [0] 51 | 52 | if data_format == 'channels_last': 53 | self.grid = Grid(shape=self.image.shape[:-1]) 54 | self.interpolators = [] 55 | for i, x in enumerate(np.rollaxis(image, -1)): 56 | self.interpolators.append(interpolator(x, **kwargs)) 57 | try: 58 | if self.interpolators[i].default_cval is not None: 59 | self.interpolators[i].default_cval = cval[i] 60 | except AttributeError: 61 | pass 62 | 63 | elif data_format == 'channels_first': 64 | self.grid = Grid(shape=self.image.shape[1:]) 65 | self.interpolators = [] 66 | for i, x in enumerate(image): 67 | self.interpolators.append(interpolator(x, **kwargs)) 68 | try: 69 | if self.interpolators[i].default_cval is not None: 70 | self.interpolators[i].default_cval = cval[i] 71 | except AttributeError: 72 | pass 73 | 74 | else: 75 | raise ValueError('Option data_format of MultiChannelInterpolator ' 76 | 'should be either' 77 | ' \'channels_first\' or \'channels_last\'.') 78 | 79 | def __repr__(self): 80 | return '{}({}D, {})'.format( 81 | self.__class__.__name__, self.image.ndim - 1, self.data_format) 82 | 83 | @property 84 | def shape(self): 85 | return self.image.shape 86 | 87 | def sample(self, points, **kwargs): 88 | """ 89 | Samples the image at given points. 90 | 91 | Args: 92 | points (np.array): An N x ndims array of points. 93 | **kwargs (dict): redirected to wrapped Interpolator's sample() method 94 | Returns: 95 | np.array: nchan x N-shaped or N x nchan-shaped array of intensities 96 | at the points (depending on data_format). 97 | """ 98 | cvals = kwargs.pop('cval', self.nchan * [0]) 99 | 100 | if self.data_format == 'channels_last': 101 | return np.rollaxis(np.array([ 102 | x.sample(points, cval=cval, **kwargs) for cval, x in zip(cvals, self.interpolators) 103 | ]), 0, self.image.ndim) 104 | if self.data_format == 'channels_first': 105 | return np.array([ 106 | x.sample(points, cval=cval, **kwargs) for cval, x in zip(cvals, self.interpolators) 107 | ]) 108 | 109 | def resample(self, grid, **kwargs): 110 | """ 111 | Reamples the image at a given grid. 112 | 113 | Args: 114 | grid (Grid): The new grid. 115 | **kwargs (dict): redirected to wrapped Interpolator's resample() method 116 | Returns: 117 | np.array: The resampled image at the new grid. 118 | """ 119 | rescaled_grid = grid.scaled_to(self.interpolators[0].image.shape) 120 | return self.sample(rescaled_grid.grid, 121 | **kwargs) 122 | 123 | def transform(self, *transforms, **kwargs): 124 | """ 125 | Transforms the image by transforming the original image's grid and 126 | resampling the image at the transformed grid. 127 | 128 | Args: 129 | *transforms (list): A list of Transform objects. 130 | **sampling_options (dict): Sampling kwargs accepted by 131 | scipy.ndimage.map_coordinates(). 132 | Returns: 133 | np.array: The transformed image. 134 | """ 135 | transformed_grid = self.interpolators[0].grid.transform(*transforms) 136 | return self.resample(transformed_grid, **kwargs) 137 | -------------------------------------------------------------------------------- /gryds/interpolators/bspline.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Resample images on a new Grid instance using B-spline interplation 4 | 5 | 6 | from __future__ import division, print_function, absolute_import 7 | 8 | import scipy.ndimage as nd 9 | from ..config import DTYPE 10 | from .grid import Grid 11 | from .base import Interpolator 12 | 13 | 14 | class BSplineInterpolator(Interpolator): 15 | """An interpolator for an image that can resample an image on a new grid, 16 | or transform an image. 17 | 18 | Attributes: 19 | image (np.ndarray): The wrapped ND image. 20 | grid (Grid): The image's default sampling grid. 21 | default_mode (str): Determines how edges are treated. 22 | default_order (int): B-Spline order. 23 | default_cval (numeric): Constant value for mode='constant'. 24 | """ 25 | 26 | def __init__(self, image, mode='constant', order=3, cval=0): 27 | """ 28 | Args: 29 | image (np.array): An image array. 30 | order (int): The order of the B-spline. Default is 3. Use 0 for 31 | binary images. Use 1 for normal linear interpolation. 32 | mode (str): How edges of image domain should be treated when 33 | transformed of 'constant', 'nearest', 'mirror', 'reflect', 34 | 'wrap'. Default is 'constant'. See https://docs.scipy.org/doc/ 35 | scipy-0.14.0/reference/generated/ 36 | scipy.ndimage.interpolation.map_coordinates.html for more 37 | information about modes. 38 | cval (numeric): Constant value for mode='constant'. 39 | """ 40 | super(BSplineInterpolator, self).__init__( 41 | image 42 | ) 43 | self.default_mode = mode 44 | self.default_order = order 45 | self.default_cval = cval 46 | 47 | def sample(self, points, mode=None, order=None, cval=None): 48 | """ 49 | Samples the image at given points. 50 | 51 | Args: 52 | points (np.array): An N x ndims array of points. 53 | order (int): The order of the B-spline. Default is 3. Use 0 for 54 | binary images. Use 1 for normal linear interpolation. 55 | mode (str): How edges of image domain should be treated when 56 | transformed of 'constant', 'nearest', 'mirror', 'reflect', 57 | 'wrap'. Default is 'constant'. See https://docs.scipy.org/doc/ 58 | scipy-0.14.0/reference/generated/ 59 | scipy.ndimage.interpolation.map_coordinates.html for more 60 | information about modes. 61 | cval (numeric): Constant value for mode='constant' 62 | Returns: 63 | np.array: N-shaped array of intensities at the points. 64 | """ 65 | new_mode = mode if mode else self.default_mode 66 | new_order = order if order else self.default_order 67 | new_cval = cval if cval else self.default_cval 68 | 69 | sample = nd.map_coordinates(input=self.image, 70 | coordinates=points, 71 | mode=new_mode, 72 | order=new_order, 73 | cval=new_cval) 74 | return sample.astype(DTYPE) 75 | 76 | def resample(self, grid, mode=None, order=None, cval=None): 77 | """ 78 | Reamples the image at a given grid. 79 | 80 | Args: 81 | grid (Grid): The new grid. 82 | order (int): The order of the B-spline. Default is 3. Use 0 for 83 | binary images. Use 1 for normal linear interpolation. 84 | mode (str): How edges of image domain should be treated when 85 | transformed of 'constant', 'nearest', 'mirror', 'reflect', 86 | 'wrap'. Default is 'constant'. See https://docs.scipy.org/doc/ 87 | scipy-0.14.0/reference/generated/ 88 | scipy.ndimage.interpolation.map_coordinates.html for more 89 | information about modes. 90 | cval (numeric): Constant value for mode='constant' 91 | Returns: 92 | np.array: The resampled image at the new grid. 93 | """ 94 | rescaled_grid = grid.scaled_to(self.image.shape) 95 | new_image = self.sample(rescaled_grid.grid, 96 | mode=mode, 97 | order=order, 98 | cval=cval) 99 | return new_image.astype(DTYPE) 100 | 101 | def transform(self, *transforms, **kwargs): 102 | """ 103 | Transforms the image by transforming the original image's grid and 104 | resampling the image at the transformed grid. 105 | 106 | Args: 107 | *transforms (list): A list of Transform objects. 108 | order (int): The order of the B-spline. Default is 3. Use 0 for 109 | binary images. Use 1 for normal linear interpolation. 110 | mode (str): How edges of image domain should be treated when 111 | transformed of 'constant', 'nearest', 'mirror', 'reflect', 112 | 'wrap'. Default is 'constant'. See https://docs.scipy.org/doc/ 113 | scipy-0.14.0/reference/generated/ 114 | scipy.ndimage.interpolation.map_coordinates.html for more 115 | information about modes. 116 | cval (numeric): Constant value for mode='constant' 117 | Returns: 118 | np.array: The transformed image. 119 | """ 120 | mode = kwargs['mode'] if 'mode' in kwargs else None 121 | order = kwargs['order'] if 'order' in kwargs else None 122 | cval = kwargs['cval'] if 'cval' in kwargs else None 123 | 124 | transformed_grid = self.grid.transform(*transforms) 125 | new_grid = self.resample(transformed_grid, 126 | mode=mode, order=order, cval=cval) 127 | return new_grid.astype(DTYPE) 128 | -------------------------------------------------------------------------------- /gryds/transformers/affine.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # Affine transformation 4 | # For the sake of simplicity, the ND generalization does not exist for this 5 | # transformation, as it severely complicates the implementation. 6 | # 7 | # However, 4D affine transformations can be implemented by subclassing 8 | # LinearTransformation, or simply defining a LinearTransformation with the 9 | # appropriate transformation matrix. 10 | 11 | 12 | from __future__ import division, print_function, absolute_import 13 | 14 | import numpy as np 15 | from ..config import DTYPE 16 | from .linear import LinearTransformation 17 | 18 | 19 | class AffineTransformation(LinearTransformation): 20 | """Affine transformation for 2D or 3D augmented coordinates. Subclasses 21 | LinearTransformation, as this is merely a filling in of the linear 22 | transformation's matrix instance variable. 23 | 24 | Attributes: 25 | ndim (int): The number of dimensions. 26 | parameters (np.ndarray): An (ndim ) x (ndim + 1) array 27 | representing the augmented affine matrix, where ndim is either 28 | 2 or 3. 29 | """ 30 | 31 | def __init__(self, ndim, center=None, center_of=None, scaling=None, 32 | angles=None, translation=None, shear_matrix=None): 33 | """ 34 | Given a shear matrix G, a center c, a scaling s, angles a, and 35 | translation t computes on a point x: 36 | 37 | R * G * S * (x - c) + c 38 | 39 | where S = s * np.eye(ndim) and R = rotation_matrix_nd(a) 40 | 41 | Args: 42 | shear_matrix (np.array): An (ndim x ndim) matrix with shear 43 | components. 44 | scaling (np.array): An (ndim) length array of scaling factors. 45 | angles (np.array): A size 1 or 3 array (for 2D and 3D transforms 46 | respectively) of angles in radians. 47 | translation (np.array): The (ndim) array of translation. 48 | center (np.array): The (ndim) array of the center of rotation in 49 | relative coordinates (i.e. in the [0, 1)^ndim domain. 50 | Raises: 51 | ValueError: If the number of angles is not 1 or 3. 52 | ValueError: If the number of elements in the shear_matrix, scaling, 53 | angles, and translation array do not match ndim. 54 | """ 55 | if center_of is not None: 56 | center = _center_of(center_of) 57 | matrix = _affine_matrix( 58 | ndim=ndim, center=center, scaling=scaling, angles=angles, 59 | translation=translation, shear_matrix=shear_matrix 60 | ) 61 | super(AffineTransformation, self).__init__(matrix) 62 | 63 | def _transform_points(self, points): 64 | augmented_points = np.ones((self.ndim + 1, points.shape[1])) 65 | augmented_points[:self.ndim] = points 66 | transformed_points = np.dot(self.parameters, augmented_points) 67 | return transformed_points[:self.ndim, :] 68 | 69 | 70 | def _center_of(image): 71 | """Returns the center coordinate of an image, i.e. (shape - 1) / 2.""" 72 | return [(x - 1) / (2. * x) for x in image.shape] 73 | 74 | 75 | def _affine_matrix(ndim, center=None, shear_matrix=None, scaling=None, 76 | angles=None, translation=None): 77 | """ 78 | Args: 79 | shear_matrix (np.array): An (ndim x ndim) matrix with shear 80 | components. 81 | scaling (np.array): An (ndim) length array of scaling factors. 82 | angles (np.array): A size 1 or 3 array (for 2D and 3D transforms 83 | respectively) of angles in radians. 84 | translation (np.array): The (ndim) array of translation. 85 | center (np.array): The (ndim) array of the center of rotation in 86 | relative coordinates (i.e. in the [0, 1)^ndim domain. 87 | Raises: 88 | ValueError: If the number of angles is not 1 or 3. 89 | ValueError: If the number of elements in the shear_matrix, scaling, 90 | angles, and translation array do not match ndim. 91 | Warnings: 92 | When shear_matrix contains a scaling components (i.e. determinant != 0). 93 | """ 94 | if angles is not None: 95 | angles = np.array(angles, dtype=DTYPE) 96 | if len(angles) == 1 and ndim == 2: 97 | rotation_matrix = rotation_matrix_2d(*angles) 98 | elif len(angles) == 3 and ndim == 3: 99 | rotation_matrix = rotation_matrix_3d(*angles) 100 | else: 101 | raise ValueError( 102 | 'Number of angles ({}) not ' 103 | 'supported.'.format(len(angles))) 104 | else: 105 | rotation_matrix = np.eye(ndim) 106 | 107 | if shear_matrix is not None: 108 | shear_matrix = np.array(shear_matrix, dtype=DTYPE) 109 | if shear_matrix.shape != (ndim, ndim): 110 | raise ValueError( 111 | 'Number of dimensions in the shear matrix {} does not match ' 112 | 'ndim {}'.format(shear_matrix.shape, ndim)) 113 | 114 | shear_det = np.linalg.det(shear_matrix) 115 | if shear_det != 1: 116 | print('WARNING: Shear matrix has a scale component. ' 117 | 'Determinant not equal to 1, but {}.'.format(shear_det)) 118 | else: 119 | shear_matrix = np.eye(ndim) 120 | 121 | if scaling is not None: 122 | scaling = np.array(scaling, dtype=DTYPE) 123 | if len(scaling) != ndim: 124 | raise ValueError( 125 | 'Number of dimensions in the scaling array {} does not match ' 126 | 'ndim {}'.format(len(scaling), ndim)) 127 | else: 128 | scaling = np.ones(ndim) 129 | scaling_matrix = np.diag(scaling) 130 | 131 | if translation is not None: 132 | translation = np.array(translation, dtype=DTYPE) 133 | if len(translation) != ndim: 134 | raise ValueError( 135 | 'Number of dimensions in the translation array {} does not ' 136 | 'match ndim {}'.format(len(translation), ndim)) 137 | else: 138 | translation = np.zeros(ndim) 139 | 140 | pre_translation = np.eye(ndim + 1, dtype=DTYPE) 141 | if center is not None: 142 | center = np.array(center, dtype=DTYPE) 143 | translation += center 144 | pre_translation[:ndim, -1] = -center 145 | 146 | transform_matrix = np.zeros((ndim, ndim + 1), dtype=DTYPE) 147 | transform_matrix[:ndim, :ndim] = np.eye(ndim, dtype=DTYPE) 148 | mat = np.dot(rotation_matrix, np.dot(shear_matrix, scaling_matrix)) 149 | 150 | transform_matrix[:, :-1] = mat 151 | transform_matrix[:, -1] = translation 152 | 153 | matrix = np.dot(transform_matrix, pre_translation) 154 | return matrix.astype(DTYPE) 155 | 156 | 157 | def rotation_matrix_2d(theta): 158 | """2D rotation matrix for a single rotation angle theta.""" 159 | return np.array([ 160 | [np.cos(theta), -np.sin(theta)], 161 | [np.sin(theta), np.cos(theta)] 162 | ]) 163 | 164 | 165 | def rotation_matrix_3d(alpha, beta, gamma): 166 | """3D rotation matrix for three rotation angles alpha, beta, gamma.""" 167 | Rx = np.array([ 168 | [1, 0, 0], 169 | [0, np.cos(alpha), -np.sin(alpha)], 170 | [0, np.sin(alpha), np.cos(alpha)] 171 | ]) 172 | Ry = np.array([ 173 | [np.cos(beta), 0, np.sin(beta)], 174 | [0, 1, 0], 175 | [-np.sin(beta), 0, np.cos(beta)] 176 | ]) 177 | Rz = np.array([ 178 | [np.cos(gamma), -np.sin(gamma), 0], 179 | [np.sin(gamma), np.cos(gamma), 0], 180 | [0, 0, 1] 181 | ]) 182 | return np.dot(np.dot(Rx, Ry), Rz) 183 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------