ImageApi¶
- class ImageApi[source]¶
Bases:
supervisely.api.module_api.RemoveableBulkModuleApi
API for working with
Image
.ImageApi
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") image_info = api.image.get_info_by_id(image_id) # api usage example
Methods
Use this context manager to set the key name of meta object that will be used for custom sorting.
Add tag with given ID to Image by ID.
Add tag with given ID to Images by IDs.
Checks existing hashes for Images.
Checks existing links for Images.
Checks if Image has been uploaded.
_convert_info_to_json
Copies Image with given ID to destination Dataset.
Copies Images with given IDs to Dataset.
Copies Images with given IDs to Dataset.
Downloads Image from Dataset to local path by ID.
Downloads blob file from Supervisely storage by download ID of any Image that belongs to this file.
Downloads blob file from Supervisely storage by download ID asynchronously.
Downloads multiple blob files from Supervisely storage by download IDs asynchronously.
Download Images with given IDs from Dataset in Binary format.
Downloads Image bytes with given ID in batch asynchronously.
Downloads Images bytes with given IDs asynchronously and returns reults in the same order as in the input list.
Downloads Image bytes with given ID.
Download Image with given id in numpy format.
Downloads Image with given ID in NumPy format asynchronously.
Download Images with given IDs in numpy format.
Downloads Images with given IDs in NumPy format asynchronously.
Download Images with given hashes in Supervisely server in numpy format.
download_nps_by_hashes_generator
download_nps_generator
Downloads Image from Dataset to local path by ID.
Downloads Image with given ID to local path.
Download Images with given ids and saves them for the given paths.
Download Images with given IDs and saves them to given local paths asynchronously.
Download Images with given hashes in Supervisely server and saves them for the given paths.
Updates the information about the image by given ID with provided parameters.
Check if image with given name exists in dataset with given id.
Get file with blob images offsets from the team storage.
List of filtered Images in the given
Dataset
.Generates a free name for an entity with the given parent_id and name.
Returns list of free names for given dataset.
Get Image information by ID.
Get Images information by ID.
Returns image info by image name from given dataset id.
List of Images in the given
Dataset
.Get list of all or limited quantity entities from the Supervisely server.
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
Returns a generator that yields lists of images in the given
Dataset
orProject
.Yields list of images in dataset asynchronously page by page.
Get the list of items for a given page number.
Yields list of images in dataset asynchronously page by page.
Gets Project ID by Image ID.
Group images for multi-view by tag with given name.
Get list of all
ImageInfo
field names.Get string name of
ImageInfo
NamedTuple.Moves Image with given ID to destination Dataset.
Moves Images with given IDs to Dataset.
Moves Images with given IDs to Dataset.
Previews Image with the given resolution parameters.
Raises error if images with given names already exist in dataset.
Remove image from supervisely by id.
Remove images from supervisely by IDs.
Renames Image with given ID.
Sets custom sort value for image with given ID.
Sets custom sort values for images with given IDs.
This method helps to change local source to remote for images without re-uploading them as new.
Get full Image URL link in Supervisely server.
Updates a copy of the meta dictionary with a new custom sort value.
It is possible to add custom JSON data to every image for storing some additional information.
Update tag value with given ID.
Uploads images from blob file in Team Files to dataset.
Upload images from blob file in Team Files by offsets to Dataset with prepared names.
Upload images from blob file in Team Files by offsets to Dataset.
Uploads all images with supported extensions from given directory to Supervisely.
Uploads all images with supported extensions from given directories to Supervisely.
Upload Image from given hash to Dataset.
Upload images from given hashes to Dataset.
Upload Image by ID to Dataset.
Upload Images by IDs to Dataset.
Uploads Image from given link to Dataset.
Uploads Images from given links to Dataset.
Upload medical 2D images (DICOM) to Supervisely and group them by specified or default tag.
Uploads multispectral image to Supervisely, if channels are provided, they will be uploaded as separate images.
Uploads images to Supervisely and adds a tag to them.
Upload given Image in numpy format with given name to Dataset.
Upload given Images in numpy format with given names to Dataset.
Uploads Image with given name from given local path to Dataset.
Uploads Images with given names from given local path to Dataset.
Gets Image URL by ID.
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.ImageInfo
- add_custom_sort(key)[source]¶
Use this context manager to set the key name of meta object that will be used for custom sorting. This context manager allows you to set the
sort_by
attribute of ImageApi object for the duration of the context, then delete it. If nested functions support this functionality, each image they process will automatically receive a custom sorting parameter based on the available meta object.- Parameters
- key : str
It is a key name of meta object that will be used for sorting.
-
add_tag(image_id, tag_id, value=
None
)[source]¶ Add tag with given ID to Image by ID.
- Parameters
- Returns
None
- Return type
NoneType
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_id = 2389126 tag_id = 277083 api.image.add_tag(image_id, tag_id)
-
add_tag_batch(image_ids, tag_id, value=
None
, progress_cb=None
, batch_size=100
, tag_meta=None
)[source]¶ Add tag with given ID to Images by IDs.
- Parameters
- image_ids : List[int]
List of Images IDs in Supervisely.
- tag_id : int
Tag ID in Supervisely.
- value : int or str or None, optional
Tag value.
- progress_cb : tqdm or callable, optional
Function for tracking progress of adding tag.
- batch_size : int, optional
Batch size
- tag_meta : TagMeta, optional
Tag Meta. Needed for value validation, omit to skip validation
- Returns
None
- Return type
NoneType
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_ids = [2389126, 2389127] tag_id = 277083 api.image.add_tag_batch(image_ids, tag_id)
-
check_existing_hashes(hashes, progress_cb=
None
)[source]¶ Checks existing hashes for Images.
- Parameters
- hashes : List[str]
List of hashes.
- progress_cb : tqdm or callable, optional
Function for tracking progress of checking.
- Returns
List of existing hashes
- Return type
List[str]
- Usage example
Checkout detailed example here (you must be logged into your Supervisely account)
# Helpful method when your uploading was interrupted # You can check what images has been successfully uploaded by their hashes and what not # And continue uploading the rest of the images from that point import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() # Find project project = api.project.get_info_by_id(WORKSPACE_ID, PROJECT_ID) # Get paths of all images in a directory images_paths = sly.fs.list_files('images_to_upload') # Calculate hashes for all images paths hash_to_image = {} images_hashes = [] for idx, item in enumerate(images_paths): item_hash = sly.fs.get_file_hash(item) images_hashes.append(item_hash) hash_to_image[item_hash] = item # Get hashes that are already on server remote_hashes = api.image.check_existing_hashes(images_hashes) already_uploaded_images = {hh: hash_to_image[hh] for hh in remote_hashes}
-
check_existing_links(links, progress_cb=
None
, team_id=None
)[source]¶ Checks existing links for Images.
- check_image_uploaded(hash)[source]¶
Checks if Image has been uploaded.
- Parameters
- hash : str
Image hash in Supervisely.
- Returns
True if Image with given hash exist, otherwise False
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_check_uploaded = api.image.check_image_uploaded("YZKQrZH5C0rBvGGA3p7hjWahz3/pV09u5m30Bz8GeYs=") print(image_check_uploaded) # Output: True
-
copy(dst_dataset_id, id, change_name_if_conflict=
False
, with_annotations=False
)[source]¶ Copies Image with given ID to destination Dataset.
- Parameters
- dst_dataset_id : int
Destination Dataset ID in Supervisely.
- id : int
Image ID in Supervisely.
- change_name_if_conflict : bool, optional
If True adds suffix to the end of Image name when Dataset already contains an Image with identical name, If False and images with the identical names already exist in Dataset raises error.
- with_annotations : bool, optional
If True Image will be copied to Dataset with annotations, otherwise only Images without annotations.
- Returns
Information about Image. See
info_sequence
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() dst_ds_id = 365184 img_id = 121236920 img_info = api.image.copy(dst_ds_id, img_id, with_annotations=True)
-
copy_batch(dst_dataset_id, ids, change_name_if_conflict=
False
, with_annotations=False
, progress_cb=None
)[source]¶ Copies Images with given IDs to Dataset.
- Parameters
- dst_dataset_id : int
Destination Dataset ID in Supervisely.
- ids : List[int]
Images IDs in Supervisely.
- change_name_if_conflict : bool, optional
If True adds suffix to the end of Image name when Dataset already contains an Image with identical name, If False and images with the identical names already exist in Dataset raises error.
- with_annotations : bool, optional
If True Image will be copied to Dataset with annotations, otherwise only Images without annotations.
- progress_cb : tqdm or callable, optional
Function for tracking the progress of copying.
- Raises
TypeError
if type of ids is not list- Raises
ValueError
if images ids are from the destination Dataset- Returns
List with information about Images. See
info_sequence
- Return type
List[ImageInfo]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() ds_lemon_id = 1780 ds_lemon_img_infos = api.image.get_list(ds_lemon_id) lemons_img_ids = [lemon_img_info.id for lemon_img_info in ds_lemon_img_infos] ds_fruit_id = 2574 ds_fruit_img_infos = api.image.copy_batch(ds_fruit_id, lemons_img_ids, with_annotations=True)
-
copy_batch_optimized(src_dataset_id, src_image_infos, dst_dataset_id, with_annotations=
True
, progress_cb=None
, dst_names=None
, batch_size=500
, skip_validation=False
, save_source_date=True
)[source]¶ Copies Images with given IDs to Dataset.
- Parameters
- src_dataset_id : int
Source Dataset ID in Supervisely.
- src_image_infos : List [
ImageInfo
] ImageInfo objects of images to copy.
- dst_dataset_id : int
Destination Dataset ID in Supervisely.
- with_annotations : bool, optional
If True Image will be copied to Dataset with annotations, otherwise only Images without annotations.
- progress_cb : tqdm or callable, optional
Function for tracking the progress of copying.
- dst_names : List [
ImageInfo
], optional ImageInfo list with existing items in destination dataset.
- batch_size : int, optional
Number of elements to copy for each request.
- skip_validation : bool, optional
Flag for skipping additinal validations.
- save_source_date : bool, optional
Save source annotation dates (creation and modification) or create a new date.
- Raises
TypeError
if type of src_image_infos is not list- Returns
List with information about Images. See
info_sequence
- Return type
List[ImageInfo]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() src_ds_id = 2231 img_infos = api.image.get_list(src_ds_id) dest_ds_id = 2574 dest_img_infos = api.image.copy_batch_optimized(src_ds_id, img_infos, dest_ds_id)
- download(id, path)[source]¶
Downloads Image from Dataset to local path by ID.
- Parameters
- Returns
None
- Return type
NoneType
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_info = api.image.get_info_by_id(770918) save_path = os.path.join("/home/admin/work/projects/lemons_annotated/ds1/test_imgs/", img_info.name) api.image.download_path(770918, save_path)
-
download_blob_file(project_id, download_id, path=
None
, log_progress=True
, chunk_size=None
)[source]¶ Downloads blob file from Supervisely storage by download ID of any Image that belongs to this file.
- Parameters
- project_id : int
Project ID in Supervisely.
- download_id : str
Download ID of any Image that belongs to the blob file in Supervisely storage.
- path : str, optional
Path to save the blob file. If None, returns blob file content as bytes.
- progress_cb : tqdm or callable, optional
Function for tracking download progress.
- chunk_size : int, optional
Size of chunk for streaming. Default is 8 MB.
- Returns
Blob file content if path is None, otherwise None.
- Return type
bytes or None
- Usage example
api = sly.Api.from_env() image_id = 6789 image_info = api.image.get_info_by_id(image_id) project_id = api.dataset.get_info_by_id(image_info.dataset_id).project_id # Download and save to file api.image.download_blob_file(project_id, image_info.download_id, "/path/to/save/archive.tar") # Get archive as bytes archive_bytes = api.image.download_blob_file(project_id, image_info.download_id)
-
async download_blob_file_async(project_id, download_id, path, semaphore=
None
, log_progress=True
, progress_cb=None
)[source]¶ Downloads blob file from Supervisely storage by download ID asynchronously.
- Parameters
- project_id : int
Project ID in Supervisely.
- download_id : str
Download ID of any Image that belongs to the blob file in Supervisely storage.
- path : str
Path to save the blob file.
- semaphore : asyncio.Semaphore, optional
Semaphore for limiting the number of simultaneous downloads.
- log_progress : bool, optional
If True, shows progress bar.
- progress_cb : tqdm or callable, optional
Function for tracking download progress.
-
async download_blob_files_async(project_id, download_ids, paths, semaphore=
None
, log_progress=True
, progress_cb=None
)[source]¶ Downloads multiple blob files from Supervisely storage by download IDs asynchronously.
- Parameters
- project_id : int
Project ID in Supervisely.
- download_ids : List[str]
List of download IDs of any Image that belongs to the blob files in Supervisely storage.
- paths : List[str]
List of paths to save the blob files.
- semaphore : asyncio.Semaphore, optional
Semaphore for limiting the number of simultaneous downloads.
- log_progress : bool, optional
If True, shows progress bar.
- progress_cb : tqdm or callable, optional
Function for tracking download progress.
-
download_bytes(dataset_id, ids, progress_cb=
None
)[source]¶ Download Images with given IDs from Dataset in Binary format.
- Parameters
- Returns
List of Images in binary format
- Return type
List[bytes]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_bytes = api.image.download_bytes(dataset_id, [770918]) print(img_bytes) # Output: [b'ÿØÿàJFIF\ ...']
-
async download_bytes_generator_async(dataset_id, img_ids, semaphore=
None
, headers=None
, check_hash=False
, progress_cb=None
, progress_cb_type='number'
)[source]¶ Downloads Image bytes with given ID in batch asynchronously. Yields tuple of Image ID and bytes of downloaded image. Uses bulk download API method.
- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- img_ids :
List[int]
List of Image IDs in Supervisely.
- semaphore :
asyncio.Semaphore
, optional Semaphore for limiting the number of simultaneous downloads.
- headers : dict, optional
Headers for request.
- check_hash : bool, optional
If True, checks hash of downloaded bytes. Default is False.
- progress_cb : Optional[Union[tqdm, Callable]]
Function for tracking download progress.
- progress_cb_type : Literal["number", "size"], optional
Type of progress callback. Can be “number” or “size”. Default is “number”.
- Returns
Tuple of Image ID and bytes of downloaded image.
- Return type
Tuple[int, bytes]
- Usage example
import supervisely as sly import asyncio os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() dataset_id = 123456 img_ids = [770918, 770919, 770920, 770921, ... , 770992] tasks = [] for batch in batched(img_ids, 50): task = api.image.download_bytes_batch_async(dataset_id, batch) tasks.append(task) results = await asyncio.gather(*tasks)
-
async download_bytes_many_async(ids, semaphore=
None
, headers=None
, check_hash=True
, progress_cb=None
, progress_cb_type='number'
)[source]¶ Downloads Images bytes with given IDs asynchronously and returns reults in the same order as in the input list.
- Parameters
- ids :
List[int]
List of Image IDs in Supervisely.
- semaphore :
asyncio.Semaphore
, optional Semaphore for limiting the number of simultaneous downloads.
- headers : dict, optional
Headers for every request.
- check_hash : bool, optional
If True, checks hash of downloaded images.
- progress_cb : Optional[Union[tqdm, Callable]]
Function for tracking download progress.
- progress_cb_type : Literal["number", "size"], optional
Type of progress callback. Can be “number” or “size”. Default is “number”.
- ids :
- Returns
List of bytes of downloaded images.
- Return type
List[bytes]
- Usage example
import supervisely as sly import asyncio os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN api = sly.Api.from_env() loop = sly.utils.get_or_create_event_loop() semaphore = asyncio.Semaphore(100) img_bytes_list = loop.run_until_complete(api.image.download_bytes_imgs_async(ids, semaphore))
-
async download_bytes_single_async(id, semaphore=
None
, range_start=None
, range_end=None
, headers=None
, check_hash=True
, progress_cb=None
, progress_cb_type='number'
)[source]¶ Downloads Image bytes with given ID.
- Parameters
- id : int
Image ID in Supervisely.
- semaphore :
asyncio.Semaphore
, optional Semaphore for limiting the number of simultaneous downloads.
- range_start : int, optional
Start byte of range for partial download.
- range_end : int, optional
End byte of range for partial download.
- headers : dict, optional
Headers for request.
- check_hash : bool, optional
If True, checks hash of downloaded bytes. Check is not supported for partial downloads. When range is set, hash check is disabled.
- progress_cb : Optional[Union[tqdm, Callable]]
Function for tracking download progress.
- progress_cb_type : Literal["number", "size"], optional
Type of progress callback. Can be “number” or “size”. Default is “number”.
- Returns
Bytes of downloaded image.
- Return type
- Usage example
import supervisely as sly import asyncio os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_id = 770918 loop = sly.utils.get_or_create_event_loop() img_bytes = loop.run_until_complete(api.image.download_bytes_async(img_id))
-
download_np(id, keep_alpha=
False
)[source]¶ Download Image with given id in numpy format.
- Parameters
- Returns
Image in RGB numpy matrix format
- Return type
np.ndarray
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_np = api.image.download_np(770918)
-
async download_np_async(id, semaphore=
None
, keep_alpha=False
, progress_cb=None
, progress_cb_type='number'
)[source]¶ Downloads Image with given ID in NumPy format asynchronously.
- Parameters
- id : int
Image ID in Supervisely.
- semaphore :
asyncio.Semaphore
, optional Semaphore for limiting the number of simultaneous downloads.
- keep_alpha : bool, optional
If True keeps alpha mask for image, otherwise don’t.
- progress_cb : tqdm or callable, optional
Function for tracking download progress.
- progress_cb_type : Literal["number", "size"], optional
Type of progress callback. Can be “number” or “size”. Default is “number”.
- Returns
Image in RGB numpy matrix format
- Return type
np.ndarray
- Usage example
import supervisely as sly import asyncio from tqdm.asyncio import tqdm os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() DATASET_ID = 98357 semaphore = asyncio.Semaphore(100) images = api.image.get_list(DATASET_ID) tasks = [] pbar = tqdm(total=len(images), desc="Downloading images", unit="image") for image in images: task = api.image.download_np_async(image.id, semaphore, progress_cb=pbar) tasks.append(task) results = await asyncio.gather(*tasks)
-
download_nps(dataset_id, ids, progress_cb=
None
, keep_alpha=False
)[source]¶ Download Images with given IDs in numpy format.
- Parameters
- Returns
List of Images in RGB numpy matrix format
- Return type
List[np.ndarray]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_ids = [770918, 770919, 770920] image_nps = api.image.download_nps(dataset_id, image_ids)
-
async download_nps_async(ids, semaphore=
None
, keep_alpha=False
, progress_cb=None
, progress_cb_type='number'
)[source]¶ Downloads Images with given IDs in NumPy format asynchronously.
- Parameters
- ids :
List[int]
List of Image IDs in Supervisely.
- semaphore :
asyncio.Semaphore
, optional Semaphore for limiting the number of simultaneous downloads.
- keep_alpha : bool, optional
If True keeps alpha mask for images, otherwise don’t.
- progress_cb : tqdm or callable, optional
Function for tracking download progress.
- progress_cb_type : Literal["number", "size"], optional
Type of progress callback. Can be “number” or “size”. Default is “number”.
- ids :
- Returns
List of Images in RGB numpy matrix format
- Return type
List[np.ndarray]
- Usage example
import supervisely as sly import asyncio os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() DATASET_ID = 98357 semaphore = asyncio.Semaphore(100) images = api.image.get_list(DATASET_ID) img_ids = [image.id for image in images] loop = sly.utils.get_or_create_event_loop() results = loop.run_until_complete( api.image.download_nps_async(img_ids, semaphore) )
-
download_nps_by_hashes(hashes, keep_alpha=
False
, progress_cb=None
)[source]¶ Download Images with given hashes in Supervisely server in numpy format.
- Parameters
- hashes : List[str]
List of images hashes in Supervisely.
- progress_cb : tqdm or callable, optional
Function for tracking download progress.
- Returns
List of images
- Return type
- class
List[np.ndarray]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_ids = [770918, 770919, 770920] image_hashes = [] for img_id in image_ids: img_info = api.image.get_info_by_id(image_id) image_hashes.append(img_info.hash) image_nps = api.image.download_nps_by_hashes(image_hashes)
- download_path(id, path)[source]¶
Downloads Image from Dataset to local path by ID.
- Parameters
- Returns
None
- Return type
NoneType
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_info = api.image.get_info_by_id(770918) save_path = os.path.join("/home/admin/work/projects/lemons_annotated/ds1/test_imgs/", img_info.name) api.image.download_path(770918, save_path)
-
async download_path_async(id, path, semaphore=
None
, range_start=None
, range_end=None
, headers=None
, check_hash=True
, progress_cb=None
, progress_cb_type='number'
)[source]¶ Downloads Image with given ID to local path.
- Parameters
- id : int
Image ID in Supervisely.
- path : str
Local save path for Image.
- semaphore :
asyncio.Semaphore
, optional Semaphore for limiting the number of simultaneous downloads.
- range_start : int, optional
Start byte of range for partial download.
- range_end : int, optional
End byte of range for partial download.
- headers : dict, optional
Headers for request.
- check_hash : bool, optional
If True, checks hash of downloaded file. Check is not supported for partial downloads. When range is set, hash check is disabled.
- progress_cb : tqdm or callable, optional
Function for tracking download progress.
- progress_cb_type : Literal["number", "size"], optional
Type of progress callback. Can be “number” or “size”. Default is “number”.
- Returns
None
- Return type
NoneType
- Usage example
import supervisely as sly import asyncio os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_info = api.image.get_info_by_id(770918) save_path = os.path.join("/path/to/save/", img_info.name) semaphore = asyncio.Semaphore(100) loop = sly.utils.get_or_create_event_loop() loop.run_until_complete( api.image.download_path_async(img_info.id, save_path, semaphore) )
-
download_paths(dataset_id, ids, paths, progress_cb=
None
)[source]¶ Download Images with given ids and saves them for the given paths.
- Parameters
- dataset_id :
int
Dataset ID in Supervisely, where Images are located.
- ids :
List[int]
List of Image IDs in Supervisely.
- paths :
List[str]
Local save paths for Images.
- progress_cb : tqdm or callable, optional
Function for tracking download progress.
- dataset_id :
- Raises
ValueError
if len(ids) != len(paths)- Returns
None
- Return type
NoneType
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() local_save_dir = "/home/admin/work/projects/lemons_annotated/ds1/test_imgs" save_paths = [] image_ids = [771755, 771756, 771757, 771758, 771759, 771760] img_infos = api.image.get_info_by_id_batch(image_ids) p = tqdm(desc="Images downloaded: ", total=len(img_infos)) for img_info in img_infos: save_paths.append(os.path.join(local_save_dir, img_info.name)) api.image.download_paths(2573, image_ids, save_paths, progress_cb=p) # Progress: # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 0, "total": 6, "timestamp": "2021-03-15T19:47:15.406Z", "level": "info"} # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 1, "total": 6, "timestamp": "2021-03-15T19:47:16.366Z", "level": "info"} # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 2, "total": 6, "timestamp": "2021-03-15T19:47:16.367Z", "level": "info"} # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 3, "total": 6, "timestamp": "2021-03-15T19:47:16.367Z", "level": "info"} # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 4, "total": 6, "timestamp": "2021-03-15T19:47:16.367Z", "level": "info"} # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 5, "total": 6, "timestamp": "2021-03-15T19:47:16.368Z", "level": "info"} # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 6, "total": 6, "timestamp": "2021-03-15T19:47:16.368Z", "level": "info"}
-
async download_paths_async(ids, paths, semaphore=
None
, headers=None
, check_hash=True
, progress_cb=None
, progress_cb_type='number'
)[source]¶ Download Images with given IDs and saves them to given local paths asynchronously.
- Parameters
- ids :
List[int]
List of Image IDs in Supervisely.
- paths :
List[str]
Local save paths for Images.
- semaphore :
asyncio.Semaphore
, optional Semaphore for limiting the number of simultaneous downloads.
- headers : dict, optional
Headers for request.
- check_hash : bool, optional
If True, checks hash of downloaded images.
- progress_cb : tqdm or callable, optional
Function for tracking download progress.
- progress_cb_type : Literal["number", "size"], optional
Type of progress callback. Can be “number” or “size”. Default is “number”.
- ids :
- Raises
ValueError
if len(ids) != len(paths)- Returns
None
- Return type
NoneType
- Usage example
import supervisely as sly import asyncio os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() ids = [770918, 770919] paths = ["/path/to/save/image1.png", "/path/to/save/image2.png"] loop = sly.utils.get_or_create_event_loop() loop.run_until_complete(api.image.download_paths_async(ids, paths))
-
download_paths_by_hashes(hashes, paths, progress_cb=
None
)[source]¶ Download Images with given hashes in Supervisely server and saves them for the given paths.
- Parameters
- Raises
ValueError
if len(hashes) != len(paths)- Returns
None
- Return type
NoneType
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() dataset_id = 447130 dir_for_save = '/home/admin/Downloads/img' hashes = [] paths = [] imgs_info = api.image.get_list(dataset_id) for im_info in imgs_info: hashes.append(im_info.hash) # It is necessary to save images with the same names(extentions) as on the server paths.append(os.path.join(dir_for_save, im_info.name)) api.image.download_paths_by_hashes(hashes, paths)
-
edit(id, name=
None
, description=None
, meta=None
, return_json=False
)[source]¶ Updates the information about the image by given ID with provided parameters. At least one parameter must be set, otherwise ValueError will be raised.
- Parameters
- Return_json
If True, return response in JSON format, otherwise convert it ImageInfo object. This parameter is only added for backward compatibility for update_meta method. It’s not recommended to use it in new code.
- Raises
ValueError
if at least one parameter is not set- Raises
:class:`ValueError if meta parameter was set and it is not a dictionary
- Returns
Information about updated image as ImageInfo object or as dict if return_json is True
- Return type
- Usage example
import supervisely as sly api = sly.Api.from_env() image_id = 123456 new_image_name = "IMG_3333_new.jpg" api.image.edit(id=image_id, name=new_image_name)
-
get_blob_offsets_file(team_file_id, progress_cb=
None
)[source]¶ Get file with blob images offsets from the team storage.
-
get_filtered_list(dataset_id=
None
, filters=None
, sort='id'
, sort_order='asc'
, force_metadata_for_links=True
, limit=None
, return_first_response=False
, project_id=None
)[source]¶ List of filtered Images in the given
Dataset
. Differs in a more flexible filter format from the get_list() method.- Parameters
- dataset_id :
int
Dataset
ID in which the Images are located.- filters :
List[Dict]
, optional List of params to sort output Images.
- sort :
str
, optional Field name to sort. One of {‘id’ (default), ‘name’, ‘description’, ‘labelsCount’, ‘createdAt’, ‘updatedAt’, ‘customSort’}.
- sort_order :
str
, optional Sort order. One of {‘asc’ (default), ‘desc’}
- project_id :
int
Project
ID in which the Images are located.
- dataset_id :
- Returns
Objects with image information from Supervisely.
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() # Get list of Images with names containing subsequence '2008' img_infos = api.image.get_filtered_list(dataset_id, filters=[{ 'type': 'images_filename', 'data': { 'value': '2008' } }])
- 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
- Returns
Returns free name.
- Return type
- 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.supervisely.com' 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, force_metadata_for_links=
True
)[source]¶ Get Image information by ID.
- Parameters
- id : int
Image ID in Supervisely.
- Returns
Object with image information from Supervisely.
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() # You can get Image ID by listing all images in the Dataset as shown in get_list # Or you can open certain image in Supervisely Annotation Tool UI and get last digits of the URL img_info = api.image.get_info_by_id(770918)
-
get_info_by_id_batch(ids, progress_cb=
None
, force_metadata_for_links=True
)[source]¶ Get Images information by ID.
- Parameters
- ids : List[int]
Images IDs in Supervisely.
- progress_cb : tqdm or callable, optional
Function for tracking the progress.
- Returns
Objects with image information from Supervisely.
- Return type
List[ImageInfo]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_ids = [376728, 376729, 376730, 376731, 376732, 376733] img_infos = image.get_info_by_id_batch(img_ids)
-
get_info_by_name(dataset_id, name, force_metadata_for_links=
True
)[source]¶ Returns image info by image name from given dataset id.
- Parameters
- Returns
Object with image information from Supervisely.
- Return type
-
get_list(dataset_id=
None
, filters=None
, sort='id'
, sort_order='asc'
, limit=None
, force_metadata_for_links=True
, return_first_response=False
, project_id=None
, only_labelled=False
, fields=None
, recursive=False
)[source]¶ List of Images in the given
Dataset
.- Parameters
- dataset_id :
int
Dataset
ID in which the Images are located.- filters :
List[Dict]
, optional List of params to sort output Images.
- sort :
str
, optional Field name to sort. One of {‘id’ (default), ‘name’, ‘description’, ‘labelsCount’, ‘createdAt’, ‘updatedAt’,
customSort
}- sort_order :
str
, optional Sort order. One of {‘asc’ (default), ‘desc’}
- limit :
int
, optional Max number of list elements. No limit if None (default).
- force_metadata_for_links : bool, optional
If True, updates meta for images with remote storage links when listing.
- return_first_response : bool, optional
If True, returns first response without waiting for all pages.
- project_id :
int
Project
ID in which the Images are located.- only_labelled : bool, optional
If True, returns only images with labels.
- fields : List[str], optional
List of fields to return. If None, returns all fields.
- recursive : bool, optional
If True, returns all images from dataset recursively (including images in nested datasets).
- dataset_id :
- Returns
Objects with image information from Supervisely.
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() # Get list of Images with width = 1067 img_infos = api.image.get_list(dataset_id, filters=[{ 'field': 'width', 'operator': '=', 'value': '1067' }]) print(img_infos) # Output: [ImageInfo(id=770915, # name='IMG_3861.jpeg', # link=None, # hash='ZdpMD+ZMJx0R8BgsCzJcqM7qP4M8f1AEtoYc87xZmyQ=', # mime='image/jpeg', # ext='jpeg', # size=148388, # width=1067, # height=800, # labels_count=4, # dataset_id=2532, # created_at='2021-03-02T10:04:33.973Z', # updated_at='2021-03-02T10:04:33.973Z', # meta={}, # path_original='/h5un6l2bnaz1vj8a9qgms4-public/images/original/7/h/Vo/...jpg', # full_storage_url='http://app.supervise.ly/h5un6l2bnaz1vj8a9qgms4-public/images/original/7/h/Vo/...jpg'), # tags=[], # ImageInfo(id=770916, # name='IMG_1836.jpeg', # link=None, # hash='YZKQrZH5C0rBvGGA3p7hjWahz3/pV09u5m30Bz8GeYs=', # mime='image/jpeg', # ext='jpeg', # size=140222, # width=1067, # height=800, # labels_count=3, # dataset_id=2532, # created_at='2021-03-02T10:04:33.973Z', # updated_at='2021-03-02T10:04:33.973Z', # meta={}, # path_original='/h5un6l2bnaz1vj8a9qgms4-public/images/original/C/Y/Hq/...jpg', # full_storage_url='http://app.supervise.ly/h5un6l2bnaz1vj8a9qgms4-public/images/original/C/Y/Hq/...jpg'), # tags=[] # ]
-
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
-
get_list_generator(dataset_id=
None
, filters=None
, sort='id'
, sort_order='asc'
, limit=None
, force_metadata_for_links=False
, batch_size=None
, project_id=None
)[source]¶ Returns a generator that yields lists of images in the given
Dataset
orProject
.- Parameters
- dataset_id :
int
Dataset
ID in which the Images are located.- filters :
List[Dict]
, optional List of params to sort output Images.
- sort :
str
, optional Field name to sort. One of {‘id’ (default), ‘name’, ‘description’, ‘labelsCount’, ‘createdAt’, ‘updatedAt’,
customSort
}- sort_order :
str
, optional Sort order. One of {‘asc’ (default), ‘desc’}
- limit :
int
, optional Max number of list elements. No limit if None (default).
- force_metadata_for_links : bool, optional
If True, updates meta for images with remote storage links when listing.
- batch_size : int, optional
Number of images to get in each request.
- project_id :
int
Project
ID in which the Images are located.
- dataset_id :
- Return type
- Returns
Generator that yields lists of images in the given
Dataset
orProject
.- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() for images_batch in api.image.get_list_generator(dataset_id): print(images_batch)
-
async get_list_generator_async(dataset_id=
None
, filters=None
, sort='id'
, sort_order='asc'
, force_metadata_for_links=True
, only_labelled=False
, fields=None
, per_page=None
, semaphore=None
, **kwargs)[source]¶ Yields list of images in dataset asynchronously page by page.
- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- filters : List[Dict[str, str]], optional
Filters for images.
- sort : str, optional
Field name to sort. One of {‘id’ (default), ‘name’, ‘description’, ‘labelsCount’, ‘createdAt’, ‘updatedAt’, ‘customSort’}.
- sort_order : str, optional
Sort order for images. One of {‘asc’ (default), ‘desc’}
- force_metadata_for_links : bool, optional
If True, forces metadata for links.
- only_labelled : bool, optional
If True, returns only labelled images.
- fields : List[str], optional
List of fields to return.
- per_page : int, optional
Number of images to return per page.
- semaphore :
asyncio.Semaphore
, optional Semaphore for limiting the number of simultaneous requests.
- kwargs
Additional arguments.
- Returns
List of images in dataset.
- Return type
AsyncGenerator[List[ImageInfo]]
- Usage example
import supervisely as sly import asyncio os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() loop = sly.utils.get_or_create_event_loop() images = loop.run_until_complete(api.image.get_list_async(123456, per_page=600))
- 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.
-
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 thepagesCount
differs from the requested number.- semaphore :
asyncio.Semaphore
, optional Semaphore for limiting the number of simultaneous requests.
- kwargs
Additional arguments.
- Returns
List of images in dataset.
- Return type
AsyncGenerator[List[ImageInfo]]
- Usage example
import supervisely as sly import asyncio os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' 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))
- get_project_id(image_id)[source]¶
Gets Project ID by Image ID.
- Parameters
- image_id : int
Image ID in Supervisely.
- Returns
Project ID where Image is located.
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_id = 121236920 img_project_id = api.image.get_project_id(img_id) print(img_project_id) # Output: 53939
-
group_images_for_multiview(image_ids, group_name, multiview_tag_name=
None
)[source]¶ Group images for multi-view by tag with given name. If tag does not exist in project, will create it first.
- Note:
All images must belong to the same project.
Tag must be of type ANY_STRING and applicable to images.
Recommended number of images in group is 6-12.
- Parameters
- image_ids : List[int]
List of Images IDs in Supervisely.
- group_name : str
Group name. Images will be assigned by group tag with this value.
- multiview_tag_name : str, optional
Multiview tag name in Supervisely. If None, will use default ‘multiview’ tag name. If tag does not exist in project, will create it first.
- Returns
None
- Return type
NoneType
- Raises
ValueError – if tag is not of type ANY_STRING or not applicable to images
- Usage example
# ? option 1 import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() BATCH_SIZE = 6 image_ids = [2389126, 2389127, 2389128, 2389129, 2389130, 2389131, ...] # group images for multiview for group_name, ids in enumerate(sly.batched(image_ids, batch_size=BATCH_SIZE)): api.image.group_images_for_multiview(ids, group_name) # ? option 2 (with sly.ApiContext) import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() BATCH_SIZE = 6 image_ids = [2389126, 2389127, 2389128, 2389129, 2389130, 2389131, ...] project_id = 111111 # change to your project id # * make sure that `with_settings=True` is set to get project settings from server project_meta_json = api.project.get_meta(project_id, with_settings=True) project_meta = sly.ProjectMeta.from_json(project_meta_json) # create custom tag meta (optional) multiview_tag_name = 'cars' tag_meta = sly.TagMeta(multiview_tag_name, sly.TagValueType.ANY_STRING) project_meta = project_meta.add_tag_meta(tag_meta) project_meta = api.project.update_meta(project_id, project_meta) # update meta on server # group images for multiview with sly.ApiContext(api, project_id=project_id, project_meta=project_meta): for group_name, ids in enumerate(sly.batched(image_ids, batch_size=BATCH_SIZE)): api.image.group_images_for_multiview(ids, group_name, multiview_tag_name)
- static info_sequence()[source]¶
Get list of all
ImageInfo
field names.- Returns
List of
ImageInfo
field names.`- Return type
List[str]
- static info_tuple_name()[source]¶
Get string name of
ImageInfo
NamedTuple.- Returns
NamedTuple name.
- Return type
-
move(dst_dataset_id, id, change_name_if_conflict=
False
, with_annotations=False
)[source]¶ Moves Image with given ID to destination Dataset.
- Parameters
- dst_dataset_id : int
Destination Dataset ID in Supervisely.
- id : int
Image ID in Supervisely.
- change_name_if_conflict : bool, optional
If True adds suffix to the end of Image name when Dataset already contains an Image with identical name, If False and images with the identical names already exist in Dataset raises error.
- with_annotations : bool, optional
If True Image will be copied to Dataset with annotations, otherwise only Images without annotations.
- Returns
Information about Image. See
info_sequence
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() dst_ds_id = 365484 img_id = 533336920 img_info = api.image.copy(dst_ds_id, img_id, with_annotations=True)
-
move_batch(dst_dataset_id, ids, change_name_if_conflict=
False
, with_annotations=False
, progress_cb=None
)[source]¶ Moves Images with given IDs to Dataset.
- Parameters
- dst_dataset_id : int
Destination Dataset ID in Supervisely.
- ids : List[int]
Images IDs in Supervisely.
- change_name_if_conflict : bool, optional
If True adds suffix to the end of Image name when Dataset already contains an Image with identical name, If False and images with the identical names already exist in Dataset raises error.
- with_annotations : bool, optional
If True Image will be copied to Dataset with annotations, otherwise only Images without annotations.
- progress_cb : tqdm or callable, optional
Function for tracking the progress of moving.
- Raises
TypeError
if type of ids is not list- Raises
ValueError
if images ids are from the destination Dataset- Returns
List with information about Images. See
info_sequence
- Return type
List[ImageInfo]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() ds_lemon_id = 1780 ds_kiwi_id = 1233 ds_lemon_img_infos = api.image.get_list(ds_lemon_id) ds_kiwi_img_infos = api.image.get_list(ds_kiwi_id) fruit_img_ids = [] for lemon_img_info, kiwi_img_info in zip(ds_lemon_img_infos, ds_kiwi_img_infos): fruit_img_ids.append(lemon_img_info.id) fruit_img_ids.append(kiwi_img_info.id) ds_fruit_id = 2574 ds_fruit_img_infos = api.image.move_batch(ds_fruit_id, fruit_img_ids, with_annotations=True)
-
move_batch_optimized(src_dataset_id, src_image_infos, dst_dataset_id, with_annotations=
True
, progress_cb=None
, dst_names=None
, batch_size=500
, skip_validation=False
, save_source_date=True
)[source]¶ Moves Images with given IDs to Dataset.
- Parameters
- src_dataset_id : int
Source Dataset ID in Supervisely.
- src_image_infos : List [
ImageInfo
] ImageInfo objects of images to move.
- dst_dataset_id : int
Destination Dataset ID in Supervisely.
- with_annotations : bool, optional
If True Image will be copied to Dataset with annotations, otherwise only Images without annotations.
- progress_cb : tqdm or callable, optional
Function for tracking the progress of moving.
- dst_names : List [
ImageInfo
], optional ImageInfo list with existing items in destination dataset.
- batch_size : int, optional
Number of elements to copy for each request.
- skip_validation : bool, optional
Flag for skipping additinal validations.
- save_source_date : bool, optional
Save source annotation dates (creation and modification) or create a new date.
- Raises
TypeError
if type of src_image_infos is not list- Returns
List with information about Images. See
info_sequence
- Return type
List[ImageInfo]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() src_ds_id = 2231 img_infos = api.image.get_list(src_ds_id) dest_ds_id = 2574 dest_img_infos = api.image.move_batch_optimized(src_ds_id, img_infos, dest_ds_id)
-
preview_url(url, width=
None
, height=None
, quality=70
, ext='jpeg'
, method='auto'
)[source]¶ Previews Image with the given resolution parameters. Learn more about resize parameters here.
- Parameters
- url : str
Full Image storage URL.
- width : int
Preview Image width.
- height : int
Preview Image height.
- quality : int
Preview Image quality.
- ext : str, optional
Preview Image extension, available values: “jpeg”, “png”.
- method : str, optional
Preview Image resize method, available values: “fit”, “fill”, “fill-down”, “force”, “auto”.
- Returns
New URL with resized Image
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_id = 376729 img_info = api.image.get_info_by_id(image_id) img_preview_url = api.image.preview_url(img_info.full_storage_url, width=512, height=256)
-
raise_name_intersections_if_exist(dataset_id, names, message=
None
)[source]¶ Raises error if images with given names already exist in dataset. Default error message: “Images with the following names already exist in dataset [ID={dataset_id}]: {name_intersections}. Please, rename images and try again or set change_name_if_conflict=True to rename automatically on upload.”
- remove(image_id)[source]¶
Remove image from supervisely by id. All image IDs must belong to the same dataset. Therefore, it is necessary to sort IDs before calling this method.
- Parameters
- image_id : int
Images ID in Supervisely.
- Returns
None
- Return type
NoneType
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_id = 2389126 api.image.remove(image_id)
-
remove_batch(ids, progress_cb=
None
, batch_size=50
)[source]¶ Remove images from supervisely by IDs. IDs must belong to the same project.
- Parameters
- ids : List[int]
List of Images IDs in Supervisely.
- progress_cb : tqdm or callable, optional
Function for tracking progress of removing.
- Returns
None
- Return type
NoneType
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_ids = [2389126, 2389127] api.image.remove_batch(image_ids)
- rename(id, name)[source]¶
Renames Image with given ID.
- Parameters
- Returns
Information about updated Image.
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_id = 376729 new_image_name = 'new_image_name.jpg' img_info = api.image.rename(image_id, new_image_name)
- set_remote(images, links)[source]¶
This method helps to change local source to remote for images without re-uploading them as new.
- Parameters
- Returns
json-encoded content of a response.
- Usage example
import supervisely as sly api = sly.Api.from_env() images = [123, 124, 125] links = [ "s3://bucket/lemons/ds1/img/IMG_444.jpeg", "s3://bucket/lemons/ds1/img/IMG_445.jpeg", "s3://bucket/lemons/ds1/img/IMG_446.jpeg", ] result = api.image.set_remote(images, links)
- storage_url(path_original)[source]¶
Get full Image URL link in Supervisely server.
- Parameters
- path_original : str
Original Image path in Supervisely server.
- Returns
Full Image URL link in Supervisely server
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_id = 376729 img_info = api.image.get_info_by_id(image_id) img_storage_url = api.image.storage_url(img_info.path_original)
- static update_custom_sort(meta, custom_sort)[source]¶
Updates a copy of the meta dictionary with a new custom sort value.
- update_meta(id, meta)[source]¶
It is possible to add custom JSON data to every image for storing some additional information. Updates Image metadata by ID. Metadata is visible in Labeling Tool. Supervisely also have 2 apps: import metadata and export metadata
- Parameters
- Raises
TypeError
if meta type is not dict- Returns
Image information in dict format with new meta
- Return type
- Usage example
import os import json import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() image_info = api.image.get_info_by_id(id=3212008) print(image_info.meta) # Output: {} new_meta = {'Camera Make': 'Canon', 'Color Space': 'sRGB', 'Focal Length': '16 mm'} new_image_info = api.image.update_meta(id=3212008, meta=new_meta) image_info = api.image.get_info_by_id(id=3212008) print(json.dumps(obj=image_info.meta, indent=4)) # Output: { # "Camera Make": "Canon", # "Color Space": "sRGB", # "Focal Length": "16 mm" # }
- update_tag_value(tag_id, value)[source]¶
Update tag value with given ID.
- Parameters
- tag_id :
int
Tag ID in Supervisely.
- value : str or float
Tag value.
- project_meta : ProjectMeta
Project Meta.
- tag_id :
- Returns
Information about updated tag.
- Return type
- Usage example
import supervisely as sly
os.environ[‘SERVER_ADDRESS’] = ‘https://app.supervisely.com’ os.environ[‘API_TOKEN’] = ‘Your Supervisely API Token’ api = sly.Api.from_env()
tag_id = 277083 new_value = ‘new_value’ api.image.update_tag_value(tag_id, new_value)
-
upload_blob_images(dataset, blob_file, metas=
None
, change_name_if_conflict=True
, progress_cb=None
, return_image_infos_generator=False
)[source]¶ Uploads images from blob file in Team Files to dataset.
IMPORTANT: File with image offsets should be in the same directory as the blob file. This file should be named as the blob file but with the suffix
_offsets.pkl
. It must be a Pickle file with the BlobImageInfos that define the range of bytes representing the image in the binary. To prepare the offsets file, use thesupervisely.fs.save_blob_offsets_pkl
function.- Parameters
- dataset : Union[DatasetInfo, int]
Dataset in Supervisely. Can be DatasetInfo object or dataset ID. It is recommended to use DatasetInfo object to avoid additional API requests.
- blob_file : Union[FileInfo, str]
Blob file in Team Files. Can be FileInfo object or path to blob file. It is recommended to use FileInfo object to avoid additional API requests.
- metas : Optional[List[Dict[str, Any]], optional
List of metas for images.
- change_name_if_conflict : bool, optional
If True adds suffix to the end of Image name when Dataset already contains an Image with identical name, If False and images with the identical names already exist in Dataset skips them.
- progress_cb : Optional[Union[tqdm, Callable]]
Function for tracking upload progress. Tracks the count of processed items.
- return_image_infos_generator : bool, optional
If True, returns generator of ImageInfo objects. Otherwise, returns None.
- Returns
Generator of ImageInfo objects if return_image_infos_generator is True, otherwise None.
- Return type
Union[Generator[ImageInfo, None], None]
-
upload_by_offsets(dataset, team_file_id, names=
None
, offsets=None
, progress_cb=None
, metas=None
, batch_size=50
, skip_validation=False
, conflict_resolution=None
, validate_meta=False
, use_strict_validation=False
, use_caching_for_validation=False
)[source]¶ Upload images from blob file in Team Files by offsets to Dataset with prepared names. To upload large number of images, use
api.image.upload_by_offsets_generator()
instead.If you include
metas
during the upload, you can add a custom sort parameter for images. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting.- Parameters
- dataset : Union[DatasetInfo,int]
Dataset ID or DatasetInfo object in Supervisely.
- team_file_id : int
ID of the binary file in the team storage.
- names : List[str], optional
Images names with extension.
REQUIRED if there is no file containing offsets in the team storage at the same level as the TAR file. Offset file must be named as the TAR file with the
_offsets.pkl
suffix and must be represented in pickle format. Example:tar_name_offsets.pkl
- offsets : List[dict], optional
List of dictionaries with file offsets that define the range of bytes representing the image in the binary. Example:
[{"offsetStart": 0, "offsetEnd": 100}, {"offsetStart": 101, "offsetEnd": 200}]
.REQUIRED if there is no file containing offsets in the team storage at the same level as the TAR file. Offset file must be named as the TAR file with the
_offsets.pkl
suffix and must be represented in pickle format. Example:tar_name_offsets.pkl
- progress_cb : tqdm or callable, optional
Function for tracking the progress of uploading.
- metas : List[dict], optional
Custom additional image infos that contain images technical and/or user-generated data as list of separate dicts.
- batch_size : int, optional
Number of images to upload in one batch.
- skip_validation : bool, optional
Skips validation for images, can result in invalid images being uploaded.
- conflict_resolution : Optional[Literal["rename", "skip", "replace"]]
The strategy to resolve upload conflicts. ‘Replace’ option will replace the existing images in the dataset with the new images. The images that are being deleted are logged. ‘Skip’ option will ignore the upload of new images that would result in a conflict. An original image’s ImageInfo list will be returned instead. ‘Rename’ option will rename the new images to prevent any conflict.
- validate_meta : bool, optional
If True, validates provided meta with saved JSON schema.
- use_strict_validation : bool, optional
If True, uses strict validation.
- use_caching_for_validation : bool, optional
If True, uses caching for validation.
- Returns
List with information about Images. See
info_sequence
- Return type
List[ImageInfo]
- Usage example
import supervisely as sly from supervisely.api.module_api import ApiField server_address = 'https://app.supervisely.com' api_token = 'Your Supervisely API Token' api = sly.Api(server_address, api_token) dataset_id = 452984 names = ['lemon_1.jpg', 'lemon_1.jpg'] offsets = [ {ApiField.OFFSET_START: 0, ApiField.OFFSET_END: 100}, {ApiField.OFFSET_START: 101, ApiField.OFFSET_END: 200} ] team_file_id = 123456 new_imgs_info = api.image.upload_by_offsets(dataset_id, team_file_id, names, offsets, metas) # Output example: # ImageInfo(id=136281, # name='lemon_1.jpg', # link=None, # hash=None, # mime=None, # ext=None, # size=100, # width=None, # height=None, # labels_count=0, # dataset_id=452984, # created_at='2025-03-21T18:30:08.551Z', # updated_at='2025-03-21T18:30:08.551Z', # meta={}, # path_original='/h5un6l2.../eyJ0eXBlIjoic291cmNlX2Jsb2I...', # full_storage_url='http://storage:port/h5un6l2..., # tags=[], # created_by_id=user), # ImageInfo(...)
-
upload_by_offsets_generator(dataset, team_file_id, offsets_file_path=
None
, progress_cb=None
, metas=None
, batch_size=10000
, skip_validation=False
, conflict_resolution=None
, validate_meta=False
, use_strict_validation=False
, use_caching_for_validation=False
)[source]¶ Upload images from blob file in Team Files by offsets to Dataset. Generates information about uploaded images in batches of max size 10000. File names will be taken from the offset file.
This method is better suited for large datasets, as it does not require resulting all the images into memory at once.
If you include
metas
during the upload, you can add a custom sort parameter for images. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting.- Parameters
- dataset : Union[DatasetInfo,int]
Dataset ID or DatasetInfo object in Supervisely.
- team_file_id : int
ID of the binary file in the team storage.
- offsets_file_path : str, optional
Local path to the file with blob images offsets.
- progress_cb : tqdm or callable, optional
Function for tracking the progress of uploading.
- metas : Dict, optional
Custom additional image infos as dict where:
keys
- image names,values
- image technical and/or user-generated data dicts- batch_size : int, optional
Number of images to upload in one batch.
- skip_validation : bool, optional
Skips validation for images, can result in invalid images being uploaded.
- conflict_resolution : Optional[Literal["rename", "skip", "replace"]]
The strategy to resolve upload conflicts. ‘Replace’ option will replace the existing images in the dataset with the new images. The images that are being deleted are logged. ‘Skip’ option will ignore the upload of new images that would result in a conflict. An original image’s ImageInfo list will be returned instead. ‘Rename’ option will rename the new images to prevent any conflict.
- validate_meta : bool, optional
If True, validates provided meta with saved JSON schema.
- use_strict_validation : bool, optional
If True, uses strict validation.
- use_caching_for_validation : bool, optional
If True, uses caching for validation.
- Returns
Generator with information about Images. See
ImageInfo
- Return type
Generator[ImageInfo, None, None]
- Usage example
import supervisely as sly from supervisely.api.module_api import ApiField server_address = 'https://app.supervisely.com' api_token = 'Your Supervisely API Token' api = sly.Api(server_address, api_token) dataset_id = 452984 team_file_id = 123456 img_infos = [] new_imgs_info_generator = api.image.upload_by_offsets_generator(dataset_id, team_file_id) for img_infos_batch in new_imgs_info_generator: img_infos.extend(img_infos_batch)
-
upload_dir(dataset_id, dir_path, recursive=
True
, change_name_if_conflict=True
, progress_cb=None
)[source]¶ Uploads all images with supported extensions from given directory to Supervisely. Optionally, uploads images from subdirectories of given directory.
- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- dir_path : str
Path to directory with images.
- recursive : bool, optional
If True uploads images from subdirectories of given directory recursively, otherwise only images from given directory.
- change_name_if_conflict : bool, optional
If True adds suffix to the end of Image name when Dataset already contains an Image with identical name, If False and images with the identical names already exist in Dataset raises error.
- progress_cb : Optional[Union[tqdm, Callable]]
Function for tracking upload progress.
- Returns
List of uploaded images infos
- Return type
List[ImageInfo]
-
upload_dirs(dataset_id, dir_paths, recursive=
True
, change_name_if_conflict=True
, progress_cb=None
)[source]¶ Uploads all images with supported extensions from given directories to Supervisely. Optionally, uploads images from subdirectories of given directories.
- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- dir_paths : List[str]
List of paths to directories with images.
- recursive : bool, optional
If True uploads images from subdirectories of given directories recursively, otherwise only images from given directories.
- change_name_if_conflict : bool, optional
If True adds suffix to the end of Image name when Dataset already contains an Image with identical name, If False and images with the identical names already exist in Dataset raises error.
- progress_cb : Optional[Union[tqdm, Callable]]
Function for tracking upload progress.
- Returns
List of uploaded images infos
- Return type
List[ImageInfo]
-
upload_hash(dataset_id, name, hash, meta=
None
)[source]¶ Upload Image from given hash to Dataset.
If you include
meta
during the upload, you can add a custom sort parameter for image. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- Returns
Information about Image. See
info_sequence
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() dst_dataset_id = 452984 im_info = api.image.get_info_by_id(193940090) hash = im_info.hash # It is necessary to upload image with the same name(extention) as in src dataset name = im_info.name meta = {1: 'meta_example'} new_in_info = api.image.upload_hash(dst_dataset_id, name, hash, meta) print(json.dumps(new_in_info, indent=4)) # Output: [ # 196793586, # "IMG_0748.jpeg", # null, # "NEjmnmdd7DOzaFAKK/nCIl5CtcwZeMkhW3CHe875p9g=", # "image/jpeg", # "jpeg", # 66885, # 600, # 500, # 0, # 452984, # "2021-03-16T09:09:45.587Z", # "2021-03-16T09:09:45.587Z", # { # "1": "meta_example" # }, # "/h5un6l2bnaz1vj8a9qgms4-public/images/original/P/a/kn/W2mzMQg435d6wG0.jpg", # "https://app.supervise.ly/h5un6l2bnaz1vj8a9qgms4-public/images/original/P/a/kn/W2mzMQg435hiHJAPgMU.jpg" # ] # Add custom sort parameter for image new_dataset_id = 452985 im_info = api.image.get_info_by_id(193940090) print(im_info.meta) # Output: {'my-key':'a'} with api.image.add_custom_sort(key="my-key"): img_info = api.image.upload_hash(new_dataset_id, name=im_info.name, hash=im_info.hash, meta=im_info.meta)
-
upload_hashes(dataset_id, names, hashes, progress_cb=
None
, metas=None
, batch_size=50
, skip_validation=False
, conflict_resolution=None
, validate_meta=False
, use_strict_validation=False
, use_caching_for_validation=False
)[source]¶ Upload images from given hashes to Dataset.
If you include
metas
during the upload, you can add a custom sort parameter for images. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- names : List[str]
Images names with extension.
- hashes : List[str]
Images hashes.
- progress_cb : tqdm or callable, optional
Function for tracking the progress of uploading.
- metas : List[dict], optional
Custom additional image infos that contain images technical and/or user-generated data as list of separate dicts.
- batch_size : int, optional
Number of images to upload in one batch.
- skip_validation : bool, optional
Skips validation for images, can result in invalid images being uploaded.
- conflict_resolution : Optional[Literal["rename", "skip", "replace"]]
The strategy to resolve upload conflicts. ‘Replace’ option will replace the existing images in the dataset with the new images. The images that are being deleted are logged. ‘Skip’ option will ignore the upload of new images that would result in a conflict. An original image’s ImageInfo list will be returned instead. ‘Rename’ option will rename the new images to prevent any conflict.
- validate_meta : bool, optional
If True, validates provided meta with saved JSON schema.
- use_strict_validation : bool, optional
If True, uses strict validation.
- use_caching_for_validation : bool, optional
If True, uses caching for validation.
- Returns
List with information about Images. See
info_sequence
- Return type
List[ImageInfo]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() src_dataset_id = 447130 hashes = [] names = [] metas = [] imgs_info = api.image.get_list(src_dataset_id) # Create lists of hashes, images names and meta information for each image for im_info in imgs_info: hashes.append(im_info.hash) # It is necessary to upload images with the same names(extentions) as in src dataset names.append(im_info.name) metas.append({im_info.name: im_info.size}) dst_dataset_id = 452984 progress = sly.Progress("Images upload: ", len(hashes)) new_imgs_info = api.image.upload_hashes(dst_dataset_id, names, hashes, progress.iters_done_report, metas) # Output: # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 0, "total": 10, "timestamp": "2021-03-16T11:59:07.444Z", "level": "info"} # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 10, "total": 10, "timestamp": "2021-03-16T11:59:07.644Z", "level": "info"} # Add custom sort parameter for images new_dataset_id = 452985 new_metas = [{'my-key':'a'}, {'my-key':'b'}, {'my-key':'c'}] with api.image.add_custom_sort(key="my-key"): img_infos = api.image.upload_hashes(new_dataset_id, names=names, hashes=hashes, metas=new_metas)
-
upload_id(dataset_id, name, id, meta=
None
)[source]¶ Upload Image by ID to Dataset.
If you include
meta
during the upload, you can add a custom sort parameter for image. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- Returns
Information about Image. See
info_sequence
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() dst_dataset_id = 452984 im_info = api.image.get_info_by_id(193940090) id = im_info.id # It is necessary to upload image with the same name(extention) as in src dataset name = im_info.name meta = {1: 'meta_example'} new_in_info = api.image.upload_id(dst_dataset_id, name, id, meta) print(json.dumps(new_in_info, indent=4)) # Output: [ # 196793605, # "IMG_0748.jpeg", # null, # "NEjmnmdd7DOzaFAKK/nCIl5CtcwZeMkhW3CHe875p9g=", # "image/jpeg", # "jpeg", # 66885, # 600, # 500, # 0, # 452984, # "2021-03-16T09:27:12.620Z", # "2021-03-16T09:27:12.620Z", # { # "1": "meta_example" # }, # "/h5un6l2bnaz1vj8a9qgms4-public/images/original/P/a/kn/W2mzMQg435d6wG0AJGJTOsL1FqMUNOPqu4VdzFAN36LqtGwBIE4AmLOQ1BAxuIyB0bHJAPgMU.jpg", # "https://app.supervise.ly/h5un6l2bnaz1vj8a9qgms4-public/images/original/P/a/kn/iEaDEkejnfnb1Tz56ka0hiHJAPgMU.jpg" # ] # Add custom sort parameter for image new_dataset_id = 452985 im_info = api.image.get_info_by_id(193940090) print(im_info.meta) # Output: {"my-key": "a"} with api.image.add_custom_sort(key="my-key"): img_info = api.image.upload_id(new_dataset_id, name=im_info.name, id=im_info.id, meta=im_info.meta)
-
upload_ids(dataset_id, names, ids, progress_cb=
None
, metas=None
, batch_size=50
, force_metadata_for_links=True
, infos=None
, skip_validation=False
, conflict_resolution=None
)[source]¶ Upload Images by IDs to Dataset.
If you include
metas
during the upload, you can add a custom sort parameter for images. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- dataset_id : int
Destination Dataset ID in Supervisely.
- names : List[str]
Source images names with extension.
- ids : List[int]
Images IDs.
- progress_cb : tqdm or callable, optional
Function for tracking the progress of uploading.
- metas : List[dict], optional
Custom additional image infos that contain images technical and/or user-generated data as list of separate dicts.
- batch_size : int, optional
Number of images to upload in one batch.
- force_metadata_for_links : bool, optional
Calculate metadata for links. If False, metadata will be empty.
- infos : List[ImageInfo], optional
DEPRECATED: This parameter is not used.
- skip_validation : bool, optional
Skips validation for images, can result in invalid images being uploaded.
- conflict_resolution : Optional[Literal["rename", "skip", "replace"]]
The strategy to resolve upload conflicts. ‘Replace’ option will replace the existing images in the dataset with the new images. The images that are being deleted are logged. ‘Skip’ option will ignore the upload of new images that would result in a conflict. An original image’s ImageInfo list will be returned instead. ‘Rename’ option will rename the new images to prevent any conflict.
- Returns
List with information about Images. See
info_sequence
- Return type
List[ImageInfo]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() src_dataset_id = 447130 ids = [] names = [] metas = [] imgs_info = api.image.get_list(src_dataset_id) # Create lists of ids, images names and meta information for each image for im_info in imgs_info: ids.append(im_info.id) # It is necessary to upload images with the same names(extentions) as in src dataset names.append(im_info.name) metas.append({im_info.name: im_info.size}) dst_dataset_id = 452984 progress = sly.Progress("Images upload: ", len(ids)) new_imgs_info = api.image.upload_ids(dst_dataset_id, names, ids, progress.iters_done_report, metas) # Output: # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 0, "total": 10, "timestamp": "2021-03-16T12:31:36.550Z", "level": "info"} # {"message": "progress", "event_type": "EventType.PROGRESS", "subtask": "Images downloaded: ", "current": 10, "total": 10, "timestamp": "2021-03-16T12:31:37.119Z", "level": "info"} # Add custom sort parameter for images new_dataset_id = 452985 new_metas = [{'my-key':'a'}, {'my-key':'b'}, {'my-key':'c'}] with api.image.add_custom_sort(key="my-key"): img_infos = api.image.upload_ids(new_dataset_id, names=names, ids=ids, metas=new_metas)
-
upload_link(dataset_id, name, link, meta=
None
, force_metadata_for_links=True
)[source]¶ Uploads Image from given link to Dataset.
If you include
meta
during the upload, you can add a custom sort parameter for image. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- name : str
Image name with extension.
- link : str
Link to Image.
- meta : dict, optional
Custom additional image info that contain image technical and/or user-generated data.
- force_metadata_for_links : bool, optional
Calculate metadata for link. If False, metadata will be empty.
- Returns
Information about Image. See
info_sequence
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_name = 'Avatar.jpg' img_link = 'https://m.media-amazon.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_.jpg' img_info = api.image.upload_link(dataset_id, img_name, img_link) # Add custom sort parameter for image img_meta = {"my-key": "a"} with api.image.add_custom_sort(key="my-key"): img_info = api.image.upload_link(dataset_id, img_name, img_link, meta=img_meta)
-
upload_links(dataset_id, names, links, progress_cb=
None
, metas=None
, batch_size=50
, force_metadata_for_links=True
, skip_validation=False
, conflict_resolution=None
)[source]¶ Uploads Images from given links to Dataset.
If you include
metas
during the upload, you can add a custom sort parameter for images. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- names : List[str]
Images names with extension.
- links : List[str]
Links to Images.
- progress_cb : tqdm or callable, optional
Function for tracking the progress of uploading.
- metas : List[dict], optional
Custom additional image infos that contain images technical and/or user-generated data as list of separate dicts.
- force_metadata_for_links : bool, optional
Calculate metadata for links. If False, metadata will be empty.
- skip_validation : bool, optional
Skips validation for images, can result in invalid images being uploaded.
- conflict_resolution : Optional[Literal["rename", "skip", "replace"]]
The strategy to resolve upload conflicts. ‘Replace’ option will replace the existing images in the dataset with the new images. The images that are being deleted are logged. ‘Skip’ option will ignore the upload of new images that would result in a conflict. An original image’s ImageInfo list will be returned instead. ‘Rename’ option will rename the new images to prevent any conflict.
- Returns
List with information about Images. See
info_sequence
- Return type
List[ImageInfo]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_names = ['Avatar.jpg', 'Harry Potter.jpg', 'Avengers.jpg'] img_links = ['https://m.media-amazon.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_.jpg', 'https://m.media-amazon.com/images/M/MV5BNDYxNjQyMjAtNTdiOS00NGYwLWFmNTAtNThmYjU5ZGI2YTI1XkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_.jpg', 'https://m.media-amazon.com/images/M/MV5BNjQ3NWNlNmQtMTE5ZS00MDdmLTlkZjUtZTBlM2UxMGFiMTU3XkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_.jpg'] img_infos = api.image.upload_links(dataset_id, img_names, img_links) # Add custom sort parameter for images img_metas = [{'my-key':'a'}, {'my-key':'b'}, {'my-key':'c'}] with api.image.add_custom_sort(key="my-key"): img_infos = api.image.upload_links(dataset_id, names=img_names, links=img_links, metas=img_metas)
-
upload_medical_images(dataset_id, paths, group_tag_name=
None
, metas=None
, progress_cb=None
)[source]¶ Upload medical 2D images (DICOM) to Supervisely and group them by specified or default tag.
If you include
metas
during the upload, you can add a custom sort parameter for images. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- paths : List[str]
List of paths to images.
- group_tag_name : str, optional
Group name. All images will be assigned by tag with this group name. If
group_tag_name
is None, the images will be grouped by one of the default tags.- metas : List[Dict], optional
Custom additional image infos that contain images technical and/or user-generated data as list of separate dicts.
- progress_cb : tqdm or callable, optional
Function for tracking upload progress.
- Returns
List of uploaded images infos.
- Return type
List[ImageInfo]
- Raises
- Usage example
import os from dotenv import load_dotenv from tqdm import tqdm 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/medical_01.dcm', 'path/to/medical_02.dcm'] metas = [{'meta':'01'}, {'meta':'02'}] group_tag_name = 'StudyInstanceUID' pbar = tqdm(desc="Uploading images", total=len(paths)) image_infos = api.image.upload_medical_images(dataset_id, paths, group_tag_name, metas) # Add custom sort parameter for images metas = [{'my-key':'a'}, {'my-key':'b'}] with api.image.add_custom_sort(key="my-key"): image_infos = api.image.upload_medical_images(dataset_id, paths, group_tag_name, metas)
-
upload_multispectral(dataset_id, image_name, channels=
None
, rgb_images=None
, progress_cb=None
)[source]¶ Uploads multispectral image to Supervisely, if channels are provided, they will be uploaded as separate images. If rgb_images are provided, they will be uploaded without splitting into channels as RGB images.
- Parameters
- dataset_id : int
dataset ID to upload images to
- image_name : str
name of the image with extension.
- channels : List[np.ndarray], optional
list of numpy arrays with image channels
- rgb_images : List[str], optional
list of paths to RGB images which will be uploaded as is
- progress_cb : tqdm or callable, optional
function for tracking upload progress
- Returns
list of uploaded images infos
- Return type
List[ImageInfo]
- Usage example
import os import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_name = "demo1.png" image = cv2.imread(f"demo_data/{image_name}") # Extract channels as 2d numpy arrays: channels = [a, b, c] channels = [image[:, :, i] for i in range(image.shape[2])] image_infos = api.image.upload_multispectral(api, dataset.id, image_name, channels)
-
upload_multiview_images(dataset_id, group_name, paths=
None
, metas=None
, progress_cb=None
, links=None
, conflict_resolution='rename'
, force_metadata_for_links=False
)[source]¶ Uploads images to Supervisely and adds a tag to them. At least one of
paths
orlinks
must be provided.If you include
metas
during the upload, you can add a custom sort parameter for images. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- tag_name : str
Tag name in Supervisely. If tag does not exist in project, create it first. Tag must be of type ANY_STRING.
- group_name : str
Group name. All images will be assigned by tag with this group name.
- paths : List[str]
List of paths to images.
- metas : Optional[List[Dict]]
Custom additional image infos that contain images technical and/or user-generated data as list of separate dicts.
- progress_cb : Optional[Union[tqdm, Callable]]
Function for tracking upload progress.
- links : Optional[List[str]]
List of links to images.
- conflict_resolution : Optional[Literal["rename", "skip", "replace"]]
The strategy to resolve upload conflicts. Options:
’replace’: Replaces the existing images in the dataset with the new ones if there is a conflict and logs the deletion of existing images.
’skip’: Ignores uploading the new images if there is a conflict; the original image’s ImageInfo list will be returned instead.
’rename’: (default) Renames the new images to prevent name conflicts.
- force_metadata_for_links : Optional[bool]
Specifies whether to force retrieving metadata for images from links. If False, metadata fields in the response can be empty (if metadata has not been retrieved yet).
- Returns
List of uploaded images infos
- Return type
List[ImageInfo]
- Raises
Exception – if tag does not exist in project or tag is not of type ANY_STRING
- Usage example
import os from dotenv import load_dotenv import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication 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'] group_name = 'audi' image_infos = api.image.upload_multiview_images(dataset_id, group_name, paths) # Add custom sort parameter for images metas = [{'my-key':'a'}, {'my-key':'b'}] with api.image.add_custom_sort(key="my-key"): image_infos = api.image.upload_multiview_images(dataset_id, group_name, paths, metas)
-
upload_np(dataset_id, name, img, meta=
None
)[source]¶ Upload given Image in numpy format with given name to Dataset.
If you include
meta
during the upload, you can add a custom sort parameter for image. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- Returns
Information about Image. See
info_sequence
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_np = sly.image.read("/home/admin/Downloads/7777.jpeg") img_info = api.image.upload_np(dataset_id, name="7777.jpeg", img=img_np) # Add custom sort parameter for image img_meta = {'my-key':'a'} with api.image.add_custom_sort(key="my-key"): img_info = api.image.upload_np(dataset_id, name="7777.jpeg", img=img_np, meta=img_meta)
-
upload_nps(dataset_id, names, imgs, progress_cb=
None
, metas=None
, conflict_resolution=None
)[source]¶ Upload given Images in numpy format with given names to Dataset.
If you include
metas
during the upload, you can add a custom sort parameter for images. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- names : List[str]
Images names with extension.
- imgs : List[np.ndarray]
Images in RGB numpy matrix format
- progress_cb : tqdm or callable, optional
Function for tracking the progress of uploading.
- metas : List[dict], optional
Custom additional image infos that contain images technical and/or user-generated data as list of separate dicts.
- conflict_resolution : Optional[Literal["rename", "skip", "replace"]]
The strategy to resolve upload conflicts. ‘Replace’ option will replace the existing images in the dataset with the new images. The images that are being deleted are logged. ‘Skip’ option will ignore the upload of new images that would result in a conflict. An original image’s ImageInfo list will be returned instead. ‘Rename’ option will rename the new images to prevent any conflict.
- Returns
List with information about Images. See
info_sequence
- Return type
List[ImageInfo]
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_np_1 = sly.image.read("/home/admin/Downloads/7777.jpeg") img_np_2 = sly.image.read("/home/admin/Downloads/8888.jpeg") img_np_3 = sly.image.read("/home/admin/Downloads/9999.jpeg") img_names = ["7777.jpeg", "8888.jpeg", "9999.jpeg"] img_nps = [img_np_1, img_np_2, img_np_3] img_infos = api.image.upload_nps(dataset_id, names=img_names, imgs=img_nps) # Add custom sort parameter for images img_metas = [{'my-key':'a'}, {'my-key':'b'}, {'my-key':'c'}] with api.image.add_custom_sort(key="my-key"): img_infos = api.image.upload_nps(dataset_id, names=img_names, imgs=img_nps, metas=img_metas)
-
upload_path(dataset_id, name, path, meta=
None
, validate_meta=False
, use_strict_validation=False
, use_caching_for_validation=False
)[source]¶ Uploads Image with given name from given local path to Dataset.
If you include
meta
during the upload, you can add a custom sort parameter for image. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- name : str
Image name with extension.
- path : str
Local Image path.
- meta : dict, optional
Custom additional image info that contain image technical and/or user-generated data.
- validate_meta : bool, optional
If True, validates provided meta with saved JSON schema.
- use_strict_validation : bool, optional
If True, uses strict validation.
- use_caching_for_validation : bool, optional
If True, uses caching for validation.
- Returns
Information about Image. See
info_sequence
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_info = api.image.upload_path(dataset_id, name="7777.jpeg", path="/home/admin/Downloads/7777.jpeg") # Add custom sort parameter for image img_meta = {'my-key':'a'} with api.image.add_custom_sort(key="my-key"): img_info = api.image.upload_path(dataset_id, name="7777.jpeg", path="/home/admin/Downloads/7777.jpeg", meta=img_meta)
-
upload_paths(dataset_id, names, paths, progress_cb=
None
, metas=None
, conflict_resolution=None
, validate_meta=False
, use_strict_validation=False
, use_caching_for_validation=False
)[source]¶ Uploads Images with given names from given local path to Dataset.
If you include
metas
during the upload, you can add a custom sort parameter for images. To achieve this, use the context managerapi.image.add_custom_sort()
with the desired key name from the meta dictionary to be used for sorting. Refer to the example section for more details.- Parameters
- dataset_id : int
Dataset ID in Supervisely.
- names : List[str]
List of Images names with extension.
- paths : List[str]
List of local Images pathes.
- progress_cb : tqdm or callable, optional
Function for tracking the progress of uploading.
- metas : List[dict], optional
Custom additional image infos that contain images technical and/or user-generated data as list of separate dicts.
- conflict_resolution : Optional[Literal["rename", "skip", "replace"]]
The strategy to resolve upload conflicts. ‘Replace’ option will replace the existing images in the dataset with the new images. The images that are being deleted are logged. ‘Skip’ option will ignore the upload of new images that would result in a conflict. An original image’s ImageInfo list will be returned instead. ‘Rename’ option will rename the new images to prevent any conflict.
- validate_meta : bool, optional
If True, validates provided meta with saved JSON schema.
- use_strict_validation : bool, optional
If True, uses strict validation.
- use_caching_for_validation : bool, optional
If True, uses caching for validation.
- Raises
ValueError
if len(names) != len(paths)- Returns
List with information about Images. See
info_sequence
- Return type
List[ImageInfo]
- Usage example
os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() img_names = ["7777.jpeg", "8888.jpeg", "9999.jpeg"] image_paths = ["/home/admin/Downloads/img/770918.jpeg", "/home/admin/Downloads/img/770919.jpeg", "/home/admin/Downloads/img/770920.jpeg"] img_infos = api.image.upload_paths(dataset_id, names=img_names, paths=img_paths) # Add custom sort parameter for images img_metas = [{'my-key':'a'}, {'my-key':'b'}, {'my-key':'c'}] with api.image.add_custom_sort(key="my-key"): img_infos = api.image.upload_paths(dataset_id, names=img_names, paths=img_paths, metas=img_metas)
- url(team_id, workspace_id, project_id, dataset_id, image_id)[source]¶
Gets Image URL by ID.
- Parameters
- Returns
Image URL
- Return type
- Usage example
import supervisely as sly os.environ['SERVER_ADDRESS'] = 'https://app.supervisely.com' os.environ['API_TOKEN'] = 'Your Supervisely API Token' api = sly.Api.from_env() team_id = 16087 workspace_id = 23821 project_id = 53939 dataset_id = 254737 image_id = 121236920 img_url = api.image.url(team_id, workspace_id, project_id, dataset_id, image_id) print(url) # Output: https://app.supervise.ly/app/images/16087/23821/53939/254737#image-121236920