Giter Site home page Giter Site logo

pyelastix's Introduction

PyElastix - Python wrapper for the Elastix nonrigid registration toolkit

This Python module wraps the Elastix registration toolkit. Elastix is a powerful tool, suitable for 2D and 3D images, capable of rigid as well as non-rigid (i.e. elastic) image registration.

For an overview of other image registration projects in Python, see http://pyimreg.github.io.

Installation

Install this library using pip install pyelastix or conda install pyelastix -c conda-forge. This module depends on numpy.

Further, the Elastix command-line application needs to be installed on your computer. You can obtain a copy at http://elastix.isi.uu.nl/.

This module tries to detect the Elastix executable in a series of common locations, such as program directories, the user directory, and next to this module. The executable (or the directory that contains it) can also be provided by setting the ELASTIX_PATH environment variable.

How it works

This module writes the images to register to disk, calls Elastix to do the registration, and reads the resulting data. The temporary data is automatically cleaned up. This approach keeps this module relatively easy, while providing the full power of the awesome Elastix registration toolkit.

Example

# Given im1 and im2 images stored as numpy arrays ...

import pyelastix

# Get params and change a few values
params = pyelastix.get_default_params()
params.MaximumNumberOfIterations = 200
params.FinalGridSpacingInVoxels = 10

# Apply the registration (im1 and im2 can be 2D or 3D)
im1_deformed, field = pyelastix.register(im1, im2, params)

See example.py for a more complete example.

API


Parameters()

Struct object to represent the parameters for the Elastix registration toolkit. Sets of parameters can be combined by addition. (When adding p1 + p2, any parameters present in both objects will take the value that the parameter has in p2.)

Use get_default_params() to get a Parameters struct with sensible default values.

get_advanced_params()

Get Parameters struct with parameters that most users do not want to think about.

get_default_params(type='BSPLINE')

Get Parameters struct with parameters that users may want to tweak. The given type specifies the type of allowed transform, and can be 'RIGID', 'AFFINE', 'BSPLINE'.

For detail on what parameters are available and how they should be used, we refer to the Elastix documentation. Here is a description of the most common parameters:

  • Transform (str): Can be 'BSplineTransform', 'EulerTransform', or 'AffineTransform'. The transformation to apply. Chosen based on type.
  • FinalGridSpacingInPhysicalUnits (int): When using the BSplineTransform, the final spacing of the grid. This controls the smoothness of the final deformation.
  • AutomaticScalesEstimation (bool): When using a rigid or affine transform. Scales the affine matrix elements compared to the translations, to make sure they are in the same range. In general, it's best to use automatic scales estimation.
  • AutomaticTransformInitialization (bool): When using a rigid or affine transform. Automatically guess an initial translation by aligning the geometric centers of the fixed and moving.
  • NumberOfResolutions (int): Most registration algorithms adopt a multiresolution approach to direct the solution towards a global optimum and to speed up the process. This parameter specifies the number of scales to apply the registration at. (default 4)
  • MaximumNumberOfIterations (int): Maximum number of iterations in each resolution level. 200-2000 works usually fine for nonrigid registration. The more, the better, but the longer computation time. This is an important parameter! (default 500).

get_elastix_exes()

Get the executables for elastix and transformix. Raises an error if they cannot be found.

get_tempdir()

Get the temporary directory where pyelastix stores its temporary files. The directory is specific to the current process and the calling thread. Generally, the user does not need this; directories are automatically cleaned up. Though Elastix log files are also written here.

register(im1, im2, params, exact_params=False, verbose=1)

Perform the registration of im1 to im2, using the given parameters. Returns (im1_deformed, field), where field is a tuple with arrays describing the deformation for each dimension (x-y-z order, in world units).

Parameters:

  • im1 (ndarray or file location): The moving image (the one to deform).
  • im2 (ndarray or file location): The static (reference) image.
  • params (dict or Parameters): The parameters of the registration. Default parameters can be obtained using the get_default_params() method. Note that any parameter known to Elastix can be added to the parameter struct, which enables tuning the registration in great detail. See get_default_params() and the Elastix docs for more info.
  • exact_params (bool): If True, use the exact given parameters. If False (default) will process the parameters, checking for incompatible parameters, extending values to lists if a value needs to be given for each dimension.
  • verbose (int): Verbosity level. If 0, will not print any progress. If 1, will print the progress only. If 2, will print the full output produced by the Elastix executable. Note that error messages produced by Elastix will be printed regardless of the verbose level.

If im1 is a list of images, performs a groupwise registration. In this case the resulting field is a list of fields, each indicating the deformation to the "average" image.

pyelastix's People

Contributors

almarklein avatar samtzai avatar soupault avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyelastix's Issues

elastix on MacOS, dyld: Library not loaded: libANNlib.dylib

I know there is a solution http://elastix.isi.uu.nl/FAQ.php#Q_LibraryNotLoaded
But I can not make it work, I can get:echo $DYLD_LIBRARY_PATH
/Users/xiaowanli/Desktop/segmentation/softwares/registration/elastix_macosx64_v4.8/lib
This means I set the path right, but I still get this errors when I run the example in repo. Any ideas? Here is the full version of error message:

Found elastix version: 4.800 in 'elastix'
Calling Elastix to register images ...

dyld: Library not loaded: libANNlib.dylib
Referenced from: /Users/xiaowanli/Desktop/segmentation/softwares/registration/elastix_macosx64_v4.8/bin/elastix
Reason: image not found

Traceback (most recent call last):
File "registration.py", line 30, in
im3, field = pyelastix.register(im1, im2, params)
File "/anaconda/lib/python3.6/site-packages/pyelastix.py", line 502, in register
_system3(command, verbose)
File "/anaconda/lib/python3.6/site-packages/pyelastix.py", line 337, in _system3
raise RuntimeError('An error occured during the registration.')
RuntimeError: An error occured during the registration.

2D-3D registration

Hello,

I want to implement a 2D-3D registration case with parameters from this page: http://elastix.bigr.nl/wiki/index.php/Par0013#Application.

For this task, I have to use:
params.Metric = 'GradientDifference'

I have faced the following error:
"Description: itk::ERROR: GradientDifferenceMetric(0x56530c3cd800): Metric can only be used for 2D-3D registration. FixedImageSize[2] must be 1"

But my im2 (FixedImage) is a 3D NumPy array with 2200, 2200, 1 shape.
What should I do?

I tried to put only a 2D NumPy array with 2200, 2200 shape.
But in this case, I get the following message:
ERROR: problem defining fixed image dimension.; The parameter file says: 3; The fixed image header says: 2

Registered image quality

For some reason the registered image seems to have lost a lot of information during the processing. I am registering 16 bit images and the registered images seems to be composed of floats with very low values (~5 as maximum).
In addition, are the fields obtained one for the x-direction and the other for the y-direction?

Package status

Hi @almarklein ,

I was wondering what is the current status of this package? Do you have any plans to maintain and/or further develop the wrapper?
I'm potentially interested in finalizing it and solving the remaining issues.

Added 20.06.2019 TODO:

  • CI via Azure
  • Examples

Installation instructions for macOS

If you would like to add installation instructions for Mac, they are the same as for linux, but the PATH variables are:

export PATH=path/to/bin:$PATH
export DYLD_LIBRARY_PATH=path/to/lib:$PATH

Getting transformation matrix

Hi, I want to know if there's any way to get the transformation matrix (print or save it) after the registration is done. It will be very useful for my case.

image registration

I have 4 immunofluorescence images from 4 adjacent slides (in tiff), which should cover ~2-cell in z-stack. I need to align those slides (I think it is called image registration).

Ideally, I need to make a pipeline that aligns these four images into a single one, and outputting the "moving" and "rotation" matrices of each image.

Is that a possible thing with your package?

Thank you very much!

Get affine transformation parameters

Hi !

Is it possible to get the affine transformation parameters ? From what I understand, they are stored in temporary files and deleted before the register function ends, so that it's not possible to get them.

Thanks !

RGB image registration

Hello, is this package applicable for RGB image registration? if so, how do I set it? Thx

applying transform to other images

Sorry if this is not the appropriate forum, but does this wrapper provide methods for calling transformix from within Python? The pyelastix.register function outputs an image and a deformation field but deletes the temporary files used to determine the transformation, so I can't use the same transformation on a separate image set

average intensity & std in result image

Hi,

First thanks for this great toolkit to use Elastix.
Actually I face a very similar problem with @123aaron that my result image seems change the intensity distribution form the 0 to 70 to -5 to 10 approximately.
I'm not sure this kind of normalization comes from Elastix or pyelastix and it will be helpful if you can give me some suggesstion

Thank you!

Aimyy

Output error

Hi,

How can i directly specify on my python script the path to the output directoy when calling register method? It is giving me the error regarding the inexistance of result.0.mhd file...

Thanks

No such file or directory: '/opt/local/bin'

Any hint?

Get params and change a few values

params = pyelastix.get_default_params()
params.MaximumNumberOfIterations = 200
params.FinalGridSpacingInVoxels = 10

Apply the registration (im1 and im2 can be 2D or 3D)

im1_deformed, field = pyelastix.register(im1, im2, params)

FileNotFoundError Traceback (most recent call last)
in ()
5
6 # Apply the registration (im1 and im2 can be 2D or 3D)
----> 7 im1_deformed, field = pyelastix.register(im1, im2, params)

/projects/sysbio/projects/czi/immune/anaconda2/envs/py36/lib/python3.6/site-packages/pyelastix.py in register(im1, im2, params, exact_params, verbose)
495
496 # Compile command to execute
--> 497 command = [get_elastix_exes()[0],
498 '-m', path_im1, '-f', path_im2,
499 '-out', tempdir, '-p', path_params]

/projects/sysbio/projects/czi/immune/anaconda2/envs/py36/lib/python3.6/site-packages/pyelastix.py in get_elastix_exes()
154
155 # Find exe
--> 156 elastix, ver = _find_executables('elastix')
157 if elastix:
158 base, ext = os.path.splitext(elastix)

/projects/sysbio/projects/czi/immune/anaconda2/envs/py36/lib/python3.6/site-packages/pyelastix.py in _find_executables(name)
130 # Try harder
131 for d in possible_locations:
--> 132 for sub in reversed(sorted(os.listdir(d))):
133 if sub.startswith(name):
134 exe = os.path.join(d, sub, exe_name)

FileNotFoundError: [Errno 2] No such file or directory: '/opt/local/bin'

Output scale/range

Hi,

Thanks for putting the wrapper together, it works well.

However, I am having a issue with the output data. My input images/arrays are both converted to 8bit (0-255), but the output is gives values in the range of around (-0.019... - 0.099...). is there a reason why the scales are so different on the output? Can the wrapper be coerced into matching the output scale to the input?
My aim is to not lose the initial values of the moving image such that I can convert back to the prior values from the 8bit conversion.

Thanks.

Color image registration

I tried to register with color images, but it got very strange results. Do you know the reason for this?
联想截图_20240427140353
filename

Executable detection in Linux

After reading the web and github of elastix, I still can not figure out how to install the Elastix command line application. And an error occurred to me, i.e. [Errno 2] No such file or directory: '/opt/local/bin'
I tried to install SimpleElastix, but lots of error occurred, so I gave up and tried to use pyelastix.

No such file or directory:'/tmp/pyelastix/../result.0.mhd'

Hi,

I get the following error:

In [26]:im3, field = pyelastix.register(im1, im2, params)
Calling Elastix to register images ...
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-27-67b09ffdefda> in <module>()
----> 1 im3, field = pyelastix.register(im1, im2, params)

/usr/local/lib/python2.7/dist-packages/pyelastix.pyc in register(im1, im2, params, exact_params, verbose)
    507         except IOError as why:
    508             tmp = "An error occured during registration: " + str(why)
--> 509             raise RuntimeError(tmp)
    510
    511     # Find deformation field

RuntimeError: An error occured during registration: [Errno 2] No such file or directory: '/tmp/pyelastix/id_3862_140449827452240/result.0.mhd'

In that folder there is no result.0mhd file but there are im1.mhd, im1.raw, im2.mhd, im2.raw, and params.txt.

Have you ever see such an error or do you know how to solve it?

Thanks

Edit: 1. Environment is Ubuntu 14.04 and 16.04 and 2. Elastix works properly from command line :
elastix -f im1.png -m im2.png -out /tmp/pyelastix/xx -p /tmp/pyelastix/xx/params.txt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.