ImageApi¶
- class ImageApi(api)[source]¶
Bases:
RemoveableBulkModuleApiAPI for working with images.
- Parameters:
- Usage Example:
import supervisely as sly api = sly.Api.from_env() image_info = api.image.get_info_by_id(image_id)
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.
Add tag with given ID to Images by IDs with different values.
Checks existing hashes for Images.
Checks existing links for Images.
Checks if Image has been uploaded.
Convert information about an entity to a dictionary.
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_generatordownload_nps_generatorDownloads 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
DatasetorProject.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.
Get list of subsequent image IDs after the specified image ID.
Group images for multi-view by tag with given name.
Sequence of fields that are returned by the API to represent ImageInfo.
Name of the tuple that represents ImageInfo.
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.
Updates the
updated_atfield of images with the timestamp of the embeddings were created.Updates the source of existing images by setting new remote links.
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 parent images and overlay images linked to them.
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_ATTEMPTSMaximum number of attempts that will be made to wait for a certain condition to be met.
WAIT_ATTEMPT_TIMEOUT_SECNumber of seconds for intervals between attempts.
- InfoType¶
alias of
ImageInfo
- static info_sequence()[source]¶
Sequence of fields that are returned by the API to represent ImageInfo.
- Returns:
List of ImageInfo field names.
- Return type:
List[str]
- static info_tuple_name()[source]¶
Name of the tuple that represents ImageInfo.
- Returns:
NamedTuple name.
- Return type:
- static update_custom_sort(meta, custom_sort)[source]¶
Updates a copy of the meta dictionary with a new custom sort value.
- 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_byattribute 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.
-
add_tag(image_id, tag_id, value=
None)[source]¶ Add tag with given ID to Image by ID.
- Parameters:
- Returns:
None
- Return type:
None
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_id = 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=
None¶ Tag Meta. Needed for value validation, omit to skip validation
- Returns:
None
- Return type:
None
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_ids = [2389126, 2389127] tag_id = 277083 api.image.add_tag_batch(image_ids, tag_id)
-
add_tags_batch(image_ids, tag_ids, values=
None, log_progress=False, batch_size=100, tag_metas=None)[source]¶ Add tag with given ID to Images by IDs with different values.
- Parameters:
List of Images IDs in Supervisely.
Tag IDs in Supervisely.
List of tag values for each image or single value for all images.
If True, will log progress.
Batch size
Tag Metas. Needed for values validation, omit to skip validation
- Returns:
List of tags IDs.
- Return type:
List[int]
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_ids = [2389126, 2389127] tag_ids = 277083 values = ['value1', 'value2'] api.image.add_tags_batch(image_ids, tag_ids, values)
-
check_existing_hashes(hashes, progress_cb=
None)[source]¶ Checks existing hashes for Images.
- Parameters:
- Returns:
List of existing hashes
- Return type:
List[str]
- Usage Example:
# 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 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() # See also: https://app.supervisely.com/explore/notebooks/guide-10-check-existing-images-and-upload-only-the-new-ones-1545/overview # 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:
- Returns:
True if Image with given hash exist, otherwise False
- Return type:
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_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:
ImageInfo object with information about the Image.
- Return type:
- 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() 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
ValueError – if images ids are from the destination
Dataset
- Returns:
List with information about Images.
- Return type:
List[
ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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¶
ImageInfoobjects 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=
None¶ 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.
- Return type:
List[
ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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:
None
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() img_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:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_id = 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 os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() img_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 of Image IDs in Supervisely.
- semaphore=
None¶ 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 os import asyncio from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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 of Image IDs in Supervisely.
- semaphore=
None¶ 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”.
- Returns:
List of bytes of downloaded images.
- Return type:
List[bytes]- Usage Example:
import os import asyncio from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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=
None¶ 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 os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() img_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 os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_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=
None¶ 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 os import asyncio from tqdm.asyncio import tqdm from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() DATASET_ID = 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 os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_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 of Image IDs in Supervisely.
- semaphore=
None¶ 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”.
- Returns:
List of Images in RGB numpy matrix format
- Return type:
List[np.ndarray]- Usage Example:
import os import asyncio from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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:
- Returns:
List of images
- Return type:
List[np.ndarray]
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_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:
None
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() img_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=
None¶ 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:
None
- Usage Example:
import os import asyncio from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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:
- Raises:
ValueError – if len(ids) != len(paths)
- Returns:
None
- Return type:
None
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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 of Image IDs in Supervisely.
- paths¶
Local save paths for Images.
- semaphore=
None¶ 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”.
- Raises:
ValueError – if length of
idsandpathsis not equal- Returns:
None
- Return type:
None
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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:
None
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() dataset_id = 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
ValueError – if meta parameter was set and it is not a dictionary
- Returns:
Information about updated image as
ImageInfoobject or as dict if return_json is True- Return type:
ImageInfoor dict- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_id = 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=
None¶ 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.
- Returns:
Objects with image information from Supervisely.
- Return type:
- 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() # 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 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() 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_free_names(dataset_id, names)[source]¶
Returns list of free names for given dataset.
-
get_info_by_id(id, force_metadata_for_links=
True)[source]¶ Get Image information by ID.
- Parameters:
- Returns:
Object with image information from Supervisely.
- Return type:
- 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() # 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, fields=None)[source]¶ Get Images information by ID.
- Parameters:
- Returns:
Objects with image information from Supervisely.
- Return type:
List[
ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() img_ids = [376728, 376729, 376730, 376731, 376732, 376733] img_infos = api.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, entities_collection_id=None, ai_search_collection_id=None, ai_search_threshold=None, ai_search_threshold_direction='above', extra_fields=None)[source]¶ List of Images in the given
Dataset.- Parameters:
- dataset_id : int¶
Dataset ID in which the Images are located.
- filters=
None¶ 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).
- entities_collection_id : int, optional¶
EntitiesCollection ID of
Defaulttype to which the images belong.- ai_search_collection_id : int, optional¶
EntitiesCollection ID of type
AI Searchto which the images belong.- ai_search_threshold : float, optional¶
Confidence level to filter images in AI Search collection.
- ai_search_threshold_direction : str, optional¶
Direction of the confidence level filter. One of {‘above’ (default), ‘below’}.
- extra_fields : List[str], optional¶
List of extra fields to return. If None, returns no extra fields.
- Returns:
Objects with image information from Supervisely.
- Return type:
- 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() # 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.supervisely.com/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.supervisely.com/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
- Returns:
List of entities.
- Return type:
List[dict]
-
get_list_all_pages_generator(method, data, progress_cb=
None, convert_json_info_cb=None, limit=None, return_first_response=False)¶ This generator function retrieves a list of all or a limited quantity of entities from the Supervisely server, yielding batches of entities as they are retrieved
- Parameters:
- method : str¶
Request method name
- data : dict¶
Dictionary with request body info
- progress_cb : Progress, optional¶
Function for tracking download progress.
- convert_json_info_cb : Callable, optional¶
Function for convert json info
- limit : int, optional¶
Number of entity to retrieve
- return_first_response : bool, optional¶
Specify if return first response
-
get_list_generator(dataset_id=
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
DatasetorProject.- Parameters:
- dataset_id : int¶
Dataset ID in which the Images are located.
- filters=
None¶ 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.
- Returns:
Generator that yields lists of images in the given
DatasetorProject.- 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() 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=
None¶ 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 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() 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_pagelimit. Will be automatically adjusted if thepagesCountdiffers from the requested number.- semaphore=
None¶ Semaphore for limiting the number of simultaneous requests.
- Returns:
List of images in dataset.
- Return type:
AsyncGenerator[List[
ImageInfo]]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() method = 'images.list' data = {'datasetId': 123456} loop = sly.utils.get_or_create_event_loop() images = loop.run_until_complete(api.image.get_list_generator_async(method, data))
- get_project_id(image_id)[source]¶
Gets Project ID by Image ID.
- Parameters:
- Returns:
Project ID where Image is located.
- Return type:
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() img_id = 121236920 img_project_id = api.image.get_project_id(img_id) print(img_project_id) # Output: 53939
-
get_subsequent_image_ids(image_id, images_count=
None, job_id=None, params=None, dataset_id=None, project_id=None)[source]¶ Get list of subsequent image IDs after the specified image ID.
- Parameters:
- image_id : int¶
Image ID in Supervisely.
- images_count : int, optional¶
Number of subsequent images to retrieve. If None, retrieves all subsequent images.
- job_id : int, optional¶
Job ID to filter images. If None, does not filter by job ID.
- params : dict, optional¶
Additional parameters for filtering and sorting images.
- dataset_id : int, optional¶
Dataset ID to filter images.
- project_id : int, optional¶
Project ID to filter images. If None, makes a request to retrieve it from the specified image.
-
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.
- Raises:
ValueError – if tag is not of type ANY_STRING or not applicable to images
- Returns:
None
- Return type:
None
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() # Option 1 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) 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)
-
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.
- Return type:
- 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() 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
ValueError – if images ids are from the destination
Dataset
- Returns:
List with information about Images.
- Return type:
List[
ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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¶
ImageInfoobjects 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=
None¶ 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.
- Return type:
List[
ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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 os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_id = 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:
- Returns:
None
- Return type:
None
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_id = 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:
- Returns:
None
- Return type:
None
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_ids = [2389126, 2389127] api.image.remove_batch(image_ids)
- rename(id, name)[source]¶
Renames Image with given ID.
- Parameters:
- Returns:
ImageInfo object with information about the updated Image.
- Return type:
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_id = 376729 new_image_name = 'new_image_name.jpg' img_info = api.image.rename(image_id, new_image_name)
- set_custom_sort(id, sort_value)[source]¶
Sets custom sort value for image with given ID.
- set_custom_sort_bulk(ids, sort_values)[source]¶
Sets custom sort values for images with given IDs.
-
set_embeddings_updated_at(ids, timestamps=
None)[source]¶ Updates the
updated_atfield of images with the timestamp of the embeddings were created.- Parameters:
- Returns:
None
- Return type:
NoneType
- Usage Example:
import os import datetime from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_ids = [123, 456, 789] timestamps = [datetime.datetime.now().isoformat() for _ in image_ids] api.image.set_embeddings_updated_at(image_ids, timestamps)
- set_remote(images, links)[source]¶
Updates the source of existing images by setting new remote links. This method is used when an image was initially uploaded as a file or added via a link, but later it was decided to change its location (e.g., moved to another storage or re-uploaded elsewhere). By updating the link, the image source can be redirected to the new location.
- Parameters:
- Returns:
json-encoded content of a response.
- 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() 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:
- Returns:
Full Image URL link in Supervisely server
- Return type:
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_id = 376729 img_info = api.image.get_info_by_id(image_id) img_storage_url = api.image.storage_url(img_info.path_original)
- 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 from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_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¶
Tag ID in Supervisely.
- value : str or float¶
Tag value.
- project_meta :
ProjectMeta ProjectMeta object.
- Returns:
Information about updated tag.
- Return type:
- 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() 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_pklfunction.- Parameters:
- dataset¶
Dataset in Supervisely. Can be DatasetInfo object or dataset ID. It is recommended to use DatasetInfo object to avoid additional API requests.
- blob_file¶
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, parent_ids=None)[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
metasduring 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¶
Dataset ID or
DatasetInfoobject 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.pklsuffix 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.pklsuffix 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.
- parent_ids : List[Optional[int]], optional¶
Optional list of parent IDs for the images
- Returns:
List with information about Images.
- Return type:
List[ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly from supervisely.api.module_api import ApiField # 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 = 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
metasduring 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¶
Dataset ID or
DatasetInfoobject 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.
- Return type:
Generator[ImageInfo, None, None]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() dataset_id = 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, parent_id=None)[source]¶ Upload Image from given hash to Dataset.
If you include
metaduring 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.
- hash : str¶
Image hash.
- meta : dict, optional¶
Custom additional image info that contain image technical and/or user-generated data.
- parent_id : int, optional¶
Optional parent ID for the image. Used exclusively for “overlay” labeling interface.
- Returns:
Information about Image.
- Return type:
- 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() 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.supervisely.com/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, parent_ids=None)[source]¶ Upload images from given hashes to Dataset.
If you include
metasduring 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.
- parent_ids : List[Optional[int]], optional¶
Optional list of parent IDs for the images
- Returns:
List with information about Images.
- Return type:
List[ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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, parent_id=None)[source]¶ Upload Image by ID to Dataset.
If you include
metaduring 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¶
Destination Dataset ID in Supervisely.
- name : str¶
Image name with extension.
- id : int¶
Source image ID in Supervisely.
- meta : dict, optional¶
Custom additional image info that contain image technical and/or user-generated data.
- parent_id : int, optional¶
Optional parent ID for the image
- Returns:
Information about Image.
- Return type:
- 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() 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.supervisely.com/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, parent_ids=None)[source]¶ Upload Images by IDs to Dataset.
If you include
metasduring 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=
None¶ 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.
- parent_ids : List[Optional[int]], optional¶
Optional list of parent IDs for the images
- Returns:
List with information about Images.
- Return type:
List[
ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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, parent_id=None)[source]¶ Uploads Image from given link to Dataset.
If you include
metaduring 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 remote 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.
- parent_id : int, optional¶
Optional parent ID for the image
- Returns:
ImageInfo object with information about the Image.
- Return type:
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() img_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, parent_ids=None)[source]¶ Uploads Images from given links to Dataset.
If you include
metasduring 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.
- parent_ids : List[Optional[int]], optional¶
Optional list of parent IDs for the images
- Returns:
List with information about Images.
- Return type:
List[
ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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
metasduring 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_nameis 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.
- Raises:
ValueError – If tag does not exist in project or tag is not of type ANY_STRING
ValueError – If length of
metasis not equal to the length ofpaths.RuntimeError – If file has unsupported extension. Supported extensions: {sly_image.SUPPORTED_IMG_EXTS}
- Returns:
List of uploaded images infos
- Return type:
List[
ImageInfo]- Usage Example:
import os from tqdm import tqdm from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() dataset_id = 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 from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() image_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
pathsorlinksmust be provided.If you include
metasduring 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.
- 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": Replace existing images in the dataset and log deletions."skip": Skip uploading conflicting images and return existingImageInfo."rename": (default) Rename new images to prevent 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).
- Raises:
ValueError – if tag does not exist in project or tag is not of type ANY_STRING
- Returns:
List of uploaded images infos
- Return type:
List[
ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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, parent_id=None)[source]¶ Upload given Image in numpy format with given name to Dataset.
If you include
metaduring 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.
- Return type:
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() img_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, parent_ids=None)[source]¶ Upload given Images in numpy format with given names to Dataset.
If you include
metasduring 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.
- parent_ids : List[Optional[int]], optional¶
Optional list of parent IDs for the images
- Returns:
List with information about Images.
- Return type:
List[
ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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'}] parent_ids = [1, 2, 3] 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, parent_ids=parent_ids)
-
upload_overlay_images(dataset_id, names, paths=
None, links=None, hashes=None, overlay_names=None, overlay_paths=None, overlay_links=None, overlay_hashes=None, batch_size=50, conflict_resolution='rename', force_metadata_for_links=False)[source]¶ Uploads parent images and overlay images linked to them.
This method first uploads parent images to the destination dataset and then uploads overlay images with references to the uploaded parents.
Parent-to-overlay mapping is by index:
overlay_names[i]contains overlay names fornames[i]. Each parent can have multiple overlays (one-to-many mapping).Exactly one parent source must be provided:
pathslinkshashes
Exactly one overlay source must be provided:
overlay_pathsoverlay_linksoverlay_hashes
- Parameters:
- dataset_id : int¶
Dataset ID in Supervisely.
- names : List[str]¶
Parent image names.
- paths : List[str], optional¶
Local paths to parent images.
- links : List[str], optional¶
Remote links to parent images.
- hashes : List[str], optional¶
Hashes of parent images already uploaded to Supervisely storage.
- overlay_names : List[List[str]]¶
List of overlay name lists.
overlay_names[i]contains overlay names fornames[i].- overlay_paths : List[List[str]], optional¶
Local paths to overlay images grouped by parent index.
overlay_paths[i]corresponds tooverlay_names[i].- overlay_links : List[List[str]], optional¶
Remote links to overlay images grouped by parent index.
overlay_links[i]corresponds tooverlay_names[i].- overlay_hashes : List[List[str]], optional¶
Hashes of overlay images grouped by parent index.
overlay_hashes[i]corresponds tooverlay_names[i].- batch_size : int, optional¶
Number of images uploaded in one batch for link/hash-based uploads.
- conflict_resolution : Optional[Literal["rename", "skip", "replace"]]¶
The strategy to resolve upload conflicts. Options:
"replace": Replace existing images in the dataset and log deletions."skip": Skip uploading conflicting images and return existingImageInfo."rename": (default) Rename new images to prevent conflicts.
- force_metadata_for_links : bool, optional¶
Specifies whether to force retrieving metadata for images uploaded from links. If False, metadata fields in the response can be empty until metadata is retrieved.
- Raises:
ValueError – If input list lengths do not match, if the parent mapping is invalid, or if not exactly one source is provided for parents or overlays.
- Returns:
Tuple of two values: - uploaded parent image infos; - uploaded overlay image infos grouped by parent index
(
overlay_infos_grouped[i]corresponds tonames[i]).- Return type:
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() dataset_id = 123456 names = ["scene_01.png", "scene_02.png"] paths = [ "/path/to/scene_01.png", "/path/to/scene_02.png", ] # Multiple overlays can be linked to each parent using list of lists overlay_names = [ ["scene_01_mask.png", "scene_01_depth.png"], # overlays for scene_01.png ["scene_02_mask.png"], # overlays for scene_02.png ] overlay_paths = [ ["/path/to/scene_01_mask.png", "/path/to/scene_01_depth.png"], ["/path/to/scene_02_mask.png"], ] parent_infos, overlay_infos = api.image.upload_overlay_images( dataset_id=dataset_id, names=names, paths=paths, overlay_names=overlay_names, overlay_paths=overlay_paths, )
-
upload_path(dataset_id, name, path, meta=
None, validate_meta=False, use_strict_validation=False, use_caching_for_validation=False, parent_id=None)[source]¶ Uploads Image with given name from given local path to Dataset.
If you include
metaduring 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.
- parent_id : int, optional¶
Optional parent ID for the image. Used exclusively for “overlay” labeling interface.
- Returns:
Information about Image.
- Return type:
- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() img_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, parent_ids=None)[source]¶ Uploads Images with given names from given local path to Dataset.
If you include
metasduring 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.
- parent_ids : List[Optional[int]], optional¶
Optional list of parent IDs for the images
- Raises:
ValueError – if len(names) != len(paths)
- Returns:
List with information about Images.
- Return type:
List[
ImageInfo]- Usage Example:
import os from dotenv import load_dotenv import supervisely as sly # Load secrets and create API object from .env file (recommended) # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication if sly.is_development(): load_dotenv(os.path.expanduser("~/supervisely.env")) api = sly.Api.from_env() 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 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() 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.supervisely.com/app/images/16087/23821/53939/254737#image-121236920