Write data and metadata into files on disk using Nibabel. .. code-block:: python import numpy as np from monai.data import NibabelWriter np_data = np.arange(48).reshape(3, 4, 4) writer = NibabelWriter() writer.set_data_array(np_data, channel_dim=No
| 532 | |
| 533 | @require_pkg(pkg_name="nibabel") |
| 534 | class NibabelWriter(ImageWriter): |
| 535 | """ |
| 536 | Write data and metadata into files on disk using Nibabel. |
| 537 | |
| 538 | .. code-block:: python |
| 539 | |
| 540 | import numpy as np |
| 541 | from monai.data import NibabelWriter |
| 542 | |
| 543 | np_data = np.arange(48).reshape(3, 4, 4) |
| 544 | writer = NibabelWriter() |
| 545 | writer.set_data_array(np_data, channel_dim=None) |
| 546 | writer.set_metadata({"affine": np.eye(4), "original_affine": np.eye(4)}) |
| 547 | writer.write("test1.nii.gz", verbose=True) |
| 548 | |
| 549 | """ |
| 550 | |
| 551 | output_dtype: DtypeLike |
| 552 | affine: Any |
| 553 | |
| 554 | def __init__(self, output_dtype: DtypeLike = np.float32, **kwargs): |
| 555 | """ |
| 556 | Args: |
| 557 | output_dtype: output data type. |
| 558 | kwargs: keyword arguments passed to ``ImageWriter``. |
| 559 | |
| 560 | The constructor will create ``self.output_dtype`` internally. |
| 561 | ``affine`` is initialized as instance members (default ``None``), |
| 562 | user-specified ``affine`` should be set in ``set_metadata``. |
| 563 | """ |
| 564 | super().__init__(output_dtype=output_dtype, affine=None, **kwargs) |
| 565 | |
| 566 | def set_data_array( |
| 567 | self, data_array: NdarrayOrTensor, channel_dim: int | None = 0, squeeze_end_dims: bool = True, **kwargs |
| 568 | ): |
| 569 | """ |
| 570 | Convert ``data_array`` into 'channel-last' numpy ndarray. |
| 571 | |
| 572 | Args: |
| 573 | data_array: input data array with the channel dimension specified by ``channel_dim``. |
| 574 | channel_dim: channel dimension of the data array. Defaults to 0. |
| 575 | ``None`` indicates data without any channel dimension. |
| 576 | squeeze_end_dims: if ``True``, any trailing singleton dimensions will be removed. |
| 577 | kwargs: keyword arguments passed to ``self.convert_to_channel_last``, |
| 578 | currently support ``spatial_ndim``, defaulting to ``3``. |
| 579 | """ |
| 580 | self.data_obj = self.convert_to_channel_last( |
| 581 | data=data_array, |
| 582 | channel_dim=channel_dim, |
| 583 | squeeze_end_dims=squeeze_end_dims, |
| 584 | spatial_ndim=kwargs.pop("spatial_ndim", 3), |
| 585 | ) |
| 586 | |
| 587 | def set_metadata(self, meta_dict: Mapping | None, resample: bool = True, **options): |
| 588 | """ |
| 589 | Resample ``self.data_obj`` if needed. This method assumes ``self.data_obj`` is a 'channel-last' ndarray. |
| 590 | |
| 591 | Args: |
no outgoing calls
searching dependent graphs…