volume

Functions

compose_ijk_2_world_mat(meta)

Transform 4x4 matrix from voxels to world coordinates.

convert_nifti_to_nrrd(path)

Convert NIFTI volume to NRRD format.

encode(volume_np, volume_meta)

Encodes a volume from NumPy format into a NRRD format.

get_extension(path)

Get extension for given path.

get_meta(sitk_shape, min_intensity, ...[, ...])

Get normalized meta-data for a volume.

has_valid_ext(path)

Checks if Volume file from given path has supported extension.

inspect_dicom_series(root_dir[, logging])

Search for DICOM series in the directory and its subdirectories.

inspect_nrrd_series(root_dir[, logging])

Inspect a directory for NRRD series by recursively listing files with the ".nrrd" extension and returns a list of NRRD file paths found in the directory.

is_nifti_file(path)

Check if the file is a NIFTI file.

is_valid_ext(ext)

Checks if given extension is supported.

is_valid_format(path)

Checks if a given file has a supported format. :type path: str :param path: Path to file. :type path: str :return: True if file format in list of supported Volume formats, False - in otherwise :rtype: bool :Usage example: .. code-block:: python import supervisely as sly sly.volume.is_valid_format('/volumes/dcm01.dcm') # True sly.volume.is_valid_format('/volumes/nrrd.py') # False.

normalize_volume_meta(meta)

Normalize volume metadata.

read_dicom_serie_volume(paths[, anonymize])

Read DICOM series volumes with given paths.

read_dicom_serie_volume_np(paths[, anonymize])

Read DICOM series volumes with given paths.

read_dicom_tags(path[, allowed_keys, anonymize])

Read DICOM tags from a DICOM file.

read_nrrd_serie_volume(path)

Read NRRD volume with given path.

read_nrrd_serie_volume_np(paths)

Read NRRD volume with given path.

rescale_slope_intercept(value, slope, intercept)

Rescale intensity value using the given slope and intercept.

validate_format(path)

Raise error if Volume file from given path couldn't be read or file extension is not supported.

world_2_ijk_mat(ijk_2_world)

Transform 4x4 matrix from world to voxels coordinates.

Description

Functions for processing volumes

compose_ijk_2_world_mat(meta)[source]

Transform 4x4 matrix from voxels to world coordinates.

Parameters
meta : dict

Volume metadata.

Usage example
import supervisely as sly

mat = sly.volume.volume.compose_ijk_2_world_mat(volume_meta)

# Output:
# [
#     [   0.76171899    0.            0.         -194.23840308]
#     [   0.            0.76171899    0.         -217.53840613]
#     [   0.            0.            2.5        -347.75      ]
#     [   0.            0.            0.            1.        ]
# ]
Return type

ndarray

convert_nifti_to_nrrd(path)[source]

Convert NIFTI volume to NRRD format. Volume automatically reordered to RAS orientation as closest to canonical.

Parameters
path : str

Path to NIFTI volume file.

Returns

Volume data in NumPy array format and dictionary with metadata (NRRD header).

Return type

Tuple[np.ndarray, dict]

Usage example
import supervisely as sly

path = "/home/admin/work/volumes/vol_01.nii"
data, header = sly.volume.convert_nifti_to_nrrd(path)
encode(volume_np, volume_meta)[source]

Encodes a volume from NumPy format into a NRRD format.

Parameters
volume_np : np.ndarray

NumPy array representing the volume data.

volume_meta : dict

Metadata of the volume.

Returns

Encoded volume data in bytes.

Return type

bytes

Usage example
import numpy as np
import supervisely as sly

volume_np = np.random.rand(256, 256, 256)
volume_meta = {
    "ACS": "RAS",
    "channelsCount": 1,
    "dimensionsIJK": { "x": 512, "y": 512, "z": 139 },
    "directions": (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0),
    "intensity": { "max": 3071.0, "min": -3024.0 },
    "origin": (-194.238403081894, -217.5384061336518, -347.7500000000001),
    "rescaleIntercept": 0,
    "rescaleSlope": 1,
    "spacing": (0.7617189884185793, 0.7617189884185793, 2.5),
    "windowCenter": 23.5,
    "windowWidth": 6095.0
}

encoded_volume = sly.volume.encode(volume_np, volume_meta)
get_extension(path)[source]

Get extension for given path.

Parameters
path : str

Path to volume.

Returns

Path extension

Return type

str

Usage example
import supervisely as sly

path = "src/upload/folder/CTACardio.nrrd"
ext = sly.volume.get_extension(path=path) # .nrrd
get_meta(sitk_shape, min_intensity, max_intensity, spacing, origin, directions, dicom_tags={})[source]

Get normalized meta-data for a volume.

Parameters
sitk_shape : tuple

Tuple representing the shape of the volume in (x, y, z) dimensions.

min_intensity : float

Minimum intensity value in the volume.

max_intensity : float

Maximum intensity value in the volume.

spacing : tuple

Tuple representing the spacing between voxels in (x, y, z) dimensions.

origin : tuple

Tuple representing the origin of the volume in (x, y, z) dimensions.

directions : tuple

Tuple representing the direction matrix of the volume.

dicom_tags : dict, optional

Dictionary containing additional DICOM tags for the volume meta-data.

Returns

Dictionary containing the normalized meta-data for the volume.

Return type

dict

Usage example
import SimpleITK as sitk
import supervisely as sly

path = "/home/admin/work/volumes/vol_01.nrrd"

reader = sitk.ImageSeriesReader()
reader.SetFileNames(path)
sitk_volume = reader.Execute()
sitk_volume = _sitk_image_orient_ras(sitk_volume)
dicom_tags = read_dicom_tags(paths[0], anonymize=anonymize)

f_min_max = sitk.MinimumMaximumImageFilter()
f_min_max.Execute(sitk_volume)
meta = get_meta(
    sitk_volume.GetSize(),
    f_min_max.GetMinimum(),
    f_min_max.GetMaximum(),
    sitk_volume.GetSpacing(),
    sitk_volume.GetOrigin(),
    sitk_volume.GetDirection(),
    dicom_tags,
)
has_valid_ext(path)[source]

Checks if Volume file from given path has supported extension.

Parameters
path : str

Path to volume file.

Returns

True if Volume file has supported extension else False

Return type

bool

Usage example
import supervisely as sly

volume_path = "/home/admin/work/volumes/vol_01.nrrd"
sly.volume.has_valid_ext(volume_path) # True
inspect_dicom_series(root_dir, logging=True)[source]

Search for DICOM series in the directory and its subdirectories. If several series with the same UID are found in the directory, then the series are numbered in the format: “series_uid_01”, “series_uid_02”, etc.

Parameters
root_dir : str

Directory path with volumes.

logging : bool

Specify whether to print logging messages.

Returns

Dictionary with DICOM volumes IDs and corresponding file names.

Return type

dict

Usage example
import supervisely as sly

path = "src/upload/Dicom_files/"
series_infos = sly.volume.inspect_dicom_series(root_dir=path)
inspect_nrrd_series(root_dir, logging=True)[source]

Inspect a directory for NRRD series by recursively listing files with the “.nrrd” extension and returns a list of NRRD file paths found in the directory.

Parameters
root_dir : str

Directory to inspect for NRRD series.

logging : bool

Specify whether to print logging messages.

Returns

List of NRRD file paths found in the given directory.

Return type

List[str]

Usage example
import supervisely as sly

path = "/home/admin/work/volumes/"
nrrd_paths = sly.volume.inspect_nrrd_series(root_dir=path)
is_nifti_file(path)[source]

Check if the file is a NIFTI file.

Parameters
filepath : str

Path to the file.

Returns

True if the file is a NIFTI file, False otherwise.

Return type

bool

is_valid_ext(ext)[source]

Checks if given extension is supported.

Parameters
ext : str

Volume file extension.

Returns

True if extensions is in the list of supported extensions else False

Return type

bool

Usage example
import supervisely as sly

sly.volume.is_valid_ext(".nrrd")  # True
sly.volume.is_valid_ext(".mp4") # False
is_valid_format(path)[source]

Checks if a given file has a supported format. :type path: str :param path: Path to file. :type path: str :return: True if file format in list of supported Volume formats, False - in otherwise :rtype: bool :Usage example:

normalize_volume_meta(meta)[source]

Normalize volume metadata.

Parameters
meta : dict

Metadata of the volume.

Returns

Normalized volume metadata.

Return type

dict

Usage example
import supervisely as sly

normalized_meta = sly.volume.volume.volume.normalize_volume_meta(volume_meta)

print(normalized_meta)
# Output:
# {
#     'ACS': 'RAS',
#     'channelsCount': 1,
#     'dimensionsIJK': {'x': 512, 'y': 512, 'z': 139},
#     'directions': (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0),
#     'intensity': {'max': 3071.0, 'min': -3024.0},
#     'origin': (-194.238403081894, -217.5384061336518, -347.7500000000001),
#     'rescaleIntercept': 0,
#     'rescaleSlope': 1,
#     'spacing': (0.7617189884185793, 0.7617189884185793, 2.5),
#     'windowCenter': 23.5,
#     'windowWidth': 6095.0
# }
read_dicom_serie_volume(paths, anonymize=True)[source]

Read DICOM series volumes with given paths.

Parameters
paths : List[str]

Paths to DICOM volume files.

anonymize : bool

Specify whether to hide PatientID and PatientName fields.

Returns

Volume data in SimpleITK.Image format and dictionary with metadata.

Return type

Tuple[SimpleITK.Image, dict]

Usage example
import supervisely as sly

paths = ["/home/admin/work/volumes/vol_01.nrrd"]
sitk_volume, meta = sly.volume.read_dicom_serie_volume(paths)
read_dicom_serie_volume_np(paths, anonymize=True)[source]

Read DICOM series volumes with given paths.

Parameters
paths : List[str]

Paths to DICOM volume files.

anonymize : bool

Specify whether to hide PatientID and PatientName fields.

Returns

Volume data in NumPy array format and dictionary with metadata

Return type

Tuple[np.ndarray, dict]

Usage example
import supervisely as sly

volume_path = ["/home/admin/work/volumes/vol_01.nrrd"]
volume_np, meta = sly.volume.read_dicom_serie_volume_np(volume_path)
read_dicom_tags(path, allowed_keys=['SeriesInstanceUID', 'Modality', 'WindowCenter', 'WindowWidth', 'RescaleIntercept', 'RescaleSlope', 'PhotometricInterpretation', 'PatientID', 'PatientName'], anonymize=True)[source]

Read DICOM tags from a DICOM file.

Parameters
path : str

Path to the DICOM file.

allowed_keys : Union[None, List[str]], optional

List of allowed DICOM keywords to be extracted. Default is None, which means all keywords are allowed.

anonymize : bool, optional

Flag to indicate whether to anonymize certain tags or not.

Returns

Dictionary containing the extracted DICOM tags.

Return type

dict

Usage example
import supervisely as sly

path = "src/upload/Dicom_files/nnn.dcm"
dicom_tags = sly.volume.read_dicom_tags(path=path)
read_nrrd_serie_volume(path)[source]

Read NRRD volume with given path.

Parameters
path : List[str]

Paths to DICOM volume files.

Returns

Volume data in SimpleITK.Image format and dictionary with metadata.

Return type

Tuple[SimpleITK.Image, dict]

Usage example
import supervisely as sly

path = "/home/admin/work/volumes/vol_01.nrrd"
sitk_volume, meta = sly.volume.read_nrrd_serie_volume(path)
read_nrrd_serie_volume_np(paths)[source]

Read NRRD volume with given path.

Parameters
path : List[str]

Paths to NRRD volume file.

Returns

Volume data in NumPy array format and dictionary with metadata.

Return type

Tuple[np.ndarray, dict]

Usage example
import supervisely as sly

path = "/home/admin/work/volumes/vol_01.nrrd"
np_volume, meta = sly.volume.read_nrrd_serie_volume_np(path)
rescale_slope_intercept(value, slope, intercept)[source]

Rescale intensity value using the given slope and intercept.

Parameters
value : float

The intensity value to be rescaled.

slope : float

The slope for rescaling.

intercept : float

The intercept for rescaling.

Returns

The rescaled intensity value.

Return type

float

Usage example
import supervisely as sly

meta["intensity"]["min"] = sly.volume.volume.rescale_slope_intercept(
    meta["intensity"]["min"],
    meta["rescaleSlope"],
    meta["rescaleIntercept"],
)
validate_format(path)[source]

Raise error if Volume file from given path couldn’t be read or file extension is not supported.

Parameters
path : str

Path to Volume file.

Raises

UnsupportedVolumeFormat if Volume file from given path couldn’t be read or file extension is not supported.

Returns

None

Return type

NoneType

Usage example
import supervisely as sly

volume_path = "/home/admin/work/volumes/vol_01.mp4"
sly.volume.validate_format(volume_path)
# File /home/admin/work/volumes/vol_01.mp4 has unsupported volume extension. Supported extensions: [".nrrd", ".dcm"].
world_2_ijk_mat(ijk_2_world)[source]

Transform 4x4 matrix from world to voxels coordinates.

Parameters
ijk_2_world : np.ndarray

4x4 matrix.

Usage example
import supervisely as sly

mat = sly.volume.volume.world_2_ijk_mat(world_mat)

# Output:
# [
#     [  1.3128201    0.           0.         255.00008013]
#     [  0.           1.3128201    0.         285.58879251]
#     [  0.           0.           0.4        139.1       ]
#     [  0.           0.           0.           1.        ]
# ]
Return type

ndarray