AnnotationApi

class AnnotationApi(api)[source]

Bases: ModuleApi

API for working with image annotations.

Parameters:
api

Api object to use for API connection.

Usage Example:
import supervisely as sly
api = sly.Api.from_env()
ann_infos = api.annotation.get_list(dataset_id=254737)

Methods

append_labels

Append labels to image with given ID in API.

append_labels_group

Append group of labels to corresponding multiview images.

convert_info_to_json

Convert information about an entity to a dictionary.

copy

Copy annotation from one image ID to another image ID in API.

copy_batch

Copy annotations from one images IDs to another in API.

copy_batch_by_ids

Copy annotations from one images IDs to another images IDs in API.

download

Download AnnotationInfo by image ID from API.

download_async

Download AnnotationInfo by image ID from API.

download_batch

Get list of AnnotationInfos for given dataset ID from API.

download_batch_async

Get list of AnnotationInfos for given dataset ID from API.

download_bulk_async

Get list of AnnotationInfos for given dataset ID from API.

download_json

Download Annotation in json format by image ID from API.

download_json_batch

Get list of AnnotationInfos for given dataset ID from API.

exists

exists

get_free_name

get_free_name

get_info_by_id

get_info_by_id

get_info_by_name

get_info_by_name

get_label_by_id

Returns Supervisely Label object by it's ID.

get_list

Get list of information about all annotations for a given dataset.

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

get_list_generator

Get list of information about all annotations for a given dataset.

get_list_idx_page_async

Get the list of items for a given page number.

get_list_page_generator_async

Yields list of images in dataset asynchronously page by page.

info_sequence

NamedTuple AnnotationInfo information about Annotation.

info_tuple_name

NamedTuple name - AnnotationInfo.

update_label

Updates label with given ID in Supervisely with new Label object.

update_label_priority

Updates label's priority with given ID in Supervisely.

upload_ann

Loads an Annotation to a given image ID in the API.

upload_anns

Loads Annotation objects to given image IDs in the API.

upload_anns_async

Optimized method for uploading annotations to images in large batches.

upload_anns_fast

Upload annotations to images in a dataset using optimized method.

upload_json

Loads an annotation from dict to a given image ID in the API.

upload_jsons

Loads an annotations from dicts to a given images IDs in the API.

upload_path

Loads an annotation from a given path to a given image ID in the API.

upload_paths

Loads an annotations from a given paths to a given images IDs in the API.

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 AnnotationInfo

classmethod convert_info_to_json(info)

Convert information about an entity to a dictionary.

Parameters:
info : NamedTuple

Information about the entity.

Returns:

Dictionary with information about the entity.

Return type:

dict

static info_sequence()[source]

NamedTuple AnnotationInfo information about Annotation.

Usage Example:
AnnotationInfo(
    image_id=121236919,
    image_name="IMG_1836",
    annotation={
        "description": "",
        "tags": [],
        "size": {"height": 800, "width": 1067},
        "objects": [],
    },
    created_at="2019-12-19T12:06:59.435Z",
    updated_at="2021-02-06T11:07:26.080Z",
)
static info_tuple_name()[source]

NamedTuple name - AnnotationInfo.

append_labels(image_id, labels, skip_bounds_validation=False)[source]

Append labels to image with given ID in API.

Parameters:
image_id : int

Image ID to append labels.

labels

List of labels to append.

Returns:

None

Return type:

None

append_labels_group(dataset_id, image_ids, labels, project_meta=None, group_name=None)[source]

Append group of labels to corresponding multiview images. This method will automatically add a tech tag to the labels to group them together. Please note that grouped labels is supported only in images project with multiview setup.

Parameters:
dataset_id : int

Dataset ID in Supervisely.

image_ids : List[int]

List of Images IDs in Supervisely.

labels

List of Labels in Supervisely.

project_meta=None

Project meta. If not provided, will try to get it from the server.

group_name : str, optional

Group name. Labels will be assigned by tag with this value.

Returns:

None

Return type:

None

Raises:

ValueError – if number of images and labels are not the same

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()

dataset_id = 123456
paths = ['path/to/audi_01.png', 'path/to/audi_02.png']
images_group_name = 'audi'

image_infos = api.image.upload_multiview_images(dataset_id, images_group_name, paths)

image_ids = [info.id for info in image_infos]
labels = [label1, label2]
labels_group_name = 'left_wheel'

# Upload group of labels to corresponding multiview images
api.annotation.append_labels_group(dataset_id, image_ids, labels, group_name=labels_group_name)
copy(src_image_id, dst_image_id, force_metadata_for_links=True, skip_bounds_validation=False)[source]

Copy annotation from one image ID to another image ID in API.

Parameters:
src_image_id : int

Image ID in Supervisely.

dst_image_id : int

Image ID in Supervisely.

Returns:

None

Return type:

None

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()

src_id = 121236918
dst_id = 547837053
api.annotation.copy(src_id, dst_id)
copy_batch(src_image_ids, dst_image_ids, progress_cb=None, force_metadata_for_links=True, skip_bounds_validation=False)[source]

Copy annotations from one images IDs to another in API.

Parameters:
src_image_ids : List[int]

Images IDs in Supervisely.

dst_image_ids : List[int]

Unique IDs of images in API.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

Raises:

RuntimeError – if len(src_image_ids) != len(dst_image_ids)

Returns:

None

Return type:

None

Usage Example:
import os
from tqdm import tqdm
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()

src_ids = [121236918, 121236919]
dst_ids = [547837053, 547837054]
p = tqdm(desc="Annotations copy: ", total=len(src_ids))

copy_anns = api.annotation.copy_batch(src_ids, dst_ids, progress_cb=p)
# Output:
# {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Annotations copy: ", "current": 0, "total": 2, "timestamp": "2021-03-16T15:24:31.286Z", "level": "info"}
# {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Annotations copy: ", "current": 2, "total": 2, "timestamp": "2021-03-16T15:24:31.288Z", "level": "info"}
copy_batch_by_ids(src_image_ids, dst_image_ids, batch_size=50, save_source_date=True)[source]

Copy annotations from one images IDs to another images IDs in API.

Parameters:
src_image_ids : List[int]

Images IDs in Supervisely.

dst_image_ids : List[int]

Images IDs in Supervisely.

Returns:

None

Return type:

None

Raises:

RuntimeError – if len(src_image_ids) != len(dst_image_ids)

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()

src_ids = [121236918, 121236919]
dst_ids = [547837053, 547837054]
api.annotation.copy_batch_by_ids(src_ids, dst_ids)
download(image_id, with_custom_data=False, force_metadata_for_links=True, figure_filters=None)[source]

Download AnnotationInfo by image ID from API.

Parameters:
image_id : int

Image ID in Supervisely.

with_custom_data : bool, optional

Include custom data in the response.

Force metadata for links.

figure_filters : List[Dict[str, Any]], optional

Optional figure filters applied to labels in the downloaded annotation. Uses the same filter format as images.list. See https://api.docs.supervisely.com/#tag/Figures/paths/~1figures.list/get for more details.

Returns:

Information about Annotation.

Return type:

AnnotationInfo

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()

image_id = 121236918
ann_info = api.annotation.download(image_id)
print(json.dumps(ann_info, indent=4))
# Output: [
#     121236918,
#     "IMG_0748.jpeg",
#     {
#         "description": "",
#         "tags": [],
#         "size": {
#             "height": 800,
#             "width": 1067
#         },
#         "objects": []
#     },
#     "2019-12-19T12:06:59.435Z",
#     "2021-02-06T11:07:26.080Z"
# ]
async download_async(image_id, semaphore=None, with_custom_data=False, force_metadata_for_links=True, progress_cb=None, progress_cb_type='number', figure_filters=None)[source]

Download AnnotationInfo by image ID from API.

Parameters:
image_id : int

Image ID in Supervisely.

semaphore : asyncio.Semaphore, optional

Semaphore for limiting the number of simultaneous downloads.

with_custom_data : bool, optional

Include custom data in the response.

Force metadata for links.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

progress_cb_type : str, optional

Type of progress callback. Can be “number” or “size”. Default is “number”.

figure_filters : List[Dict[str, Any]], optional

Optional figure filters applied to labels in the downloaded annotation. Uses the same filter format as images.list. See https://api.docs.supervisely.com/#tag/Figures/paths/~1figures.list/get for more details.

Returns:

Information about Annotation.

Return type:

AnnotationInfo

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()

image_id = 121236918
loop = sly.utils.get_or_create_event_loop()
ann_info = loop.run_until_complete(api.annotation.download_async(image_id))

filtered_ann_info = loop.run_until_complete(
    api.annotation.download_async(
        image_id,
        figure_filters=[{"type": "objects_class", "data": {"from": 1, "to": 9999, "include": True, "classId": 123}}],
    )
)
download_batch(dataset_id, image_ids, progress_cb=None, with_custom_data=False, force_metadata_for_links=True, figure_filters=None)[source]

Get list of AnnotationInfos for given dataset ID from API.

Parameters:
dataset_id : int

Dataset ID in Supervisely.

image_ids : List[int]

List of integers.

progress_cb : tqdm

Function for tracking download progress.

with_custom_data : bool, optional

Include custom data in the response.

Force metadata for links.

figure_filters : List[Dict[str, Any]], optional

Optional figure filters applied to labels in downloaded annotations. Uses the same filter format as images.list. See https://api.docs.supervisely.com/#tag/Figures/paths/~1figures.list/get for more details.

Returns:

Information about Annotations.

Return type:

List[AnnotationInfo]

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()

dataset_id = 254737
image_ids = [121236918, 121236919]
p = tqdm(desc="Annotations downloaded: ", total=len(image_ids))

ann_infos = api.annotation.download_batch(dataset_id, image_ids, progress_cb=p)
# Output:
# {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Annotations downloaded: ", "current": 0, "total": 2, "timestamp": "2021-03-16T15:20:06.168Z", "level": "info"}
# {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Annotations downloaded: ", "current": 2, "total": 2, "timestamp": "2021-03-16T15:20:06.510Z", "level": "info"}

Optimizing the download process by using the context to avoid redundant API calls.:
# 1. Download the project meta
project_id = api.dataset.get_info_by_id(dataset_id).project_id
project_meta = api.project.get_meta(project_id)

# 2. Use the context to avoid redundant API calls
dataset_id = 254737
image_ids = [121236918, 121236919]
with sly.ApiContext(api, dataset_id=dataset_id, project_id=project_id, project_meta=project_meta):
ann_infos = api.annotation.download_batch(dataset_id, image_ids)
async download_batch_async(dataset_id, image_ids, semaphore=None, with_custom_data=False, force_metadata_for_links=True, progress_cb=None, progress_cb_type='number', figure_filters=None)[source]

Get list of AnnotationInfos for given dataset ID from API.

Parameters:
dataset_id : int

Dataset ID in Supervisely.

image_ids : List[int]

List of integers.

semaphore : asyncio.Semaphore, optional

Semaphore for limiting the number of simultaneous downloads.

with_custom_data : bool, optional

Include custom data in the response.

Force metadata for links.

progress_cb : tqdm or callable, optional

Function for tracking download progress. Total should be equal to len(image_ids) or None.

progress_cb_type : str, optional

Type of progress callback. Can be “number” or “size”. Default is “number”.

figure_filters : List[Dict[str, Any]], optional

Optional figure filters applied to labels in downloaded annotations. Uses the same filter format as images.list. See https://api.docs.supervisely.com/#tag/Figures/paths/~1figures.list/get for more details.

Returns:

Information about Annotations.

Return type:

List[AnnotationInfo]

Usage Example:
import os
from tqdm import tqdm
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()

dataset_id = 254737
image_ids = [121236918, 121236919]
pbar = tqdm(desc="Download annotations", total=len(image_ids))

loop = sly.utils.get_or_create_event_loop()
ann_infos = loop.run_until_complete(
                api.annotation.download_batch_async(dataset_id, image_ids, progress_cb=pbar)
            )

filtered_ann_infos = loop.run_until_complete(
    api.annotation.download_batch_async(
        dataset_id,
        image_ids,
        figure_filters=[{"type": "objects_class", "data": {"from": 1, "to": 9999, "include": True, "classId": 123}}],
    )
)
async download_bulk_async(dataset_id, image_ids, progress_cb=None, with_custom_data=False, force_metadata_for_links=True, semaphore=None, figure_filters=None)[source]

Get list of AnnotationInfos for given dataset ID from API. This method is optimized for downloading a large number of small size annotations with a single API call.

Parameters:
dataset_id : int

Dataset ID in Supervisely.

image_ids : List[int]

List of integers.

progress_cb : tqdm

Function for tracking download progress.

with_custom_data : bool, optional

Include custom data in the response.

Force metadata for links.

semaphore : asyncio.Semaphore, optional

Semaphore for limiting the number of simultaneous downloads.

figure_filters : List[Dict[str, Any]], optional

Optional figure filters applied to labels in downloaded annotations. Uses the same filter format as images.list. See https://api.docs.supervisely.com/#tag/Figures/paths/~1figures.list/get for more details.

Returns:

Information about Annotations.

Return type:

List[AnnotationInfo]

Usage Example:
import os
from tqdm import tqdm
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()

dataset_id = 254737
image_ids = [121236918, 121236919]
p = tqdm(desc="Annotations downloaded: ", total=len(image_ids))

ann_infos = await api.annotation.download_bulk_async(dataset_id, image_ids, progress_cb=p)

filtered_ann_infos = await api.annotation.download_bulk_async(
    dataset_id,
    image_ids,
    figure_filters=[{"type": "objects_class", "data": {"from": 1, "to": 9999, "include": True, "classId": 123}}],
)

# Optimizing the download process by using the context to avoid redundant API calls:
# 1. Download the project meta
project_id = api.dataset.get_info_by_id(dataset_id).project_id
project_meta = api.project.get_meta(project_id)

# 2. Use the context to avoid redundant API calls
dataset_id = 254737
image_ids = [121236918, 121236919]
with sly.ApiContext(api, dataset_id=dataset_id, project_id=project_id, project_meta=project_meta):
ann_infos = await api.annotation.download_bulk_async(dataset_id, image_ids)
download_json(image_id, with_custom_data=False, force_metadata_for_links=True, figure_filters=None)[source]

Download Annotation in json format by image ID from API.

Parameters:
image_id : int

Image ID in Supervisely.

with_custom_data : bool, optional

Include custom data in the response.

Force metadata for links.

figure_filters : List[Dict[str, Any]], optional

Optional figure filters applied to labels in the downloaded annotation. Uses the same filter format as images.list. See https://api.docs.supervisely.com/#tag/Figures/paths/~1figures.list/get for more details.

Returns:

Annotation in json format

Return type:

dict

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()

image_id = 121236918
ann_json = api.annotation.download_json(image_id)
print(ann_json)
# Output: {
#         "description": "",
#         "tags": [],
#         "size": {
#             "height": 800,
#             "width": 1067
#         },
#         "objects": []
#     }

filtered_ann_json = api.annotation.download_json(
    image_id,
    figure_filters=[{"type": "objects_class", "data": {"from": 1, "to": 9999, "include": True, "classId": 123}}],
)
download_json_batch(dataset_id, image_ids, progress_cb=None, force_metadata_for_links=True, figure_filters=None)[source]

Get list of AnnotationInfos for given dataset ID from API.

Parameters:
dataset_id : int

Dataset ID in Supervisely.

image_ids : List[int]

List of integers.

progress_cb : tqdm

Function for tracking download progress.

Force metadata for links.

figure_filters : List[Dict[str, Any]], optional

Optional figure filters applied to labels in downloaded annotations. Uses the same filter format as images.list. See https://api.docs.supervisely.com/#tag/Figures/paths/~1figures.list/get for more details.

Returns:

Information about Annotations.

Return type:

List[AnnotationInfo]

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()

dataset_id = 254737
image_ids = [121236918, 121236919]
p = tqdm(desc="Annotations downloaded: ", total=len(image_ids))

anns_jsons = api.annotation.download_json_batch(dataset_id, image_ids, progress_cb=p)
# Output:
# {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Annotations downloaded: ", "current": 0, "total": 2, "timestamp": "2021-03-16T15:20:06.168Z", "level": "info"}
# {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Annotations downloaded: ", "current": 2, "total": 2, "timestamp": "2021-03-16T15:20:06.510Z", "level": "info"}

filtered_anns_jsons = api.annotation.download_json_batch(
    dataset_id,
    image_ids,
    figure_filters=[{"type": "objects_class", "data": {"from": 1, "to": 9999, "include": True, "classId": 123}}],
)
exists(parent_id, name)[source]
get_free_name(parent_id, name)[source]
get_info_by_id(id)[source]
get_info_by_name(parent_id, name)[source]
get_label_by_id(label_id, project_meta, with_tags=True)[source]

Returns Supervisely Label object by it’s ID.

Parameters:
label_id : int

ID of the label to get

project_meta

Supervisely ProjectMeta object

with_tags : bool, optional

If True, tags will be added to the Label object

Returns:

Label object

Return type:

Label

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()

label_id = 121236918

project_id = 254737
project_meta = sly.ProjectMeta.from_json(api.project.get_meta(project_id))

label = api.annotation.get_label_by_id(label_id, project_meta)
get_list(dataset_id, filters=None, progress_cb=None, force_metadata_for_links=True)[source]

Get list of information about all annotations for a given dataset.

Parameters:
dataset_id : int

Dataset ID in Supervisely.

filters : List[dict], optional

List of parameters to sort output Annotations.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

Returns:

Information about Annotations.

Return type:

List[AnnotationInfo]

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()

dataset_id = 254737
ann_infos = api.annotation.get_list(dataset_id)
print(json.dumps(ann_infos[0], indent=4))
# Output: [
#     121236918,
#     "IMG_0748.jpeg",
#     {
#         "description": "",
#         "tags": [],
#         "size": {
#             "height": 800,
#             "width": 1067
#         },
#         "objects": []
#     },
#     "2019-12-19T12:06:59.435Z",
#     "2021-02-06T11:07:26.080Z"
# ]

ann_infos_filter = api.annotation.get_list(dataset_id, filters={ 'field': 'name', 'operator': '=', 'value': 'IMG_1836' })
print(json.dumps(ann_infos_filter, indent=4))
# Output: [
#     121236919,
#     "IMG_1836",
#     {
#         "description": "",
#         "tags": [],
#         "size": {
#             "height": 800,
#             "width": 1067
#         },
#         "objects": []
#     },
#     "2019-12-19T12:06:59.435Z",
#     "2021-02-06T11:07:26.080Z"
# ]
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

Returns:

List of entities.

Return type:

List[dict]

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

get_list_generator(dataset_id, filters=None, progress_cb=None, batch_size=50, force_metadata_for_links=True)[source]

Get list of information about all annotations for a given dataset.

Parameters:
dataset_id : int

Dataset ID in Supervisely.

filters : List[dict], optional

List of parameters to sort output Annotations.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

Returns:

Information about Annotations.

Return type:

List[AnnotationInfo]

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()

dataset_id = 254737
ann_infos = api.annotation.get_list_generator(dataset_id)
print(json.dumps(ann_infos[0], indent=4))
# Output: [
#     121236918,
#     "IMG_0748.jpeg",
#     {
#         "description": "",
#         "tags": [],
#         "size": {
#             "height": 800,
#             "width": 1067
#         },
#         "objects": []
#     },
#     "2019-12-19T12:06:59.435Z",
#     "2021-02-06T11:07:26.080Z"
# ]

ann_infos_filter = api.annotation.get_list_generator(dataset_id, filters={ 'field': 'name', 'operator': '=', 'value': 'IMG_1836' })
print(json.dumps(ann_infos_filter, indent=4))
# Output: [
#     121236919,
#     "IMG_1836",
#     {
#         "description": "",
#         "tags": [],
#         "size": {
#             "height": 800,
#             "width": 1067
#         },
#         "objects": []
#     },
#     "2019-12-19T12:06:59.435Z",
#     "2021-02-06T11:07:26.080Z"
# ]
async get_list_idx_page_async(method, data)

Get the list of items for a given page number. Page number is specified in the data dictionary.

Parameters:
method : str

Method to call for listing items.

data : dict

Data to pass to the API method.

Returns:

List of items.

Return type:

Tuple[int, List[NamedTuple]]

async get_list_page_generator_async(method, data, pages_count=None, semaphore=None)

Yields list of images in dataset asynchronously page by page.

Parameters:
method : str

Method to call for listing items.

data : dict

Data to pass to the API method.

pages_count : int, optional

Preferred number of pages to retrieve if used with a per_page limit. Will be automatically adjusted if the pagesCount differs from the requested number.

semaphore=None

Semaphore for limiting the number of simultaneous requests.

Returns:

List of images in dataset.

Return type:

AsyncGenerator[List[ImageInfo]]

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()

method = 'images.list'
data = {'datasetId': 123456}

loop = sly.utils.get_or_create_event_loop()
images = loop.run_until_complete(api.image.get_list_generator_async(method, data))
update_label(label_id, label)[source]

Updates label with given ID in Supervisely with new Label object.

NOTE: This method only updates label’s geometry and tags, not class title, etc.

Parameters:
label_id : int

ID of the label to update

label

Label object

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()

new_label: sly.Label
label_id = 121236918

api.annotation.update_label(label_id, new_label)
update_label_priority(label_id, priority)[source]

Updates label’s priority with given ID in Supervisely. Priority increases with the number: a higher number indicates a higher priority. The higher priority means that the label will be displayed on top of the others. The lower priority means that the label will be displayed below the others.

Parameters:
label_id : int

ID of the label to update

priority : int

New priority of the label

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()

label_ids = [123, 456, 789]
priorities = [1, 2, 3]

for label_id, priority in zip(label_ids, priorities):
api.annotation.update_label_priority(label_id, priority)

# The label with ID 789 will be displayed on top of the others.
# The label with ID 123 will be displayed below the others.
upload_ann(img_id, ann, skip_bounds_validation=False)[source]

Loads an Annotation to a given image ID in the API.

Parameters:
img_id : int

Image ID in Supervisely.

ann

Annotation object.

Returns:

None

Return type:

None

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()

image_id = 121236918
upl_ann = api.annotation.upload_ann(image_id, ann)
upload_anns(img_ids, anns, progress_cb=None, skip_bounds_validation=False)[source]

Loads Annotation objects to given image IDs in the API. Image IDs must be from one dataset.

Parameters:
img_ids : List[int]

Image ID in Supervisely.

anns

List of Annotation objects.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

Returns:

None

Return type:

None

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()

img_ids = [121236918, 121236919]
upl_anns = api.annotation.upload_anns(img_ids, [ann1, ann2])

# Optimizing the upload process by using the context to avoid redundant API calls.
# Usefull when uploading a large number of annotations in one dataset.
# 1. Download the project meta
dataset_id = 254737
project_id = api.dataset.get_info_by_id(dataset_id).project_id
project_meta = api.project.get_meta(project_id)

# 2. Use the context to avoid redundant API calls
with sly.ApiContext(api, dataset_id=dataset_id, project_id=project_id, project_meta=project_meta):
api.annotation.upload_anns(img_ids, [ann1, ann2])
async upload_anns_async(image_ids, anns, dataset_id=None, log_progress=True, semaphore=None)[source]

Optimized method for uploading annotations to images in large batches. This method significantly improves performance when uploading large numbers of annotations by processing different components in parallel batches.

IMPORTANT: If you pass anns as a generator, you must be sure that the generator will yield the same number of annotations as the number of image IDs provided.

The method works by: 1. Separating regular figures and alpha masks for specialized processing 2. Batching figure creation requests to reduce API overhead 3. Processing image-level tags, object tags, and geometries separately 4. Using concurrent async operations to maximize throughput 5. Processing alpha mask geometries with specialized upload method

This approach can be faster than traditional sequential upload methods when dealing with large annotation batches.

Parameters:
image_ids : List[int]

List of image IDs in Supervisely.

anns

List of annotations to upload. Can be a generator or a list.

dataset_id : int, optional

Dataset ID. If None, will be determined from image IDs or context.

log_progress : bool, optional

Whether to log progress information.

semaphore : asyncio.Semaphore, optional

Semaphore to control concurrency level. If None, a default will be used.

Returns:

None

Return type:

None

Usage Example:
import os
import asyncio
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()

# Prepare your annotations and image IDs
image_ids = [121236918, 121236919]
anns = [annotation1, annotation2]

# Option 1: Using the synchronous wrapper
api.annotation.upload_anns_fast(image_ids, anns)

# Option 2: Using the async method directly
upload_annotations = api.annotation.upload_anns_async(
        image_ids,
        anns,
        semaphore=asyncio.Semaphore(10)  # Control concurrency
)

sly.run_coroutine(upload_annotations)
upload_anns_fast(image_ids, anns, dataset_id=None, log_progress=True)[source]

Upload annotations to images in a dataset using optimized method.

Parameters:
image_ids : List[int]

List of image IDs in Supervisely.

anns

List of Annotation objects.

dataset_id : int, optional

Dataset ID. If None, will be determined from image IDs or context.

log_progress : bool, optional

Whether to log progress information.

Returns:

None

Return type:

None

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()

dataset_id = 123456
image_ids = [121236918, 121236919]
anns = [annotation1, annotation2]
api.annotation.upload_fast(image_ids, anns, dataset_id)
upload_json(img_id, ann_json, skip_bounds_validation=False)[source]

Loads an annotation from dict to a given image ID in the API.

Parameters:
img_id : int

Image ID in Supervisely.

ann_json : dict

Annotation in JSON format.

Returns:

None

Return type:

None

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()

image_id = 121236918
upl_json = api.annotation.upload_json(image_id, ann_json)
upload_jsons(img_ids, ann_jsons, progress_cb=None, skip_bounds_validation=False)[source]

Loads an annotations from dicts to a given images IDs in the API. Images IDs must be from one dataset.

Parameters:
img_ids : List[int]

Image ID in Supervisely.

ann_jsons : List[dict]

Annotation in JSON format.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

Returns:

None

Return type:

None

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()

img_ids = [121236918, 121236919]
api.annotation.upload_jsons(img_ids, ann_jsons)

# Optimizing the upload process by using the context to avoid redundant API calls.
# Usefull when uploading a large number of annotations in one dataset.
# 1. Download the project meta
dataset_id = 254737
project_id = api.dataset.get_info_by_id(dataset_id).project_id
project_meta = api.project.get_meta(project_id)

# 2. Use the context to avoid redundant API calls
with sly.ApiContext(api, dataset_id=dataset_id, project_id=project_id, project_meta=project_meta):
api.annotation.upload_jsons(img_ids, ann_jsons)
upload_path(img_id, ann_path, skip_bounds_validation=False)[source]

Loads an annotation from a given path to a given image ID in the API.

Parameters:
img_id : int

Image ID in Supervisely.

ann_path : str

Path to annotation on host.

Returns:

None

Return type:

None

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()

image_id = 121236918
ann_path = '/home/admin/work/supervisely/example/ann.json'
upl_path = api.annotation.upload_path(image_id, ann_path)
upload_paths(img_ids, ann_paths, progress_cb=None, skip_bounds_validation=False)[source]

Loads an annotations from a given paths to a given images IDs in the API. Images IDs must be from one dataset.

Parameters:
img_ids : List[int]

Images IDs in Supervisely.

ann_paths : List[str]

Paths to annotations on local machine.

progress_cb : tqdm or callable, optional

Function for tracking download progress.

Returns:

None

Return type:

None

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()

img_ids = [121236918, 121236919]
ann_pathes = ['/home/admin/work/supervisely/example/ann1.json', '/home/admin/work/supervisely/example/ann2.json']
upl_paths = api.annotation.upload_paths(img_ids, ann_pathes)

# Optimizing the upload process by using the context to avoid redundant API calls.
# Usefull when uploading a large number of annotations in one dataset.
# 1. Download the project meta
dataset_id = 254737
project_id = api.dataset.get_info_by_id(dataset_id).project_id
project_meta = api.project.get_meta(project_id)

# 2. Use the context to avoid redundant API calls
with sly.ApiContext(api, dataset_id=dataset_id, project_id=project_id, project_meta=project_meta):
api.annotation.upload_paths(img_ids, ann_pathes)