AlphaMask

class AlphaMask(data, origin=None, sly_id=None, class_id=None, labeler_login=None, updated_at=None, created_at=None, extra_validation=True)[source]

Bases: Bitmap

Bitmap mask with per-pixel alpha; used for semi-transparent segmentation. Immutable.

AlphaMask geometry for a single Label. AlphaMask object is immutable.

Parameters:
data : np.ndarray

AlphaMask mask data. Must be a numpy array with values in range [0, 255].

origin=None

PointLocation: top, left corner of AlphaMask. Position of the AlphaMask within image.

sly_id : int, optional

AlphaMask ID in Supervisely server.

class_id : int, optional

ID of ObjClass to which AlphaMask belongs.

labeler_login : str, optional

Login of the user who created AlphaMask.

updated_at : str, optional

Date and Time when AlphaMask was modified last. Date Format: Year:Month:Day:Hour:Minute:Seconds. Example: ‘2021-01-22T19:37:50.158Z’.

created_at : str, optional

Date and Time when AlphaMask was created. Date Format is the same as in “updated_at” parameter.

extra_validation : bool, optional

If True, additional validation is performed. Throws a ValueError if values of the data are not in the range [0, 255]. If True it will affect performance.

:raises ValueError, if data values are not in the range [0, 255].

Usage Example:
import supervisely as sly

# Create simple alpha mask:
mask = np.array([[0, 0, 0, 0, 0],
                [0, 50, 50, 50, 0],
                [0, 50, 0, 50, 0],
                [0, 50, 50, 50, 0],
                [0, 0, 0, 0, 0]], dtype=np.uint8)

figure = sly.AlphaMask(mask)

origin = figure.origin.to_json()
print(json.dumps(origin, indent=4))
# Output: {
#     "points": {
#         "exterior": [
#             [
#                 1,
#                 1
#             ]
#         ],
#         "interior": []
#     }

# Create alpha mask from PNG image:
img = sly.imaging.image.read(os.path.join(os.getcwd(), 'black_white.png'))
mask = img[:, :, 3]
figure = sly.AlphaMask(mask)

Methods

allowed_transforms

Returns the allowed transforms for the AlphaMask.

base64_2_data

Convert base64 encoded string to numpy array.

bitwise_mask

Make bitwise operations between a given numpy array and Bitmap.

clone

Clone from GEOMETRYYY

config_from_json

Convert geometry config from json format

config_to_json

Convert geometry config to json format

convert

Convert geometry to another geometry shape.

crop

Crops current Bitmap.

data_2_base64

Convert numpy array to base64 encoded string.

draw

draw_contour

Draws the figure contour on a given bitmap canvas :param bitmap: np.ndarray :param color: [R, G, B] :param thickness: (int) :param config: drawing config specific to a concrete subclass, e.g. per edge colors.

fliplr

Flip current Bitmap in horizontal.

flipud

Flip current Bitmap in vertical.

from_json

Convert a json dict to BitmapBase.

from_path

Read alpha_channel from image by path.

geometry_name

Returns the name of the geometry.

get_mask

Returns 2D boolean mask of the geometry.

name

Get the name of the geometry.

relative_crop

Crops object like "crop" method, but return results with coordinates relative to rect :param rect: Rectangle for crop.

resize

Resizes current Bitmap.

rotate

Rotates current AlphaMask.

scale

Scale current Bitmap.

skeletonize

Compute the skeleton, medial axis transform or morphological thinning of Bitmap.

to_bbox

Create Rectangle object from current Bitmap.

to_contours

Get list of contours in Bitmap.

to_json

Convert the BitmapBase to a json dict.

translate

Translate current Bitmap.

validate

Validate geometry.

Attributes

area

AlphaMask area.

data

Get mask data of Bitmap.

origin

Position of the Bitmap within image.

classmethod allowed_transforms()[source]

Returns the allowed transforms for the AlphaMask.

classmethod from_json(json_data)

Convert a json dict to BitmapBase. Read more about Supervisely format.

Parameters:
json_data : dict

Bitmap in json format as a dict.

Returns:

Bitmap.

Return type:

BitmapBase

Usage Example:
import supervisely as sly

figure_json = {
    "bitmap": {
        "origin": [1, 1],
        "data": "eJzrDPBz5+WS4mJgYOD19HAJAtLMIMwIInOeqf8BUmwBPiGuQPr///9Lb86/C2QxlgT5BTM4PLuRBuTwebo4hlTMSa44sKHhISMDuxpTYrr03F6gDIOnq5/LOqeEJgDM5ht6"
    },
    "shape": "bitmap",
    "geometryType": "bitmap"
}

figure = sly.Bitmap.from_json(figure_json)
classmethod from_path(path)[source]

Read alpha_channel from image by path.

Parameters:
path : str

Path to image

Returns:

Alpha mask

Return type:

AlphaMask

classmethod name()

Get the name of the geometry.

Same as geometry_name(), but shorter. In order to make the code more concise.

Returns:

string with name of geometry

static base64_2_data(s)[source]

Convert base64 encoded string to numpy array. Supports both compressed and uncompressed masks.

Parameters:
s : str

Input base64 encoded string.

Returns:

numpy array

Return type:

np.ndarray

Usage Example:
import supervisely as sly

encoded_string = 'eJzrDPBz5+WS4mJgYOD19HAJAtLMIMwIInOeqf8BUmwBPiGuQPr///9Lb86/C2QxlgT5BTM4PLuRBuTwebo4hlTMSa44sKHhISMDuxpTYrr03F6gDIOnq5/LOqeEJgDM5ht6'
figure_data = sly.AlphaMask.base64_2_data(encoded_string)
print(figure_data)

uncompressed_string = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA'
mask = sly.AlphaMask.base64_2_data(uncompressed_string)
print(mask)
static config_from_json(config)

Convert geometry config from json format

Parameters:
config : dict

dictionary(geometry config) in json format

Returns:

dictionary(geometry config) in json format

Return type:

dict

static config_to_json(config)

Convert geometry config to json format

Parameters:
config : dict

dictionary(geometry config)

Returns:

dictionary(geometry config) in json format

Return type:

dict

static data_2_base64(mask)[source]

Convert numpy array to base64 encoded string.

Parameters:
mask : np.ndarray

Bool numpy array.

Returns:

Base64 encoded string

Return type:

str

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 annotation from API
meta_json = api.project.get_meta(PROJECT_ID)
meta = sly.ProjectMeta.from_json(meta_json)
ann_info = api.annotation.download(IMAGE_ID)
ann = sly.Annotation.from_json(ann_info.annotation, meta)

# Get AlphaMask from annotation
for label in ann.labels:
    if type(label.geometry) == sly.AlphaMask:
        figure = label.geometry

encoded_string = sly.AlphaMask.data_2_base64(figure.data)
print(encoded_string)
# 'eJzrDPBz5+WS4mJgYOD19HAJAtLMIMwIInOeqf8BUmwBPiGuQPr///9Lb86/C2QxlgT5BTM4PLuRBuTwebo4hlTMSa44sKHhISMDuxpTYrr03F6gDIOnq5/LOqeEJgDM5ht6'
static geometry_name()[source]

Returns the name of the geometry.

Returns:

name of the geometry

Return type:

str

bitwise_mask(full_target_mask, bit_op)

Make bitwise operations between a given numpy array and Bitmap.

Parameters:
full_target_mask : np.ndarray

Input numpy array.

bit_op

Type of bitwise operation(and, or, not, xor), uses numpy logic functions.

Returns:

Bitmap or empty list.

Return type:

Bitmap

Usage Example:
import supervisely as sly

mask = np.array([[0, 0, 0, 0, 0],
                [0, 1, 1, 1, 0],
                [0, 1, 0, 1, 0],
                [0, 1, 1, 1, 0],
                [0, 0, 0, 0, 0]], dtype=np.bool_)

figure = sly.Bitmap(mask)

array = np.array([[0, 0, 0, 0, 0],
                [0, 1, 1, 1, 0],
                [0, 0, 1, 0, 0],
                [0, 0, 1, 0, 0],
                [0, 0, 0, 0, 0]], dtype=np.bool_)

bitwise_figure = figure.bitwise_mask(array, np.logical_and)
print(bitwise_figure.data)
# Output:
# [[ True  True  True]
#  [False False False]
#  [False  True False]]
clone()

Clone from GEOMETRYYY

convert(new_geometry, contour_radius=0, approx_epsilon=None)

Convert geometry to another geometry shape.

Parameters:
new_geometry

New geometry shape.

contour_radius : int

Radius of the contour.

approx_epsilon : float

Approximation epsilon.

Returns:

List of geometries.

Return type:

List[Geometry]

crop(rect)

Crops current Bitmap.

Parameters:
rect

Rectangle object for cropping.

Returns:

List of Bitmaps

Return type:

List[Bitmap]

Usage Example:
crop_figures = figure.crop(sly.Rectangle(1, 1, 300, 350))
draw(bitmap, color, thickness=1, config=None)
Parameters:
bitmap

np.ndarray

color

Color [R, G, B]

thickness=1

used only in Polyline and Point

config : dict

Drawing config specific to a concrete subclass, e.g. per edge colors

Raises:

NotImplementedError – if method is not implemented in subclass

draw_contour(bitmap, color, thickness=1, config=None)

Draws the figure contour on a given bitmap canvas :param bitmap: np.ndarray :param color: [R, G, B] :param thickness: (int) :param config: drawing config specific to a concrete subclass, e.g. per edge colors

fliplr(img_size)

Flip current Bitmap in horizontal.

Parameters:
img_size : Tuple[int, int]

img_size which belongs Bitmap.

Returns:

Flipped bitmap in horizontal.

Return type:

BitmapBase

Usage Example:
# Remember that Bitmap class object is immutable, and we need to assign new instance of Bitmap to a new variable
height, width = 300, 400
fliplr_figure = figure.fliplr((height, width))
flipud(img_size)

Flip current Bitmap in vertical.

Parameters:
img_size : Tuple[int, int]

img_size which belongs Bitmap.

Returns:

Flipped bitmap in vertical.

Return type:

BitmapBase

Usage Example:
# Remember that Bitmap class object is immutable, and we need to assign new instance of Bitmap to a new variable
height, width = 300, 400
flipud_figure = figure.flipud((height, width))
get_mask(img_size)

Returns 2D boolean mask of the geometry. With shape as img_size (height, width) and filled with True values inside the geometry and False values outside. dtype = np.bool shape = img_size

Parameters:
img_size : Tuple[int, int]

size of the image (height, width)

Returns:

2D boolean mask of the geometry

Return type:

np.ndarray

relative_crop(rect)

Crops object like “crop” method, but return results with coordinates relative to rect :param rect: Rectangle for crop. :type rect: Rectangle :returns: List of Geometry after relative crop. :rtype: List[Geometry]` :raises NotImplementedError: if method is not implemented in subclass

resize(in_size, out_size)

Resizes current Bitmap.

Parameters:
in_size : Tuple[int, int]

Input image size (height, width) to which Bitmap belongs.

out_size : Tuple[int, int]

Output image size (height, width) to which Bitmap belongs.

Returns:

Resized bitmap.

Return type:

Bitmap

Usage Example:
in_height, in_width = 800, 1067
out_height, out_width = 600, 800
# Remember that Bitmap class object is immutable, and we need to assign new instance of Bitmap to a new variable
resize_figure = figure.resize((in_height, in_width), (out_height, out_width))
rotate(rotator)[source]

Rotates current AlphaMask.

Parameters:
rotator

ImageRotator for AlphaMask rotation.

Returns:

Alpha mask

Return type:

AlphaMask

Usage Example:
import supervisely as sly
from supervisely.geometry.image_rotator import ImageRotator

height, width = ann.img_size
rotator = ImageRotator((height, width), 25)
# Remember that AlphaMask class object is immutable, and we need to assign new instance of AlphaMask to a new variable
rotate_figure = figure.rotate(rotator)
scale(factor)

Scale current Bitmap.

Parameters:
factor : float

Scale parameter.

Returns:

Scaled bitmap.

Return type:

BitmapBase

Usage Example:
# Remember that Bitmap class object is immutable, and we need to assign new instance of Bitmap to a new variable
scale_figure = figure.scale(0.75)
skeletonize(method_id)

Compute the skeleton, medial axis transform or morphological thinning of Bitmap.

Parameters:
method_id

Method to convert bool numpy array.

Returns:

Skeletonized bitmap.

Return type:

Bitmap

Usage Example:
# Remember that Bitmap class object is immutable, and we need to assign new instance of Bitmap to a new variable
skeleton_figure = figure.skeletonize(SkeletonizeMethod.SKELETONIZE)
med_ax_figure = figure.skeletonize(SkeletonizeMethod.MEDIAL_AXIS)
thin_figure = figure.skeletonize(SkeletonizeMethod.THINNING)
to_bbox()

Create Rectangle object from current Bitmap.

Returns:

Rectangle from bitmap.

Return type:

Rectangle

Usage Example:
rectangle = figure.to_bbox()
to_contours()

Get list of contours in Bitmap.

Returns:

List of polygons from bitmap.

Return type:

List[Polygon]

Usage Example:
figure_contours = figure.to_contours()
to_json()

Convert the BitmapBase to a json dict. Read more about Supervisely format.

Returns:

Json format as a dict

Return type:

dict

Usage Example:
import supervisely as sly

mask = np.array([[0, 0, 0, 0, 0],
                [0, 1, 1, 1, 0],
                [0, 1, 0, 1, 0],
                [0, 1, 1, 1, 0],
                [0, 0, 0, 0, 0]], dtype=np.bool_)

figure = sly.Bitmap(mask)
figure_json = figure.to_json()
print(json.dumps(figure_json, indent=4))
# Output: {
#    "bitmap": {
#        "origin": [1, 1],
#        "data": "eJzrDPBz5+WS4mJgYOD19HAJAtLMIMwIInOeqf8BUmwBPiGuQPr///9Lb86/C2QxlgT5BTM4PLuRBuTwebo4hlTMSa44sKHhISMDuxpTYrr03F6gDIOnq5/LOqeEJgDM5ht6"
#    },
#    "shape": "bitmap",
#    "geometryType": "bitmap"
# }
translate(drow, dcol)

Translate current Bitmap.

Parameters:
drow : int

Horizontal shift.

dcol : int

Vertical shift.

Returns:

Translated bitmap.

Return type:

BitmapBase

Usage Example:
# Remember that Bitmap class object is immutable, and we need to assign new instance of Bitmap to a new variable
translate_figure = figure.translate(150, 250)
validate(obj_class_shape, settings)

Validate geometry.

Parameters:
obj_class_shape : str

Object class shape.

settings : dict

Settings.

Raises:

ValueError – if geometry validation error

property area : float

AlphaMask area.

Returns:

Area of current AlphaMask

Return type:

float

Usage Example:
print(figure.area)
# Output: 88101.0
property data : numpy.ndarray

Get mask data of Bitmap.

Returns:

Data of Bitmap.

Return type:

np.ndarray

property origin : supervisely.geometry.point_location.PointLocation

Position of the Bitmap within image.

Returns:

Top, left corner of Bitmap.

Return type:

PointLocation