warpfield 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- warpfield-0.0.1/LICENSE +22 -0
- warpfield-0.0.1/PKG-INFO +216 -0
- warpfield-0.0.1/README.md +192 -0
- warpfield-0.0.1/pyproject.toml +44 -0
- warpfield-0.0.1/setup.cfg +4 -0
- warpfield-0.0.1/src/warpfield/__init__.py +6 -0
- warpfield-0.0.1/src/warpfield/__main__.py +75 -0
- warpfield-0.0.1/src/warpfield/ndimage.py +240 -0
- warpfield-0.0.1/src/warpfield/register.py +660 -0
- warpfield-0.0.1/src/warpfield/utils.py +224 -0
- warpfield-0.0.1/src/warpfield/warp.py +105 -0
- warpfield-0.0.1/src/warpfield.egg-info/PKG-INFO +216 -0
- warpfield-0.0.1/src/warpfield.egg-info/SOURCES.txt +15 -0
- warpfield-0.0.1/src/warpfield.egg-info/dependency_links.txt +1 -0
- warpfield-0.0.1/src/warpfield.egg-info/requires.txt +11 -0
- warpfield-0.0.1/src/warpfield.egg-info/top_level.txt +1 -0
- warpfield-0.0.1/tests/test_all.py +180 -0
warpfield-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
|
|
2
|
+
The MIT License (MIT)
|
|
3
|
+
|
|
4
|
+
Copyright (c) jlab.berlin
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in
|
|
14
|
+
all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
22
|
+
THE SOFTWARE.
|
warpfield-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: warpfield
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: GPU-accelerated 3D non-rigid registration
|
|
5
|
+
Author: jlab.berlin, Maximilian Hoffmann, Benjamin Judkewitz
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/danionella/warpfield
|
|
8
|
+
Keywords: warpfield,python
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: numpy<2
|
|
13
|
+
Requires-Dist: scipy
|
|
14
|
+
Requires-Dist: cupy
|
|
15
|
+
Requires-Dist: tqdm
|
|
16
|
+
Requires-Dist: pydantic
|
|
17
|
+
Requires-Dist: pyyaml
|
|
18
|
+
Requires-Dist: h5py
|
|
19
|
+
Requires-Dist: hdf5plugin
|
|
20
|
+
Requires-Dist: nibabel
|
|
21
|
+
Requires-Dist: pydicom
|
|
22
|
+
Requires-Dist: tifffile
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+

|
|
26
|
+
[](https://opensource.org/licenses/MIT)
|
|
27
|
+

|
|
28
|
+
[](https://pypi.org/project/warpfield/)
|
|
29
|
+
[](https://anaconda.org/danionella/warpfield)
|
|
30
|
+

|
|
31
|
+
|
|
32
|
+
<img src="https://github.com/user-attachments/assets/09b2109d-5db6-4f7e-8e3d-000361455a0f"/>
|
|
33
|
+
<sup>Example shown: region-level 3D registration across subjects (video slowed down ~5x). Cell-level registration of microscopy data is also possible.</sup>
|
|
34
|
+
|
|
35
|
+
# warpfield
|
|
36
|
+
|
|
37
|
+
A GPU-accelerated Python library for non-rigid volumetric image registration / warping.
|
|
38
|
+
|
|
39
|
+
Links: [API documentation](http://danionella.github.io/warpfield), [GitHub repository](https://github.com/danionella/warpfield)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
### Features
|
|
43
|
+
|
|
44
|
+
- GPU-accelerated code for high performance ([CuPy](https://cupy.dev/), CUDA kernels & FFT plans)
|
|
45
|
+
- Typical speedup compared to CPU-based methods: > 1000x (seconds vs. hours)
|
|
46
|
+
- Forward and inverse transform of 3D volumes as well as point coordinates
|
|
47
|
+
- Support for .h5, .npy, .nii and .tiff file formats
|
|
48
|
+
- Python API and command-line interface (CLI)
|
|
49
|
+
|
|
50
|
+
### General Principle
|
|
51
|
+
|
|
52
|
+
The registration process aligns a moving 3D volume to a fixed reference volume by estimating and applying a displacement field. The process is typically performed in a multi-resolution (pyramid) fashion, starting with coarse alignment and progressively refining the displacement field at finer resolutions.
|
|
53
|
+
|
|
54
|
+
The key steps are:
|
|
55
|
+
|
|
56
|
+
1. **Preprocessing**: Enhance features in the volumes (e.g., using Difference-of-Gaussian or 'DoG' filtering) to improve registration accuracy.
|
|
57
|
+
2. **Block Matching**: Divide the volumes into smaller 3D blocks, project them to 2D (along each axis) for memory and compute efficiency, and calculate 2D cross-correlation maps. After smoothing these 2D maps across neighboring blocks, use their maxima to determine the block-level 3D displacement vector.
|
|
58
|
+
3. **Displacement Field Estimation**: Combine block-level displacement vectors into a displacement field (and optionaly apply a median filter or fit an affine transform)
|
|
59
|
+
4. **Warping**: Apply the displacement field to the moving volume to align it with the fixed volume.
|
|
60
|
+
5. **Multi-Resolution Refinement**: Repeat the above steps at progressively finer resolutions to refine the alignment.
|
|
61
|
+
|
|
62
|
+
## Hardware requirements
|
|
63
|
+
|
|
64
|
+
- A computer running Linux (recommended) or Windows
|
|
65
|
+
- A CUDA-compatible GPU with sufficient GPU memory: ≥ 30 bytes per voxel (30 GB / gigavoxel) of your 3D volume
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
## Installation
|
|
69
|
+
|
|
70
|
+
We recommend installing all dependencies via **conda** or **mamba**.
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
# Change into the repository root directory, then type:
|
|
74
|
+
mamba env create -n warpfield -f environment.yml
|
|
75
|
+
mamba activate warpfield
|
|
76
|
+
pip install -e .
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Quickstart
|
|
80
|
+
```python
|
|
81
|
+
import warpfield
|
|
82
|
+
|
|
83
|
+
# 1. Load data (note: the two volumes are expected to be of the same array shape and resolution)
|
|
84
|
+
vol_ref = np.load("reference_volume.npy")
|
|
85
|
+
vol_mov = np.load("moving_volume.npy")
|
|
86
|
+
|
|
87
|
+
# 2. Choose registration recipe (here: loaded from a YAML file. See below for alternatives)
|
|
88
|
+
recipe = warpfield.Recipe.from_yaml('default.yml')
|
|
89
|
+
|
|
90
|
+
# 3. Register moving volume
|
|
91
|
+
vol_mov_reg, warp_map, _ = warpfield.register_volume(vol_ref, vol_mov, recipe)
|
|
92
|
+
|
|
93
|
+
# 4. Optional: apply the transformation to another volume (same shape and resolution)
|
|
94
|
+
vol_another_reg = warp_map.apply(vol_another)
|
|
95
|
+
|
|
96
|
+
# 5. Optional: apply inverse transformation to the reference volume
|
|
97
|
+
vol_ref_reg = warp_map.invert_fast().unwarp(vol_ref)
|
|
98
|
+
|
|
99
|
+
# 6. Optional: apply the warp transformation to a set of coordiantes (3-by-n array, in voxel units)
|
|
100
|
+
points = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
|
|
101
|
+
points_pushed = warp_map.push_coordinates(points)
|
|
102
|
+
points_pulled = warp_map.pull_coordinates(points) # inverse transformation
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Command-Line Interface (CLI)
|
|
106
|
+
|
|
107
|
+
The `warpfield` library provides a command-line interface. This allows you to perform registration directly from the terminal without writing Python code.
|
|
108
|
+
|
|
109
|
+
#### Usage
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
python -m warpfield --fixed <fixed_image_path> --moving <moving_image_path> --recipe <recipe_path> [options]
|
|
113
|
+
# You can use the `--help` flag to see detailed instructions for the CLI:
|
|
114
|
+
python -m warpfield --help
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
#### Required Arguments
|
|
118
|
+
|
|
119
|
+
- `--fixed`: Path to the fixed image/volume file (e.g., `.nii`, `.h5`, `.npy`, etc.).
|
|
120
|
+
- `--moving`: Path to the moving image/volume file (e.g., `.nii`, `.h5`, `.npy`, etc.).
|
|
121
|
+
- `--recipe`: Path to the recipe YAML file for registration.
|
|
122
|
+
|
|
123
|
+
#### Optional Arguments
|
|
124
|
+
|
|
125
|
+
- `--output`: Path to save the registered image/volume. Defaults to `<moving>_registered.h5` if not provided.
|
|
126
|
+
- `--compression`: Compression method for saving the registered volume. Default is `gzip`.
|
|
127
|
+
- `--invert`: Additionally, register the moving image to the fixed image.
|
|
128
|
+
|
|
129
|
+
#### Output Structure
|
|
130
|
+
|
|
131
|
+
The output file is an HDF5 file containing the following datasets:
|
|
132
|
+
- `/moving_reg`: The registered moving image.
|
|
133
|
+
- `/warp_map`: A group containing the warp field and its metadata:
|
|
134
|
+
- `/warp_field`: The displacement field.
|
|
135
|
+
- `/block_size`: The block size (in voxels).
|
|
136
|
+
- `/block_stride`: The block stride (in voxels).
|
|
137
|
+
- `/fixed_reg_inv` (optional): The fixed image registered to the moving image (if `--invert` is used).
|
|
138
|
+
|
|
139
|
+
## Recipes
|
|
140
|
+
|
|
141
|
+
The registration pipeline is defined by a recipe. The recipe consists of a pre-filter (`RegFilter`) that is applied to all volumes (typically a DoG filter to sharpen features) and list of level descriptors (`LevelConfig`), each of which contains a set of parameters for the registration process. Typically, each level corresponds to a different resolution of the displacement field (the block size), with the first level being the coarsest and the last level being the finest.
|
|
142
|
+
|
|
143
|
+
### Recipe parameters
|
|
144
|
+
|
|
145
|
+
| Pre-filter parameter | Description |
|
|
146
|
+
|-------------------|-----------------------------------------------------------------------------|
|
|
147
|
+
| `clip_thresh` | Pixel value threshold for clipping each volume. Default is 0. This setting helps remove DC background, which can otherwise cause edges (the shifted volume is 0 outside the FOV). |
|
|
148
|
+
| `dog` | If True, apply a 3D Difference-of-Gaussians (DoG) pre-filter to each volume. Default is True. |
|
|
149
|
+
| `low` | The σ<sub>low</sub> value for the 3D DoG pre-filter. Default is 0.5 |
|
|
150
|
+
| `high` | The σ<sub>high</sub> value for the 3D DoG pre-filter. Default is 10.0. Note: σ<sub>low</sub> and σ<sub>high</sub> should be smaller and bigger than the feature of interest, respectively. A σ of 1 correponds to a FWHM of ~ 2.4.) |
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
| Level parameter | Description |
|
|
154
|
+
|-------------------|-----------------------------------------------------------------------------|
|
|
155
|
+
| `block_size` | Shape of blocks, whose rigid displacement is estimated. Positive numbers indicate block shape in voxels (e.g. [32, 16, 32]), while negative numbers are interpreted as "divide axis into this many blocks" (e.g. [-5, -5, -5] results in 5 blocks along each axis)|
|
|
156
|
+
| `block_stride` | Block stride – determines whether blocks overlap. Either list of int (stride sizes in voxels) or scalar float (fraction of block_size). Default is 1.0 (no overlap). Set this to a smaller value (e.g. 0.5) for overlaping blocks and higher precision, but larger (e.g. 8x) memory footprint |
|
|
157
|
+
| `project.max` | If True, apply 3D -> 2D max projections to each volume block. If false, apply mean projections. Default is True |
|
|
158
|
+
| `project.dog` | If True, apply a DoG filter to each 2D projection. Default is True |
|
|
159
|
+
| `project.low` | The σ<sub>low</sub> value for the 2D DoG filter. Default is 0.5 voxels (pixels). |
|
|
160
|
+
| `project.high` | The σ<sub>high</sub> value for the 2D DoG filter. Default is 10.0 voxels (pixels). |
|
|
161
|
+
| `project.normalize` | Whether to normalize the projections before calculating the cross-covariance (which would make it a cross-correlation). Defaults to False or 0.0. Values can range from 0.0 (False) to 1.0 (True). Values in between imply normalisation by `l2_norm**project.normalize` |
|
|
162
|
+
| `project.periodic_smooth` | If True, apply periodic smoothing. Default is False. This can help reduce block-edge effects (affecting FFT-based correlation). |
|
|
163
|
+
| `tukey_ref` | if not None, apply a Tukey window to the reference projections (alpha = tukey_ref). Default is 0.5. The Tukey window can reduce block-edge effects. |
|
|
164
|
+
| `smooth.sigmas` | Sigmas for smoothing cross-correlations across blocks. Default is [1.0, 1.0, 1.0] blocks. |
|
|
165
|
+
| `smooth.shear` | Shear parameter (specific to oblique plane wobble – ignore otherwise). Default is None. |
|
|
166
|
+
| `smooth.long_range_ratio` | Long range ratio for double gaussian kernel. Default is None. To deal with empty or low contrast regions, a second smooth with a larger (5x) sigma is applied to the cross-correlation maps and added. Typical values are between 0 (or None) and 0.1
|
|
167
|
+
| `median_filter` | If True, apply median filter to the displacement field. Default is True |
|
|
168
|
+
| `affine` | If True, fit affine transformation to the displacement field. Default is False. The affine fit ignores all edge voxels (to reduce edge effects) and therefore needs at least 4 blocks along each axis |
|
|
169
|
+
| `repeat` | Number of iterations for this level. More repeats allow each block to deviate further from neighbors, despite smoothing. Typical values range from 1-10. Disable a level by setting repeats to 0.|
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
### Defining recipes
|
|
173
|
+
|
|
174
|
+
Recipes can be loaded from YAML files (either those shipped with this package, such as [default.yml](./src/warpfield/recipes/default.yml), or your own):
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
recipe = warpfield.Recipe.from_yaml("default.yml")
|
|
178
|
+
# or your own recipe:
|
|
179
|
+
# recipe = warpfield.recipes.from_yaml("path/to/your/recipe.yaml")
|
|
180
|
+
|
|
181
|
+
# You can then modify recipe parameters programmatically, e.g.;
|
|
182
|
+
recipe.pre_filter.clip_thresh=10
|
|
183
|
+
recipe.levels[2].block_size = [32, 8, 32]
|
|
184
|
+
# ... etc.
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Alternatively, you can define a recipe from scratch using the `Recipe` class. For example:
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
# create a basic recipe with one affine registration level and a default pre-filter:
|
|
191
|
+
recipe = warpfield.Recipe()
|
|
192
|
+
|
|
193
|
+
# add non-rigid registration levels:
|
|
194
|
+
recipe.add_level(block_size=[128,128,128])
|
|
195
|
+
recipe.levels[-1].smooth.sigmas = [1.0,1.0,1.0]
|
|
196
|
+
recipe.levels[-1].repeat = 5
|
|
197
|
+
|
|
198
|
+
recipe.add_level(block_size=[64,64,64])
|
|
199
|
+
recipe.levels[-1].block_stride = 0.5
|
|
200
|
+
recipe.levels[-1].smooth.sigmas = [1.0,1.0,1.0]
|
|
201
|
+
recipe.levels[-1].repeat = 5
|
|
202
|
+
|
|
203
|
+
recipe.add_level(block_size=[32,32,32])
|
|
204
|
+
recipe.levels[-1].block_stride = 0.5
|
|
205
|
+
recipe.levels[-1].smooth.sigmas = [4.0,4.0,4.0]
|
|
206
|
+
recipe.levels[-1].smooth.long_range_ratio = 0.1
|
|
207
|
+
recipe.levels[-1].repeat = 5
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
## See also
|
|
212
|
+
|
|
213
|
+
- [Advanced Normalization Tools in Python (ANTsPy)](https://github.com/ANTsX/ANTsPy)
|
|
214
|
+
- [Computational Morphometry Toolkit (CMTK)](https://www.nitrc.org/projects/cmtk)
|
|
215
|
+
- [Constrained Large Deformation Diffeomorphic Image Registration (CLAIRE)
|
|
216
|
+
](https://github.com/andreasmang/claire)
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+

|
|
2
|
+
[](https://opensource.org/licenses/MIT)
|
|
3
|
+

|
|
4
|
+
[](https://pypi.org/project/warpfield/)
|
|
5
|
+
[](https://anaconda.org/danionella/warpfield)
|
|
6
|
+

|
|
7
|
+
|
|
8
|
+
<img src="https://github.com/user-attachments/assets/09b2109d-5db6-4f7e-8e3d-000361455a0f"/>
|
|
9
|
+
<sup>Example shown: region-level 3D registration across subjects (video slowed down ~5x). Cell-level registration of microscopy data is also possible.</sup>
|
|
10
|
+
|
|
11
|
+
# warpfield
|
|
12
|
+
|
|
13
|
+
A GPU-accelerated Python library for non-rigid volumetric image registration / warping.
|
|
14
|
+
|
|
15
|
+
Links: [API documentation](http://danionella.github.io/warpfield), [GitHub repository](https://github.com/danionella/warpfield)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
### Features
|
|
19
|
+
|
|
20
|
+
- GPU-accelerated code for high performance ([CuPy](https://cupy.dev/), CUDA kernels & FFT plans)
|
|
21
|
+
- Typical speedup compared to CPU-based methods: > 1000x (seconds vs. hours)
|
|
22
|
+
- Forward and inverse transform of 3D volumes as well as point coordinates
|
|
23
|
+
- Support for .h5, .npy, .nii and .tiff file formats
|
|
24
|
+
- Python API and command-line interface (CLI)
|
|
25
|
+
|
|
26
|
+
### General Principle
|
|
27
|
+
|
|
28
|
+
The registration process aligns a moving 3D volume to a fixed reference volume by estimating and applying a displacement field. The process is typically performed in a multi-resolution (pyramid) fashion, starting with coarse alignment and progressively refining the displacement field at finer resolutions.
|
|
29
|
+
|
|
30
|
+
The key steps are:
|
|
31
|
+
|
|
32
|
+
1. **Preprocessing**: Enhance features in the volumes (e.g., using Difference-of-Gaussian or 'DoG' filtering) to improve registration accuracy.
|
|
33
|
+
2. **Block Matching**: Divide the volumes into smaller 3D blocks, project them to 2D (along each axis) for memory and compute efficiency, and calculate 2D cross-correlation maps. After smoothing these 2D maps across neighboring blocks, use their maxima to determine the block-level 3D displacement vector.
|
|
34
|
+
3. **Displacement Field Estimation**: Combine block-level displacement vectors into a displacement field (and optionaly apply a median filter or fit an affine transform)
|
|
35
|
+
4. **Warping**: Apply the displacement field to the moving volume to align it with the fixed volume.
|
|
36
|
+
5. **Multi-Resolution Refinement**: Repeat the above steps at progressively finer resolutions to refine the alignment.
|
|
37
|
+
|
|
38
|
+
## Hardware requirements
|
|
39
|
+
|
|
40
|
+
- A computer running Linux (recommended) or Windows
|
|
41
|
+
- A CUDA-compatible GPU with sufficient GPU memory: ≥ 30 bytes per voxel (30 GB / gigavoxel) of your 3D volume
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
We recommend installing all dependencies via **conda** or **mamba**.
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
# Change into the repository root directory, then type:
|
|
50
|
+
mamba env create -n warpfield -f environment.yml
|
|
51
|
+
mamba activate warpfield
|
|
52
|
+
pip install -e .
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Quickstart
|
|
56
|
+
```python
|
|
57
|
+
import warpfield
|
|
58
|
+
|
|
59
|
+
# 1. Load data (note: the two volumes are expected to be of the same array shape and resolution)
|
|
60
|
+
vol_ref = np.load("reference_volume.npy")
|
|
61
|
+
vol_mov = np.load("moving_volume.npy")
|
|
62
|
+
|
|
63
|
+
# 2. Choose registration recipe (here: loaded from a YAML file. See below for alternatives)
|
|
64
|
+
recipe = warpfield.Recipe.from_yaml('default.yml')
|
|
65
|
+
|
|
66
|
+
# 3. Register moving volume
|
|
67
|
+
vol_mov_reg, warp_map, _ = warpfield.register_volume(vol_ref, vol_mov, recipe)
|
|
68
|
+
|
|
69
|
+
# 4. Optional: apply the transformation to another volume (same shape and resolution)
|
|
70
|
+
vol_another_reg = warp_map.apply(vol_another)
|
|
71
|
+
|
|
72
|
+
# 5. Optional: apply inverse transformation to the reference volume
|
|
73
|
+
vol_ref_reg = warp_map.invert_fast().unwarp(vol_ref)
|
|
74
|
+
|
|
75
|
+
# 6. Optional: apply the warp transformation to a set of coordiantes (3-by-n array, in voxel units)
|
|
76
|
+
points = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
|
|
77
|
+
points_pushed = warp_map.push_coordinates(points)
|
|
78
|
+
points_pulled = warp_map.pull_coordinates(points) # inverse transformation
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Command-Line Interface (CLI)
|
|
82
|
+
|
|
83
|
+
The `warpfield` library provides a command-line interface. This allows you to perform registration directly from the terminal without writing Python code.
|
|
84
|
+
|
|
85
|
+
#### Usage
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
python -m warpfield --fixed <fixed_image_path> --moving <moving_image_path> --recipe <recipe_path> [options]
|
|
89
|
+
# You can use the `--help` flag to see detailed instructions for the CLI:
|
|
90
|
+
python -m warpfield --help
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
#### Required Arguments
|
|
94
|
+
|
|
95
|
+
- `--fixed`: Path to the fixed image/volume file (e.g., `.nii`, `.h5`, `.npy`, etc.).
|
|
96
|
+
- `--moving`: Path to the moving image/volume file (e.g., `.nii`, `.h5`, `.npy`, etc.).
|
|
97
|
+
- `--recipe`: Path to the recipe YAML file for registration.
|
|
98
|
+
|
|
99
|
+
#### Optional Arguments
|
|
100
|
+
|
|
101
|
+
- `--output`: Path to save the registered image/volume. Defaults to `<moving>_registered.h5` if not provided.
|
|
102
|
+
- `--compression`: Compression method for saving the registered volume. Default is `gzip`.
|
|
103
|
+
- `--invert`: Additionally, register the moving image to the fixed image.
|
|
104
|
+
|
|
105
|
+
#### Output Structure
|
|
106
|
+
|
|
107
|
+
The output file is an HDF5 file containing the following datasets:
|
|
108
|
+
- `/moving_reg`: The registered moving image.
|
|
109
|
+
- `/warp_map`: A group containing the warp field and its metadata:
|
|
110
|
+
- `/warp_field`: The displacement field.
|
|
111
|
+
- `/block_size`: The block size (in voxels).
|
|
112
|
+
- `/block_stride`: The block stride (in voxels).
|
|
113
|
+
- `/fixed_reg_inv` (optional): The fixed image registered to the moving image (if `--invert` is used).
|
|
114
|
+
|
|
115
|
+
## Recipes
|
|
116
|
+
|
|
117
|
+
The registration pipeline is defined by a recipe. The recipe consists of a pre-filter (`RegFilter`) that is applied to all volumes (typically a DoG filter to sharpen features) and list of level descriptors (`LevelConfig`), each of which contains a set of parameters for the registration process. Typically, each level corresponds to a different resolution of the displacement field (the block size), with the first level being the coarsest and the last level being the finest.
|
|
118
|
+
|
|
119
|
+
### Recipe parameters
|
|
120
|
+
|
|
121
|
+
| Pre-filter parameter | Description |
|
|
122
|
+
|-------------------|-----------------------------------------------------------------------------|
|
|
123
|
+
| `clip_thresh` | Pixel value threshold for clipping each volume. Default is 0. This setting helps remove DC background, which can otherwise cause edges (the shifted volume is 0 outside the FOV). |
|
|
124
|
+
| `dog` | If True, apply a 3D Difference-of-Gaussians (DoG) pre-filter to each volume. Default is True. |
|
|
125
|
+
| `low` | The σ<sub>low</sub> value for the 3D DoG pre-filter. Default is 0.5 |
|
|
126
|
+
| `high` | The σ<sub>high</sub> value for the 3D DoG pre-filter. Default is 10.0. Note: σ<sub>low</sub> and σ<sub>high</sub> should be smaller and bigger than the feature of interest, respectively. A σ of 1 correponds to a FWHM of ~ 2.4.) |
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
| Level parameter | Description |
|
|
130
|
+
|-------------------|-----------------------------------------------------------------------------|
|
|
131
|
+
| `block_size` | Shape of blocks, whose rigid displacement is estimated. Positive numbers indicate block shape in voxels (e.g. [32, 16, 32]), while negative numbers are interpreted as "divide axis into this many blocks" (e.g. [-5, -5, -5] results in 5 blocks along each axis)|
|
|
132
|
+
| `block_stride` | Block stride – determines whether blocks overlap. Either list of int (stride sizes in voxels) or scalar float (fraction of block_size). Default is 1.0 (no overlap). Set this to a smaller value (e.g. 0.5) for overlaping blocks and higher precision, but larger (e.g. 8x) memory footprint |
|
|
133
|
+
| `project.max` | If True, apply 3D -> 2D max projections to each volume block. If false, apply mean projections. Default is True |
|
|
134
|
+
| `project.dog` | If True, apply a DoG filter to each 2D projection. Default is True |
|
|
135
|
+
| `project.low` | The σ<sub>low</sub> value for the 2D DoG filter. Default is 0.5 voxels (pixels). |
|
|
136
|
+
| `project.high` | The σ<sub>high</sub> value for the 2D DoG filter. Default is 10.0 voxels (pixels). |
|
|
137
|
+
| `project.normalize` | Whether to normalize the projections before calculating the cross-covariance (which would make it a cross-correlation). Defaults to False or 0.0. Values can range from 0.0 (False) to 1.0 (True). Values in between imply normalisation by `l2_norm**project.normalize` |
|
|
138
|
+
| `project.periodic_smooth` | If True, apply periodic smoothing. Default is False. This can help reduce block-edge effects (affecting FFT-based correlation). |
|
|
139
|
+
| `tukey_ref` | if not None, apply a Tukey window to the reference projections (alpha = tukey_ref). Default is 0.5. The Tukey window can reduce block-edge effects. |
|
|
140
|
+
| `smooth.sigmas` | Sigmas for smoothing cross-correlations across blocks. Default is [1.0, 1.0, 1.0] blocks. |
|
|
141
|
+
| `smooth.shear` | Shear parameter (specific to oblique plane wobble – ignore otherwise). Default is None. |
|
|
142
|
+
| `smooth.long_range_ratio` | Long range ratio for double gaussian kernel. Default is None. To deal with empty or low contrast regions, a second smooth with a larger (5x) sigma is applied to the cross-correlation maps and added. Typical values are between 0 (or None) and 0.1
|
|
143
|
+
| `median_filter` | If True, apply median filter to the displacement field. Default is True |
|
|
144
|
+
| `affine` | If True, fit affine transformation to the displacement field. Default is False. The affine fit ignores all edge voxels (to reduce edge effects) and therefore needs at least 4 blocks along each axis |
|
|
145
|
+
| `repeat` | Number of iterations for this level. More repeats allow each block to deviate further from neighbors, despite smoothing. Typical values range from 1-10. Disable a level by setting repeats to 0.|
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
### Defining recipes
|
|
149
|
+
|
|
150
|
+
Recipes can be loaded from YAML files (either those shipped with this package, such as [default.yml](./src/warpfield/recipes/default.yml), or your own):
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
recipe = warpfield.Recipe.from_yaml("default.yml")
|
|
154
|
+
# or your own recipe:
|
|
155
|
+
# recipe = warpfield.recipes.from_yaml("path/to/your/recipe.yaml")
|
|
156
|
+
|
|
157
|
+
# You can then modify recipe parameters programmatically, e.g.;
|
|
158
|
+
recipe.pre_filter.clip_thresh=10
|
|
159
|
+
recipe.levels[2].block_size = [32, 8, 32]
|
|
160
|
+
# ... etc.
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Alternatively, you can define a recipe from scratch using the `Recipe` class. For example:
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
# create a basic recipe with one affine registration level and a default pre-filter:
|
|
167
|
+
recipe = warpfield.Recipe()
|
|
168
|
+
|
|
169
|
+
# add non-rigid registration levels:
|
|
170
|
+
recipe.add_level(block_size=[128,128,128])
|
|
171
|
+
recipe.levels[-1].smooth.sigmas = [1.0,1.0,1.0]
|
|
172
|
+
recipe.levels[-1].repeat = 5
|
|
173
|
+
|
|
174
|
+
recipe.add_level(block_size=[64,64,64])
|
|
175
|
+
recipe.levels[-1].block_stride = 0.5
|
|
176
|
+
recipe.levels[-1].smooth.sigmas = [1.0,1.0,1.0]
|
|
177
|
+
recipe.levels[-1].repeat = 5
|
|
178
|
+
|
|
179
|
+
recipe.add_level(block_size=[32,32,32])
|
|
180
|
+
recipe.levels[-1].block_stride = 0.5
|
|
181
|
+
recipe.levels[-1].smooth.sigmas = [4.0,4.0,4.0]
|
|
182
|
+
recipe.levels[-1].smooth.long_range_ratio = 0.1
|
|
183
|
+
recipe.levels[-1].repeat = 5
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
## See also
|
|
188
|
+
|
|
189
|
+
- [Advanced Normalization Tools in Python (ANTsPy)](https://github.com/ANTsX/ANTsPy)
|
|
190
|
+
- [Computational Morphometry Toolkit (CMTK)](https://www.nitrc.org/projects/cmtk)
|
|
191
|
+
- [Constrained Large Deformation Diffeomorphic Image Registration (CLAIRE)
|
|
192
|
+
](https://github.com/andreasmang/claire)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=42", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "warpfield"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
description = "GPU-accelerated 3D non-rigid registration"
|
|
9
|
+
authors = [
|
|
10
|
+
{ name = "jlab.berlin" },
|
|
11
|
+
{ name = "Maximilian Hoffmann" },
|
|
12
|
+
{ name = "Benjamin Judkewitz" },
|
|
13
|
+
]
|
|
14
|
+
license = { text = "MIT" }
|
|
15
|
+
readme = "README.md"
|
|
16
|
+
keywords = ["warpfield", "python"]
|
|
17
|
+
requires-python = ">=3.9"
|
|
18
|
+
dependencies = [
|
|
19
|
+
"numpy<2",
|
|
20
|
+
"scipy",
|
|
21
|
+
"cupy",
|
|
22
|
+
"tqdm",
|
|
23
|
+
"pydantic",
|
|
24
|
+
"pyyaml",
|
|
25
|
+
"h5py",
|
|
26
|
+
"hdf5plugin",
|
|
27
|
+
"nibabel",
|
|
28
|
+
"pydicom",
|
|
29
|
+
"tifffile",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/danionella/warpfield"
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.packages.find]
|
|
36
|
+
where = ["src"]
|
|
37
|
+
include = ["warpfield*"]
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
addopts = ["--import-mode=importlib"]
|
|
41
|
+
|
|
42
|
+
[tool.black]
|
|
43
|
+
line-length = 120
|
|
44
|
+
skip_magic_trailing_comma = true
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import os
|
|
3
|
+
import logging
|
|
4
|
+
import numpy as np
|
|
5
|
+
import h5py
|
|
6
|
+
import hdf5plugin
|
|
7
|
+
|
|
8
|
+
from .utils import import_data
|
|
9
|
+
from .register import register_volumes, Recipe
|
|
10
|
+
|
|
11
|
+
# Configure logging
|
|
12
|
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main():
|
|
16
|
+
parser = argparse.ArgumentParser(description="GPU-accelerated volumetric image registration tool.")
|
|
17
|
+
parser.add_argument("--fixed", required=True, help="Path to the fixed image/volume file.")
|
|
18
|
+
parser.add_argument("--moving", required=True, help="Path to the moving image/volume file.")
|
|
19
|
+
parser.add_argument("--recipe", required=True, help="Path to the recipe YAML file for registration.")
|
|
20
|
+
parser.add_argument("--output", help="Path to save the registered image/volume.")
|
|
21
|
+
parser.add_argument(
|
|
22
|
+
"--compression",
|
|
23
|
+
type=str,
|
|
24
|
+
default="gzip",
|
|
25
|
+
help="Compression method for saving the registered volume (default: gzip).",
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument(
|
|
28
|
+
"--invert", action="store_true", help="Invert the warp map and register the moving image to the fixed image."
|
|
29
|
+
)
|
|
30
|
+
args = parser.parse_args()
|
|
31
|
+
output_path = args.output or f"{os.path.splitext(args.moving)[0]}_registered.h5"
|
|
32
|
+
|
|
33
|
+
# load
|
|
34
|
+
logging.info(f"Loading fixed image from {args.fixed}...")
|
|
35
|
+
fixed_image, _ = import_data(args.fixed)
|
|
36
|
+
logging.info(f"Loading moving image from {args.moving}...")
|
|
37
|
+
moving_image, _ = import_data(args.moving)
|
|
38
|
+
if fixed_image.ndim != 3 or moving_image.ndim != 3:
|
|
39
|
+
raise ValueError("Both fixed and moving images must be 3D volumes.")
|
|
40
|
+
if fixed_image.shape != moving_image.shape:
|
|
41
|
+
raise ValueError("Fixed and moving images must have the same shape.")
|
|
42
|
+
# report shape
|
|
43
|
+
logging.info(f"Volume shapes: {fixed_image.shape}")
|
|
44
|
+
recipe = Recipe.from_yaml(args.recipe)
|
|
45
|
+
|
|
46
|
+
# register
|
|
47
|
+
logging.info("Registering the moving image to the fixed image...")
|
|
48
|
+
registered_image, warp_map, _ = register_volumes(fixed_image, moving_image, recipe, verbose=True)
|
|
49
|
+
|
|
50
|
+
if args.invert:
|
|
51
|
+
logging.info("Inverting the warp map...")
|
|
52
|
+
warp_map_inv = warp_map.invert_fast()
|
|
53
|
+
logging.info("Registering the fixed image to the moving image...")
|
|
54
|
+
fixed_reg_inv = warp_map_inv.unwarp(moving_image)
|
|
55
|
+
|
|
56
|
+
# save
|
|
57
|
+
# consider args.invert when logging and reporting fixed_reg_inv:
|
|
58
|
+
logging.info(
|
|
59
|
+
f"Saving to {output_path}:/moving_reg, {'...:/fixed_reg_inv, ' if args.invert else ''}and :/warp_map..."
|
|
60
|
+
)
|
|
61
|
+
with h5py.File(output_path, "w") as f:
|
|
62
|
+
f.create_dataset("moving_reg", data=registered_image, compression=args.compression)
|
|
63
|
+
f.create_dataset("recipe_json", data=recipe.model_dump_json().encode("utf-8"))
|
|
64
|
+
warp_map_group = f.create_group("warp_map")
|
|
65
|
+
warp_map_group.create_dataset("warp_field", data=warp_map.warp_field.get(), compression=args.compression)
|
|
66
|
+
warp_map_group.create_dataset("block_size", data=warp_map.block_size.get())
|
|
67
|
+
warp_map_group.create_dataset("block_stride", data=warp_map.block_stride.get())
|
|
68
|
+
if args.invert:
|
|
69
|
+
f.create_dataset("fixed_reg_inv", data=fixed_reg_inv, compression=args.compression)
|
|
70
|
+
|
|
71
|
+
logging.info("Done!")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
if __name__ == "__main__":
|
|
75
|
+
main()
|