-
Notifications
You must be signed in to change notification settings - Fork 1.4k
39 sliding window workflow #56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
07efc77
[DLMED] add support to SlidingWindow inference and image padding
Nic-Ma 786810f
[DLMED] add Nifti writer for model output data
Nic-Ma 3b1f298
Merge branch '39-sliding-window-inference' into 39-sliding-window-wor…
wyli 5ae9352
Merge branch '39-nifti-writer' into 39-sliding-window-workflow
wyli a0894ad
initial sliding window inference workflow
wyli 775715d
[DLMED] add checkpoint loader as ignite event-handler
Nic-Ma 17f574f
added iter_dense_patch_slices, rename buffered_slices to slice_batche…
wyli 85d2e15
Merge branch '39-load-checkpoint-eventhandler' into 39-sliding-window…
wyli 78e17ca
include checkpoint loader handler
wyli 8427da6
renaming iter_dense_patch_slices to dense_patch_slices
wyli 7f2a671
Merge branch 'master' into 39-sliding-window-workflow
wyli 2401e21
updates interfaces of sliding window predictor and seg saver
wyli 3925c2d
fixes sliding window unit test
wyli 064e6b3
Fix canonical transformation bug in nifti writer. (#74)
madil90 3f4968b
resolves image writer issues
wyli 99ce679
Merge branch 'master' into 39-sliding-window-workflow
wyli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -103,6 +103,7 @@ venv.bak/ | |
| # mypy | ||
| .mypy_cache/ | ||
| examples/scd_lvsegs.npz | ||
| .temp/ | ||
| .idea/ | ||
|
|
||
| *~ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| # Copyright 2020 MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import os | ||
| import sys | ||
| import tempfile | ||
| from glob import glob | ||
|
|
||
| import nibabel as nib | ||
| import numpy as np | ||
| import torch | ||
| import torchvision.transforms as transforms | ||
| from ignite.engine import Engine | ||
| from torch.utils.data import DataLoader | ||
|
|
||
| from monai import config | ||
| from monai.handlers.checkpoint_loader import CheckpointLoader | ||
| from monai.handlers.segmentation_saver import SegmentationSaver | ||
| from monai.data.nifti_reader import NiftiDataset | ||
| from monai.transforms import AddChannel, Rescale, ToTensor | ||
| from monai.networks.nets.unet import UNet | ||
| from monai.networks.utils import predict_segmentation | ||
| from monai.data.synthetic import create_test_image_3d | ||
| from monai.utils.sliding_window_inference import sliding_window_inference | ||
|
|
||
| sys.path.append("..") # assumes the framework is found here, change as necessary | ||
| config.print_config() | ||
|
|
||
| tempdir = tempfile.mkdtemp() | ||
| # tempdir = './temp' | ||
| for i in range(50): | ||
| im, seg = create_test_image_3d(256, 256, 256) | ||
|
|
||
| n = nib.Nifti1Image(im, np.eye(4)) | ||
| nib.save(n, os.path.join(tempdir, 'im%i.nii.gz' % i)) | ||
|
|
||
| n = nib.Nifti1Image(seg, np.eye(4)) | ||
| nib.save(n, os.path.join(tempdir, 'seg%i.nii.gz' % i)) | ||
|
|
||
| images = sorted(glob(os.path.join(tempdir, 'im*.nii.gz'))) | ||
| segs = sorted(glob(os.path.join(tempdir, 'seg*.nii.gz'))) | ||
| imtrans = transforms.Compose([Rescale(), AddChannel(), ToTensor()]) | ||
| segtrans = transforms.Compose([AddChannel(), ToTensor()]) | ||
| ds = NiftiDataset(images, segs, transform=imtrans, seg_transform=segtrans, image_only=False) | ||
|
|
||
| device = torch.device("cpu:0") | ||
| roi_size = (64, 64, 64) | ||
| sw_batch_size = 4 | ||
| net = UNet( | ||
| dimensions=3, | ||
| in_channels=1, | ||
| num_classes=1, | ||
| channels=(16, 32, 64, 128, 256), | ||
| strides=(2, 2, 2, 2), | ||
| num_res_units=2, | ||
| ) | ||
| net.to(device) | ||
|
|
||
|
|
||
| def _sliding_window_processor(_engine, batch): | ||
| net.eval() | ||
| img, seg, meta_data = batch | ||
| with torch.no_grad(): | ||
| seg_probs = sliding_window_inference(img, roi_size, sw_batch_size, lambda x: net(x)[0], device) | ||
| return predict_segmentation(seg_probs) | ||
|
|
||
|
|
||
| infer_engine = Engine(_sliding_window_processor) | ||
|
|
||
| # checkpoint_handler = ModelCheckpoint('./', 'net', n_saved=10, save_interval=3, require_empty=False) | ||
| # infer_engine.add_event_handler(event_name=Events.EPOCH_COMPLETED, handler=checkpoint_handler, to_save={'net': net}) | ||
|
|
||
| SegmentationSaver(output_path='tempdir', output_ext='.nii.gz', output_postfix='seg').attach(infer_engine) | ||
| CheckpointLoader(load_path='./net_checkpoint_9.pth', load_dict={'net': net}).attach(infer_engine) | ||
|
|
||
| loader = DataLoader(ds, batch_size=1, num_workers=1, pin_memory=torch.cuda.is_available()) | ||
| state = infer_engine.run(loader) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| # Copyright 2020 MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import numpy as np | ||
| import nibabel as nib | ||
|
|
||
|
|
||
| def write_nifti(data, affine, file_name, target_affine=None, dtype="float32"): | ||
| """Write numpy data into nifti files to disk. | ||
|
|
||
| Args: | ||
| data (numpy.ndarray): input data to write to file. | ||
| affine (numpy.ndarray): affine information for the data. | ||
| file_name (string): expected file name that saved on disk. | ||
| target_affine (numpy.ndarray, optional): | ||
| before saving the (data, affine), transform the data into the orientation defined by `target_affine`. | ||
| dtype (np.dtype, optional): convert the image to save to this data type. | ||
| """ | ||
| assert isinstance(data, np.ndarray), 'input data must be numpy array.' | ||
| if affine is None: | ||
| affine = np.eye(4) | ||
|
|
||
| if target_affine is None: | ||
| results_img = nib.Nifti1Image(data.astype(dtype), affine) | ||
| else: | ||
| start_ornt = nib.orientations.io_orientation(affine) | ||
| target_ornt = nib.orientations.io_orientation(target_affine) | ||
| ornt_transform = nib.orientations.ornt_transform(start_ornt, target_ornt) | ||
|
|
||
| reverted_results = nib.orientations.apply_orientation(data, ornt_transform) | ||
| results_img = nib.Nifti1Image(reverted_results.astype(dtype), target_affine) | ||
|
|
||
| nib.save(results_img, file_name) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.