monai
medical
katielink commited on
Commit
8d6f091
1 Parent(s): acf024e

Initial version

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - monai
4
+ - medical
5
+ library_name: monai
6
+ license: apache-2.0
7
+ ---
8
+ # MedNIST Hand Image Registration
9
+
10
+ Based on [the tutorial of 2D registration](https://github.com/Project-MONAI/tutorials/tree/main/2d_registration)
11
+
12
+ ## Downloading the Dataset
13
+ Download the dataset [from here](https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/MedNIST.tar.gz) and extract the contents to a convenient location.
14
+
15
+ The MedNIST dataset was gathered from several sets from [TCIA](https://wiki.cancerimagingarchive.net/display/Public/Data+Usage+Policies+and+Restrictions),
16
+ [the RSNA Bone Age Challenge](http://rsnachallenges.cloudapp.net/competitions/4),
17
+ and [the NIH Chest X-ray dataset](https://cloud.google.com/healthcare/docs/resources/public-datasets/nih-chest).
18
+
19
+ The dataset is kindly made available by [Dr. Bradley J. Erickson M.D., Ph.D.](https://www.mayo.edu/research/labs/radiology-informatics/overview) (Department of Radiology, Mayo Clinic)
20
+ under the Creative Commons [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/).
21
+
22
+ If you use the MedNIST dataset, please acknowledge the source.
23
+
24
+ ## Training
25
+
26
+ Training with same-subject image inputs
27
+ ```bash
28
+ python -m monai.bundle run training --config_file configs/train.yaml --dataset_dir "/workspace/data/MedNIST/Hand"
29
+ ```
30
+
31
+ Training with cross-subject image inputs
32
+ ```bash
33
+ python -m monai.bundle run training \
34
+ --config_file configs/train.yaml \
35
+ --dataset_dir "/workspace/data/MedNIST/Hand" \
36
+ --cross_subjects True
37
+ ```
38
+
39
+ Training from an existing checkpoint file, for example, `models/model_key_metric=-0.0734.pt`:
40
+ ```bash
41
+ python -m monai.bundle run training --config_file configs/train.yaml [...omitting other args] --ckpt "models/model_key_metric=-0.0734.pt"
42
+ ```
43
+
44
+ ## Inference
45
+
46
+ The following figure shows an intra-subject (`--cross_subjects False`) model inference results (Fixed, moving and predicted images from left to right)
47
+
48
+ ![fixed](./examples/008502_fixed_6.png)
49
+ ![moving](./examples/008502_moving_6.png)
50
+ ![predicted](./examples/008502_pred_6.png)
51
+
52
+ The command shows an inference workflow with the checkpoint `"models/model_key_metric=-0.0890.pt"` and using device `"cuda:1"`:
53
+ ```bash
54
+ python -m monai.bundle run eval \
55
+ --config_file configs/inference.yaml \
56
+ --ckpt "models/model_key_metric=-0.0890.pt" \
57
+ --logging_file configs/logging.conf \
58
+ --device "cuda:1"
59
+ ```
60
+
61
+ ## Fine-tuning for cross-subject alignments
62
+
63
+ The following commands starts a finetuning workflow based on the checkpoint `"models/model_key_metric=-0.0065.pt"`
64
+ for `5` epochs using the global mutual information loss.
65
+
66
+ ```bash
67
+ python -m monai.bundle run training \
68
+ --config_file configs/train.yaml \
69
+ --cross_subjects True \
70
+ --ckpt "models/model_key_metric=-0.0065.pt" \
71
+ --lr 0.000001 \
72
+ --trainer#loss_function "@mutual_info_loss" \
73
+ --max_epochs 5
74
+ ```
75
+ The following figure shows an inter-subject (`--cross_subjects True`) model inference results (Fixed, moving and predicted images from left to right)
76
+
77
+ ![fixed](./examples/008501_fixed_7.png)
78
+ ![moving](./examples/008504_moving_7.png)
79
+ ![predicted](./examples/008504_pred_7.png)
80
+
81
+ ## Visualize the first pair of images for debugging (requires `matplotlib`)
82
+
83
+ ```bash
84
+ python -m monai.bundle run display --config_file configs/train.yaml
85
+ ```
86
+
87
+ ```bash
88
+ python -m monai.bundle run display --config_file configs/train.yaml --cross_subjects True
89
+ ```
90
+
91
+ # License
92
+ Copyright (c) MONAI Consortium
93
+
94
+ Licensed under the Apache License, Version 2.0 (the "License");
95
+ you may not use this file except in compliance with the License.
96
+ You may obtain a copy of the License at
97
+
98
+ http://www.apache.org/licenses/LICENSE-2.0
99
+
100
+ Unless required by applicable law or agreed to in writing, software
101
+ distributed under the License is distributed on an "AS IS" BASIS,
102
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
103
+ See the License for the specific language governing permissions and
104
+ limitations under the License.
configs/inference.yaml ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ imports:
3
+ - $import glob
4
+ - $import matplotlib.pyplot as plt
5
+ dataset_dir: "../MedNIST/Hand"
6
+ # inference with 10 images, modify the indices to run it with different image inputs
7
+ datalist: "$list(sorted(glob.glob(@dataset_dir + '/*.jpeg')))[8500:8510]"
8
+
9
+ bundle_root: "./"
10
+ device: "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')"
11
+ output_dir: "$@bundle_root + '/eval'"
12
+ ckpt: "$@bundle_root + '/models/model.pt'"
13
+ cross_subjects: false # whether the input images are from the same subject
14
+
15
+ image_load:
16
+ - _target_: LoadImage
17
+ image_only: True
18
+ ensure_channel_first: True
19
+
20
+ - _target_: ScaleIntensityRange
21
+ a_min: 0.0
22
+ a_max: 255.0
23
+ b_min: 0.0
24
+ b_max: 1.0
25
+
26
+ - _target_: EnsureType
27
+ device: "@device"
28
+
29
+ image_aug:
30
+ - _target_: RandAffine
31
+ spatial_size: [64, 64]
32
+ translate_range: 5
33
+ scale_range: [-0.15, 0.15]
34
+ prob: 1.0
35
+ rotate_range: $np.pi / 8
36
+ mode: bilinear
37
+ padding_mode: border
38
+ cache_grid: True
39
+ device: "@device"
40
+
41
+ preprocessing:
42
+ _target_: Compose
43
+ transforms: "$@image_load + @image_aug"
44
+
45
+ datasets:
46
+ - _target_: ShuffleBuffer
47
+ data:
48
+ _target_: Dataset
49
+ data: "@datalist"
50
+ transform: {_target_: Compose, transforms: "@image_load"}
51
+ seed: "$int(3) if @cross_subjects else int(2)"
52
+ - _target_: ShuffleBuffer
53
+ data:
54
+ _target_: Dataset
55
+ data: "@datalist"
56
+ transform: $@preprocessing.set_random_state(3)
57
+ seed: 2
58
+
59
+ zip_dataset:
60
+ _target_: IterableDataset
61
+ data: "$map(lambda t: dict(image=monai.transforms.concatenate(t), m_img=t[0], label=t[1]), zip(*@datasets))"
62
+
63
+ data_loader:
64
+ _target_: ThreadDataLoader
65
+ dataset: "@zip_dataset"
66
+ batch_size: 1
67
+ num_workers: 0
68
+
69
+
70
+ # components for debugging
71
+ first_pair: $monai.utils.misc.first(@data_loader)
72
+ display:
73
+ - $monai.utils.set_determinism(seed=23)
74
+ - $print(@first_pair.keys())
75
+ - $plt.subplot(1,3,1)
76
+ - $plt.imshow(@first_pair['image'][0, 0], cmap="gray")
77
+ - $plt.subplot(1,3,2)
78
+ - $plt.imshow(@first_pair['image'][0, 1], cmap="gray")
79
+ - $plt.subplot(1,3,3)
80
+ - $plt.imshow(np.abs(@first_pair['image'][0, 0] - @first_pair['image'][0, 1]), cmap="gray")
81
+ - $plt.show()
82
+
83
+ # network definition
84
+ network_def:
85
+ _target_: scripts.net.RegResNet
86
+ image_size: [64, 64]
87
+ spatial_dims: 2
88
+ mode: "bilinear"
89
+ padding_mode: "border"
90
+
91
+ # create the primary evaluator
92
+ handlers:
93
+ - _target_: CheckpointLoader
94
+ load_path: "@ckpt"
95
+ load_dict: {model: "@network_def"}
96
+ - _target_: StatsHandler
97
+ iteration_log: false
98
+
99
+ inferer: {_target_: SimpleInferer}
100
+
101
+ evaluator:
102
+ _target_: SupervisedEvaluator
103
+ device: "@device"
104
+ val_data_loader: "@data_loader"
105
+ network: "@network_def"
106
+ epoch_length: $len(@datalist) // @data_loader#batch_size
107
+ inferer: "@inferer"
108
+ val_handlers: "@handlers"
109
+ postprocessing:
110
+ _target_: Compose
111
+ transforms:
112
+ - _target_: SaveImaged
113
+ keys: [m_img]
114
+ resample: False
115
+ output_dir: "@output_dir"
116
+ output_ext: "png"
117
+ output_postfix: "moving"
118
+ output_dtype: "$np.uint8"
119
+ scale: 255
120
+ separate_folder: False
121
+ writer: "PILWriter"
122
+ output_name_formatter: "$lambda x, s: dict(idx=s._data_index, subject=x['filename_or_obj'])"
123
+ - _target_: SaveImaged
124
+ keys: [label]
125
+ resample: False
126
+ output_dir: "@output_dir"
127
+ output_ext: "png"
128
+ output_postfix: "fixed"
129
+ output_dtype: "$np.uint8"
130
+ scale: 255
131
+ separate_folder: False
132
+ writer: "PILWriter"
133
+ output_name_formatter: "$lambda x, s: dict(idx=s._data_index, subject=x['filename_or_obj'])"
134
+ - _target_: SaveImaged
135
+ keys: [pred]
136
+ resample: False
137
+ output_dir: "@output_dir"
138
+ output_ext: "png"
139
+ output_postfix: "pred"
140
+ output_dtype: "$np.uint8"
141
+ scale: 255
142
+ separate_folder: False
143
+ writer: "PILWriter"
144
+ output_name_formatter: "$lambda x, s: dict(idx=s._data_index, subject=x['filename_or_obj'])"
145
+
146
+ eval:
147
+ - $monai.utils.set_determinism(seed=123)
148
+ - "$setattr(torch.backends.cudnn, 'benchmark', True)"
149
+ - $@evaluator.run()
configs/logging.conf ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [loggers]
2
+ keys=root
3
+
4
+ [handlers]
5
+ keys=consoleHandler
6
+
7
+ [formatters]
8
+ keys=fullFormatter
9
+
10
+ [logger_root]
11
+ level=INFO
12
+ handlers=consoleHandler
13
+
14
+ [handler_consoleHandler]
15
+ class=StreamHandler
16
+ level=INFO
17
+ formatter=fullFormatter
18
+ args=(sys.stdout,)
19
+
20
+ [formatter_fullFormatter]
21
+ format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
configs/metadata.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/meta_schema_20220324.json",
3
+ "version": "0.0.1",
4
+ "changelog": {
5
+ "0.0.1": "Initial version"
6
+ },
7
+ "monai_version": "1.0.1",
8
+ "pytorch_version": "1.13.0",
9
+ "numpy_version": "1.22.2",
10
+ "optional_packages_version": {
11
+ "pytorch-ignite": "0.4.8"
12
+ },
13
+ "task": "Spatial transformer for hand image registration from the MedNIST dataset",
14
+ "description": "This is an example of a ResNet and spatial transformer for hand xray image registration",
15
+ "authors": "MONAI team",
16
+ "copyright": "Copyright (c) MONAI Consortium",
17
+ "intended_use": "This is an example of image registration using MONAI, suitable for demonstration purposes only.",
18
+ "data_type": "jpeg",
19
+ "network_data_format": {
20
+ "inputs": {
21
+ "image": {
22
+ "type": "image",
23
+ "format": "magnitude",
24
+ "num_channels": 2,
25
+ "spatial_shape": [
26
+ 64,
27
+ 64
28
+ ],
29
+ "dtype": "float32",
30
+ "value_range": [
31
+ 0,
32
+ 1
33
+ ],
34
+ "is_patch_data": false,
35
+ "channel_def": {
36
+ "0": "moving image",
37
+ "1": "fixed image"
38
+ }
39
+ }
40
+ },
41
+ "outputs": {
42
+ "pred": {
43
+ "type": "image",
44
+ "format": "magnitude",
45
+ "num_channels": 1,
46
+ "spatial_shape": [
47
+ 64,
48
+ 64
49
+ ],
50
+ "dtype": "float32",
51
+ "value_range": [
52
+ 0,
53
+ 1
54
+ ],
55
+ "is_patch_data": false,
56
+ "channel_def": {
57
+ "0": "image"
58
+ }
59
+ }
60
+ }
61
+ }
62
+ }
configs/train.yaml ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ imports:
3
+ - $import glob
4
+ - $import matplotlib.pyplot as plt
5
+
6
+ # workflow parameters
7
+ bundle_root: "./"
8
+ device: "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')"
9
+ ckpt_dir: "$@bundle_root + '/models'" # folder to save new checkpoints
10
+ ckpt: "" # path to load an existing checkpoint
11
+ val_interval: 1 # every epoch
12
+ max_epochs: 300
13
+ cross_subjects: false # whether the input images are from the same subject
14
+
15
+ # construct the moving and fixed datasets
16
+ dataset_dir: "../MedNIST/Hand"
17
+ datalist: "$list(sorted(glob.glob(@dataset_dir + '/*.jpeg')))[:7000]" # training with 7000 images
18
+ val_datalist: "$list(sorted(glob.glob(@dataset_dir + '/*.jpeg')))[7000:8500]" # validation with 1500 images
19
+
20
+ image_load:
21
+ - _target_: LoadImage
22
+ image_only: True
23
+ ensure_channel_first: True
24
+
25
+ - _target_: ScaleIntensityRange
26
+ a_min: 0.0
27
+ a_max: 255.0
28
+ b_min: 0.0
29
+ b_max: 1.0
30
+
31
+ - _target_: EnsureType
32
+ device: "@device"
33
+
34
+ image_aug:
35
+ - _target_: RandAffine
36
+ spatial_size: [64, 64]
37
+ translate_range: 5
38
+ scale_range: [-0.15, 0.15]
39
+ prob: 1.0
40
+ rotate_range: $np.pi / 8
41
+ mode: bilinear
42
+ padding_mode: border
43
+ cache_grid: True
44
+ device: "@device"
45
+
46
+ - _target_: RandGridDistortion
47
+ prob: 0.2
48
+ num_cells: 8
49
+ device: "@device"
50
+ distort_limit: 0.1
51
+
52
+ preprocessing:
53
+ _target_: Compose
54
+ transforms: "$@image_load + @image_aug"
55
+
56
+ cache_datasets:
57
+ - _target_: ShuffleBuffer
58
+ data:
59
+ _target_: CacheDataset
60
+ data: "@datalist"
61
+ transform: $@preprocessing.set_random_state(123)
62
+ hash_as_key: true
63
+ runtime_cache: true
64
+ epochs: "@max_epochs"
65
+ seed: "$int(3) if @cross_subjects else int(2)"
66
+ - _target_: ShuffleBuffer
67
+ data:
68
+ _target_: CacheDataset
69
+ data: "@datalist"
70
+ transform: $@preprocessing.set_random_state(234)
71
+ hash_as_key: true
72
+ runtime_cache: true
73
+ epochs: "@max_epochs"
74
+ seed: 2
75
+
76
+ zip_dataset:
77
+ _target_: IterableDataset
78
+ data: "$map(lambda t: dict(image=monai.transforms.concatenate(t), label=t[1]), zip(*@cache_datasets))"
79
+
80
+ data_loader:
81
+ _requires_:
82
+ - $@cache_datasets[0].data.disable_share_memory_cache() # to cache on GPU
83
+ - $@cache_datasets[1].data.disable_share_memory_cache()
84
+ _target_: ThreadDataLoader
85
+ dataset: "@zip_dataset"
86
+ batch_size: 64
87
+ num_workers: 0
88
+
89
+
90
+ # components for debugging
91
+ first_pair: $monai.utils.misc.first(@data_loader)
92
+ display:
93
+ - $monai.utils.set_determinism(seed=123)
94
+ - $print(@first_pair.keys(), @first_pair['image'].meta['filename_or_obj'])
95
+ - "$print(@trainer#loss_function(@first_pair['image'][:, 0:1], @first_pair['image'][:, 1:2]))" # print loss
96
+ - $plt.subplot(1,2,1)
97
+ - $plt.imshow(@first_pair['image'][0, 0], cmap="gray")
98
+ - $plt.subplot(1,2,2)
99
+ - $plt.imshow(@first_pair['image'][0, 1], cmap="gray")
100
+ - $plt.show()
101
+
102
+
103
+ # network definition
104
+ net:
105
+ _target_: scripts.net.RegResNet
106
+ image_size: [64, 64]
107
+ spatial_dims: 2
108
+ mode: "bilinear"
109
+ padding_mode: "border"
110
+
111
+ optimizer:
112
+ _target_: torch.optim.Adam
113
+ params: $@net.parameters()
114
+ lr: 0.00001
115
+
116
+ # create a validation evaluator
117
+ val:
118
+ cache_datasets:
119
+ - _target_: ShuffleBuffer
120
+ data:
121
+ _target_: CacheDataset
122
+ data: "@val_datalist"
123
+ transform: $@preprocessing.set_random_state(123)
124
+ hash_as_key: true
125
+ runtime_cache: true
126
+ epochs: -1 # infinite
127
+ seed: "$int(3) if @cross_subjects else int(2)"
128
+ - _target_: ShuffleBuffer
129
+ data:
130
+ _target_: CacheDataset
131
+ data: "@val_datalist"
132
+ transform: $@preprocessing.set_random_state(234)
133
+ hash_as_key: true
134
+ runtime_cache: true
135
+ epochs: -1 # infinite
136
+ seed: 2
137
+
138
+ zip_dataset:
139
+ _target_: IterableDataset
140
+ data: "$map(lambda t: dict(image=monai.transforms.concatenate(t), label=t[1]), zip(*@val#cache_datasets))"
141
+
142
+ data_loader:
143
+ _requires_:
144
+ - $@val#cache_datasets[0].data.disable_share_memory_cache()
145
+ - $@val#cache_datasets[1].data.disable_share_memory_cache()
146
+ _target_: ThreadDataLoader
147
+ dataset: "@val#zip_dataset"
148
+ batch_size: 64
149
+ num_workers: 0
150
+
151
+ evaluator:
152
+ _target_: SupervisedEvaluator
153
+ device: "@device"
154
+ val_data_loader: "@val#data_loader"
155
+ network: "@net"
156
+ epoch_length: $len(@val_datalist) // @val#data_loader#batch_size
157
+ inferer: "$monai.inferers.SimpleInferer()"
158
+ metric_cmp_fn: "$lambda x, y: x < y"
159
+ key_val_metric:
160
+ val_mse:
161
+ _target_: MeanSquaredError
162
+ output_transform: "$monai.handlers.from_engine(['pred', 'label'])"
163
+ additional_metrics: {"mutual info loss": "@loss_metric#metric_handler"}
164
+ val_handlers:
165
+ - _target_: StatsHandler
166
+ iteration_log: false
167
+ - _target_: CheckpointSaver
168
+ save_dir: "@ckpt_dir"
169
+ save_dict: {model: "@net"}
170
+ save_key_metric: true
171
+ key_metric_negative_sign: true
172
+ # key_metric_filename: "model.pt"
173
+
174
+ # training handlers
175
+ handlers:
176
+ - _target_: StatsHandler
177
+ tag_name: "train_loss"
178
+ output_transform: "$monai.handlers.from_engine(['loss'], first=True)"
179
+ - _target_: ValidationHandler
180
+ validator: "@val#evaluator"
181
+ epoch_level: true
182
+ interval: "@val_interval"
183
+
184
+ loss_metric:
185
+ metric_handler:
186
+ _target_: IgniteMetric
187
+ output_transform: "$monai.handlers.from_engine(['pred', 'label'])"
188
+ metric_fn:
189
+ _target_: LossMetric
190
+ loss_fn: "@mutual_info_loss"
191
+ get_not_nans: true
192
+
193
+ ckpt_loader:
194
+ - _target_: CheckpointLoader
195
+ load_path: "@ckpt"
196
+ load_dict: {model: "@net"}
197
+
198
+ lncc_loss:
199
+ _target_: LocalNormalizedCrossCorrelationLoss
200
+ spatial_dims: 2
201
+ kernel_size: 5
202
+ kernel_type: rectangular
203
+ reduction: mean
204
+
205
+ mutual_info_loss:
206
+ _target_: GlobalMutualInformationLoss
207
+
208
+ # create the primary trainer
209
+ trainer:
210
+ _target_: SupervisedTrainer
211
+ device: "@device"
212
+ train_data_loader: "@data_loader"
213
+ network: "@net"
214
+ max_epochs: "@max_epochs"
215
+ epoch_length: $len(@datalist) // @data_loader#batch_size
216
+ loss_function: "@lncc_loss"
217
+ optimizer: "@optimizer"
218
+ train_handlers: "$@handlers + @ckpt_loader if @ckpt else @handlers"
219
+
220
+ training:
221
+ - $monai.utils.set_determinism(seed=23)
222
+ - "$setattr(torch.backends.cudnn, 'benchmark', True)"
223
+ - $@trainer.run()
docs/README.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MedNIST Hand Image Registration
2
+
3
+ Based on [the tutorial of 2D registration](https://github.com/Project-MONAI/tutorials/tree/main/2d_registration)
4
+
5
+ ## Downloading the Dataset
6
+ Download the dataset [from here](https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/MedNIST.tar.gz) and extract the contents to a convenient location.
7
+
8
+ The MedNIST dataset was gathered from several sets from [TCIA](https://wiki.cancerimagingarchive.net/display/Public/Data+Usage+Policies+and+Restrictions),
9
+ [the RSNA Bone Age Challenge](http://rsnachallenges.cloudapp.net/competitions/4),
10
+ and [the NIH Chest X-ray dataset](https://cloud.google.com/healthcare/docs/resources/public-datasets/nih-chest).
11
+
12
+ The dataset is kindly made available by [Dr. Bradley J. Erickson M.D., Ph.D.](https://www.mayo.edu/research/labs/radiology-informatics/overview) (Department of Radiology, Mayo Clinic)
13
+ under the Creative Commons [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/).
14
+
15
+ If you use the MedNIST dataset, please acknowledge the source.
16
+
17
+ ## Training
18
+
19
+ Training with same-subject image inputs
20
+ ```bash
21
+ python -m monai.bundle run training --config_file configs/train.yaml --dataset_dir "/workspace/data/MedNIST/Hand"
22
+ ```
23
+
24
+ Training with cross-subject image inputs
25
+ ```bash
26
+ python -m monai.bundle run training \
27
+ --config_file configs/train.yaml \
28
+ --dataset_dir "/workspace/data/MedNIST/Hand" \
29
+ --cross_subjects True
30
+ ```
31
+
32
+ Training from an existing checkpoint file, for example, `models/model_key_metric=-0.0734.pt`:
33
+ ```bash
34
+ python -m monai.bundle run training --config_file configs/train.yaml [...omitting other args] --ckpt "models/model_key_metric=-0.0734.pt"
35
+ ```
36
+
37
+ ## Inference
38
+
39
+ The following figure shows an intra-subject (`--cross_subjects False`) model inference results (Fixed, moving and predicted images from left to right)
40
+
41
+ ![fixed](./examples/008502_fixed_6.png)
42
+ ![moving](./examples/008502_moving_6.png)
43
+ ![predicted](./examples/008502_pred_6.png)
44
+
45
+ The command shows an inference workflow with the checkpoint `"models/model_key_metric=-0.0890.pt"` and using device `"cuda:1"`:
46
+ ```bash
47
+ python -m monai.bundle run eval \
48
+ --config_file configs/inference.yaml \
49
+ --ckpt "models/model_key_metric=-0.0890.pt" \
50
+ --logging_file configs/logging.conf \
51
+ --device "cuda:1"
52
+ ```
53
+
54
+ ## Fine-tuning for cross-subject alignments
55
+
56
+ The following commands starts a finetuning workflow based on the checkpoint `"models/model_key_metric=-0.0065.pt"`
57
+ for `5` epochs using the global mutual information loss.
58
+
59
+ ```bash
60
+ python -m monai.bundle run training \
61
+ --config_file configs/train.yaml \
62
+ --cross_subjects True \
63
+ --ckpt "models/model_key_metric=-0.0065.pt" \
64
+ --lr 0.000001 \
65
+ --trainer#loss_function "@mutual_info_loss" \
66
+ --max_epochs 5
67
+ ```
68
+ The following figure shows an inter-subject (`--cross_subjects True`) model inference results (Fixed, moving and predicted images from left to right)
69
+
70
+ ![fixed](./examples/008501_fixed_7.png)
71
+ ![moving](./examples/008504_moving_7.png)
72
+ ![predicted](./examples/008504_pred_7.png)
73
+
74
+ ## Visualize the first pair of images for debugging (requires `matplotlib`)
75
+
76
+ ```bash
77
+ python -m monai.bundle run display --config_file configs/train.yaml
78
+ ```
79
+
80
+ ```bash
81
+ python -m monai.bundle run display --config_file configs/train.yaml --cross_subjects True
82
+ ```
83
+
84
+ # License
85
+ Copyright (c) MONAI Consortium
86
+
87
+ Licensed under the Apache License, Version 2.0 (the "License");
88
+ you may not use this file except in compliance with the License.
89
+ You may obtain a copy of the License at
90
+
91
+ http://www.apache.org/licenses/LICENSE-2.0
92
+
93
+ Unless required by applicable law or agreed to in writing, software
94
+ distributed under the License is distributed on an "AS IS" BASIS,
95
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
96
+ See the License for the specific language governing permissions and
97
+ limitations under the License.
docs/data_license.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2022 MONAI Consortium
2
+ Licensed under the Apache License, Version 2.0 (the "License");
3
+ you may not use this file except in compliance with the License.
4
+ You may obtain a copy of the License at
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+ Unless required by applicable law or agreed to in writing, software
7
+ distributed under the License is distributed on an "AS IS" BASIS,
8
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ See the License for the specific language governing permissions and
10
+ limitations under the License.
11
+
12
+ Third Party Licenses
13
+ -----------------------------------------------------------------------
14
+
15
+ /*********************************************************************/
16
+ i. MedNIST Dataset
17
+ The dataset is kindly made available by Dr. Bradley J. Erickson M.D., Ph.D. (https://www.mayo.edu/research/labs/radiology-informatics/overview), Department of Radiology, Mayo Clinic under the Creative Commons [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/).
18
+
19
+ The MedNIST dataset was gathered from several sets from:
20
+ * TCIA (https://wiki.cancerimagingarchive.net/display/Public/Data+Usage+Policies+and+Restrictions)
21
+ * the RSNA Bone Age Challenge (http://rsnachallenges.cloudapp.net/competitions/4),
22
+ * the NIH Chest X-ray dataset (https://cloud.google.com/healthcare/docs/resources/public-datasets/nih-chest).
23
+
24
+ If you use the MedNIST dataset, please acknowledge the source. For the license and usage conditions of the source datasets, please see their respective sites.
docs/examples/008501_fixed_7.png ADDED
docs/examples/008502_fixed_6.png ADDED
docs/examples/008502_moving_6.png ADDED
docs/examples/008502_pred_6.png ADDED
docs/examples/008504_moving_7.png ADDED
docs/examples/008504_pred_7.png ADDED
models/model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b997c0803bdfcde07394522809e09b1d7b41c38ccfc909f5d80ab5b7de8aed4
3
+ size 45611604
scripts/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
scripts/net.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ import torch.nn as nn
13
+ from monai.networks.blocks import Warp
14
+ from monai.networks.nets import resnet18
15
+ from monai.networks.nets.regunet import AffineHead
16
+
17
+
18
+ class RegResNet(nn.Module):
19
+ def __init__(
20
+ self,
21
+ image_size=(64, 64),
22
+ spatial_dims=2,
23
+ mod=None,
24
+ mode="bilinear",
25
+ padding_mode="border",
26
+ features=400, # feature dimension of `mod`
27
+ ):
28
+ super().__init__()
29
+ self.features = resnet18(n_input_channels=2, spatial_dims=spatial_dims) if mod is None else mod
30
+ self.affine_head = AffineHead(
31
+ spatial_dims=spatial_dims, image_size=image_size, decode_size=[1] * spatial_dims, in_channels=features
32
+ )
33
+ self.warp = Warp(mode=mode, padding_mode=padding_mode)
34
+ self.image_size = image_size
35
+
36
+ def forward(self, x):
37
+ self.features.to(device=x.device)
38
+ self.affine_head.to(device=x.device)
39
+ out = self.features(x)
40
+ ddf = self.affine_head([out], self.image_size)
41
+ f = self.warp(x[:, :1], ddf) # warp the first channel
42
+ return f