dosma.data_io package¶
Submodules¶
dosma.data_io.dicom_io module¶
DICOM I/O.
This module contains DICOM input/output helpers.
Note
- Dicom utilizes LPS convention:
LPS: right –> left, anterior –> posterior, inferior –> superior
we will call it LPS+, such that letters correspond to increasing end of axis
- ivar ~dosma.data_io.dicom_io.TOTAL_NUM_ECHOS_KEY
Hexadecimal encoding of DICOM tag corresponding to number of echos.
- vartype ~dosma.data_io.dicom_io.TOTAL_NUM_ECHOS_KEY
tuple[int]
-
class
dosma.data_io.dicom_io.DicomReader(num_workers: int = 0, verbose: bool = False)[source]¶ Bases:
dosma.data_io.format_io.DataReaderA class for reading DICOM files.
-
data_format_code= 2¶
-
load(path: Union[str, Sequence[str]], group_by: Union[str, tuple] = 'EchoNumbers', ignore_ext: bool = False)[source]¶ Load dicoms into MedicalVolume`s grouped by `group_by tag.
When loading files from a directory, all hidden files (files starting with “.”) are ignored. Files are sorted in alphabetical order.
- Parameters
path (str(s)) – Directory with dicom files or dicom file(s).
group_by (str or tuple, optional) – DICOM field tag name or tag number used to group dicoms. Defaults to EchoNumbers. Most DICOM headers encode different echo numbers as volumes acquired at different echo times or different phases.
ignore_ext (bool, optional) – If True, ignore extension (.dcm) when loading dicoms from directory. Defaults to False.
- Returns
Different volumes grouped by the group_by DICOM tag.
- Return type
list[MedicalVolume]
- Raises
ValueError – If group_by not specified or if single dicom file specified.
IOError – If directory or dicom file(s) specified by path do not exist.
FileNotFoundError – If no valid dicom files found.
Note
- This function sorts files using natsort, an intelligent sorting tool.
Please verify dicoms are labeled in a sequenced manner (e.g.: dicom1,dicom2,dicom3,…).
-
-
class
dosma.data_io.dicom_io.DicomWriter(num_workers: int = 0, verbose: bool = False)[source]¶ Bases:
dosma.data_io.format_io.DataWriterA class for writing volumes in DICOM format.
-
data_format_code= 2¶
-
save(volume: dosma.data_io.med_volume.MedicalVolume, dir_path: str, fname_fmt: Optional[str] = None)[source]¶ Save medical volume in dicom format.
- Parameters
volume (MedicalVolume) – Volume to save.
dir_path – Directory path to store dicom files. Dicoms are stored in directories, as multiple files are needed to store the volume.
fname_fmt (str, optional) – Formatting string for filenames. Must contain
%d, which correspopnds to slice number. Defaults to"I%0{max(4, ceil(log10(num_slices)))}d.dcm"(e.g."I0001.dcm").
- Raises
ValueError – If im does not have initialized headers. Or if im was flipped across any axis. Flipping changes scanner origin, which is currently not handled.
-
dosma.data_io.format_io module¶
I/O formatting templates.
This module consists of the templates for input/output (I/O) helper classes.
- ivar ~dosma.data_io.format_io.SUPPORTED_VISUALIZATION_FORMATS
Image formats that are supported for visualization.
- vartype ~dosma.data_io.format_io.SUPPORTED_VISUALIZATION_FORMATS
tuple[str]
-
class
dosma.data_io.format_io.DataReader[source]¶ Bases:
abc.ABCAbstract class for reading medical data.
Format-specific readers should inherit from this class.
- Variables
data_format_code (ImageDataFormat) – Should be defined by subclasses.
-
data_format_code= None¶
-
class
dosma.data_io.format_io.DataWriter[source]¶ Bases:
abc.ABCAbstract class for writing medical data.
Format-specific writers should inherit from this class.
- Variables
data_format_code (ImageDataFormat) – Should be defined by subclasses.
-
data_format_code= None¶
-
abstract
save(volume, file_path: str)[source]¶ Save volume.
- Parameters
volume (MedicalVolume) – Volume to save.
file_path (str) – File path to save volume to.
-
class
dosma.data_io.format_io.ImageDataFormat(value)[source]¶ Bases:
enum.EnumEnum describing supported data formats for medical volume I/O.
-
dicom= 2¶
-
classmethod
get_image_data_format(file_or_dir_path: str)[source]¶ Get the ImageDataFormat that corresponds to the file path.
Matches extension to file path. If input is a directory path, then it is classified as ImageDataFormat.dicom.
- Parameters
file_or_dir_path (str) – Path to a file or a directory.
- Returns
Format corresponding to file or directory path.
- Return type
- Raises
ValueError – If no compatible ImageDataFormat found.
-
is_filetype(file_path: str) → bool[source]¶ Verify if file path matches the file type specified by ImageDataFormat.
This method checks to make sure the extensions are appropriate.
- Parameters
file_path (str) – File path.
- Returns
True if file_path has valid extension, False otherwise.
- Return type
bool
-
nifti= 1¶
-
dosma.data_io.format_io_utils module¶
Utils for data I/O.
-
dosma.data_io.format_io_utils.convert_image_data_format(file_or_dir_path: str, new_data_format: dosma.data_io.format_io.ImageDataFormat) → str[source]¶ Change a file or directory name to convention of another data format.
- Parameters
file_or_dir_path (str) – File or directory path.
new_data_format (ImageDataFormat) – Data format convention for file/directory name.
- Returns
File/directory path based on convention of new data format.
- Return type
str
- Raises
NotImplementedError – If conversion from current image data format to new image data format not found.
-
dosma.data_io.format_io_utils.generic_load(file_or_dir_path: str, expected_num_volumes: Optional[int] = None)[source]¶ Load MedicalVolume(s) from a file or directory without knowing data format.
- Parameters
file_or_dir_path (str) – File or directory path.
expected_num_volumes (int, optional) – Number of volumes expected. If specified, assert if number of loaded volumes != expected num volumes. Defaults to None.
- Returns
- Volume(s) loaded.
If
expected_num_volumes = 1, returns :class:MedicalVolume.
- Return type
list[MedicalVolume] or MedicalVolume
- Raises
ValueError – If multiple file paths corresponding to different ImageDataFormats exist.
FileNotFoundError – If file path or corresponding versions of file path not found.
-
dosma.data_io.format_io_utils.get_filepath_variations(file_or_dir_path: str)[source]¶ Get file paths using convention for all different image data formats.
- Parameters
file_or_dir_path (str) – File or directory path.
- Returns
File paths corresponding to naming conventions of different ImageDataFormats.
- Return type
list[str]
-
dosma.data_io.format_io_utils.get_reader(data_format: dosma.data_io.format_io.ImageDataFormat) → dosma.data_io.format_io.DataReader[source]¶ Return a DataReader corresponding to the given data format.
- Parameters
data_format (ImageDataFormat) – Data format to read.
- Returns
Reader for given format.
- Return type
-
dosma.data_io.format_io_utils.get_writer(data_format: dosma.data_io.format_io.ImageDataFormat) → dosma.data_io.format_io.DataWriter[source]¶ Return a DataWriter corresponding to given data format.
- Parameters
data_format (ImageDataFormat) – Data format to write.
- Returns
Writer for given format.
- Return type
dosma.data_io.med_volume module¶
MedicalVolume
This module defines MedicalVolume, which is a wrapper for 3D volumes.
-
class
dosma.data_io.med_volume.MedicalVolume(volume: numpy.ndarray, affine: numpy.ndarray, headers: Optional[List[pydicom.dataset.FileDataset]] = None)[source]¶ Bases:
objectThe class for medical images.
Medical volumes are 3D matrices representing medical data. These volumes have inherent metadata, such as pixel/voxel spacing, global coordinates, rotation information, all of which can be characterized by an affine matrix following the RAS+ coordinate system.
Standard math and boolean operations are supported with other
MedicalVolumeobjects, numpy arrays (following standard broadcasting), and scalars. Boolean operations are performed elementwise, resulting in a volume with shape asself.volume.shape. If performing operations betweenMedicalVolumeobjects, both objects must have the same shape and affine matrix (spacing, direction, and origin). Header information is not deep copied when performing these operations to reduce computational and memory overhead. The affine matrix (self.affine) is copied as it is lightweight and often modified.2D images are also supported when viewed trivial 3D volumes with shape
(H, W, 1).Many operations are in-place and modify the instance directly (e.g. reformat(inplace=True)). To allow chaining operations, operations that are in-place return
self.- Parameters
volume (np.ndarray) – 3D volume.
affine (np.ndarray) – 4x4 array corresponding to affine matrix transform in RAS+ coordinates.
headers (list[pydicom.FileDataset]) – Headers for DICOM files.
-
property
affine¶ 4x4 affine matrix for volume in current orientation.
- Type
np.ndarray
-
clone(headers=True)[source]¶ Clones the medical volume.
- Parameters
headers (bool, optional) – If True, clone headers. If False, headers have shared memory.
- Returns
A cloned MedicalVolume.
- Return type
mv (MedicalVolume)
-
classmethod
from_sitk(image, copy=False) → dosma.data_io.med_volume.MedicalVolume[source]¶ Constructs MedicalVolume from SimpleITK.Image.
Note
Metadata information is not copied.
- Parameters
image (SimpleITK.Image) – The image.
copy (bool, optional) – If
True, copies array.
- Returns
MedicalVolume
-
property
headers¶ Headers for DICOM files.
- Type
list[pydicom.FileDataset]
-
is_identical(mv)[source]¶ Check if another medical volume is identical.
Two volumes are identical if they have the same pixel_spacing, orientation, scanner_origin, and volume.
- Parameters
mv (MedicalVolume) – Volume to compare with.
- Returns
True if identical, False otherwise.
- Return type
bool
-
is_same_dimensions(mv, precision: Optional[int] = None, err: bool = False)[source]¶ Check if two volumes have the same dimensions.
Two volumes have the same dimensions if they have the same pixel_spacing, orientation, and scanner_origin.
- Parameters
mv (MedicalVolume) – Volume to compare with.
precision (int, optional) – Number of significant figures after the decimal. If not specified, check that affine matrices between two volumes are identical. Defaults to None.
err (bool, optional) – If True and volumes do not have same dimensions, raise descriptive ValueError.
- Returns
Trueif pixel spacing, orientation, and scanner originbetween two volumes within tolerance,
Falseotherwise.
- Return type
bool
- Raises
TypeError – If
mvis not a MedicalVolume.ValueError – If
err=Trueand two volumes do not have same dimensions.
-
match_orientation(mv)[source]¶ Reorient another MedicalVolume to orientation specified by self.orientation.
- Parameters
mv (MedicalVolume) – Volume to reorient.
-
match_orientation_batch(mvs)[source]¶ Reorient a collection of MedicalVolumes to orientation specified by self.orientation.
- Parameters
mvs (list[MedicalVolume]) – Collection of MedicalVolumes.
-
property
orientation¶ Image orientation in standard orientation format.
See orientation.py for more information on conventions.
- Type
tuple[str]
-
property
pixel_spacing¶ Pixel spacing in order of current orientation.
- Type
tuple[float]
-
reformat(new_orientation: Sequence, inplace: bool = False) → dosma.data_io.med_volume.MedicalVolume[source]¶ Reorients volume to a specified orientation.
Flipping and transposing the volume array (
self.volume) returns a view if possible.Axis transpose and flipping are linear operations and therefore can be treated
independently. - working example: (‘AP’, ‘SI’, ‘LR’) –> (‘RL’, ‘PA’, ‘SI’) 1. Transpose volume and RAS orientation to appropriate column in matrix
eg. (‘AP’, ‘SI’, ‘LR’) –> (‘LR’, ‘AP’, ‘SI’) - transpose_inds=[2, 0, 1]
- Flip volume across corresponding axes
eg. (‘LR’, ‘AP’, ‘SI’) –> (‘RL’, ‘PA’, ‘SI’) - flip axes 0,1
1. Transpose: Switching (transposing) axes in volume is the same as switching columns in affine matrix
2. Flipping: Negate each column corresponding to pixel axis to flip (i, j, k) and reestablish origins based on flipped axes
- Parameters
new_orientation (Sequence) – New orientation.
inplace (bool, optional) – If True, do operation in-place and return
self.
- Returns
The reformatted volume. If
inplace=True, returnsself.- Return type
-
reformat_as(other, inplace: bool = False) → dosma.data_io.med_volume.MedicalVolume[source]¶ Reformat this to the same orientation as
other. Equivalent toself.reformat(other.orientation, inplace).- Parameters
other (MedicalVolume) – The result volume has the same orientation as
other.inplace (bool, optional) – If True, do operation in-place and return
self.
- Returns
The reformatted volume. If
inplace=True, returnsself.- Return type
-
save_volume(file_path: str, data_format: dosma.data_io.format_io.ImageDataFormat = <ImageDataFormat.nifti: 1>)[source]¶ Write volumes in specified data format.
- Parameters
file_path (str) – File path to save data. May be modified to follow convention given by the data format in which the volume will be saved.
data_format (ImageDataFormat) – Format to save data.
-
property
scanner_origin¶ Scanner origin in global RAS+ x,y,z coordinates.
- Type
tuple[float]
-
property
shape¶
-
to_sitk(vdim: Optional[int] = None)[source]¶ Converts to SimpleITK Image.
SimpleITK Image objects support vector pixel types, which are represented as an extra dimension in numpy arrays. The vector dimension can be specified with
vdim.- Parameters
vdim (int, optional) – The vector dimension.
Note
Header information is not currently copied.
- Returns
SimpleITK.Image
-
property
volume¶ 3D numpy array representing volume values.
- Type
np.ndarray
dosma.data_io.nifti_io module¶
NIfTI I/O.
This module contains NIfTI input/output helpers.
-
class
dosma.data_io.nifti_io.NiftiReader[source]¶ Bases:
dosma.data_io.format_io.DataReaderA class for reading NIfTI files.
-
data_format_code= 1¶
-
load(file_path)[source]¶ Load volume from NIfTI file path.
A NIfTI file should only correspond to one volume.
- Parameters
file_path (str) – File path to NIfTI file.
- Returns
Loaded volume.
- Return type
- Raises
FileNotFoundError – If file_path not found.
ValueError – If file_path does not end in a supported NIfTI extension.
-
-
class
dosma.data_io.nifti_io.NiftiWriter[source]¶ Bases:
dosma.data_io.format_io.DataWriterA class for writing volumes in NIfTI format.
-
data_format_code= 1¶
-
save(volume: dosma.data_io.med_volume.MedicalVolume, file_path: str)[source]¶ Save volume in NIfTI format,
- Parameters
volume (MedicalVolume) – Volume to save.
file_path (str) – File path to NIfTI file.
- Raises
ValueError – If file_path does not end in a supported NIfTI extension.
-
dosma.data_io.orientation module¶
Standardized orientation convention and utilities.
Medical image orientation convention is library and image format (DICOM, NIfTI, etc.) dependent and is often difficult to interpret. This makes it challenging to intelligently and rapidly reformat images.
We adopt a easily interpretable orientation representation for the dimensions and define utilities to convert between different orientation formats from current libraries (Nibabel, PyDicom, ITK, etc).
Orientations are represented by string axis codes:
"LR": left to right;"RL": right to left"PA": posterior to anterior;"AP": anterior to posterior"IS": inferior to superior;"SI": superior to inferior
A MedicalVolume object with orientation ("SI", "AP", "LR") has an
array where the first dimension spans superior -> inferior, the second dimension
spans anterior -> posterior, and the third dimension spans left -> right. Voxel
at (i,j,k) index (0,0,0) would be the (superior, anterior, left) corner.
In many cases, images are not acquired in the standard plane convention, but rather in a rotated frame. In this case, the orientations correspond to the closest axis the a particular dimension.
Two general conventions are followed:
All orientations are in patient voxel coordinates. Image data from (i, j, k) corresponds to the voxel at array position
arr[i,j,k].Left: corresponds to patient (not observer) left, right: corresponds to patient (not observer) right.
We adopt the RAS+ standard (as defined by NIfTI) for orienting our images.
The + in RAS+ indicates that all directions point to the increasing direction.
i.e. from -x to x:.
Image spacing, direction, and global origin are represented by a 4x4 affine matrix (\(A\)) and is identical to the nibabel affine matrix (see nibabel). The affine matrix converts pixel coordinates (i, j, k) into world (NIfTI) coordinates (x, y, z).
For example,
For details on how the affine matrix is used for reformatting see
dosma.data_io.MedicalVolume.
-
dosma.data_io.orientation.get_flip_inds(curr_orientation: tuple, new_orientation: tuple)[source]¶ Get indices to flip from
curr_orientationtonew_orientation.- Parameters
curr_orientation (tuple[str]) – Current image orientation.
new_orientation (tuple[str]) – New image orientation.
- Returns
Axes to flip.
- Return type
list[int]
- Raises
ValueError – If mismatch in orientation indices. To avoid this error, use
get_transpose_inds()prior to flipping.
Examples
>>> get_transpose_inds(("SI", "AP", "LR"), ("IS", "AP", "RL")) [0, 2]
-
dosma.data_io.orientation.get_transpose_inds(curr_orientation: tuple, new_orientation: tuple)[source]¶ Get indices for reordering planes from
curr_orientationtonew_orientation.Only permuted order of reformatting the image planes is returned. For example,
("SI", "AP", "LR")and("IS", "PA", "RL")will have no permuted indices because “SI”/”IS”, “AP”/”PA” and “RL”/”LR” each correspond to the same plane.- Parameters
curr_orientation (tuple[str]) – Current image orientation.
new_orientation (tuple[str]) – New image orientation.
- Returns
Axes to transpose to change orientation.
- Return type
tuple[int]
Examples
>>> get_transpose_inds(("SI", "AP", "LR"), ("AP", "SI", "LR")) (1,0,2) >>> get_transpose_inds(("SI", "AP", "LR"), ("IS", "PA", "RL")) (0,1,2)
-
dosma.data_io.orientation.orientation_nib_to_standard(nib_orientation)[source]¶ Convert Nibabel orientation to the standard dosma orientation format.
- Parameters
nib_orientation – a RAS+ tuple orientation used by Nibabel.
- Returns
Image orientation in the standard orientation format.
- Return type
tuple[str]
Examples
>>> orientation_nib_to_standard(("R", "A", "S")) ("LR", "PA", "IS")
-
dosma.data_io.orientation.orientation_standard_to_nib(orientation)[source]¶ Convert standard dosma orientation format to Nibabel orientation.
- Parameters
orientation – Image orientation in the standard orientation format.
- Returns
RAS+ tuple orientation used by Nibabel.
- Return type
tuple[str]
Examples
>>> orientation_nib_to_standard(("LR", "PA", "IS")) ("R", "A", "S")
Module contents¶
-
class
dosma.data_io.DataReader[source]¶ Bases:
abc.ABCAbstract class for reading medical data.
Format-specific readers should inherit from this class.
- Variables
data_format_code (ImageDataFormat) – Should be defined by subclasses.
-
data_format_code= None¶
-
class
dosma.data_io.DataWriter[source]¶ Bases:
abc.ABCAbstract class for writing medical data.
Format-specific writers should inherit from this class.
- Variables
data_format_code (ImageDataFormat) – Should be defined by subclasses.
-
data_format_code= None¶
-
abstract
save(volume, file_path: str)[source]¶ Save volume.
- Parameters
volume (MedicalVolume) – Volume to save.
file_path (str) – File path to save volume to.
-
class
dosma.data_io.DicomReader(num_workers: int = 0, verbose: bool = False)[source]¶ Bases:
dosma.data_io.format_io.DataReaderA class for reading DICOM files.
-
data_format_code= 2¶
-
load(path: Union[str, Sequence[str]], group_by: Union[str, tuple] = 'EchoNumbers', ignore_ext: bool = False)[source]¶ Load dicoms into MedicalVolume`s grouped by `group_by tag.
When loading files from a directory, all hidden files (files starting with “.”) are ignored. Files are sorted in alphabetical order.
- Parameters
path (str(s)) – Directory with dicom files or dicom file(s).
group_by (str or tuple, optional) – DICOM field tag name or tag number used to group dicoms. Defaults to EchoNumbers. Most DICOM headers encode different echo numbers as volumes acquired at different echo times or different phases.
ignore_ext (bool, optional) – If True, ignore extension (.dcm) when loading dicoms from directory. Defaults to False.
- Returns
Different volumes grouped by the group_by DICOM tag.
- Return type
list[MedicalVolume]
- Raises
ValueError – If group_by not specified or if single dicom file specified.
IOError – If directory or dicom file(s) specified by path do not exist.
FileNotFoundError – If no valid dicom files found.
Note
- This function sorts files using natsort, an intelligent sorting tool.
Please verify dicoms are labeled in a sequenced manner (e.g.: dicom1,dicom2,dicom3,…).
-
-
class
dosma.data_io.DicomWriter(num_workers: int = 0, verbose: bool = False)[source]¶ Bases:
dosma.data_io.format_io.DataWriterA class for writing volumes in DICOM format.
-
data_format_code= 2¶
-
save(volume: dosma.data_io.med_volume.MedicalVolume, dir_path: str, fname_fmt: Optional[str] = None)[source]¶ Save medical volume in dicom format.
- Parameters
volume (MedicalVolume) – Volume to save.
dir_path – Directory path to store dicom files. Dicoms are stored in directories, as multiple files are needed to store the volume.
fname_fmt (str, optional) – Formatting string for filenames. Must contain
%d, which correspopnds to slice number. Defaults to"I%0{max(4, ceil(log10(num_slices)))}d.dcm"(e.g."I0001.dcm").
- Raises
ValueError – If im does not have initialized headers. Or if im was flipped across any axis. Flipping changes scanner origin, which is currently not handled.
-
-
class
dosma.data_io.ImageDataFormat(value)[source]¶ Bases:
enum.EnumEnum describing supported data formats for medical volume I/O.
-
dicom= 2¶
-
classmethod
get_image_data_format(file_or_dir_path: str)[source]¶ Get the ImageDataFormat that corresponds to the file path.
Matches extension to file path. If input is a directory path, then it is classified as ImageDataFormat.dicom.
- Parameters
file_or_dir_path (str) – Path to a file or a directory.
- Returns
Format corresponding to file or directory path.
- Return type
- Raises
ValueError – If no compatible ImageDataFormat found.
-
is_filetype(file_path: str) → bool[source]¶ Verify if file path matches the file type specified by ImageDataFormat.
This method checks to make sure the extensions are appropriate.
- Parameters
file_path (str) – File path.
- Returns
True if file_path has valid extension, False otherwise.
- Return type
bool
-
nifti= 1¶
-
-
class
dosma.data_io.MedicalVolume(volume: numpy.ndarray, affine: numpy.ndarray, headers: Optional[List[pydicom.dataset.FileDataset]] = None)[source]¶ Bases:
objectThe class for medical images.
Medical volumes are 3D matrices representing medical data. These volumes have inherent metadata, such as pixel/voxel spacing, global coordinates, rotation information, all of which can be characterized by an affine matrix following the RAS+ coordinate system.
Standard math and boolean operations are supported with other
MedicalVolumeobjects, numpy arrays (following standard broadcasting), and scalars. Boolean operations are performed elementwise, resulting in a volume with shape asself.volume.shape. If performing operations betweenMedicalVolumeobjects, both objects must have the same shape and affine matrix (spacing, direction, and origin). Header information is not deep copied when performing these operations to reduce computational and memory overhead. The affine matrix (self.affine) is copied as it is lightweight and often modified.2D images are also supported when viewed trivial 3D volumes with shape
(H, W, 1).Many operations are in-place and modify the instance directly (e.g. reformat(inplace=True)). To allow chaining operations, operations that are in-place return
self.- Parameters
volume (np.ndarray) – 3D volume.
affine (np.ndarray) – 4x4 array corresponding to affine matrix transform in RAS+ coordinates.
headers (list[pydicom.FileDataset]) – Headers for DICOM files.
-
property
affine¶ 4x4 affine matrix for volume in current orientation.
- Type
np.ndarray
-
clone(headers=True)[source]¶ Clones the medical volume.
- Parameters
headers (bool, optional) – If True, clone headers. If False, headers have shared memory.
- Returns
A cloned MedicalVolume.
- Return type
mv (MedicalVolume)
-
classmethod
from_sitk(image, copy=False) → dosma.data_io.med_volume.MedicalVolume[source]¶ Constructs MedicalVolume from SimpleITK.Image.
Note
Metadata information is not copied.
- Parameters
image (SimpleITK.Image) – The image.
copy (bool, optional) – If
True, copies array.
- Returns
MedicalVolume
-
property
headers¶ Headers for DICOM files.
- Type
list[pydicom.FileDataset]
-
is_identical(mv)[source]¶ Check if another medical volume is identical.
Two volumes are identical if they have the same pixel_spacing, orientation, scanner_origin, and volume.
- Parameters
mv (MedicalVolume) – Volume to compare with.
- Returns
True if identical, False otherwise.
- Return type
bool
-
is_same_dimensions(mv, precision: Optional[int] = None, err: bool = False)[source]¶ Check if two volumes have the same dimensions.
Two volumes have the same dimensions if they have the same pixel_spacing, orientation, and scanner_origin.
- Parameters
mv (MedicalVolume) – Volume to compare with.
precision (int, optional) – Number of significant figures after the decimal. If not specified, check that affine matrices between two volumes are identical. Defaults to None.
err (bool, optional) – If True and volumes do not have same dimensions, raise descriptive ValueError.
- Returns
Trueif pixel spacing, orientation, and scanner originbetween two volumes within tolerance,
Falseotherwise.
- Return type
bool
- Raises
TypeError – If
mvis not a MedicalVolume.ValueError – If
err=Trueand two volumes do not have same dimensions.
-
match_orientation(mv)[source]¶ Reorient another MedicalVolume to orientation specified by self.orientation.
- Parameters
mv (MedicalVolume) – Volume to reorient.
-
match_orientation_batch(mvs)[source]¶ Reorient a collection of MedicalVolumes to orientation specified by self.orientation.
- Parameters
mvs (list[MedicalVolume]) – Collection of MedicalVolumes.
-
property
orientation¶ Image orientation in standard orientation format.
See orientation.py for more information on conventions.
- Type
tuple[str]
-
property
pixel_spacing¶ Pixel spacing in order of current orientation.
- Type
tuple[float]
-
reformat(new_orientation: Sequence, inplace: bool = False) → dosma.data_io.med_volume.MedicalVolume[source]¶ Reorients volume to a specified orientation.
Flipping and transposing the volume array (
self.volume) returns a view if possible.Axis transpose and flipping are linear operations and therefore can be treated
independently. - working example: (‘AP’, ‘SI’, ‘LR’) –> (‘RL’, ‘PA’, ‘SI’) 1. Transpose volume and RAS orientation to appropriate column in matrix
eg. (‘AP’, ‘SI’, ‘LR’) –> (‘LR’, ‘AP’, ‘SI’) - transpose_inds=[2, 0, 1]
- Flip volume across corresponding axes
eg. (‘LR’, ‘AP’, ‘SI’) –> (‘RL’, ‘PA’, ‘SI’) - flip axes 0,1
1. Transpose: Switching (transposing) axes in volume is the same as switching columns in affine matrix
2. Flipping: Negate each column corresponding to pixel axis to flip (i, j, k) and reestablish origins based on flipped axes
- Parameters
new_orientation (Sequence) – New orientation.
inplace (bool, optional) – If True, do operation in-place and return
self.
- Returns
The reformatted volume. If
inplace=True, returnsself.- Return type
-
reformat_as(other, inplace: bool = False) → dosma.data_io.med_volume.MedicalVolume[source]¶ Reformat this to the same orientation as
other. Equivalent toself.reformat(other.orientation, inplace).- Parameters
other (MedicalVolume) – The result volume has the same orientation as
other.inplace (bool, optional) – If True, do operation in-place and return
self.
- Returns
The reformatted volume. If
inplace=True, returnsself.- Return type
-
save_volume(file_path: str, data_format: dosma.data_io.format_io.ImageDataFormat = <ImageDataFormat.nifti: 1>)[source]¶ Write volumes in specified data format.
- Parameters
file_path (str) – File path to save data. May be modified to follow convention given by the data format in which the volume will be saved.
data_format (ImageDataFormat) – Format to save data.
-
property
scanner_origin¶ Scanner origin in global RAS+ x,y,z coordinates.
- Type
tuple[float]
-
property
shape¶
-
to_sitk(vdim: Optional[int] = None)[source]¶ Converts to SimpleITK Image.
SimpleITK Image objects support vector pixel types, which are represented as an extra dimension in numpy arrays. The vector dimension can be specified with
vdim.- Parameters
vdim (int, optional) – The vector dimension.
Note
Header information is not currently copied.
- Returns
SimpleITK.Image
-
property
volume¶ 3D numpy array representing volume values.
- Type
np.ndarray
-
class
dosma.data_io.NiftiReader[source]¶ Bases:
dosma.data_io.format_io.DataReaderA class for reading NIfTI files.
-
data_format_code= 1¶
-
load(file_path)[source]¶ Load volume from NIfTI file path.
A NIfTI file should only correspond to one volume.
- Parameters
file_path (str) – File path to NIfTI file.
- Returns
Loaded volume.
- Return type
- Raises
FileNotFoundError – If file_path not found.
ValueError – If file_path does not end in a supported NIfTI extension.
-
-
class
dosma.data_io.NiftiWriter[source]¶ Bases:
dosma.data_io.format_io.DataWriterA class for writing volumes in NIfTI format.
-
data_format_code= 1¶
-
save(volume: dosma.data_io.med_volume.MedicalVolume, file_path: str)[source]¶ Save volume in NIfTI format,
- Parameters
volume (MedicalVolume) – Volume to save.
file_path (str) – File path to NIfTI file.
- Raises
ValueError – If file_path does not end in a supported NIfTI extension.
-
-
dosma.data_io.convert_image_data_format(file_or_dir_path: str, new_data_format: dosma.data_io.format_io.ImageDataFormat) → str[source]¶ Change a file or directory name to convention of another data format.
- Parameters
file_or_dir_path (str) – File or directory path.
new_data_format (ImageDataFormat) – Data format convention for file/directory name.
- Returns
File/directory path based on convention of new data format.
- Return type
str
- Raises
NotImplementedError – If conversion from current image data format to new image data format not found.
-
dosma.data_io.generic_load(file_or_dir_path: str, expected_num_volumes: Optional[int] = None)[source]¶ Load MedicalVolume(s) from a file or directory without knowing data format.
- Parameters
file_or_dir_path (str) – File or directory path.
expected_num_volumes (int, optional) – Number of volumes expected. If specified, assert if number of loaded volumes != expected num volumes. Defaults to None.
- Returns
- Volume(s) loaded.
If
expected_num_volumes = 1, returns :class:MedicalVolume.
- Return type
list[MedicalVolume] or MedicalVolume
- Raises
ValueError – If multiple file paths corresponding to different ImageDataFormats exist.
FileNotFoundError – If file path or corresponding versions of file path not found.
-
dosma.data_io.get_filepath_variations(file_or_dir_path: str)[source]¶ Get file paths using convention for all different image data formats.
- Parameters
file_or_dir_path (str) – File or directory path.
- Returns
File paths corresponding to naming conventions of different ImageDataFormats.
- Return type
list[str]
-
dosma.data_io.get_reader(data_format: dosma.data_io.format_io.ImageDataFormat) → dosma.data_io.format_io.DataReader[source]¶ Return a DataReader corresponding to the given data format.
- Parameters
data_format (ImageDataFormat) – Data format to read.
- Returns
Reader for given format.
- Return type
-
dosma.data_io.get_writer(data_format: dosma.data_io.format_io.ImageDataFormat) → dosma.data_io.format_io.DataWriter[source]¶ Return a DataWriter corresponding to given data format.
- Parameters
data_format (ImageDataFormat) – Data format to write.
- Returns
Writer for given format.
- Return type