napari.layers.Labels#

class napari.layers.Labels(data, *, affine=None, blending='translucent', cache=True, colormap=None, depiction='volume', experimental_clipping_planes=None, features=None, metadata=None, multiscale=None, name=None, opacity=0.7, plane=None, projection_mode='none', properties=None, rendering='iso_categorical', rotate=None, scale=None, shear=None, translate=None, visible=True)[source]#

Bases: ScalarFieldBase

Labels (or segmentation) layer.

An image-like layer where every pixel contains an integer ID corresponding to the region it belongs to.

Parameters:
  • data (array or list of array) – Labels data as an array or multiscale. Must be integer type or bools. Please note multiscale rendering is only supported in 2D. In 3D, only the lowest resolution scale is displayed.

  • affine (n-D array or napari.utils.transforms.Affine) – (N+1, N+1) affine transformation matrix in homogeneous coordinates. The first (N, N) entries correspond to a linear transform and the final column is a length N translation vector and a 1 or a napari Affine transform object. Applied as an extra transform on top of the provided scale, rotate, and shear values.

  • blending (str) – One of a list of preset blending modes that determines how RGB and alpha values of the layer visual get mixed. Allowed values are {‘opaque’, ‘translucent’, and ‘additive’}.

  • cache (bool) – Whether slices of out-of-core datasets should be cached upon retrieval. Currently, this only applies to dask arrays.

  • colormap (CyclicLabelColormap or DirectLabelColormap or None) – Colormap to use for the labels. If None, a random colormap will be used.

  • depiction (str) – 3D Depiction mode. Must be one of {‘volume’, ‘plane’}. The default value is ‘volume’.

  • experimental_clipping_planes (list of dicts, list of ClippingPlane, or ClippingPlaneList) – Each dict defines a clipping plane in 3D in data coordinates. Valid dictionary keys are {‘position’, ‘normal’, and ‘enabled’}. Values on the negative side of the normal are discarded if the plane is enabled.

  • features (dict[str, array-like] or DataFrame) – Features table where each row corresponds to a label and each column is a feature. The first row corresponds to the background label.

  • metadata (dict) – Layer metadata.

  • multiscale (bool) – Whether the data is a multiscale image or not. Multiscale data is represented by a list of array like image data. If not specified by the user and if the data is a list of arrays that decrease in shape then it will be taken to be multiscale. The first image in the list should be the largest. Please note multiscale rendering is only supported in 2D. In 3D, only the lowest resolution scale is displayed.

  • name (str) – Name of the layer.

  • opacity (float) – Opacity of the layer visual, between 0.0 and 1.0.

  • plane (dict or SlicingPlane) – Properties defining plane rendering in 3D. Properties are defined in data coordinates. Valid dictionary keys are {‘position’, ‘normal’, ‘thickness’, and ‘enabled’}.

  • projection_mode (str) – How data outside the viewed dimensions but inside the thick Dims slice will be projected onto the viewed dimensions

  • properties (dict {str: array (N,)} or DataFrame) – Properties for each label. Each property should be an array of length N, where N is the number of labels, and the first property corresponds to background.

  • rendering (str) – 3D Rendering mode used by vispy. Must be one {‘translucent’, ‘iso_categorical’}. ‘translucent’ renders without lighting. ‘iso_categorical’ uses isosurface rendering to calculate lighting effects on labeled surfaces. The default value is ‘iso_categorical’.

  • rotate (float, 3-tuple of float, or n-D array.) – If a float convert into a 2D rotation matrix using that value as an angle. If 3-tuple convert into a 3D rotation matrix, using a yaw, pitch, roll convention. Otherwise assume an nD rotation. Angles are assumed to be in degrees. They can be converted from radians with np.degrees if needed.

  • scale (tuple of float) – Scale factors for the layer.

  • shear (1-D array or n-D array) – Either a vector of upper triangular values, or an nD shear matrix with ones along the main diagonal.

  • translate (tuple of float) – Translation values for the layer.

  • visible (bool) – Whether the layer visual is currently being displayed.

data#

Integer label data as an array or multiscale. Can be N dimensional. Every pixel contains an integer ID corresponding to the region it belongs to. The label 0 is rendered as transparent. Please note multiscale rendering is only supported in 2D. In 3D, only the lowest resolution scale is displayed.

Type:

array or list of array

multiscale#

Whether the data is a multiscale image or not. Multiscale data is represented by a list of array like image data. The first image in the list should be the largest. Please note multiscale rendering is only supported in 2D. In 3D, only the lowest resolution scale is displayed.

Type:

bool

metadata#

Labels metadata.

Type:

dict

num_colors#

Number of unique colors to use in colormap. DEPRECATED: set colormap directly, using napari.utils.colormaps.label_colormap.

Type:

int

features#

Features table where each row corresponds to a label and each column is a feature. The first row corresponds to the background label.

Type:

Dataframe-like

properties#

Properties for each label. Each property should be an array of length N, where N is the number of labels, and the first property corresponds to background.

Type:

dict {str: array (N,)}, DataFrame

color#

Custom label to color mapping. Values must be valid color names or RGBA arrays. While there is no limit to the number of custom labels, the the layer will render incorrectly if they map to more than 1024 distinct colors. DEPRECATED: set colormap directly, using napari.utils.colormaps.DirectLabelColormap.

Type:

dict of int to str or array

seed#

Seed for colormap random generator. DEPRECATED: set colormap directly, using napari.utils.colormaps.label_colormap.

Type:

float

opacity#

Opacity of the labels, must be between 0 and 1.

Type:

float

contiguous#

If True, the fill bucket changes only connected pixels of same label.

Type:

bool

n_edit_dimensions#

The number of dimensions across which labels will be edited.

Type:

int

contour#

If greater than 0, displays contours of labels instead of shaded regions with a thickness equal to its value. Must be >= 0.

Type:

int

brush_size#

Size of the paint brush in data coordinates.

Type:

float

selected_label#

Index of selected label. Can be greater than the current maximum label.

Type:

int

mode#

Interactive mode. The normal, default mode is PAN_ZOOM, which allows for normal interactivity with the canvas.

In PICK mode the cursor functions like a color picker, setting the clicked on label to be the current label. If the background is picked it will select the background label 0.

In PAINT mode the cursor functions like a paint brush changing any pixels it brushes over to the current label. If the background label 0 is selected than any pixels will be changed to background and this tool functions like an eraser. The size and shape of the cursor can be adjusted in the properties widget.

In FILL mode the cursor functions like a fill bucket replacing pixels of the label clicked on with the current label. It can either replace all pixels of that label or just those that are contiguous with the clicked on pixel. If the background label 0 is selected than any pixels will be changed to background and this tool functions like an eraser.

In ERASE mode the cursor functions similarly to PAINT mode, but to paint with background label, which effectively removes the label.

Type:

str

plane#

Properties defining plane rendering in 3D.

Type:

SlicingPlane

experimental_clipping_planes#

Clipping planes defined in data coordinates, used to clip the volume.

Type:

ClippingPlaneList

Notes

_selected_color4-tuple or None

RGBA tuple of the color of the selected label, or None if the background label 0 is selected.

inherited-members:

Methods

as_layer_data_tuple()

bind_key(key_bind[, func, overwrite])

Bind a key combination to a keymap.

block_history()

Context manager to group history-editing operations together.

block_update_properties()

click_plane_from_click_data(click_position, ...)

Calculate a (point, normal) plane parallel to the canvas in data coordinates, centered on the centre of rotation of the camera.

create(data[, meta, layer_type])

Create layer from data of type layer_type.

data_setitem(indices, value[, refresh])

Set indices in data to value, while writing to edit history.

data_to_world(position)

Convert from data coordinates to world coordinates.

fill(coord, new_label[, refresh])

Replace an existing label with a new label, either just at the connected component if the contiguous flag is True or everywhere if it is False, working in the number of dimensions specified by the n_edit_dimensions flag.

get_color(label)

Return the color corresponding to a specific label.

get_ray_intersections(position, ...[, world])

Get the start and end point for the ray extending from a point through the data bounding box.

get_source_str()

get_status([position, view_direction, ...])

Status message information of the data at a coordinate position.

get_value(position, *[, view_direction, ...])

Value of the data at a position.

new_colormap([seed])

paint(coord, new_label[, refresh])

Paint over existing labels with a new label, using the selected brush shape and size, either only on the visible slice or in all n dimensions.

paint_polygon(points, new_label)

Paint a polygon over existing labels with a new label.

projected_distance_from_mouse_drag(...)

Calculate the length of the projection of a line between two mouse clicks onto a vector (or array of vectors) in data coordinates.

redo()

refresh([event])

Refresh all layer data based on current view slice.

save(path[, plugin])

Save this layer to path with default (or specified) plugin.

set_view_slice()

swap_selected_and_background_labels()

Swap between the selected label and the background label.

undo()

world_to_data(position)

Convert from world coordinates to data coordinates.

Attributes

ModeCallable

alias of Callable[[Layer, Event], Union[None, Generator[None, None, None]]]

affine

Extra affine transform to go from physical to world coordinates.

blending

Determines how RGB and alpha values get mixed.

bounding_box

brush_size

Size of the paint in world coordinates.

brush_size_on_mouse_move

class_keymap

colormap

contiguous

fill bucket changes only connected pixels of same label.

contour

displays contours of labels instead of shaded regions.

cursor

String identifying cursor displayed over canvas.

cursor_size

Size of cursor if custom.

custom_interpolation_kernel_2d

data

Image data.

data_level

Current level of multiscale, or 0 if image.

data_raw

Data, exactly as provided by the user.

depiction

The current 3D depiction mode.

downsample_factors

Downsample factors for each level of the multiscale.

dtype

editable

Whether the current layer data is editable from the viewer.

experimental_clipping_planes

extent

Extent of layer in data and world coordinates.

features

Dataframe-like features table.

help

displayed in status bar bottom right.

interactive

keymap

level_shapes

Shapes of each level of the multiscale or just of image.

loaded

True if this layer is fully loaded in memory, False otherwise.

metadata

Key/value map for user-stored data.

mode

Interactive mode.

mouse_pan

Determine if canvas interactive panning is enabled with the mouse.

mouse_zoom

Determine if canvas interactive zooming is enabled with the mouse.

n_edit_dimensions

name

Unique name of the layer.

ndim

Number of dimensions in the data.

opacity

Opacity value between 0.0 and 1.0.

plane

preserve_labels

Defines if painting should preserve existing labels.

projection_mode

Mode of projection of the thick slice onto the viewed dimensions.

properties

Properties for each label.

rendering

Return current rendering mode.

rotate

Rotation matrix in world coordinates.

scale

Anisotropy factors to scale data into world coordinates.

selected_label

Index of selected label.

shear

Shear matrix in world coordinates.

show_selected_label

Whether to filter displayed labels to only the selected label or not

source

thumbnail

Integer array of thumbnail for the layer

translate

Factors to shift the layer by in units of world coordinates.

visible

Whether the visual is currently being displayed.

Details

block_history()[source]#

Context manager to group history-editing operations together.

While in the context, history atoms are grouped together into a “staged” history. When exiting the context, that staged history is committed to the undo history queue, and an event is emitted containing the change.

property brush_size#

Size of the paint in world coordinates.

Type:

float

property contiguous#

fill bucket changes only connected pixels of same label.

Type:

bool

property contour: int#

displays contours of labels instead of shaded regions.

Type:

int

property data: LayerDataProtocol | MultiScaleData#

Image data.

Type:

array

data_setitem(indices, value, refresh=True)[source]#

Set indices in data to value, while writing to edit history.

Parameters:
  • indices (tuple of arrays of int) – Indices in data to overwrite. Must be a tuple of arrays of length equal to the number of data dimensions. (Fancy indexing in [2]).

  • value (int or array of int) – New label value(s). If more than one value, must match or broadcast with the given indices.

  • refresh (bool, default True) – whether to refresh the view, by default True

References

property features#

Dataframe-like features table.

It is an implementation detail that this is a pandas.DataFrame. In the future, we will target the currently-in-development Data API dataframe protocol [1]. This will enable us to use alternate libraries such as xarray or cuDF for additional features without breaking existing usage of this.

If you need to specifically rely on the pandas API, please coerce this to a pandas.DataFrame using features_to_pandas_dataframe.

References

fill(coord, new_label, refresh=True)[source]#

Replace an existing label with a new label, either just at the connected component if the contiguous flag is True or everywhere if it is False, working in the number of dimensions specified by the n_edit_dimensions flag.

Parameters:
  • coord (sequence of float) – Position of mouse cursor in image coordinates.

  • new_label (int) – Value of the new label to be filled in.

  • refresh (bool) – Whether to refresh view slice or not. Set to False to batch paint calls.

get_color(label)[source]#

Return the color corresponding to a specific label.

get_status(position: _SupportsArray[dtype] | _NestedSequence[_SupportsArray[dtype]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None, *, view_direction: _SupportsArray[dtype] | _NestedSequence[_SupportsArray[dtype]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None, dims_displayed: list[int] | None = None, world: bool = False) dict[source]#

Status message information of the data at a coordinate position.

Parameters:
  • position (tuple) – Position in either data or world coordinates.

  • view_direction (Optional[np.ndarray]) – A unit vector giving the direction of the ray in nD world coordinates. The default value is None.

  • dims_displayed (Optional[List[int]]) – A list of the dimensions currently being displayed in the viewer. The default value is None.

  • world (bool) – If True the position is taken to be in world coordinates and converted into data coordinates. False by default.

Returns:

source_info – Dict containing a information that can be used in a status update.

Return type:

dict

property mode#

Interactive mode. The normal, default mode is PAN_ZOOM, which allows for normal interactivity with the canvas.

In PICK mode the cursor functions like a color picker, setting the clicked on label to be the current label. If the background is picked it will select the background label 0.

In PAINT mode the cursor functions like a paint brush changing any pixels it brushes over to the current label. If the background label 0 is selected than any pixels will be changed to background and this tool functions like an eraser. The size and shape of the cursor can be adjusted in the properties widget.

In FILL mode the cursor functions like a fill bucket replacing pixels of the label clicked on with the current label. It can either replace all pixels of that label or just those that are contiguous with the clicked on pixel. If the background label 0 is selected than any pixels will be changed to background and this tool functions like an eraser.

In ERASE mode the cursor functions similarly to PAINT mode, but to paint with background label, which effectively removes the label.

Type:

MODE

paint(coord, new_label, refresh=True)[source]#

Paint over existing labels with a new label, using the selected brush shape and size, either only on the visible slice or in all n dimensions.

Parameters:
  • coord (sequence of int) – Position of mouse cursor in image coordinates.

  • new_label (int) – Value of the new label to be filled in.

  • refresh (bool) – Whether to refresh view slice or not. Set to False to batch paint calls.

paint_polygon(points, new_label)[source]#

Paint a polygon over existing labels with a new label.

Parameters:
  • points (list of coordinates) – List of coordinates of the vertices of a polygon.

  • new_label (int) – Value of the new label to be filled in.

property preserve_labels#

Defines if painting should preserve existing labels.

Default to false to allow paint on existing labels. When set to true, existing labels will be preserved during painting.

property properties: dict[str, ndarray]#

Properties for each label.

Type:

dict {str

Type:

array (N,)}, DataFrame

property rendering#

Return current rendering mode.

Selects a preset rendering mode in vispy that determines how lablels are displayed. Options include:

  • translucent: voxel colors are blended along the view ray until the result is opaque.

  • iso_categorical: isosurface for categorical data. Cast a ray until a non-background value is encountered. At that location, lighning calculations are performed to give the visual appearance of a surface.

Returns:

The current rendering mode

Return type:

str

property selected_label#

Index of selected label.

Type:

int

property show_selected_label#

Whether to filter displayed labels to only the selected label or not

swap_selected_and_background_labels()[source]#

Swap between the selected label and the background label.