def test_register():
    """
    Top level registration of a simple unit square.
    """

    img = np.zeros((100,100))
    img[25:75, 25:75] = 1

    image = register.RegisterData(
        img,
        features={
            'points':
                {
                 '001': [25, 25],
                 '002': [25, 75],
                 '003': [75, 25],
                 '004': [75, 75],
                }
            }
        )

    template = register.RegisterData(
        img,
        features={
            'points':
                {
                 '001': [35, 35],
                 '002': [35, 85],
                 '003': [85, 35],
                 '004': [70, 70],
                }
            }
        )

    # Form feature registrator.
    feature = register.FeatureRegister(
        model=model.Shift,
        sampler=sampler.Spline,
        )

    # Perform the registration.
    _p, warp, _img, _error = feature.register(
        image,
        template
        )

    assert not np.allclose(warp, np.zeros_like(warp)), \
        "Estimated warp field is zero."
示例#2
0
def test_affine(image, template, p):
    """
    Tests image registration using a affine deformation model.
    """

    affine = register.Register(model.Affine, metric.Residual, sampler.Spline)

    # Coerce the image data into RegisterData.
    image = register.RegisterData(image)
    template = register.RegisterData(template)

    step, _search = affine.register(image, template)

    assert np.allclose(p, step.p, atol=0.5), \
        "Estimated p: {} not equal to p: {}".format(
            step.p,
            p
            )
def test_downsample():
    """
    Tests register data down-sampling.
    """
    image = register.RegisterData(misc.lena())
    for factor in [1, 2, 4, 6, 8 ,10]:
        subSampled = image.downsample(factor)
        assert subSampled.data.shape[0] == image.data.shape[0] / factor
        assert subSampled.data.shape[1] == image.data.shape[1] / factor
        assert subSampled.coords.spacing == factor
示例#4
0
def test_shift(image, template, method, p):
    """
    Tests image registration using a shift deformation model.
    """

    shift = register.Register()

    # Coerce the image data into RegisterData.
    image = register.RegisterData(image)
    template = register.RegisterData(template)

    step, _search = shift.register(image,
                                   template,
                                   model.Shift(),
                                   method=method)

    assert np.allclose(p, step.p, atol=0.5), \
        "Estimated p: {} not equal to p: {}".format(
            step.p,
            p
            )
示例#5
0
def test_CubicSpline_estimate():
    """
    Asserts that scaling a warp field is a reasonable thing to do.
    """

    scale = 2.0

    # Form a high resolution image.
    high = register.RegisterData(misc.lena().astype(np.double))

    # Form a low resolution image.
    low = high.downsample(scale)

    # Make a deformed low resolution image.
    p = model.CubicSpline(low.coords).identity
    p += np.random.rand(p.shape[0]) * 100 - 50

    warp = model.CubicSpline(low.coords).transform(p)

    dlow = sampler.Nearest(low.coords).f(low.data, low.coords.tensor -
                                         warp).reshape(low.data.shape)

    # Scale the low resolution warp field to the same size as the high resolution
    # image.

    hwarp = np.array([nd.zoom(warp[0], scale),
                      nd.zoom(warp[1], scale)]) * scale

    # Estimate the high resolution spline parameters that best fit the
    # enlarged warp field.

    invB = np.linalg.pinv(model.CubicSpline(high.coords).basis)

    pHat = np.hstack(
        (np.dot(invB, hwarp[1].flatten()), np.dot(invB, hwarp[0].flatten())))

    warpHat = model.CubicSpline(high.coords).warp(pHat)

    # Make a deformed high resolution image.
    dhigh = sampler.Nearest(high.coords).f(high.data,
                                           warpHat).reshape(high.data.shape)

    # down-sample the deformed high-resolution image and assert that the
    # pixel values are "close".
    dhigh_low = nd.zoom(dhigh, 1.0 / scale)

    # Assert that the down-sampler highresolution image is "roughly" similar to
    # the low resolution image.

    assert (np.abs((dhigh_low[:] - dlow[:])).sum() / dlow.size < 10.0), \
        "Normalized absolute error is greater than 10 pixels."
示例#6
0
    spline_model = model.CubicSpline(coords)
    spline_sampler = sampler.Spline(coords)

    p = spline_model.identity
    #TODO: Understand the effect of parameter magnitude:
    p += np.random.rand(p.shape[0]) * 100 - 50

    return spline_sampler.f(image, spline_model.warp(p)).reshape(image.shape)


image = misc.lena()
template = warp(image)

# Coerce the image data into RegisterData.
image = register.RegisterData(image).downsample(5.0)
template = register.RegisterData(template).downsample(5.0)

# Form the affine registration instance.
affine = register.Register(model.Affine, metric.Residual, sampler.Spline)

# Form the spline registration instance.
spline = register.Register(model.CubicSpline, metric.Residual, sampler.Spline)

# Compute an affine registration between the template and image.
step, search = affine.register(
    image,
    template,
)

# Compute a nonlinear (spline) registration, initialized with the warp field
示例#7
0
"""

from matplotlib.pyplot import imread

from imreg.models import model
from imreg.metrics import metric
from imreg.samplers import sampler

from imreg.visualize import plot
from imreg import register

# Form some test data (lena, lena rotated 20 degrees)
image = imread('data/frown.png')[:, :, 0]
template = imread('data/smile.png')[:, :, 0]

# Form the affine registration instance.
affine = register.Register(model.CubicSpline, metric.Residual, sampler.Spline)

# Coerce the image data into RegisterData.
image = register.RegisterData(image)
template = register.RegisterData(template)

# Smooth the template and image.
image.smooth(1.5)
template.smooth(1.5)

# Register.
step, search = affine.register(image, template, verbose=True)

plot.searchInspector(search)
示例#8
0
"""
Estimates a linear warp field, using an image pyramid to speed up the
computation.
"""

import scipy.ndimage as nd
import scipy.misc as misc

from imreg import model, metric, register
from imreg.samplers import sampler

# Form some test data (lena, lena rotated 20 degrees)
image = register.RegisterData(misc.lena())
template = register.RegisterData(nd.rotate(image.data, 20, reshape=False))

# Form the registrator.
affine = register.Register(model.Affine, metric.Residual,
                           sampler.CubicConvolution)

fullSearch = []

# Image pyramid registration can be executed like so:
pHat = None
for factor in [30., 20., 10., 5., 2., 1.]:

    if pHat is not None:
        scale = downImage.coords.spacing / factor
        # FIXME: Find a nicer way to do this.
        pHat = model.Affine.scale(pHat, scale)

    downImage = image.downsample(factor)
示例#9
0
    Randomly warps an input image using a cubic spline deformation.
    """
    coords = register.Coordinates([0, image.shape[0], 0, image.shape[1]])

    spline_model = model.CubicSpline(coords)
    spline_sampler = sampler.Spline(coords)

    p = spline_model.identity
    #TODO: Understand the effect of parameter magnitude:
    p += np.random.rand(p.shape[0]) * 100 - 50

    return spline_sampler.f(image, spline_model.warp(p)).reshape(image.shape)


# Form some test data (lena, lena rotated 20 degrees)
image = register.RegisterData(misc.lena())
template = register.RegisterData(warp(misc.lena()))

# Form the registrator.
spline = register.Register(model.CubicSpline, metric.Residual, sampler.Spline)

# Image pyramid registration can be executed like so:
fullSearch = []
displacement = None

for factor in [20., 10., 5.]:

    downImage = image.downsample(factor)
    downTemplate = template.downsample(factor)

    step, search = spline.register(downImage,
示例#10
0
define a custom kernel is shown.
"""

import numpy as np
import yaml

import matplotlib.pyplot as plt

from imreg.models import model
from imreg.samplers import sampler
from imreg.visualize import plot

from imreg import register

# Load the image and feature data.
image = register.RegisterData(np.average(plt.imread('data/frown.png'), axis=2),
                              features=yaml.load(open('data/frown.yaml')))
template = register.RegisterData(np.average(plt.imread('data/smile.png'),
                                            axis=2),
                                 features=yaml.load(open('data/smile.yaml')))

###############################################################################
# Using the implementation of thin-plate splines.
###############################################################################

# Form the feature registrator.
feature = register.FeatureRegister(
    model=model.ThinPlateSpline,
    sampler=sampler.Spline,
)

# Perform the registration.