├── .gitignore ├── LICENSE ├── MRIPreprocessor ├── __init__.py ├── mri_preprocessor.py └── utilities.py ├── README.md ├── setup.py └── test └── test.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. 202 | -------------------------------------------------------------------------------- /MRIPreprocessor/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReubenDo/MRIPreprocessor/b76b932f40323a988c55e6e0559fe5caa585aba1/MRIPreprocessor/__init__.py -------------------------------------------------------------------------------- /MRIPreprocessor/mri_preprocessor.py: -------------------------------------------------------------------------------- 1 | import ants 2 | import os 3 | from HD_BET.run import run_hd_bet 4 | import nibabel as nib 5 | import SimpleITK as sitk 6 | import torch 7 | 8 | from .utilities import crop_scans, get_mni 9 | 10 | class Preprocessor(): 11 | def __init__(self, 12 | dict_img, 13 | output_folder, 14 | label=None, 15 | prefix="", 16 | reference=None, 17 | skull_stripping=True, 18 | already_coregistered=False, 19 | mni=False, 20 | crop=False): 21 | 22 | self.dict_img = dict_img 23 | self.modalities = dict_img.keys() 24 | self.output_folder = output_folder 25 | self.label = label 26 | self.prefix = prefix 27 | self.skull_stripping = skull_stripping 28 | self.already_coregistered = already_coregistered 29 | self.mni = mni 30 | self.crop = crop 31 | 32 | 33 | if reference is None: 34 | self.reference = sorted(self.modalities)[0] 35 | else: 36 | assert reference in dict_img.keys(), "Reference has to be one the imaging modality in dict_img" 37 | self.reference = reference 38 | 39 | # Test files are existing 40 | for mod in dict_img.keys(): 41 | assert os.path.exists(dict_img[mod]), f"{dict_img[mod]} doesn't exist" 42 | if not label is None: 43 | assert os.path.exists(label), "Label map doesn't exist" 44 | 45 | 46 | 47 | # Get mni if needed 48 | if self.mni: 49 | self.mni_path = get_mni(self.skull_stripping) 50 | 51 | # Create relevant folders if needed 52 | self.coregistration_folder = os.path.join(self.output_folder, "coregistration") 53 | if not os.path.exists(self.coregistration_folder): 54 | os.makedirs(self.coregistration_folder) 55 | 56 | if self.skull_stripping: 57 | self.skullstrip_folder = os.path.join(self.output_folder, "skullstripping") 58 | if not os.path.exists(self.skullstrip_folder): 59 | os.makedirs(self.skullstrip_folder) 60 | else: 61 | self.skullstrip_folder = self.coregistration_folder 62 | 63 | if crop: 64 | self.cropping_folder = os.path.join(self.output_folder, "cropping") 65 | if not os.path.exists(self.cropping_folder): 66 | os.makedirs(self.cropping_folder) 67 | 68 | self.device = 0 if torch.cuda.is_available() else "cpu" 69 | 70 | 71 | 72 | def _save_scan(self, img, name, save_folder): 73 | if not os.path.exists(save_folder): 74 | os.makedirs(save_folder) 75 | output_filename = os.path.join(save_folder, f"{name}.nii.gz") 76 | ants.image_write(img, output_filename) 77 | 78 | def _apply_mask(self, input, output, reference, mask): 79 | # Reorient in case HD-BET changed the orientation of the raw file 80 | input_img = sitk.ReadImage(input) 81 | ref_img = sitk.ReadImage(reference) 82 | output_img = sitk.Resample( 83 | input_img, 84 | ref_img, 85 | sitk.Transform(), 86 | sitk.sitkNearestNeighbor, 87 | ) 88 | sitk.WriteImage(output_img, output) 89 | 90 | # Apply mask 91 | output_img = nib.load(output) 92 | output_affine = output_img.affine 93 | output_data = output_img.get_fdata() 94 | 95 | mask_data = nib.load(mask).get_fdata() 96 | 97 | output_data[mask_data==0] = 0 98 | output_img = nib.Nifti1Image(output_data, output_affine) 99 | nib.save(output_img, output) 100 | 101 | 102 | def _run_coregistration(self): 103 | img_reference = ants.image_read(self.dict_img[self.reference], reorient=True) 104 | 105 | # Register the reference to MNI, if needed 106 | if self.mni: 107 | print(f"[INFO] Registering to 1x1x1mm MNI space using ANTsPy") 108 | print(f"{self.reference} is used as reference") 109 | img_mni = ants.image_read(self.mni_path, reorient=True) 110 | reg = ants.registration(img_mni, img_reference, "Affine") 111 | img_reference = reg["warpedmovout"] 112 | self._save_scan(img_reference, f"{self.prefix}{self.reference}", self.coregistration_folder) 113 | reg_tomni = reg["fwdtransforms"] 114 | if not self.label is None: 115 | img_label = ants.image_read(self.label, reorient=True) 116 | warped_label = ants.apply_transforms(img_mni, img_label, reg_tomni, interpolator="nearestNeighbor") 117 | self._save_scan(warped_label, f"{self.prefix}Label", self.coregistration_folder) 118 | else: 119 | self._save_scan(img_reference, f"{self.prefix}{self.reference}", self.coregistration_folder) 120 | if not self.label is None: 121 | img_label = ants.image_read(self.label, reorient=True) 122 | self._save_scan(img_label, f"{self.prefix}Label", self.coregistration_folder) 123 | 124 | # Register the other scans, if needed 125 | modalities_toregister = list(self.modalities) 126 | modalities_toregister.remove(self.reference) 127 | for mod in modalities_toregister: 128 | if self.already_coregistered: 129 | if self.mni: # if the scans are already co-registered we reuse the ref to MNI transformation 130 | img_mod = ants.image_read(self.dict_img[mod], reorient=True) 131 | warped_img = ants.apply_transforms(img_mni, img_mod, reg_tomni, interpolator="linear") 132 | self._save_scan(warped_img, f"{self.prefix}{mod}", self.coregistration_folder) 133 | print(f"[INFO] Registration performed to MNI for {mod}") 134 | else: 135 | img_mod = ants.image_read(self.dict_img[mod], reorient=True) 136 | self._save_scan(img_mod, f"{self.prefix}{mod}", self.coregistration_folder) 137 | print(f"No co-registration performed for {mod}") 138 | 139 | else: # Scans are not co-registered 140 | img_mod = ants.image_read(self.dict_img[mod], reorient=True) 141 | reg = ants.registration(img_reference, img_mod, "Affine") 142 | self._save_scan(reg["warpedmovout"], f"{self.prefix}{mod}", self.coregistration_folder) 143 | print(f"[INFO] Registration using ANTsPy for {mod} with {self.reference} as reference") 144 | 145 | 146 | def _run_skullstripping(self): 147 | print("[INFO] Performing Skull Stripping using HD-BET") 148 | ref_co = os.path.join(self.coregistration_folder, f"{self.prefix}{self.reference}.nii.gz") 149 | ref_sk = os.path.join(self.skullstrip_folder, f"{self.prefix}{self.reference}.nii.gz") 150 | mask_sk = os.path.join(self.skullstrip_folder, f"{self.prefix}{self.reference}_mask.nii.gz") 151 | run_hd_bet(ref_co, ref_sk, mode="fast", device=self.device, do_tta=False) 152 | 153 | modalities_tosk = list(self.modalities) 154 | modalities_tosk.remove(self.reference) 155 | for mod in modalities_tosk: 156 | registered_mod = os.path.join(self.coregistration_folder, f"{self.prefix}{mod}.nii.gz") 157 | skullstripped_mod = os.path.join(self.skullstrip_folder, f"{self.prefix}{mod}.nii.gz") 158 | self._apply_mask(input=registered_mod, output=skullstripped_mod, reference=ref_sk, mask=mask_sk) 159 | 160 | if not self.label is None: 161 | registered_lab = os.path.join(self.coregistration_folder, f"{self.prefix}Label.nii.gz") 162 | skullstripped_lab = os.path.join(self.skullstrip_folder, f"{self.prefix}Label.nii.gz") 163 | self._apply_mask(input=registered_lab, output=skullstripped_lab, reference=ref_sk, mask=mask_sk) 164 | 165 | 166 | def _run_cropping(self): 167 | print("[INFO] Performing Cropping") 168 | ref_sk = os.path.join(self.skullstrip_folder, f"{self.prefix}{self.reference}.nii.gz") 169 | 170 | sk_images = [os.path.join(self.skullstrip_folder, f"{self.prefix}{mod}.nii.gz") for mod in self.modalities] 171 | cropped_images = [os.path.join(self.cropping_folder, f"{self.prefix}{mod}.nii.gz") for mod in self.modalities] 172 | 173 | if not self.label is None: 174 | sk_images.append(os.path.join(self.skullstrip_folder, f"{self.prefix}Label.nii.gz")) 175 | cropped_images.append(os.path.join(self.cropping_folder, f"{self.prefix}Label.nii.gz")) 176 | 177 | crop_scans(ref_sk, sk_images, cropped_images) 178 | 179 | 180 | 181 | def run_pipeline(self): 182 | self._run_coregistration() 183 | if self.skull_stripping: 184 | self._run_skullstripping() 185 | if self.crop: 186 | self._run_cropping() 187 | -------------------------------------------------------------------------------- /MRIPreprocessor/utilities.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import os 3 | from zipfile import ZipFile 4 | import MRIPreprocessor 5 | 6 | import nibabel as nib 7 | import SimpleITK as sitk 8 | import numpy as np 9 | 10 | def find_zeros(img_array): 11 | if len(img_array.shape) == 4: 12 | img_array = np.amax(img_array, axis=3) 13 | assert len(img_array.shape) == 3 14 | x_dim, y_dim, z_dim = tuple(img_array.shape) 15 | x_zeros, y_zeros, z_zeros = np.where(img_array == 0.) 16 | # x-plans that are not uniformly equal to zeros 17 | 18 | try: 19 | x_to_keep, = np.where(np.bincount(x_zeros) < y_dim * z_dim) 20 | x_min = min(x_to_keep) 21 | x_max = max(x_to_keep) + 1 22 | except Exception : 23 | x_min = 0 24 | x_max = x_dim 25 | try: 26 | y_to_keep, = np.where(np.bincount(y_zeros) < x_dim * z_dim) 27 | y_min = min(y_to_keep) 28 | y_max = max(y_to_keep) + 1 29 | except Exception : 30 | y_min = 0 31 | y_max = y_dim 32 | try : 33 | z_to_keep, = np.where(np.bincount(z_zeros) < x_dim * y_dim) 34 | z_min = min(z_to_keep) 35 | z_max = max(z_to_keep) + 1 36 | except: 37 | z_min = 0 38 | z_max = z_dim 39 | return x_min, x_max, y_min, y_max, z_min, z_max 40 | 41 | 42 | def crop_scans(reference, inputs, outputs): 43 | img_crop = nib.load(reference) 44 | affine = img_crop.affine 45 | img_crop_data = img_crop.get_fdata() 46 | x_min, x_max, y_min, y_max, z_min, z_max = find_zeros(img_crop_data) 47 | 48 | x_max = img_crop_data.shape[0] - x_max 49 | y_max = img_crop_data.shape[1] - y_max 50 | z_max = img_crop_data.shape[2] - z_max 51 | bounds_parameters = [x_min, x_max, y_min, y_max, z_min, z_max] 52 | low = bounds_parameters[::2] 53 | high = bounds_parameters[1::2] 54 | low = [int(k) for k in low] 55 | high = [int(k) for k in high] 56 | 57 | for i,path_mod in enumerate(inputs): 58 | image = sitk.ReadImage(path_mod) 59 | image = sitk.Crop(image, low, high) 60 | sitk.WriteImage(image, outputs[i]) 61 | 62 | 63 | 64 | def get_mni(skull_stripping): 65 | tmp_folder = os.path.join(list(MRIPreprocessor.__path__)[0], "data") 66 | path_mni = os.path.join(tmp_folder, 'mni.nii.gz') 67 | path_mask = os.path.join(tmp_folder, 'mask.nii.gz') 68 | path_mni_sk = os.path.join(tmp_folder, 'mni_sk.nii.gz') 69 | if not os.path.exists(path_mni) or not os.path.exists(path_mni_sk): 70 | print('MNI template not found. Downloading...') 71 | URL = 'http://www.bic.mni.mcgill.ca/~vfonov/icbm/2009/mni_icbm152_nlin_sym_09a_nifti.zip' 72 | 73 | # download the file contents in binary format 74 | r = requests.get(URL) 75 | 76 | # doewnload the zip 77 | tmp_folder = os.path.join(list(MRIPreprocessor.__path__)[0], "data") 78 | if not os.path.exists(tmp_folder): 79 | os.makedirs(tmp_folder) 80 | 81 | local_path = os.path.join(tmp_folder, 'mni.zip') 82 | with open(local_path, "wb") as code: 83 | code.write(r.content) 84 | 85 | filname_mni = 'mni_icbm152_nlin_sym_09a/mni_icbm152_t1_tal_nlin_sym_09a.nii' 86 | filname_mask = 'mni_icbm152_nlin_sym_09a/mni_icbm152_t1_tal_nlin_sym_09a_mask.nii' 87 | 88 | # extracting MNI file 89 | with ZipFile(local_path, 'r') as z: 90 | with open(path_mni, 'wb') as f: 91 | f.write(z.read(filname_mni)) 92 | 93 | # extracting mask file 94 | with ZipFile(local_path, 'r') as z: 95 | with open(path_mask, 'wb') as f: 96 | f.write(z.read(filname_mask)) 97 | 98 | mask = sitk.ReadImage(path_mask) 99 | mni = sitk.ReadImage(path_mni) 100 | 101 | mni_sk = mask * mni 102 | sitk.WriteImage(mni_sk, path_mni_sk) 103 | 104 | os.remove(local_path) 105 | 106 | if skull_stripping: 107 | return path_mni 108 | else: 109 | return path_mni_sk 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MRIPreprocessor 2 | 3 | This repository provides a simple pipeline to co-register different imaging modalities and skull strip them. 4 | 5 | This package uses HD-BET (https://github.com/MIC-DKFZ/HD-BET) and ANTsPy (https://github.com/ANTsX/ANTsPy). 6 | 7 | For example, this pipeline is designed for the BraTS dataset. 8 | 9 | ## To install the package: 10 | ``` 11 | pip install git+https://github.com/ReubenDo/MRIPreprocessor#egg=MRIPreprocessor 12 | ``` 13 | 14 | ## Example case 1: 15 | Let's assume we have access to 4 imaging modalities (e.g. T1, T1c, T2, FLAIR) and we want to: 16 | - co-register the scans using T1 as reference 17 | - in the MNI space (1x1x1 mm) 18 | - skull strip the scans using T1 as reference 19 | - crop the skull-stripped scans to remove the zero padding 20 | 21 | ```python 22 | from MRIPreprocessor.mri_preprocessor import Preprocessor 23 | 24 | # 4 Modalities to co-register to MNI space using an affine transformation 25 | # T1 is used as reference for the coregistration 26 | # No labelmap is used 27 | ppr = Preprocessor({'T1':'./data/example_T1.nii.gz', 28 | 'T2':'./data/example_T2.nii.gz', 29 | 'T1c':'./data/example_T1c.nii.gz', 30 | 'FLAIR':'./data/example_FLAIR.nii.gz'}, 31 | output_folder = './data/output', 32 | reference='T1', 33 | label=None, 34 | prefix='patient001_', 35 | already_coregistered=False, 36 | mni=True, 37 | crop=True) 38 | 39 | ppr.run_pipeline() 40 | ``` 41 | The output folder will contain three folders nammed `coregistration`, `skullstripping` and `cropping` containing respectively the co-registered modalities, the skull-stripped and co-registered imaging modalities and the cropped versions of these latter skull-stripped scans. (example output `'./data/output/cropping/patient001_T1.nii.gz'`) 42 | 43 | ## Example case 2: 44 | Let's assume we have access to 4 **co-registered** imaging modalities (e.g. T1, T1c, T2, FLAIR) and we want to: 45 | - co-registered them in the MNI space (1x1x1 mm) using T1 as reference 46 | - skull strip the scans using T1 as reference 47 | - crop the skull-stripped scans to remove the zero padding 48 | 49 | ```python 50 | from MRIPreprocessor.mri_preprocessor import Preprocessor 51 | 52 | # 4 Modalities to co-register to MNI space using an affine transformation 53 | # T1 is used as reference for the coregistration 54 | # No labelmap is used 55 | ppr = Preprocessor({'T1':'./data/example_T1.nii.gz', 56 | 'T2':'./data/example_T2.nii.gz', 57 | 'T1c':'./data/example_T1c.nii.gz', 58 | 'FLAIR':'./data/example_FLAIR.nii.gz'}, 59 | output_folder = './data/output', 60 | reference='T1', 61 | label=None, 62 | prefix='patient001_', 63 | already_coregistered=True, 64 | mni=True, 65 | crop=True) 66 | 67 | ppr.run_pipeline() 68 | ``` 69 | The output folder will contain three folders nammed `coregistration`, `skullstripping` and `cropping` containing respectively the co-registered modalities in the MNI space, the skull-stripped and co-registered imaging modalities and the cropped versions of these latter skull-stripped scans. (example output `'./data/output/cropping/patient001_T1.nii.gz'`) 70 | 71 | 72 | 73 | ## Example case 3: 74 | Let's assume we have access to 4 imaging modalities (T1, T1c, T2, FLAIR) and one segmentation drawn on the T1c scan. We want to: 75 | - co-register the scans using T1c as reference 76 | - in the MNI space (1x1x1 mm), including the labelmap 77 | - skull strip the scans using T1c as reference 78 | - crop the skull-stripped scans to remove the zero padding and apply the same cropping to the registered labelmap 79 | 80 | **Note that the reference scan must be the scan employed for the segmentation, here the T1c scan.** 81 | ```python 82 | from MRIPreprocessor.mri_preprocessor import Preprocessor 83 | 84 | # 4 Modalities to co-register to MNI space using an affine transformation 85 | # T1 is used as reference for the coregistration 86 | # A labelmap is used 87 | ppr = Preprocessor({'T1':'./data/example_T1.nii.gz', 88 | 'T2':'./data/example_T2.nii.gz', 89 | 'T1c':'./data/example_T1c.nii.gz', 90 | 'FLAIR':'./data/example_FLAIR.nii.gz'}, 91 | output_folder = './data/output', 92 | reference='T1c', 93 | label='./data/example_Label.nii.gz', 94 | prefix='patient001_', 95 | already_coregistered=False, 96 | mni=True, 97 | crop=True) 98 | 99 | ppr.run_pipeline() 100 | ``` 101 | The output folder will contain three folders nammed `coregistration`, `skullstripping` and `cropping` containing respectively the co-registered modalities and labelmap, the skull-stripped and co-registered imaging modalities and labelmap and the cropped versions of these latter skull-stripped scans. (example output `'./data/output/cropping/patient001_T1.nii.gz'`) 102 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """The setup script.""" 4 | 5 | from setuptools import setup, find_packages 6 | 7 | 8 | 9 | requirements = [ 10 | 'antspyx', 11 | 'nibabel', 12 | 'scipy', 13 | 'SimpleITK<2', 14 | 'HD-BET @ git+https://github.com/ReubenDo/HD-BET#egg=HD-BET', 15 | ] 16 | 17 | setup( 18 | author="Reuben Dorent", 19 | author_email='reuben.dorent@kcl.ac.uk', 20 | python_requires='>=3.6', 21 | classifiers=[ 22 | 'Development Status :: 2 - Pre-Alpha', 23 | 'Intended Audience :: Science/Research', 24 | 'License :: OSI Approved :: MIT License', 25 | 'Natural Language :: English', 26 | 'Operating System :: OS Independent', 27 | 'Programming Language :: Python :: 3.6', 28 | 'Programming Language :: Python :: 3.7', 29 | 'Programming Language :: Python :: 3.8', 30 | ], 31 | description=( 32 | "Simple preprocessor for coregistration and skull-stripping" 33 | ), 34 | install_requires=requirements, 35 | license="MIT license", 36 | long_description_content_type='text/markdown', 37 | include_package_data=True, 38 | keywords='MRIPreprocessor', 39 | name='MRIPreprocessor', 40 | packages=find_packages(include=['MRIPreprocessor']), 41 | setup_requires=[], 42 | tests_require=[], 43 | url='https://github.com/ReubenDo/MRIPreprocessor', 44 | version='0.0.4', 45 | zip_safe=False, 46 | ) 47 | -------------------------------------------------------------------------------- /test/test.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import os 3 | from zipfile import ZipFile 4 | 5 | from MRIPreprocessor.mri_preprocessor import Preprocessor 6 | 7 | # for this test we use the data provided by the bratstoolkit 8 | URL = 'https://neuronflow.github.io/BraTS-Preprocessor/downloads/example_data.zip' 9 | PATHS = { 10 | 'T1':'exam_import/OtherEXampleFromTCIA/T1_AX_OtherEXampleTCIA_TCGA-FG-6692_Si_TCGA-FG-6692_T1_AX_SE_10_se2d1_t1.nii.gz', 11 | 'T1c':'exam_import/OtherEXampleFromTCIA/MRHR_T1_AX_POST_GAD_OtherEXampleTCIA_TCGA-FG-6692_Si_TCGA-FG-6692_MRHR_T1_AX_POST_GAD_SE_13_se2d1r_t1c.nii.gz', 12 | 'T2':'exam_import/OtherEXampleFromTCIA/MRHR_T2_AX_OtherEXampleTCIA_TCGA-FG-6692_Si_TCGA-FG-6692_MRHR_T2_AX_SE_2_tse2d1_11_t2.nii.gz', 13 | 'FLAIR':'exam_import/OtherEXampleFromTCIA/MRHR_FLAIR_AX_OtherEXampleTCIA_TCGA-FG-6692_Si_TCGA-FG-6692_MRHR_FLAIR_AX_SE_IR_5_tir2d1_21_fla.nii.gz' 14 | } 15 | 16 | # download the file contents in binary format 17 | r = requests.get(URL) 18 | 19 | # doewnload the zip 20 | local_path = "data/example_data.zip" 21 | if not os.path.exists('data'): 22 | os.makedirs('data') 23 | 24 | with open(local_path, "wb") as code: 25 | code.write(r.content) 26 | 27 | # extracting 4 modalities from patient 'OtherEXampleFromTCIA' 28 | with ZipFile(local_path, 'r') as z: 29 | for mod, path_mod in PATHS.items(): 30 | with open(f'data/example_{mod}.nii.gz', 'wb') as f: 31 | f.write(z.read(path_mod)) 32 | print('Images have been downloaded properly') 33 | 34 | # Preprocessed data 35 | ppr = Preprocessor({'T1':'data/example_T1.nii.gz', 36 | 'T2':'data/example_T2.nii.gz', 37 | 'T1c':'data/example_T1c.nii.gz', 38 | 'FLAIR':'data/example_FLAIR.nii.gz'}, 39 | output_folder = 'data/output', 40 | reference='T1', 41 | mni=True, 42 | crop=True) 43 | 44 | ppr.run_pipeline() 45 | --------------------------------------------------------------------------------