Skip to content

Affine Image Registration - #3544

Closed
seanbudd wants to merge 128 commits into
scikit-image:mainfrom
seanbudd:image-registration
Closed

seanbudd wants to merge 128 commits into
scikit-image:mainfrom
seanbudd:image-registration

Conversation

@seanbudd

@seanbudd seanbudd commented Nov 12, 2018 •

Copy link
Copy Markdown
Contributor

Description

In this pull request, we implement n-dimensional image registration for affine transformations.

See ch7 elegant scipy for design philosophy

Checklist

[It's fine to submit PRs which are a work in progress! But before they are merged, all PRs should provide:]

[For detailed information on these and other aspects see scikit-image contribution guidelines]

References

addresses issue: #3502
implements: https://github.com/elegant-scipy/elegant-scipy/blob/master/markdown/ch7.markdown

For reviewers

(Don't remove the checklist below.)

  • Check that the PR title is short, concise, and will make sense 1 year
    later.
  • Check that new functions are imported in corresponding __init__.py.
  • Check that new features, API changes, and deprecations are mentioned in
    doc/release/release_dev.rst.
  • Consider backporting the PR with @meeseeksdev backport to v0.14.x

@pep8speaks

pep8speaks commented Nov 12, 2018 •

Copy link
Copy Markdown

Hello @seanbudd! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

Line 38:80: E501 line too long (84 > 79 characters)
Line 44:36: E241 multiple spaces after ','
Line 63:1: E402 module level import not at top of file
Line 128:70: E226 missing whitespace around arithmetic operator
Line 139:28: E127 continuation line over-indented for visual indent
Line 161:1: E402 module level import not at top of file

Line 216:10: W291 trailing whitespace

Line 31:26: E226 missing whitespace around arithmetic operator
Line 32:58: E226 missing whitespace around arithmetic operator
Line 169:80: E501 line too long (81 > 79 characters)

Line 664:45: E202 whitespace before ']'
Line 664:47: E231 missing whitespace after ','

Comment last updated at 2022-07-01 20:51:19 UTC

Comment thread skimage/transform/registration.py Resolved
Comment thread skimage/transform/registration.py Resolved
@seanbudd

Copy link
Copy Markdown
Contributor Author

@jni @GenevieveBuckley , any additional thoughts?

@jni

jni commented Nov 22, 2018

Copy link
Copy Markdown
Member

@seanbudd yes, we just don't have a solution!

@GenevieveBuckley and I were playing with the example and we noticed that the end alignment is pretty terrible. Which is a bad sign as this is not a particularly challenging image. Here are the things we've considered but not experimented with:

  • bring back basin-hopping in the first few steps. Personally I'm not in love with this idea.
  • allow users to provide their own optimizer function. This way you can have the example start without basin hopping, show that its results are sub-optimal, then pass in optimize.basinhopping and show the results improving.
  • fiddle with cost_mse. It's possible that the zeros around the image after transformation are messing with the score. So the idea would be to put nans around the transformed image and then alter the cost to ignore nans. (This can be done with np.nanmean.)

@GenevieveBuckley

Copy link
Copy Markdown
Contributor

I feel strongly that this third point is the one to attack first:

  • fiddle with cost_mse. It's possible that the zeros around the image after transformation are messing with the score. So the idea would be to put nans around the transformed image and then alter the cost to ignore nans. (This can be done with np.nanmean.)

It doesn't really solve the issue, since users are likely to pass in similar data at some stage, but if it works we can at least put this in the docs as a suggested workaround/fix.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor

@seanbudd I believe adding a blank line at the end of your file plot_register_affine.rst will get rid of the travis build failures. Can you try that for me now?

/home/travis/build/scikit-image/scikit-image/doc/source/auto_examples/transform/plot_register_affine.rst:23:Explicit markup ends without a blank line; unexpected unindent.

@jni

jni commented Nov 22, 2018

Copy link
Copy Markdown
Member

@GenevieveBuckley what do you mean? He has plot_register_affine.py, the rst is automatically generated. tbh I don't understand the error. I think that the reference text (..[1]:) needs to be indented at each line, followed by a blank line.

@GenevieveBuckley

Copy link
Copy Markdown
Contributor

@jni oooh oops, the .rst is autogenerated. Hm, then I'm not sure I understand this error either. Let's try your suggestion, that sounds reasonable.

@codecov-io

This comment has been minimized.

@seanbudd

Copy link
Copy Markdown
Contributor Author

I've done a fix for the RST issue, hopefully that should be fine now. I'm not really sure what the best approach for fixing the registration is. What makes the example sub-optimal? I don't think that basinhopping is such a good idea as far as I can tell, the registration isn't being caught in a different local minima (right?). Is it possible pre-processing would be enough to aid registration (eg filtering on a colour and registering using the filtered images)?

@stefanv

stefanv commented Nov 28, 2018

Copy link
Copy Markdown
Member

I can't tell from the discussion above what the problem is you are trying to solve. Could you please elaborate?

@jni

jni commented Nov 28, 2018

Copy link
Copy Markdown
Member

@stefanv as written, the registration in the gallery example doesn't converge on the correct transformation. Here's the output from the script:

mse-alignment

This points to a problem in the example at least, but probably a deeper problem about whether the optimisation is good enough to be useful as it is. (This is not a particularly hard problem as far as I can tell.)

@seanbudd

Copy link
Copy Markdown
Contributor Author

@jni I'm going to see if doing a couple iterations improves anything.

@seanbudd

Copy link
Copy Markdown
Contributor Author

@jni I'm going to see if doing a couple iterations improves anything.

I ran into strange problems doing this.

Here's the body of the modified register_affine function I was testing with.

num_dims = reference.ndim

if nlevels is None:
    min_dim = min(reference.shape)
    max_level = max(int(np.log2([min_dim])[0]) - 2, 2)
    nlevels = min(max_level, 7)

pyramid_ref = pyramid_gaussian(reference, max_layer=nlevels - 1,
    multichannel=multichannel)
pyramid_tgt = pyramid_gaussian(target, max_layer=nlevels - 1,
    multichannel=multichannel)
image_pairs = list(zip(pyramid_ref, pyramid_tgt))
old_matrix = np.identity(num_dims + 1)
err = 1
parameter_vector = _matrix_to_parameter_vector(old_matrix)

level1 = 0

while err > 0.01:
    level2 = 0
    level1 += 1
    for (ref, tgt) in reversed(image_pairs):
        print(level1, level2)
        level2 += 1
        def _cost(param):
            transformation = _parameter_vector_to_matrix(param, num_dims)
            transformed = ndi.affine_transform(tgt, transformation)
            return cost(ref, transformed)

        result = minimize(_cost, parameter_vector, method='Powell')
        parameter_vector = result.x
        iter_callback(
            tgt, _parameter_vector_to_matrix(
                parameter_vector, num_dims))
    matrix = _parameter_vector_to_matrix(parameter_vector, num_dims)
    print("here")
    err = compare_mse(ndi.affine_transform(target, old_matrix),
                    ndi.affine_transform(target, matrix))
    print(err)
    old_matrix = matrix


return matrix

I messed around with different callbacks but this one showed my issue the best

Basically, the second iteration had invalid pixel values in the registered images?

    base_num = [0]
    def callback(image, matrix):
            base_num[0] +=1
            imsave("im%d.png" % base_num[0], ndi.affine_transform(image, matrix))


    r = 0.12
    c, s = np.cos(r), np.sin(r)
    matrix_transform = np.array([[c, -s, 0], [s, c, 50], [0, 0, 1]])

    image = camera()
    target = ndi.affine_transform(image, matrix_transform)
    register_matrix = register_affine(
    image, target, nlevels=4, iter_callback=callback)

@seanbudd seanbudd changed the title Image registration Affine Image Registration Nov 28, 2018
@jni

jni commented Nov 28, 2018

Copy link
Copy Markdown
Member

@seanbudd can you tell us the error you're seeing? ie print the full traceback/warning? Anyway, I'm not sure the approach you're taking will help to kick us out of a local minimum without changing the optimization method or the image comparison computation...

@seanbudd

Copy link
Copy Markdown
Contributor Author

@jni

Traceback (most recent call last):
  File "d:/scikitimage/scikit-image/doc/examples/transform/plot_register_affine.py", line 44, in <module>
    image, target, nlevels=4, iter_callback=save_intermediate_alignments)
  File "d:\scikitimage\scikit-image\skimage\transform\registration.py", line 147, in register_affine
    parameter_vector, num_dims))
  File "d:/scikitimage/scikit-image/doc/examples/transform/plot_register_affine.py", line 34, in save_intermediate_alignments
    imsave("im%d.png" % base_num[0], ndi.affine_transform(image, matrix))
  File "d:\scikitimage\scikit-image\skimage\io\_io.py", line 142, in imsave
    return call_plugin('imsave', fname, arr, plugin=plugin, **plugin_args)
  File "d:\scikitimage\scikit-image\skimage\io\manage_plugins.py", line 210, in call_plugin
    return func(*args, **kwargs)
  File "d:\scikitimage\scikit-image\skimage\io\_plugins\pil_plugin.py", line 258, in imsave
    img = ndarray_to_pil(arr, format_str=format_str)
  File "d:\scikitimage\scikit-image\skimage\io\_plugins\pil_plugin.py", line 170, in ndarray_to_pil
    arr = img_as_uint(arr)
  File "d:\scikitimage\scikit-image\skimage\util\dtype.py", line 437, in img_as_uint
    return convert(image, np.uint16, force_copy)
  File "d:\scikitimage\scikit-image\skimage\util\dtype.py", line 255, in convert
    raise ValueError("Images of type float must be between -1 and 1.")
ValueError: Images of type float must be between -1 and 1.

As the curve on the top of the pyramid is smoother, a better initial guess for registration makes it more likely to avoid local minima as pyramid is traversed. I've attached an image to help explain my theory. Imagine if there is a small local minima at the base of each of these arrows, so we move on to the next layer, and then traverse down the curve to the next arrow base. When we reach the base of the pyramid, we are not at a global minima, we are still stuck at a local minima, so we move down to the point of the pyramid and try again, except this time we are closer to the global minima.

image

@GenevieveBuckley

Copy link
Copy Markdown
Contributor

@seanbudd can you also explain what the criteria is for stopping/avoiding an endless loop with your changed code?

@seanbudd

Copy link
Copy Markdown
Contributor Author

@seanbudd can you also explain what the criteria is for stopping/avoiding an endless loop with your changed code?

Sure, @GenevieveBuckley . The idea was to quit the while loop when the registered image converges, the final registration is the same/similar to the previous iteration

@seanbudd

Copy link
Copy Markdown
Contributor Author

also I can't see why the builds are failing now, it appears to be due to different causes. Is there anything still needed to be addressed from the CI tests?

@jni

jni commented Nov 28, 2018

Copy link
Copy Markdown
Member

There should never be an open while loop in code. (It's one of NASA's rules for reliable code.) So, if we take this approach, which I don't think is the right one generally (more below), we would need a max_iter argument.

Your error is caused by our float range checking, which I think we should abolish but it'll take time (see #3009 for discussion), because you didn't set order=1 with affine_transform. It defaults to cubic interpolation in that case which can result in interpolated values outside of your original data range.

As to the approach: I see what you're saying, but I think you'll get few cases where the bumps in the lower levels are less bumpy / more in the right direction than the bumps in the highest level of the pyramid. (As shown in that very curve diagram.) So you're better off using a better optimiser at that level than rotating through all the levels, I think, in general. Obviously there are bound to be counter-examples and also my whole intuition could be wrong, but let's see how it all plays out. =)

@seanbudd

Copy link
Copy Markdown
Contributor Author

thanks @jni for the explanation, was just curious to see if any improvements could be made. I'm not sure if there is much we can do to improve the optimiser. All the papers I have read suggest Powell to be the best optimisation method for image registration in general (or Powell-Brent http://elastix.isi.uu.nl/marius/downloads/2011_c_SPIEMI.pdf)

@jni

jni commented Nov 28, 2018

Copy link
Copy Markdown
Member

@seanbudd Very cool paper, thanks!

Well, basin-hopping is kind of a "meta-optimisation". It basically does what you're suggesting, but on a single optimisation problem: run an optimisation (say, Powell). Then, jitter the parameters by something proportional to how much you moved from your initial guess to the "optimum", and try again. If it's the same optimum, increase the jitter, otherwise, jitter another time. This way you can really explore the space. It's quite clever! Have a look at the original paper, it's quite accessible. But, getting back to your point, each of those optimisation steps can be a Powell step. So basin hopping is going to do strictly better than whatever method you're using as a "backend".

@stefanv

stefanv commented Nov 28, 2018

Copy link
Copy Markdown
Member

@jni @seanbudd What approach do you take to handle non-overlapping parts of the images?

@jni

jni commented Nov 29, 2018

Copy link
Copy Markdown
Member

@stefanv

What approach do you take to handle non-overlapping parts of the images?

No approach. =P Currently everything is zero-padded, as is the default in ndimage transforms. See my third suggestion above:

It's possible that the zeros around the image after transformation are messing with the score. So the idea would be to put nans around the transformed image and then alter the cost to ignore nans.

@sofroniewn sofroniewn mentioned this pull request Oct 11, 2020
1 of 7 tasks
jni added 4 commits December 21, 2020 20:19
stacklevel is already specified in our own utils, so adding it is
redundant when using our own warn function.
@stefanv

stefanv commented Apr 5, 2023

Copy link
Copy Markdown
Member

@seanbudd @jni Where is this PR at?

@stefanv
stefanv dismissed JDWarner’s stale review April 5, 2023 20:54

PR needs some more work.

@jni

jni commented Apr 6, 2023

Copy link
Copy Markdown
Member

@stefanv so we pulled out a lot of the stuff into smaller PRs (nD transforms, simple metrics), so this needs to merge in main and and then check over all the APIs... Otherwise I think it probably still works? 😅

@seanbudd

Copy link
Copy Markdown
Contributor Author

@jni - would you like me to perform the merge and testing?

@seanbudd

seanbudd commented Jun 26, 2024 •

Copy link
Copy Markdown
Contributor Author

I notice there's been some activity, sorry I missed the previous ping

@jni

jni commented Jul 12, 2024

Copy link
Copy Markdown
Member

OHAI @seanbudd! How are you doing???

@jboulanger has picked up our commits and added a few more features and modifications based on your work and other work in the meantime, so I think we can close this and the work can continue in #7421.

If you want to get involved again let me know, if you were just politely responding, we're all good, just slow! 😅

@jni jni closed this Jul 12, 2024
@seanbudd

Copy link
Copy Markdown
Contributor Author

Was just responding - glad to see there's been some movement!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Development

Successfully merging this pull request may close these issues.