|
| 1 | +# Copyright 2021-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 | +import numpy as np |
| 13 | +import SimpleITK |
| 14 | + |
| 15 | +import monai.deploy.core as md |
| 16 | +from monai.deploy.core import DataPath, ExecutionContext, InputContext, IOType, Operator, OutputContext |
| 17 | + |
| 18 | + |
| 19 | +@md.input("image_path", DataPath, IOType.DISK) |
| 20 | +@md.output("image", np.ndarray, IOType.IN_MEMORY) |
| 21 | +class NiftiDataLoader(Operator): |
| 22 | + """ |
| 23 | + This operator reads a nifti image, extracts the numpy array and forwards it to the next operator |
| 24 | + """ |
| 25 | + |
| 26 | + def compute(self, op_input: InputContext, op_output: OutputContext, context: ExecutionContext): |
| 27 | + input_path = op_input.get().path |
| 28 | + image_np = self.convert_and_save(input_path) |
| 29 | + op_output.set(image_np) |
| 30 | + |
| 31 | + def convert_and_save(self, nii_path): |
| 32 | + """ |
| 33 | + reads the nifti image and |
| 34 | + """ |
| 35 | + image_reader = SimpleITK.ImageFileReader() |
| 36 | + image_reader.SetFileName(str(nii_path)) |
| 37 | + image = image_reader.Execute() |
| 38 | + image_np = np.transpose(SimpleITK.GetArrayFromImage(image), [2, 1, 0]) |
| 39 | + return image_np |
| 40 | + |
| 41 | + |
| 42 | +def test(): |
| 43 | + filepath = "/home/gupta/Documents/mni_icbm152_nlin_sym_09a/mni_icbm152_gm_tal_nlin_sym_09a.nii" |
| 44 | + nii_operator = NiftiDataLoader() |
| 45 | + image_np = nii_operator.convert_and_save(filepath) |
| 46 | + |
| 47 | + |
| 48 | +def main(): |
| 49 | + test() |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + main() |
0 commit comments