volume

Functions

align_mesh_to_volume(mesh, volume_header)

Transforms the given mesh in-place using spatial information from an NRRD header.

compose_ijk_2_world_mat(meta)

Transform 4x4 matrix from voxels to world coordinates.

convert_3d_geometry_to_mesh(geometry[, ...])

Converts a 3D geometry (Mask3D) to a Trimesh mesh.

convert_3d_nifti_to_nrrd(path)

Convert 3D NIFTI volume to NRRD format.

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.

export_3d_as_mesh(geometry, output_path, ...)

Exports the 3D mesh representation of the object to a file in either STL or OBJ 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.

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

exception UnsupportedVolumeFormat[source]

Bases: Exception

Raised when a volume file format is not supported by Supervisely.

align_mesh_to_volume(mesh, volume_header)[source]

Transforms the given mesh in-place using spatial information from an NRRD header. The mesh will be tranformed to match the coordinate system defined in the header.

Parameters:
mesh : Trimesh

The mesh object to be transformed. The transformation is applied in-place.

volume_header : dict

The NRRD header containing spatial metadata, including “space directions”, “space origin”, and “space”. Field “space” should be in the format of “right-anterior-superior”, “left-anterior-superior”, etc.

Returns:

None

Return type:

None

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.        ]
# ]
convert_3d_geometry_to_mesh(geometry, spacing=(1.0, 1.0, 1.0), level=0.5, apply_decimation=False, decimation_fraction=0.5, volume_meta=None)[source]

Converts a 3D geometry (Mask3D) to a Trimesh mesh.

Parameters:
geometry

The 3D geometry to convert.

spacing : tuple

Voxel spacing in (x, y, z).

level : float

Isosurface value for marching cubes. Default is 0.5.

apply_decimation : bool

Whether to simplify the mesh. Default is False.

decimation_fraction : float

Fraction of faces to keep if decimation is applied. Default is 0.5.

volume_meta : dict, optional

Metadata of the volume. Used for mesh alignment if geometry lacks specific fields. Default is None.

Returns:

The resulting Trimesh mesh.

Return type:

trimesh.Trimesh

Usage Example:
volume_header = nrrd.read_header("path/to/volume.nrrd")
mask3d = Mask3D.create_from_file("path/to/mask3d")
mesh = convert_3d_geometry_to_mesh(mask3d, spacing=(1.0, 1.0, 1.0), level=0.7, apply_decimation=True, volume_meta=volume_header)
convert_3d_nifti_to_nrrd(path)[source]

Convert 3D 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)
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)
export_3d_as_mesh(geometry, output_path, **kwargs)[source]

Exports the 3D mesh representation of the object to a file in either STL or OBJ format.

Parameters:
geometry

The 3D geometry to be exported.

output_path : str

The path to the output file. Must have a “.stl” or “.obj” extension.

**kwargs

Additional keyword arguments for mesh generation. Supported keys: - spacing (tuple): Voxel spacing in (x, y, z). By default the value will be taken from geometry meta. - level (float): Isosurface value for marching cubes. Default is 0.5. - apply_decimation (bool): Whether to simplify the mesh. Default is False. - decimation_fraction (float): Fraction of faces to keep if decimation is applied. Default is 0.5. - volume_meta (dict): Metadata of the volume. Used for mesh alignment if geometry lacks specific fields. Default is None.

Returns:

None

Usage Example:
mask3d_path = "path/to/mask3d"
mask3d = Mask3D.create_from_file(mask3d_path)

mask3d.export_3d_as_mesh(mask3d, "output.stl", spacing=(1.0, 1.0, 1.0), level=0.7, apply_decimation=True)
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.

Parameters:
path : str

Path to file.

Returns:

True if file format in list of supported Volume formats, False - in otherwise

Return type:

bool

Usage Example:
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)[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]

Path to NRRD 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:
paths : str

Path 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 :rtype: None

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.        ]
# ]