napari.layers.Shapes¶
-
class
napari.layers.
Shapes
(data=None, *, ndim=None, properties=None, text=None, shape_type='rectangle', edge_width=1, edge_color='black', edge_color_cycle=None, edge_colormap='viridis', edge_contrast_limits=None, face_color='white', face_color_cycle=None, face_colormap='viridis', face_contrast_limits=None, z_index=0, name=None, metadata=None, scale=None, translate=None, rotate=None, shear=None, affine=None, opacity=0.7, blending='translucent', visible=True)[source]¶ Bases:
napari.layers.base.base.Layer
Shapes layer.
- Parameters
data (list or array) – List of shape data, where each element is an (N, D) array of the N vertices of a shape in D dimensions. Can be an 3-dimensional array if each shape has the same number of vertices.
ndim (int) – Number of dimensions for shapes. When data is not None, ndim must be D. An empty shapes layer can be instantiated with arbitrary ndim.
properties (dict {str: array (N,)}, DataFrame) – Properties for each shape. Each property should be an array of length N, where N is the number of shapes.
text (str, dict) – Text to be displayed with the shapes. If text is set to a key in properties, the value of that property will be displayed. Multiple properties can be composed using f-string-like syntax (e.g., ‘{property_1}, {float_property:.2f}). A dictionary can be provided with keyword arguments to set the text values and display properties. See TextManager.__init__() for the valid keyword arguments. For example usage, see /napari/examples/add_shapes_with_text.py.
shape_type (string or list) – String of shape shape_type, must be one of “{‘line’, ‘rectangle’, ‘ellipse’, ‘path’, ‘polygon’}”. If a list is supplied it must be the same length as the length of data and each element will be applied to each shape otherwise the same value will be used for all shapes.
edge_width (float or list) – Thickness of lines and edges. If a list is supplied it must be the same length as the length of data and each element will be applied to each shape otherwise the same value will be used for all shapes.
edge_color (str, array-like) – If string can be any color name recognized by vispy or hex value if starting with #. If array-like must be 1-dimensional array with 3 or 4 elements. If a list is supplied it must be the same length as the length of data and each element will be applied to each shape otherwise the same value will be used for all shapes.
edge_color_cycle (np.ndarray, list) – Cycle of colors (provided as string name, RGB, or RGBA) to map to edge_color if a categorical attribute is used color the vectors.
edge_colormap (str, napari.utils.Colormap) – Colormap to set edge_color if a continuous attribute is used to set face_color.
edge_contrast_limits (None, (float, float)) – clims for mapping the property to a color map. These are the min and max value of the specified property that are mapped to 0 and 1, respectively. The default value is None. If set the none, the clims will be set to (property.min(), property.max())
face_color (str, array-like) – If string can be any color name recognized by vispy or hex value if starting with #. If array-like must be 1-dimensional array with 3 or 4 elements. If a list is supplied it must be the same length as the length of data and each element will be applied to each shape otherwise the same value will be used for all shapes.
face_color_cycle (np.ndarray, list) – Cycle of colors (provided as string name, RGB, or RGBA) to map to face_color if a categorical attribute is used color the vectors.
face_colormap (str, napari.utils.Colormap) – Colormap to set face_color if a continuous attribute is used to set face_color.
face_contrast_limits (None, (float, float)) – clims for mapping the property to a color map. These are the min and max value of the specified property that are mapped to 0 and 1, respectively. The default value is None. If set the none, the clims will be set to (property.min(), property.max())
z_index (int or list) – Specifier of z order priority. Shapes with higher z order are displayed ontop of others. If a list is supplied it must be the same length as the length of data and each element will be applied to each shape otherwise the same value will be used for all shapes.
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.
-
data
¶ List of shape data, where each element is an (N, D) array of the N vertices of a shape in D dimensions.
- Type
(N, ) list of array
-
properties
¶ Properties for each shape. Each property should be an array of length N, where N is the number of shapes.
- Type
dict {str: array (N,)}, DataFrame
-
text
¶ Text to be displayed with the shapes. If text is set to a key in properties, the value of that property will be displayed. Multiple properties can be composed using f-string-like syntax (e.g., ‘{property_1}, {float_property:.2f}). For example usage, see /napari/examples/add_shapes_with_text.py.
-
shape_type
¶ Name of shape type for each shape.
- Type
(N, ) list of str
-
edge_width
¶ Edge width for each shape.
- Type
(N, ) list of float
-
z_index
¶ z-index for each shape.
- Type
(N, ) list of int
-
current_edge_width
¶ Thickness of lines and edges of the next shape to be added or the currently selected shape.
- Type
-
current_edge_color
¶ Color of the edge of the next shape to be added or the currently selected shape.
- Type
-
current_face_color
¶ Color of the face of the next shape to be added or the currently selected shape.
- Type
-
mode
¶ Interactive mode. The normal, default mode is PAN_ZOOM, which allows for normal interactivity with the canvas.
The SELECT mode allows for entire shapes to be selected, moved and resized.
The DIRECT mode allows for shapes to be selected and their individual vertices to be moved.
The VERTEX_INSERT and VERTEX_REMOVE modes allow for individual vertices either to be added to or removed from shapes that are already selected. Note that shapes cannot be selected in this mode.
The ADD_RECTANGLE, ADD_ELLIPSE, ADD_LINE, ADD_PATH, and ADD_POLYGON modes all allow for their corresponding shape type to be added.
- Type
Mode
-
Extended Summary
-
----------
-
_data_dict
¶ Dictionary containing all the shape data indexed by slice tuple
- Type
Dict of ShapeList
-
_data_view
¶ Object containing the currently viewed shape data.
- Type
ShapeList
-
_mode_history
¶ Interactive mode captured on press of <space>.
- Type
Mode
-
_selected_data_stored
¶ Set of selected previously displayed. Used to prevent rerendering the same highlighted shapes when no data has changed.
- Type
-
_selected_box
¶ None if no shapes are selected, otherwise a 10x2 array of vertices of the interaction box. The first 8 points are the corners and midpoints of the box. The 9th point is the center of the box, and the last point is the location of the rotation handle that can be used to rotate the box.
- Type
None | np.ndarray
-
_drag_start
¶ If a drag has been started and is in progress then a length 2 array of the initial coordinates of the drag. None otherwise.
- Type
None | np.ndarray
-
_drag_box
¶ If a drag box is being created to select shapes then this is a 2x2 array of the two extreme corners of the drag. None otherwise.
- Type
None | np.ndarray
-
_drag_box_stored
¶ If a drag box is being created to select shapes then this is a 2x2 array of the two extreme corners of the drag that have previously been rendered. None otherwise. Used to prevent rerendering the same drag box when no data has changed.
- Type
None | np.ndarray
-
_is_selecting
¶ Bool indicating if a drag box is currently being created in order to select shapes.
- Type
-
_fixed_vertex
¶ If a scaling or rotation is in progress then a length 2 array of the coordinates that are remaining fixed during the move. None otherwise.
- Type
None | np.ndarray
-
_fixed_index
¶ If a scaling or rotation is in progress then the index of the vertex of the boudning box that is remaining fixed during the move. None otherwise.
- Type
-
_update_properties
¶ Bool indicating if properties are to allowed to update the selected shapes when they are changed. Blocking this prevents circular loops when shapes are selected and the properties are changed based on that selection
- Type
-
_allow_thumnail_update
¶ Flag set to true to allow the thumbnail to be updated. Blocking the thumbnail can be advantageous where responsiveness is critical.
- Type
-
_rotation_handle_length
¶ Length of the rotation handle of the boudning box in Canvas coordinates.
- Type
-
_thumbnail_update_thresh
¶ If there are more than this number of shapes, the thumnail won’t update during interactive events
- Type
Methods
Attributes
-
add
(data, *, shape_type='rectangle', edge_width=None, edge_color=None, face_color=None, z_index=None)[source]¶ Add shapes to the current layer.
- Parameters
data (list or array) – List of shape data, where each element is an (N, D) array of the N vertices of a shape in D dimensions. Can be an 3-dimensional array if each shape has the same number of vertices.
shape_type (string | list) – String of shape shape_type, must be one of “{‘line’, ‘rectangle’, ‘ellipse’, ‘path’, ‘polygon’}”. If a list is supplied it must be the same length as the length of data and each element will be applied to each shape otherwise the same value will be used for all shapes.
edge_width (float | list) – thickness of lines and edges. If a list is supplied it must be the same length as the length of data and each element will be applied to each shape otherwise the same value will be used for all shapes.
edge_color (str | tuple | list) – If string can be any color name recognized by vispy or hex value if starting with #. If array-like must be 1-dimensional array with 3 or 4 elements. If a list is supplied it must be the same length as the length of data and each element will be applied to each shape otherwise the same value will be used for all shapes.
face_color (str | tuple | list) – If string can be any color name recognized by vispy or hex value if starting with #. If array-like must be 1-dimensional array with 3 or 4 elements. If a list is supplied it must be the same length as the length of data and each element will be applied to each shape otherwise the same value will be used for all shapes.
z_index (int | list) – Specifier of z order priority. Shapes with higher z order are displayed ontop of others. If a list is supplied it must be the same length as the length of data and each element will be applied to each shape otherwise the same value will be used for all shapes.
-
property
affine
¶ Affine transform.
- 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’).
- 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
coordinates
¶ Cursor position in data coordinates.
-
property
current_properties
¶ properties for the next added shape.
-
property
cursor_size
¶ Size of cursor if custom. None yields default size.
- Type
int | None
-
property
edge_color
¶ Array of RGBA face colors for each shape
- Type
(N x 4) np.ndarray
-
property
edge_color_cycle
¶ Color cycle for edge_color.
Can be a list of colors defined by name, RGB or RGBA
-
property
edge_color_mode
¶ Edge color setting mode
DIRECT (default mode) allows each shape color to be set arbitrarily
CYCLE allows the color to be set via a color cycle over an attribute
COLORMAP allows color to be set via a color map over an attribute
-
property
edge_colormap
¶ Return the colormap to be applied to a property to get the edge color.
- Returns
colormap – The Colormap object.
- Return type
-
property
edge_contrast_limits
¶ contrast limits for mapping the edge_color colormap property to 0 and 1
-
property
edge_width
¶ edge width for each shape.
- Type
list of float
-
expand_shape
(data)[source]¶ Expand shape from 2D to the full data dims.
- Parameters
data (array) – 2D data array of shape to be expanded.
- Returns
data_full – Full D dimensional data array of the shape.
- Return type
array
-
property
extent
¶ Extent of layer in data and world coordinates.
- Return type
Extent
-
property
face_color
¶ Array of RGBA face colors for each shape
- Type
(N x 4) np.ndarray
-
property
face_color_cycle
¶ Color cycle for face_color Can be a list of colors defined by name, RGB or RGBA
- Type
Union[np.ndarray, cycle]
- Return type
-
property
face_color_mode
¶ Face color setting mode
DIRECT (default mode) allows each shape color to be set arbitrarily
CYCLE allows the color to be set via a color cycle over an attribute
COLORMAP allows color to be set via a color map over an attribute
-
property
face_colormap
¶ Return the colormap to be applied to a property to get the face color.
- Returns
colormap – The Colormap object.
- Return type
-
property
face_contrast_limits
¶ clims for mapping the face_color colormap property to 0 and 1
-
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)¶ Status message of the data at a coordinate position.
- Parameters
- 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.
-
interaction_box
(index)[source]¶ Create the interaction box around a shape or list of shapes. If a single index is passed then the boudning box will be inherited from that shapes interaction box. If list of indices is passed it will be computed directly.
- Parameters
index (int | list) – Index of a single shape, or a list of shapes around which to construct the interaction box
- Returns
box – 10x2 array of vertices of the interaction box. The first 8 points are the corners and midpoints of the box in clockwise order starting in the upper-left corner. The 9th point is the center of the box, and the last point is the location of the rotation handle that can be used to rotate the box
- Return type
np.ndarray
-
property
loaded
¶ Return True if this layer is fully loaded in memory.
This base class says that layers are permanently in the loaded state. Derived classes that do asynchronous loading can override this.
- Return type
-
property
mode
¶ Interactive mode. The normal, default mode is PAN_ZOOM, which allows for normal interactivity with the canvas.
The SELECT mode allows for entire shapes to be selected, moved and resized.
The DIRECT mode allows for shapes to be selected and their individual vertices to be moved.
The VERTEX_INSERT and VERTEX_REMOVE modes allow for individual vertices either to be added to or removed from shapes that are already selected. Note that shapes cannot be selected in this mode.
The ADD_RECTANGLE, ADD_ELLIPSE, ADD_LINE, ADD_PATH, and ADD_POLYGON modes all allow for their corresponding shape type to be added.
- Type
MODE
-
property
properties
¶ Annotations for each shape
-
refresh
(event=None)¶ Refresh all layer data based on current view slice.
-
refresh_colors
(update_color_mapping=False)[source]¶ Calculate and update face and edge colors if using a cycle or color map
- Parameters
update_color_mapping (bool) – If set to True, the function will recalculate the color cycle map or colormap (whichever is being used). If set to False, the function will use the current color cycle map or color map. For example, if you are adding/modifying shapes and want them to be colored with the same mapping as the other shapes (i.e., the new shapes shouldn’t affect the color cycle map or colormap), set update_color_mapping=False. Default value is False.
-
refresh_text
()[source]¶ Refresh the text values.
This is generally used if the properties were updated without changing the data
-
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
shape_type
¶ name of shape type for each shape.
- Type
list of str
-
property
shear
¶ Sheer matrix in world coordinates.
- Type
array
-
property
text
¶ The TextManager object containing the text properties
- Type
TextManager
- Return type
TextManager
-
property
thumbnail
¶ Integer array of thumbnail for the layer
- Type
array
-
to_labels
(labels_shape=None)[source]¶ Return an integer labels image.
- Parameters
labels_shape (np.ndarray | tuple | None) – Tuple defining shape of labels image to be generated. If non specified, takes the max of all the vertiecs
- Returns
labels – Integer array where each value is either 0 for background or an integer up to N for points inside the shape at the index value - 1. For overlapping shapes z-ordering will be respected.
- Return type
np.ndarray
-
to_masks
(mask_shape=None)[source]¶ Return an array of binary masks, one for each shape.
- Parameters
mask_shape (np.ndarray | tuple | None) – tuple defining shape of mask to be generated. If non specified, takes the max of all the vertiecs
- Returns
masks – Array where there is one binary mask for each shape
- Return type
np.ndarray
-
property
z_index
¶ z_index for each shape.
- Type
list of int