VolumeApi

class VolumeApi[source]

Bases: supervisely.api.module_api.RemoveableBulkModuleApi

API for working with Volume. VolumeApi object is immutable.

Parameters
api : Api

API connection to the server.

Usage example
import os
from dotenv import load_dotenv

import supervisely as sly

# Load secrets and create API object from .env file (recommended)
# Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication
if sly.is_development():
    load_dotenv(os.path.expanduser("~/supervisely.env"))
api = sly.Api.from_env()

# Pass values into the API constructor (optional, not recommended)
# api = sly.Api(server_address="https://app.supervise.ly", token="4r47N...xaTatb")

volume_id = 19581134
volume_info = api.volume.get_info_by_id(volume_id) # api usage example

Methods

download_path

Download volume with given ID to local directory.

download_slice_np

Download slice as NumPy from Supervisely by ID.

exists

Checks if an entity with the given parent_id and name exists

get_free_name

Generates a free name for an entity with the given parent_id and name.

get_info_by_id

Get Volume information by ID in VolumeInfo<VolumeInfo> format.

get_info_by_name

Get information about an entity by its name from the Supervisely server.

get_list

Get list of information about all volumes for a given dataset ID.

get_list_all_pages

Get list of all or limited quantity entities from the Supervisely server.

get_list_all_pages_generator

This generator function retrieves a list of all or a limited quantity of entities from the Supervisely server, yielding batches of entities as they are retrieved

info_sequence

Get list of all VolumeInfo field names.

info_tuple_name

Get string name of VolumeInfo NamedTuple.

remove

Remove an entity with the specified ID from the Supervisely server.

remove_batch

Remove entities in batches from the Supervisely server.

upload_dicom_serie_paths

Upload given DICOM series from given paths to Dataset.

upload_hash

Upload Volume from given hash to Dataset.

upload_hashes

Upload Volumes from given hashes to Dataset.

upload_np

Upload given Volume in numpy format with given name to Dataset.

upload_nrrd_serie_path

Upload NRRD format volume from given path to Dataset.

upload_nrrd_series_paths

Upload NRRD format volumes from given paths to Dataset.

Attributes

MAX_WAIT_ATTEMPTS

Maximum number of attempts that will be made to wait for a certain condition to be met.

WAIT_ATTEMPT_TIMEOUT_SEC

Number of seconds for intervals between attempts.

InfoType

alias of supervisely.api.module_api.VolumeInfo

download_path(id, path, progress_cb=None)[source]

Download volume with given ID to local directory.

Parameters
id : int

Volume ID in Supervisely.

path : str

Local path to save volume.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

Returns

Information about Volume. See info_sequence

Return type

VolumeInfo

Usage example
import supervisely as sly
from tqdm import tqdm

os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()

src_dataset_id = 61229
volume_infos = api.volume.get_list(src_dataset_id)
volume_id = volume_infos[0].id
volume_info = api.volume.get_info_by_id(id=volume_id)

download_dir_name = "src/download/"
path = os.path.join(download_dir_name, volume_info.name)
if os.path.exists(path):
    os.remove(path)

p = tqdm(desc="Volumes upload: ", total=volume_info.sizeb, is_size=True)
api.volume.download_path(volume_info.id, path, progress_cb=p)

if os.path.exists(path):
    print(f"Volume (ID {volume_info.id}) successfully downloaded.")

# Output:
# Volume (ID 18630603) successfully downloaded.
download_slice_np(volume_id, slice_index, plane, window_center=None, window_width=None)[source]

Download slice as NumPy from Supervisely by ID.

Parameters
volume_id : int

Volume ID in Supervisely.

slice_index : int

Slice index.

plane : str

Plane of the slice in volume.

window_center : float

Window center.

window_width : int

Window width.

Returns

Information about Volume. See info_sequence

Return type

VolumeInfo

Usage example
import supervisely as sly

os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()


slice_index = 60

image_np = api.volume.download_slice_np(
    volume_id=volume_id,
    slice_index=slice_index,
    plane=sly.Plane.SAGITTAL,
)

print(f"Image downloaded as NumPy array. Image shape: {image_np.shape}")

# Output:
# Image downloaded as NumPy array. Image shape: (256, 256, 3)
exists(parent_id, name)

Checks if an entity with the given parent_id and name exists

Parameters
parent_id : int

ID of the parent entity.

name : str

Name of the entity.

Returns

Returns True if entity exists, and False if not

Return type

bool

Usage example
import supervisely as sly

# You can connect to API directly
address = 'https://app.supervise.ly/'
token = 'Your Supervisely API Token'
api = sly.Api(address, token)

# Or you can use API from environment
os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()


name = "IMG_0315.jpeg"
dataset_id = 55832
exists = api.image.exists(dataset_id, name)
print(exists) # True
get_free_name(parent_id, name)

Generates a free name for an entity with the given parent_id and name. Adds an increasing suffix to original name until a unique name is found.

Parameters
parent_id : int

ID of the parent entity.

name : str

Name of the entity.

Returns

Returns free name.

Return type

str

Usage example
import supervisely as sly

# You can connect to API directly
address = 'https://app.supervise.ly/'
token = 'Your Supervisely API Token'
api = sly.Api(address, token)

# Or you can use API from environment
os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()


name = "IMG_0315.jpeg"
dataset_id = 55832
free_name = api.image.get_free_name(dataset_id, name)
print(free_name) # IMG_0315_001.jpeg
get_info_by_id(id)[source]

Get Volume information by ID in VolumeInfo<VolumeInfo> format.

Parameters
id : int

Volume ID in Supervisely.

Returns

Information about Volume. See info_sequence

Return type

VolumeInfo

Usage example
import supervisely as sly


os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()

volume_id = 19581134
volume_info = api.volume.get_info_by_id(volume_id)
print(volume_info)
# Output:
# VolumeInfo(
#     id=19581134,
#     name='CTChest.nrrd',
#     link=None,
#     hash='+0K2oFHpqA5dwRKQlhkvhXEh52cs=',
#     mime=None,
#     ext=None,
#     sizeb=46073411,
#     created_at='2023-03-29T12:30:37.078Z',
#     updated_at='2023-03-29T12:30:37.078Z',
#     meta={
#         'ACS': 'RAS',
#         'intensity': {'max': 3071, 'min': -3024},
#         'windowWidth': 6095,
#         'rescaleSlope': 1,
#         'windowCenter': 23.5,
#         'channelsCount': 1,
#         'dimensionsIJK': {'x': 512, 'y': 512, 'z': 139},
#         'IJK2WorldMatrix': [0.7617189884185793, 0, 0, -194.238403081894, 0, 0.7617189884185793, 0, -217.5384061336518, 0, 0, 2.5, -347.7500000000001, 0, 0, 0, 1],
#         'rescaleIntercept': 0
#     },
#     path_original='/h5af-public/images/original/M/e/7R/vs0p.nrrd',
#     full_storage_url='https://dev.supervise.ly/.../original/M/e/7R/zX0p.nrrd',
#     tags=[],
#     team_id=435,
#     workspace_id=685,
#     project_id=18949,
#     dataset_id=61803,
#     file_meta={
#             'mime': 'image/nrrd',
#             'size': 46073411,
#             'type': 'int32',
#             'extra': {'stride': [1, 512, 262144],
#             'comments': []
#         }
#         'sizes': [512, 512, 139]
#         'space': 'right-anterior-superior'
#         'endian': 'little'
#         'encoding': 'gzip'
#         'dimension': 3
#         'space origin': [-194.238403081894, -217.5384061336518, -347.7500000000001]
#         'space dimension': 3
#         'space directions': [[0.7617189884185793, 0, 0], [0, 0.7617189884185793, 0], [0, 0, 2.5]]
#     }
#     figures_count=None,
#     objects_count=None,
#     processing_path='1/1560071'
# )
get_info_by_name(parent_id, name)

Get information about an entity by its name from the Supervisely server.

Parameters
parent_id : int

ID of the parent entity.

name : str

Name of the entity for which the information is being retrieved

Usage example
import supervisely as sly

# You can connect to API directly
address = 'https://app.supervise.ly/'
token = 'Your Supervisely API Token'
api = sly.Api(address, token)

# Or you can use API from environment
os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()


dataset_id = 55832
name = "IMG_0315.jpeg"
info = api.image.get_info_by_name(dataset_id, name)
print(info)
# Output: ImageInfo(id=19369643, name='IMG_0315.jpeg', ...)
get_list(dataset_id, filters=None, sort='id', sort_order='asc')[source]

Get list of information about all volumes for a given dataset ID.

Parameters
dataset_id : int

Dataset ID in Supervisely.

filters : List[Dict[str, str]], optional

List of parameters to sort output Volumes. See: https://dev.supervise.ly/api-docs/#tag/Volumes/paths/~1volumes.list/get

sort : str

Attribute to sort the list by. The default is “id”. Valid values are “id”, “name”, “description”, “createdAt”, “updatedAt”.

sort_order : str

Order in which to sort the list. The default is “asc”. Valid values are “asc” (ascending) and “desc” (descending).

Returns

List of information about volumes in given dataset.

Return type

List[VolumeInfo]

Usage example
import supervisely as sly

os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()

dataset_id = 61803

volume_infos = api.volume.get_list(dataset_id)
print(volume_infos)
# Output: [VolumeInfo(id=19581134, ...), VolumeInfo(id=19581135, ...), VolumeInfo(id=19581136, ...)]

sorted_volume_infos = api.volume.get_list(dataset_id, sort="id", sort_order="desc")
# Output: [VolumeInfo(id=19581136, ...), VolumeInfo(id=19581135, ...), VolumeInfo(id=19581134, ...)]

filtered_volume_infos = api.volume.get_list(dataset_id, filters=[{'field': 'id', 'operator': '=', 'value': '19581135'}])
print(filtered_volume_infos)
# Output: [VolumeInfo(id=19581135, ...)]
get_list_all_pages(method, data, progress_cb=None, convert_json_info_cb=None, limit=None, return_first_response=False)

Get list of all or limited quantity entities from the Supervisely server.

Parameters
method : str

Request method name

data : dict

Dictionary with request body info

progress_cb : Progress, optional

Function for tracking download progress.

convert_json_info_cb : Callable, optional

Function for convert json info

limit : int, optional

Number of entity to retrieve

return_first_response : bool, optional

Specify if return first response

get_list_all_pages_generator(method, data, progress_cb=None, convert_json_info_cb=None, limit=None, return_first_response=False)

This generator function retrieves a list of all or a limited quantity of entities from the Supervisely server, yielding batches of entities as they are retrieved

Parameters
method : str

Request method name

data : dict

Dictionary with request body info

progress_cb : Progress, optional

Function for tracking download progress.

convert_json_info_cb : Callable, optional

Function for convert json info

limit : int, optional

Number of entity to retrieve

return_first_response : bool, optional

Specify if return first response

static info_sequence()[source]

Get list of all VolumeInfo field names.

Returns

List of VolumeInfo field names.`

Return type

list

static info_tuple_name()[source]

Get string name of VolumeInfo NamedTuple.

Returns

NamedTuple name.

Return type

str

remove(id)

Remove an entity with the specified ID from the Supervisely server.

Parameters
id : int

Entity ID in Supervisely.

Usage example
import supervisely as sly

# You can connect to API directly
address = 'https://app.supervise.ly/'
token = 'Your Supervisely API Token'
api = sly.Api(address, token)

# Or you can use API from environment
os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()


image_id = 19369643
api.image.remove(image_id)
remove_batch(ids, progress_cb=None, batch_size=50)

Remove entities in batches from the Supervisely server.

Parameters
ids : List[int]

IDs of entities in Supervisely.

progress_cb : Callable

Function for control remove progress.

Usage example
import supervisely as sly

# You can connect to API directly
address = 'https://app.supervise.ly/'
token = 'Your Supervisely API Token'
api = sly.Api(address, token)

# Or you can use API from environment
os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()


image_ids = [19369645, 19369646, 19369647]
api.image.remove_batch(image_ids)
upload_dicom_serie_paths(dataset_id, name, paths, log_progress=True, anonymize=True)[source]

Upload given DICOM series from given paths to Dataset.

Parameters
dataset_id : int

Dataset ID in Supervisely.

name : str

Volume name with extension.

paths : List[str]

Local volumes paths.

log_progress : bool, optional

Determine if logs are displaying.

anonymize : bool, optional

Determine whether to hide PatientID and PatientName fields.

Returns

Information about Volume. See info_sequence

Return type

VolumeInfo

Usage example
import supervisely as sly

os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()


dicom_dir_name = "src/upload/MRHead_dicom/"
series_infos = sly.volume.inspect_dicom_series(root_dir=dicom_dir_name)

for serie_id, files in series_infos.items():
    item_path = files[0]
    name = f"{sly.fs.get_file_name(path=item_path)}.nrrd"
    dicom_info = api.volume.upload_dicom_serie_paths(
        dataset_id=dataset.id,
        name=name,
        paths=files,
        anonymize=True,
    )
    print(f"DICOM volume has been uploaded to Supervisely with ID: {dicom_info.id}")

# Output:
# DICOM volume has been uploaded to Supervisely with ID: 18630608
upload_hash(dataset_id, name, hash, meta=None)[source]

Upload Volume from given hash to Dataset.

Parameters
dataset_id : int

Dataset ID in Supervisely.

name : str

Volume name.

hash : str

Volume hash.

meta : dict

A dictionary containing data associated with the volume.

Returns

Information about Volume. See info_sequence

Return type

VolumeInfo

Usage example
import supervisely as sly

os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()

dst_dataset_id = 61958
src_volume_id = 19581134
volume_info = api.volume.get_info_by_id(src_volume_id)
hash = volume_info.hash
# It is necessary to upload volume with the same extention as in src dataset
name = volume_info.name
meta = volume_info.meta
new_volume_info = api.volume.upload_hash(dst_dataset_id, name, hash, meta)
print(new_volume_info)
# Output:
# VolumeInfo(
#     id=19613940,
#     name='CTACardio.nrrd',
#     link=None,
#     hash='+0K2oFHpqA5dwRKQlh5bDUA0jkPsEE52cs=',
#     mime=None,
#     ext=None,
#     sizeb=67614735,
#     created_at='2023-03-29T12:30:37.078Z',
#     updated_at='2023-03-29T12:30:37.078Z',
#     meta={
#         'ACS': 'RAS',
#         'intensity': {'max': 3532, 'min': -1024},
#         'windowWidth': 4556,
#         'rescaleSlope': 1,
#         'windowCenter': 1254,
#         'channelsCount': 1,
#         'dimensionsIJK': {'x': 512, 'y': 512, 'z': 321}
#         'IJK2WorldMatrix': [0.9335939999999999, 0, 0, -238.53326699999997, 0, 0.9335939999999999, 0, -238.53326699999994, 0, 0, 1.25, -200.0000000000001, 0, 0, 0, 1],
#         'rescaleIntercept': 0
#     },
#     path_original='/h5af-public/images/original/M/e/7R/zfsfX0p.nrrd',
#     full_storage_url='https://dev.supervise.ly/h5un-public/images/original/M/e/7R/zXdd0p.nrrd',
#     tags=[],
#     team_id=435,
#     workspace_id=685,
#     project_id=18949,
#     dataset_id=61958,
#     file_meta={
#             'mime': 'image/nrrd',
#             'size': 46073411,
#             'type': 'int32',
#             'extra': {'stride': [1, 512, 262144],
#             'comments': []
#         }
#         'sizes': [512, 512, 139]
#         'space': 'right-anterior-superior'
#         'endian': 'little'
#         'encoding': 'gzip'
#         'dimension': 3
#         'space origin': [-194.238403081894, -217.5384061336518, -347.7500000000001]
#         'space dimension': 3
#         'space directions': [[0.7617189884185793, 0, 0], [0, 0.7617189884185793, 0], [0, 0, 2.5]]
#     }
#     figures_count=None,
#     objects_count=None,
#     processing_path='1/1560071'
# )
upload_hashes(dataset_id, names, hashes, progress_cb=None, metas=None)[source]

Upload Volumes from given hashes to Dataset.

Parameters
dataset_id : int

Dataset ID in Supervisely.

names : List[str]

Volumes names.

hashes : List[str]

Volumes hashes.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

metas : List[dict], optional

Volumes metadata.

Returns

List with information about Volumes. See info_sequence

Return type

List[VolumeInfo]

Usage example
import supervisely as sly
from tqdm import tqdm

os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()

src_dataset_id = 61958
dst_dataset_id = 55853

hashes = []
names = []
metas = []
volume_infos = api.volume.get_list(src_dataset_id)

# Create lists of hashes, volumes names and meta information for each volume
for volume_info in volume_infos:
    hashes.append(volume_info.hash)
    # It is necessary to upload volumes with the same names(extentions) as in src dataset
    names.append(volume_info.name)
    metas.append(volume_info.meta)

p = tqdm(desc="api.volume.upload_hashes", total=len(hashes))
new_volumes_info = api.volume.upload_hashes(
    dataset_id=dst_dataset_id,
    names=names,
    hashes=hashes,
    progress_cb=p,
    metas=metas,
)

# Output:
# {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Volumes upload: ", "current": 0, "total": 2, "timestamp": "2023-04-04T07:47:11.506Z", "level": "info"}
# {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Volumes upload: ", "current": 2, "total": 2, "timestamp": "2023-04-04T07:47:11.563Z", "level": "info"}
upload_np(dataset_id, name, np_data, meta, progress_cb=None, batch_size=30)[source]

Upload given Volume in numpy format with given name to Dataset.

Parameters
dataset_id : int

Dataset ID in Supervisely.

name : str

Volume name with extension.

np_data : np.ndarray

image in RGB format(numpy matrix)

meta : dict, optional

Volume metadata.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

Returns

Information about Volume. See info_sequence

Return type

VolumeInfo

Usage example
import supervisely as sly

os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()

np_volume, meta = sly.volume.read_nrrd_serie_volume_np(local_path)
nrrd_info_np = api.volume.upload_np(
    dataset.id,
    "MRHead_np.nrrd",
    np_volume,
    meta,
)
print(f"Volume uploaded as NumPy array to Supervisely with ID:{nrrd_info_np.id}")

# Output:
# Volume uploaded as NumPy array to Supervisely with ID:18562982
upload_nrrd_serie_path(dataset_id, name, path, log_progress=True)[source]

Upload NRRD format volume from given path to Dataset.

Parameters
dataset_id : int

Dataset ID in Supervisely.

name : str

Volume name with extension.

path : str

Local volume path.

log_progress : bool, optional

Determine if logs are displaying.

Returns

Information about Volume. See info_sequence

Return type

VolumeInfo

Usage example
import supervisely as sly

os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()


local_path = "src/upload/nrrd/MRHead.nrrd"

nrrd_info = api.volume.upload_nrrd_serie_path(
    dataset.id,
    "MRHead.nrrd",
    local_path,
)
print(f'"{nrrd_info.name}" volume uploaded to Supervisely with ID:{nrrd_info.id}')

# Output:
# "NRRD_1.nrrd" volume uploaded to Supervisely with ID:18562981
upload_nrrd_series_paths(dataset_id, names, paths, progress_cb=None, log_progress=True)[source]

Upload NRRD format volumes from given paths to Dataset.

Parameters
dataset_id : int

Dataset ID in Supervisely.

names : List[str]

Volumes names with extensions.

paths : List[str]

Local volumes paths.

log_progress : bool, optional

Determine if logs are displaying.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

Returns

Information about Volume. See info_sequence

Return type

VolumeInfo

Usage example
import supervisely as sly

os.environ['SERVER_ADDRESS'] = 'https://app.supervise.ly'
os.environ['API_TOKEN'] = 'Your Supervisely API Token'
api = sly.Api.from_env()


local_dir_name = "src/upload/nrrd/"
all_nrrd_names = os.listdir(local_dir_name)
names = [f"1_{name}" for name in all_nrrd_names]
paths = [os.path.join(local_dir_name, name) for name in all_nrrd_names]

volume_infos = api.volume.upload_nrrd_series_paths(dataset.id, names, paths)
print(f"All volumes has been uploaded with IDs: {[x.id for x in volume_infos]}")

# Output:
# All volumes has been uploaded with IDs: [18630605, 18630606, 18630607]