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, properties=None, rendering='iso_categorical', rotate=None, scale=None, shear=None, translate=None, visible=True)[source]#
Bases:
_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. 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’}.
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.
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:
- num_colors#
Number of unique colors to use in colormap. DEPRECATED: set
colormap
directly, using napari.utils.colormaps.label_colormap.- Type:
- 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:
- contour#
If greater than 0, displays contours of labels instead of shaded regions with a thickness equal to its value. Must be >= 0.
- Type:
- 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:
- 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.
Methods
as_layer_data_tuple
()bind_key
(key[, func, overwrite])Bind a key combination to a keymap.
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.
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 between the selected label and the background label.
undo
()world_to_data
(position)Convert from world coordinates to data coordinates.
Attributes
Extra affine transform to go from physical to world coordinates.
Determines how RGB and alpha values get mixed.
bounding_box
Size of the paint in world coordinates.
class_keymap
custom color dict for label coloring
Color mode to change how color is represented.
colormap
fill bucket changes only connected pixels of same label.
displays contours of labels instead of shaded regions.
String identifying cursor displayed over canvas.
Size of cursor if custom.
custom_interpolation_kernel_2d
Image data.
Current level of multiscale, or 0 if image.
Data, exactly as provided by the user.
The current 3D depiction mode.
Downsample factors for each level of the multiscale.
dtype
Whether the current layer data is editable from the viewer.
Extent of layer in data and world coordinates.
Dataframe-like features table.
displayed in status bar bottom right.
interactive
Shapes of each level of the multiscale or just of image.
Has the data for this layer been loaded yet.
Key/value map for user-stored data.
Interactive mode.
Determine if canvas interactive panning is enabled with the mouse.
Determine if canvas interactive zooming is enabled with the mouse.
Unique name of the layer.
Number of dimensions in the data.
Number of unique colors to use in colormap.
Opacity value between 0.0 and 1.0.
Defines if painting should preserve existing labels.
Properties for each label.
Return current rendering mode.
Rotation matrix in world coordinates.
Anisotropy factors to scale data into world coordinates.
Seed for colormap random generator.
Index of selected label.
Shear matrix in world coordinates.
Whether to filter displayed labels to only the selected label or not
source
Integer array of thumbnail for the layer
Factors to shift the layer by in units of world coordinates.
translate_grid
Whether the visual is currently being displayed.
Details
- property affine#
Extra affine transform to go from physical to world coordinates.
- Type:
napari.utils.transforms.Affine
- 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
, orControl-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’), and blend_equation=(‘func_add’).
- Blending.TRANSLUCENT_NO_DEPTH
Allows for multiple layers to be blended with different opacity, but no depth testing is performed. Corresponds to
depth_test=False
, cull_face=False, blend=True, blend_func=(‘src_alpha’, ‘one_minus_src_alpha’), and blend_equation=(‘func_add’).- 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’), and blend_equation=(‘func_add’).
- Blending.MINIMUM
Allows for multiple layers to be blended together such that the minimum of each RGB component and alpha are selected. Useful for creating overlays with inverted colormaps. It corresponds to depth_test=False, cull_face=False, blend=True, blend_equation=(‘min’).
- Type:
Blending mode
- 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.
- click_plane_from_click_data(click_position: ndarray, view_direction: ndarray, dims_displayed: List) Tuple[ndarray, ndarray] #
Calculate a (point, normal) plane parallel to the canvas in data coordinates, centered on the centre of rotation of the camera.
- Parameters:
click_position (np.ndarray) – click position in world coordinates from mouse event.
view_direction (np.ndarray) – view direction in world coordinates from mouse event.
dims_displayed (List) – dimensions of the data array currently in view.
- Returns:
click_plane – tuple of (plane_position, plane_normal) in data coordinates.
- Return type:
Tuple[np.ndarray, np.ndarray]
- 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.
- classmethod create(data, meta: dict | None = None, layer_type: str | None = None) Layer #
Create layer from data of type layer_type.
Primarily intended for usage by reader plugin hooks and creating a layer from an unwrapped layer data tuple.
- Parameters:
data (Any) – Data in a format that is valid for the corresponding layer_type.
meta (dict, optional) – Dict of keyword arguments that will be passed to the corresponding layer constructor. If any keys in meta are not valid for the corresponding layer type, an exception will be raised.
layer_type (str) – Type of layer to add. Must be the (case insensitive) name of a Layer subclass. If not provided, the layer is assumed to be “image”, unless data.dtype is one of (np.int32, np.uint32, np.int64, np.uint64), in which case it is assumed to be “labels”.
- Raises:
ValueError – If
layer_type
is not one of the recognized layer types.TypeError – If any keyword arguments in
meta
are unexpected for the corresponding add_* method for this layer_type.
Examples
A typical use case might be to upack a tuple of layer data with a specified layer_type.
>>> data = ( ... np.random.random((10, 2)) * 20, ... {'face_color': 'blue'}, ... 'points', ... ) >>> Layer.create(*data)
- property data#
Image data.
- Type:
array
- property data_raw#
Data, exactly as provided by the user.
- 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 [1]_).
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
..[1] https://numpy.org/doc/stable/user/basics.indexing.html
- data_to_world(position)#
Convert from data coordinates to world coordinates.
- property depiction#
The current 3D depiction mode.
- Selects a preset depiction mode in vispy
volume: images are rendered as 3D volumes.
- plane: images are rendered as 2D planes embedded in 3D.
plane position, normal, and thickness are attributes of layer.plane which can be modified directly.
- property extent: Extent#
Extent of layer in data and world coordinates.
- 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.
- get_ray_intersections(position: List[float], view_direction: ndarray, dims_displayed: List[int], world: bool = True) Tuple[ndarray, ndarray] | Tuple[None, None] #
Get the start and end point for the ray extending from a point through the data bounding box.
- Parameters:
position – the position of the point in nD coordinates. World vs. data is set by the world keyword argument.
view_direction (np.ndarray) – a unit vector giving the direction of the ray in nD coordinates. World vs. data is set by the world keyword argument.
dims_displayed – a list of the dimensions currently being displayed in the viewer.
world (bool) – True if the provided coordinates are in world coordinates. Default value is True.
- Returns:
start_point (np.ndarray) – The point on the axis-aligned data bounding box that the cursor click intersects with. This is the point closest to the camera. The point is the full nD coordinates of the layer data. If the click does not intersect the axis-aligned data bounding box, None is returned.
end_point (np.ndarray) – The point on the axis-aligned data bounding box that the cursor click intersects with. This is the point farthest from the camera. The point is the full nD coordinates of the layer data. If the click does not intersect the axis-aligned data bounding box, None is returned.
- get_status(position: Tuple | None = None, *, view_direction: ndarray | 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:
- get_value(position: Tuple[float], *, view_direction: ndarray | None = None, dims_displayed: List[int] | None = None, world=False)#
Value of the data at a position.
If the layer is not visible, return None.
- Parameters:
position (tuple of float) – 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:
value – Value of the data. If the layer is not visible return None.
- Return type:
tuple, None
- 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
- 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.
- 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.
- projected_distance_from_mouse_drag(start_position: ndarray, end_position: ndarray, view_direction: ndarray, vector: ndarray, dims_displayed: List | ndarray)#
Calculate the length of the projection of a line between two mouse clicks onto a vector (or array of vectors) in data coordinates.
- Parameters:
start_position (np.ndarray) – Starting point of the drag vector in data coordinates
end_position (np.ndarray) – End point of the drag vector in data coordinates
view_direction (np.ndarray) – Vector defining the plane normal of the plane onto which the drag vector is projected.
vector (np.ndarray) – (3,) unit vector or (n, 3) array thereof on which to project the drag vector from start_event to end_event. This argument is defined in data coordinates.
dims_displayed (Union[List, np.ndarray]) – (3,) list of currently displayed dimensions
- Returns:
projected_distance
- Return type:
(1, ) or (n, ) np.ndarray of float
- property properties: Dict[str, ndarray]#
Properties for each label.
- Type:
dict {str
- Type:
array (N,)}, DataFrame
- 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 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:
- property rotate#
Rotation matrix in world coordinates.
- Type:
array
- save(path: str, plugin: str | None = None) List[str] #
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:
- property shear#
Shear matrix in world coordinates.
- Type:
array
- 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.
- property thumbnail#
Integer array of thumbnail for the layer
- Type:
array
- world_to_data(position)#
Convert from world coordinates to data coordinates.