Mask3D

class Mask3D[source]

Bases: supervisely.geometry.geometry.Geometry

Mask 3D geometry for a single Label. Mask3D object is immutable.

Parameters
data : np.ndarray

Mask 3D mask data. Must be a numpy array with only 2 unique values: [0, 1] or [0, 255] or [False, True].

sly_id : int, optional

Mask 3D ID in Supervisely server.

class_id : int, optional

ID of ObjClass to which Mask 3D belongs.

labeler_login : str, optional

Login of the user who created Mask 3D.

updated_at : str, optional

Date and Time when Mask 3D 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 Mask 3D was created. Date Format is the same as in “updated_at” parameter.

volume_header : dict, optional

NRRD header dictionary. Optional.

convert_to_ras : bool, optional

If True, converts the mask to RAS orientation. Default is True.

Raises

ValueError, if data is not bool or no pixels set to True in data

Usage example
import supervisely as sly

# Create simple Mask 3D
mask3d = np.zeros((3, 3, 3), dtype=np.bool_)
mask3d[0:2, 0:2, 0:2] = True

shape = sly.Mask3D(mask3d)

print(shape.data)
# Output:
#    [[[ True  True False]
#      [ True  True False]
#      [False False False]]

#     [[ True  True False]
#      [ True  True False]
#      [False False False]]

#     [[False False False]
#      [False False False]
#      [False False False]]]

Methods

add_mask_2d

Draw a 2D mask on a 3D Mask.

allowed_transforms

base64_2_data

Convert base64 encoded string to numpy array.

clone

Clone from GEOMETRYYY

config_from_json

config_to_json

convert

create_from_file

Creates Mask3D geometry from file.

create_header

Create header for encoding Mask3D to NRRD bytes

crop

param rect

Rectangle

data_2_base64

Convert numpy array to base64 encoded string.

draw

param bitmap

np.ndarray

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.

fliplr

param img_size

(rows, cols)

flipud

param img_size

(rows, cols)

from_bytes

Create a Mask3D geometry object from bytes.

from_file

Load figure geometry from file.

from_json

Convert a json dict to Mask 3D.

geometry_name

Return geometry name

get_mask

Returns 2D boolean mask of the geometry.

name

Same as geometry_name(), but shorter.

orient_ras

Transforms the mask data and updates spatial metadata (origin, directions, spacing) to align with the RAS coordinate system using SimpleITK.

relative_crop

Crops object like "crop" method, but return results with coordinates relative to rect :param rect: :return: list of Geometry

resize

param in_size

(rows, cols)

rotate

Rotates around image center -> New Geometry :param rotator: ImageRotator :return: Geometry

scale

Scales around origin with a given factor.

set_volume_space_meta

Set space, space directions, and space origin attributes from a NRRD header dictionary.

to_bbox

rtype

Rectangle

to_json

Convert the Mask 3D to a json dict.

translate

param drow

int rows shift

validate

Attributes

area

return

float

space

Get the space of the Mask3D.

space_directions

Get the space directions of the Mask3D.

space_origin

Get the space origin of the Mask3D as a list of floats.

add_mask_2d(mask_2d, plane_name, slice_index, origin=None)[source]

Draw a 2D mask on a 3D Mask.

Parameters
mask_2d : np.ndarray

2D array with a flat mask.

plane_name : str

Name of the plane: “axial”, “sagittal”, “coronal”.

slice_index : int

Slice index of the volume figure.

origin : Optional[List[int]], NoneType

(row, col) position. The top-left corner of the mask is located on the specified slice (optional).

static base64_2_data(encoded_string)[source]

Convert base64 encoded string to numpy array.

Parameters
s : str

Input base64 encoded string.

Returns

Bool numpy array

Return type

np.ndarray

Usage example
import supervisely as sly

encoded_string = 'H4sIAGWoWmQC/zPWMdYxrmFkZAAiIIAz4AAAE56ciyEAAAA='
figure_data = sly.Mask3D.base64_2_data(encoded_string)
print(figure_data)
# [[[1 1 0]
#   [1 1 0]
#   [0 0 0]]
#  [[1 1 0]
#   [1 1 0]
#   [0 0 0]]
#  [[0 0 0]
#   [0 0 0]
#   [0 0 0]]]
clone()

Clone from GEOMETRYYY

classmethod create_from_file(file_path)[source]

Creates Mask3D geometry from file.

Parameters
file_path : str

Path to nrrd file with data

Return type

Mask3D

create_header()[source]

Create header for encoding Mask3D to NRRD bytes

Returns

Header for NRRD file

Return type

OrderedDict

crop(rect)
Parameters
rect

Rectangle

Returns

list of Geometry

static data_2_base64(data)[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 supervisely as sly
import os
import nrrd

address = 'https://app.supervisely.com/'
token = 'Your Supervisely API Token'
api = sly.Api(address, token)

meta_json = api.project.get_meta(PROJECT_ID)
meta = sly.ProjectMeta.from_json(meta_json)

ann_json = api.volume.annotation.download_bulk(DATASET_ID, [VOLUME_ID])

figure_id = ann_json[0]["spatialFigures"][0]["id"]
path_for_mesh = f"meshes/{figure_id}.nrrd"
api.volume.figure.download_stl_meshes([figure_id], [path_for_mesh])

mask3d_data, _ = sly.volume.volume.read_nrrd_serie_volume_np(path_for_mesh)
encoded_string = sly.Mask3D.data_2_base64(mask3d_data)

print(encoded_string)
# 'H4sIAGWoWmQC/zPWMdYxrmFkZAAiIIAz4AAAE56ciyEAAAA='
draw(bitmap, color, thickness=1, config=None)
Parameters
bitmap

np.ndarray

color

[R, G, B]

thickness

used only in Polyline and Point

config

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

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)
Parameters
img_size

(rows, cols)

Returns

Geometry

flipud(img_size)
Parameters
img_size

(rows, cols)

Returns

Geometry

classmethod from_bytes(geometry_bytes)[source]

Create a Mask3D geometry object from bytes.

Parameters
geometry_bytes : bytes

NRRD file represented as bytes.

Returns

A Mask3D geometry object.

Return type

Mask3D

static from_file(figure, file_path)[source]

Load figure geometry from file.

Parameters
figure : VolumeFigure

Spatial figure

file_path : str

Path to nrrd file with data

classmethod from_json(json_data)[source]

Convert a json dict to Mask 3D.

Parameters
data : dict

Mask in json format as a dict.

Returns

Mask3D object

Return type

Mask3D

Usage example
import supervisely as sly

figure_json = {
    "mask_3d": {
        "data": "eJzrDPBz5+WS4mJgYOD19HAJAtLMIMwIInOeqf8BUmwBPiGuQPr///9Lb86/C2QxlgT5BTM4PLuRBuTwebo4hlTMSa44sKHhISMDuxpTYrr03F6gDIOnq5/LOqeEJgDM5ht6",
    },
    "shape": "mask_3d",
    "geometryType": "mask_3d"
}

figure = sly.Mask3D.from_json(figure_json)
static geometry_name()[source]

Return geometry name

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

classmethod name()

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

Returns

string with name of geometry

orient_ras()[source]

Transforms the mask data and updates spatial metadata (origin, directions, spacing) to align with the RAS coordinate system using SimpleITK.

Return type

None

relative_crop(rect)

Crops object like “crop” method, but return results with coordinates relative to rect :param rect: :return: list of Geometry

resize(in_size, out_size)
Parameters
in_size

(rows, cols)

out_size

(128, 256) (128, KEEP_ASPECT_RATIO) (KEEP_ASPECT_RATIO, 256)

Returns

Geometry

rotate(rotator)

Rotates around image center -> New Geometry :param rotator: ImageRotator :return: Geometry

scale(factor)

Scales around origin with a given factor. :param: factor (float): :return: Geometry

set_volume_space_meta(header)[source]

Set space, space directions, and space origin attributes from a NRRD header dictionary.

Parameters
header : dict

NRRD header dictionary.

to_bbox()
Return type

Rectangle

Returns

Rectangle

to_json()[source]

Convert the Mask 3D to a json dict.

Returns

Json format as a dict

Return type

dict

Usage example
import supervisely as sly

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

figure = sly.Mask3D(mask)
figure_json = figure.to_json()
print(json.dumps(figure_json, indent=4))
# Output: {
#    "mask_3d": {
#        "data": "eJzrDPBz5+WS4mJgYOD19HAJAtLMIMwIInOeqf8BUmwBPiGuQPr///9Lb86/C2QxlgT5BTM4PLuRBuTwebo4hlTMSa44sKHhISMDuxpTYrr03F6gDIOnq5/LOqeEJgDM5ht6",
#    },
#    "shape": "mask_3d",
#    "geometryType": "mask_3d"
# }
translate(drow, dcol)
Parameters
drow

int rows shift

dcol

int cols shift

Returns

Geometry

property area
Returns

float

property space

Get the space of the Mask3D.

Returns

Space of the Mask3D.

Return type

str

property space_directions

Get the space directions of the Mask3D.

Returns

Space directions of the Mask3D.

Return type

List[List[float]]

property space_origin

Get the space origin of the Mask3D as a list of floats.

Returns

Space origin of the Mask3D.

Return type

List[float] or None