napari.layers.Labels

class napari.layers.Labels(data, *, num_colors=50, properties=None, color=None, seed=0.5, name=None, metadata=None, scale=None, translate=None, rotate=None, shear=None, affine=None, opacity=0.7, blending='translucent', visible=True, multiscale=None)[source]

Bases: napari.layers.image.image._ImageBase

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.

  • num_colors (int) – Number of unique colors to use in colormap.

  • properties (dict {str: array (N,)}, 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.

  • color (dict of int to str or array) – Custom label to color mapping. Values must be valid color names or RGBA arrays.

  • seed (float) – Seed for colormap random generator.

  • name (str) – Name of the layer.

  • metadata (dict) – Layer metadata.

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

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

  • 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.

  • 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.

  • 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 lenght N translation vector and a 1 or a napari AffineTransform object. If provided then translate, scale, rotate, and shear values are ignored.

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

  • 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’}.

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

  • 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.

data

Integer valued label data. Can be N dimensional. Every pixel contains an integer ID corresponding to the region it belongs to. The label 0 is rendered as transparent.

Type

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.

Type

bool

metadata

Labels metadata.

Type

dict

num_colors

Number of unique colors to use in colormap.

Type

int

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.

Type

dict of int to str or array

seed

Seed for colormap random generator.

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_dimensional

If True, paint and fill edit labels across all dimensions.

Type

bool

contour

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

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

Extended Summary
----------
_data_raw

2D labels data for the currently viewed slice.

Type

array (N, M)

_selected_color

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

Type

4-tuple or None

Methods

Attributes

property affine

Affine transform.

Type

napari.utils.transforms.Affine

property attenuation

attenuation rate for attenuated_mip rendering.

Type

float

bind_key(key, func=<object object>, *, overwrite=False)

Bind a key combination to a keymap.

Parameters
  • keymap (dict of str: callable) – Keymap to modify.

  • key (str or ..) – Key combination. ... acts as a wildcard if no key combinations can be matched in the keymap (this will overwrite all key combinations further down the lookup chain).

  • func (callable, None, or ..) – Callable to bind to the key combination. If None is passed, unbind instead. ... acts as a blocker, effectively unbinding the key combination for all keymaps further down the lookup chain.

  • overwrite (bool, keyword-only, optional) – Whether to overwrite the key combination if it already exists.

Returns

unbound – Callable unbound by this operation, if any.

Return type

callable or None

Notes

Key combinations are represented in the form [modifier-]key, e.g. a, Control-c, or Control-Alt-Delete. Valid modifiers are Control, Alt, Shift, and Meta.

Letters will always be read as upper-case. Due to the native implementation of the key system, Shift pressed in certain key combinations may yield inconsistent or unexpected results. Therefore, it is not recommended to use Shift with non-letter keys. On OSX, Control is swapped with Meta such that pressing Command reads as Control.

Special keys include Shift, Control, Alt, Meta, Up, Down, Left, Right, PageUp, PageDown, Insert, Delete, Home, End, Escape, Backspace, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Space, Enter, and Tab

Functions take in only one argument: the parent that the function was bound to.

By default, all functions are assumed to work on key presses only, but can be denoted to work on release too by separating the function into two statements with the yield keyword:

@viewer.bind_key('h')
def hello_world(viewer):
    # on key press
    viewer.status = 'hello world!'

    yield

    # on key release
    viewer.status = 'goodbye world :('

To create a keymap that will block others, bind_key(..., ...)`.

property blending

Determines how RGB and alpha values get mixed.

Blending.OPAQUE

Allows for only the top layer to be visible and corresponds to depth_test=True, cull_face=False, blend=False.

Blending.TRANSLUCENT

Allows for multiple layers to be blended with different opacity and corresponds to depth_test=True, cull_face=False, blend=True, blend_func=(‘src_alpha’, ‘one_minus_src_alpha’).

Blending.ADDITIVE

Allows for multiple layers to be blended together with different colors and opacity. Useful for creating overlays. It corresponds to depth_test=False, cull_face=False, blend=True, blend_func=(‘src_alpha’, ‘one’).

Type

Blending mode

property brush_shape

Paintbrush shape

Type

str

property brush_size

Size of the paint in world coordinates.

Type

float

property color

custom color dict for label coloring

Type

dict

property color_mode

Color mode to change how color is represented.

AUTO (default) allows color to be set via a hash function with a seed.

DIRECT allows color of each label to be set directly by a color dict.

property colormap

colormap for luminance images.

Type

napari.utils.Colormap

property colormaps

names of available colormaps.

Type

tuple of str

property contiguous

fill bucket changes only connected pixels of same label.

Type

bool

property contour

displays contours of labels instead of shaded regions.

Type

int

property contrast_limits

Limits to use for the colormap.

Type

list of float

property contrast_limits_range

The current valid range of the contrast limits.

property coordinates

Cursor position in data coordinates.

property cursor

String identifying cursor displayed over canvas.

Type

str

property cursor_size

Size of cursor if custom. None yields default size.

Type

int | None

property data

Image data.

Type

array

property data_level

Current level of multiscale, or 0 if image.

Type

int

property displayed_coordinates

List of currently displayed coordinates.

Type

list

property downsample_factors

Downsample factors for each level of the multiscale.

Type

list

property editable

Whether the current layer data is editable from the viewer.

Type

bool

property extent

Extent of layer in data and world coordinates.

Return type

Extent

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 either just in the current slice if the n_dimensional flag is False or on the entire data if it is True.

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_message()

Generate a status message based on the coordinates and value

Returns

msg – String containing a message that can be used as a status update.

Return type

string

get_status(position=None, world=False)[source]

Status message of the data at a coordinate position.

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

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

Returns

msg – String containing a message that can be used as a status update.

Return type

string

get_value(position=None, *, world=False)

Value of the data at a position.

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

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

Returns

value – Value of the data.

Return type

tuple, None

property help

displayed in status bar bottom right.

Type

str

property interactive

Determine if canvas pan/zoom interactivity is enabled.

Type

bool

property interpolation

Return current interpolation mode.

Selects a preset interpolation mode in vispy that determines how volume is displayed. Makes use of the two Texture2D interpolation methods and the available interpolation methods defined in vispy/gloo/glsl/misc/spatial_filters.frag

Options include: ‘bessel’, ‘bicubic’, ‘bilinear’, ‘blackman’, ‘catrom’, ‘gaussian’, ‘hamming’, ‘hanning’, ‘hermite’, ‘kaiser’, ‘lanczos’, ‘mitchell’, ‘nearest’, ‘spline16’, ‘spline36’

Returns

The current interpolation mode

Return type

str

property iso_threshold

threshold for isosurface.

Type

float

property level_shapes

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

Type

array

property loaded

Has the data for this layer been loaded yet.

With asynchronous loading the layer might exist but its data for the current slice has not been loaded.

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

property n_dimensional

paint and fill edits labels across all dimensions.

Type

bool

property name

Unique name of the layer.

Type

str

property ndim

Number of dimensions in the data.

Type

int

property num_colors

Number of unique colors to use in colormap.

Type

int

property opacity

Opacity value between 0.0 and 1.0.

Type

float

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.

property position

Cursor position in world slice coordinates.

Type

tuple

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

Properties for each label.

Type

dict {str

Type

array (N,)}, DataFrame

Return type

Dict[str, ndarray]

refresh(event=None)

Refresh all layer data based on current view slice.

property rendering

Return current rendering mode.

Selects a preset rendering mode in vispy that determines how volume is displayed. Options include:

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

  • mip: maximum intensity projection. Cast a ray and display the maximum value that was encountered.

  • additive: voxel colors are added along the view ray until the result is saturated.

  • iso: isosurface. Cast a ray until a certain threshold is encountered. At that location, lighning calculations are performed to give the visual appearance of a surface.

  • attenuated_mip: attenuated maximum intensity projection. Cast a ray and attenuate values based on integral of encountered values, display the maximum value that was encountered after attenuation. This will make nearer objects appear more prominent.

Returns

The current rendering mode

Return type

str

reset_contrast_limits()

Scale contrast limits to data range

reset_contrast_limits_range()

Scale contrast limits range to data type.

Currently, this only does something if the data type is an unsigned integer… otherwise it’s unclear what the full range should be.

property rotate

Rotation matrix in world coordinates.

Type

array

save(path, plugin=None)

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

Parameters
  • path (str) – A filepath, directory, or URL to open. Extensions may be used to specify output format (provided a plugin is available for the requested format).

  • plugin (str, optional) – Name of the plugin to use for saving. If None then all plugins corresponding to appropriate hook specification will be looped through to find the first one that can save the data.

Returns

File paths of any files that were written.

Return type

list of str

property scale

Anisotropy factors to scale data into world coordinates.

Type

list

property seed

Seed for colormap random generator.

Type

float

property selected

Whether this layer is selected or not.

Type

bool

property selected_label

Index of selected label.

Type

int

property shear

Sheer matrix in world coordinates.

Type

array

property show_selected_label

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

property status

displayed in status bar bottom left.

Type

str

property thumbnail

Integer array of thumbnail for the layer

Type

array

property translate

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

Type

list

property translate_grid

Factors to shift the layer by.

Type

list

property visible

Whether the visual is currently being displayed.

Type

bool