napari.components package

Submodules

napari.components.add_layers_mixin module

class AddLayersMixin[source]

Bases: object

A mixin that adds add_* methods for adding layers to the ViewerModel.

Each method corresponds to adding one or more layers to the viewer. Methods that just add a single layer contain the keyword arguments and copies of the documentation from that the layer. These are copied and pasted instead of being autogenerated because IDEs like PyCharm parse the source code for docs instead of pulling it up dynamically.

These methods are separated into a mixin to keep the ViewerModel class easier to read and make these methods easier to maintain.

add_image(data=None, *, channel_axis=None, rgb=None, colormap=None, contrast_limits=None, gamma=1, interpolation='nearest', rendering='mip', iso_threshold=0.5, attenuation=0.05, name=None, metadata=None, scale=None, translate=None, opacity=1, blending=None, visible=True, multiscale=None) → Union[napari.layers.image.image.Image, List[napari.layers.image.image.Image]][source]

Add an image layer to the layers list.

Parameters
  • data (array or list of array) – Image data. Can be N dimensional. If the last dimension has length 3 or 4 can be interpreted as RGB or RGBA if rgb is True. If a list and arrays are decreasing in shape then the data is treated as a multiscale image.

  • channel_axis (int, optional) – Axis to expand image along. If provided, each channel in the data will be added as an individual image layer. In channel_axis mode, all other parameters MAY be provided as lists, and the Nth value will be applied to the Nth channel in the data. If a single value is provided, it will be broadcast to all Layers.

  • rgb (bool or list) – Whether the image is rgb RGB or RGBA. If not specified by user and the last dimension of the data has length 3 or 4 it will be set as True. If False the image is interpreted as a luminance image. If a list then must be same length as the axis that is being expanded as channels.

  • colormap (str, napari.utils.Colormap, tuple, dict, list) – Colormaps to use for luminance images. If a string must be the name of a supported colormap from vispy or matplotlib. If a tuple the first value must be a string to assign as a name to a colormap and the second item must be a Colormap. If a dict the key must be a string to assign as a name to a colormap and the value must be a Colormap. If a list then must be same length as the axis that is being expanded as channels, and each colormap is applied to each new image layer.

  • contrast_limits (list (2,)) – Color limits to be used for determining the colormap bounds for luminance images. If not passed is calculated as the min and max of the image. If list of lists then must be same length as the axis that is being expanded and then each colormap is applied to each image.

  • gamma (list, float) – Gamma correction for determining colormap linearity. Defaults to 1. If a list then must be same length as the axis that is being expanded as channels.

  • interpolation (str or list) – Interpolation mode used by vispy. Must be one of our supported modes. If a list then must be same length as the axis that is being expanded as channels.

  • rendering (str or list) – Rendering mode used by vispy. Must be one of our supported modes. If a list then must be same length as the axis that is being expanded as channels.

  • iso_threshold (float or list) – Threshold for isosurface. If a list then must be same length as the axis that is being expanded as channels.

  • attenuation (float or list) – Attenuation rate for attenuated maximum intensity projection. If a list then must be same length as the axis that is being expanded as channels.

  • name (str or list of str) – Name of the layer. If a list then must be same length as the axis that is being expanded as channels.

  • metadata (dict or list of dict) – Layer metadata. If a list then must be a list of dicts with the same length as the axis that is being expanded as channels.

  • scale (tuple of float or list) – Scale factors for the layer. If a list then must be a list of tuples of float with the same length as the axis that is being expanded as channels.

  • translate (tuple of float or list) – Translation values for the layer. If a list then must be a list of tuples of float with the same length as the axis that is being expanded as channels.

  • opacity (float or list) – Opacity of the layer visual, between 0.0 and 1.0. If a list then must be same length as the axis that is being expanded as channels.

  • blending (str or list) – 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’}. If a list then must be same length as the axis that is being expanded as channels.

  • visible (bool or list of bool) – Whether the layer visual is currently being displayed. If a list then must be same length as the axis that is being expanded as channels.

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

Returns

layer – The newly-created image layer or list of image layers.

Return type

napari.layers.Image or list

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

Add a labels (or segmentation) layer to the layers list.

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

Using the viewer’s label editing tools (painting, erasing) will modify the input-array in-place.

To avoid this, pass a copy as follows:

layer = viewer.add_labels(data.copy()) # do some painting/editing

Get the modified labels as follows:

result = layer.data

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.

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

Returns

layer – The newly-created labels layer.

Return type

napari.layers.Labels

add_layer(layer: napari.layers.base.base.Layer)napari.layers.base.base.Layer[source]

Add a layer to the viewer.

Parameters

layer (napari.layers.Layer) – Layer to add.

Returns

layer – The layer that was added (same as input).

Return type

napari.layers.Layer or list

add_points(data=None, *, properties=None, text=None, symbol='o', size=10, 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, n_dimensional=False, name=None, metadata=None, scale=None, translate=None, opacity=1, blending='translucent', visible=True)napari.layers.points.points.Points[source]

Add a points layer to the layers list.

Parameters
  • data (array (N, D)) – Coordinates for N points in D dimensions.

  • properties (dict {str: array (N,)}, DataFrame) – Properties for each point. Each property should be an array of length N, where N is the number of points.

  • text (str, dict) – Text to be displayed with the points. 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_points_with_text.py.

  • symbol (str) – Symbol to be used for the point markers. Must be one of the following: arrow, clobber, cross, diamond, disc, hbar, ring, square, star, tailed_arrow, triangle_down, triangle_up, vbar, x.

  • size (float, array) – Size of the point marker. If given as a scalar, all points are made the same size. If given as an array, size must be the same broadcastable to the same shape as the data.

  • edge_width (float) – Width of the symbol edge in pixels.

  • edge_color (str, array-like) – Color of the point marker border. Numeric color values should be RGB(A).

  • 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) – Color of the point marker body. Numeric color values should be RGB(A).

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

  • n_dimensional (bool) – If True, renders points not just in central plane but also in all n-dimensions according to specified point marker size.

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

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

Returns

layer – The newly-created points layer.

Return type

napari.layers.Points

Notes

See vispy’s marker visual docs for more details: http://api.vispy.org/en/latest/visuals.html#vispy.visuals.MarkersVisual

add_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, opacity=0.7, blending='translucent', visible=True)napari.layers.shapes.shapes.Shapes[source]

Add a shapes layer to the layers list.

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.

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

Returns

layer – The newly-created shapes layer.

Return type

napari.layers.Shapes

add_surface(data, *, colormap='gray', contrast_limits=None, gamma=1, name=None, metadata=None, scale=None, translate=None, opacity=1, blending='translucent', visible=True)napari.layers.surface.surface.Surface[source]

Add a surface layer to the layers list.

Parameters
  • data (3-tuple of array) – The first element of the tuple is an (N, D) array of vertices of mesh triangles. The second is an (M, 3) array of int of indices of the mesh triangles. The third element is the (K0, …, KL, N) array of values used to color vertices where the additional L dimensions are used to color the same mesh with different values.

  • colormap (str, napari.utils.Colormap, tuple, dict) – Colormap to use for luminance images. If a string must be the name of a supported colormap from vispy or matplotlib. If a tuple the first value must be a string to assign as a name to a colormap and the second item must be a Colormap. If a dict the key must be a string to assign as a name to a colormap and the value must be a Colormap.

  • contrast_limits (list (2,)) – Color limits to be used for determining the colormap bounds for luminance images. If not passed is calculated as the min and max of the image.

  • gamma (float) – Gamma correction for determining colormap linearity. Defaults to 1.

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

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

Returns

layer – The newly-created surface layer.

Return type

napari.layers.Surface

add_vectors(data, *, properties=None, edge_width=1, edge_color='red', edge_color_cycle=None, edge_colormap='viridis', edge_contrast_limits=None, length=1, name=None, metadata=None, scale=None, translate=None, opacity=0.7, blending='translucent', visible=True)napari.layers.vectors.vectors.Vectors[source]

Add a vectors layer to the layers list.

Parameters
  • data ((N, 2, D) or (N1, N2, .., ND, D) array) – An (N, 2, D) array is interpreted as “coordinate-like” data and a list of N vectors with start point and projections of the vector in D dimensions. An (N1, N2, …, ND, D) array is interpreted as “image-like” data where there is a length D vector of the projections at each pixel.

  • properties (dict {str: array (N,)}, DataFrame) – Properties for each vector. Each property should be an array of length N, where N is the number of vectors.

  • edge_width (float) – Width for all vectors in pixels.

  • length (float) – Multiplicative factor on projections for length of all vectors.

  • edge_color (str) – Color of all of the vectors.

  • 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 vector color if a continuous attribute is used to set edge_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())

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

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

Returns

layer – The newly-created vectors layer.

Return type

napari.layers.Vectors

open(path: Union[str, Sequence[str]], *, stack: bool = False, plugin: Optional[str] = None, layer_type: Optional[str] = None, **kwargs) → List[napari.layers.base.base.Layer][source]

Open a path or list of paths with plugins, and add layers to viewer.

A list of paths will be handed one-by-one to the napari_get_reader hook if stack is False, otherwise the full list is passed to each plugin hook.

Parameters
  • path (str or list of str) – A filepath, directory, or URL (or a list of any) to open.

  • stack (bool, optional) – If a list of strings is passed and stack is True, then the entire list will be passed to plugins. It is then up to individual plugins to know how to handle a list of paths. If stack is False, then the path list is broken up and passed to plugin readers one by one. by default False.

  • plugin (str, optional) – Name of a plugin to use. If provided, will force path to be read with the specified plugin. If the requested plugin cannot read path, an exception will be raised.

  • layer_type (str, optional) – If provided, will force data read from path to be passed to the corresponding add_<layer_type> method (along with any additional) kwargs provided to this function. This may result in exceptions if the data returned from the path is not compatible with the layer_type.

  • **kwargs – All other keyword arguments will be passed on to the respective add_layer method.

Returns

layers – A list of any layers that were added to the viewer.

Return type

list

prune_kwargs(kwargs: Dict[str, Any], layer_type: str) → Dict[str, Any][source]

Return copy of kwargs with only keys valid for add_<layer_type>

Parameters
  • kwargs (dict) – A key: value mapping where some or all of the keys are parameter names for the corresponding Viewer.add_<layer_type> method.

  • layer_type (str) – The type of layer that is going to be added with these kwargs.

Returns

pruned_kwargs – A key: value mapping where all of the keys are valid parameter names for the corresponding Viewer.add_<layer_type> method.

Return type

dict

Raises

ValueError – If AddLayersMixin does not provide an add_<layer_type> method for the provided layer_type.

Examples

>>> test_kwargs = {
...     'scale': (0.75, 1),
...     'blending': 'additive',
...     'num_colors': 10,
... }
>>> prune_kwargs(test_kwargs, 'image')
{'scale': (0.75, 1), 'blending': 'additive'}
>>> # only labels has the ``num_colors`` argument
>>> prune_kwargs(test_kwargs, 'labels')
{'scale': (0.75, 1), 'blending': 'additive', 'num_colors': 10}
valid_add_kwargs() → Dict[str, Set[str]][source]

Return a dict where keys are layer types & values are valid kwargs.

napari.components.dims module

class Dims(ndim=None, *, ndisplay=2, order=None, axis_labels=None)[source]

Bases: object

Dimensions object modeling slicing and displaying.

Parameters
  • ndim (int, optional) – Number of dimensions

  • ndisplay (int, optional) – Number of displayed dimensions.

  • order (list of int, optional) – Order in which dimensions are displayed where the last two or last three dimensions correspond to row x column or plane x row x column if ndisplay is 2 or 3.

  • axis_labels (list of str, optional) – Dimension names

events

Event emitter group

Type

EmitterGroup

range

List of tuples (min, max, step), one for each dimension. In a world coordinates space.

Type

list of 3-tuple

point

List of floats setting the current value of the range slider when in POINT mode, one for each dimension. In a world coordinates space.

Type

list of float

current_step

Tuple the slider position for each dims slider, in slider coordinates.

Type

tuple of int

nsteps

Number of steps available to each slider.

Type

tuple of int

ndim

Number of dimensions.

Type

int

displayed

List of dimensions that are displayed.

Type

tuple

not_displayed

List of dimensions that are not displayed.

Type

tuple

displayed_order

Order of only displayed dimensions.

Type

tuple

property axis_labels

List of labels for each axis.

property current_step

value of slider position for each dimension.

Type

Tuple of int

property displayed

Dimensions that are displayed.

Type

Tuple

property displayed_order

Order of only displayed dimensions.

Type

Tuple

property ndim

Returns the number of dimensions.

Returns

ndim – Number of dimensions

Return type

int

property ndisplay

Number of displayed dimensions.

Type

Int

property not_displayed

Dimensions that are not displayed.

Type

Tuple

property nsteps

Number of slider steps for each dimension.

property order

Display order of dimensions.

Type

List of int

property point

value of each dimension.

Type

List of float

property range

(min, max, step size) of each dimension.

Type

List of 3-tuple

reset()[source]

Reset dims values to initial states.

set_axis_label(axis: int, label: str)[source]

Sets a new axis label for the given axis.

Parameters
  • axis (int) – Dimension index

  • label (str) – Given label

set_current_step(axis: int, value: int)[source]

Sets the slider step at which to slice this dimension.

The position of the slider in world coordinates gets calculated from the current_step of the slider.

Parameters
  • axis (int) – Dimension index.

  • value (int or float) – Value of the point.

set_point(axis: int, value: Union[int, float])[source]

Sets point to slice dimension in world coordinates.

The desired point gets transformed into an integer step of the slider and stored in the current_step.

Parameters
  • axis (int) – Dimension index.

  • value (int or float) – Value of the point.

set_range(axis: int, _range: Sequence[Union[int, float]])[source]

Sets the range (min, max, step) for a given dimension.

Parameters
  • axis (int) – Dimension index.

  • _range (tuple) – Range specified as (min, max, step).

napari.components.layerlist module

class LayerList(iterable=)[source]

Bases: napari.utils.list._model.ListModel

List-like layer collection with built-in reordering and callback hooks.

Parameters

iterable (iterable) – Iterable of napari.layer.Layer

events
Event hooks:
  • added(item, index): whenever an item is added

  • removed(item): whenever an item is removed

  • reordered(): whenever the list is reordered

Type

vispy.util.event.EmitterGroup

move_selected(index, insert)[source]

Reorder list by moving the item at index and inserting it at the insert index. If additional items are selected these will get inserted at the insert index too. This allows for rearranging the list based on dragging and dropping a selection of items, where index is the index of the primary item being dragged, and insert is the index of the drop location, and the selection indicates if multiple items are being dragged. If the moved layer is not selected select it.

Parameters
  • index (int) – Index of primary item to be moved

  • insert (int) – Index that item(s) will be inserted at

property ndim

Maximum dimensionality of layers.

Defaults to 2 if no data is present.

Returns

ndim

Return type

int

remove_selected()[source]

Removes selected items from list.

save(path: str, *, selected: bool = False, plugin: Optional[str] = None) → List[str][source]

Save all or only selected layers to a path using writer plugins.

If plugin is not provided and only one layer is targeted, then we directly call the corresponding``napari_write_<layer_type>`` hook (see single layer writer hookspecs) which will loop through implementations and stop when the first one returns a non-None result. The order in which implementations are called can be changed with the Plugin sorter in the GUI or with the corresponding hook’s bring_to_front() method.

If plugin is not provided and multiple layers are targeted, then we call napari_get_writer() which loops through plugins to find the first one that knows how to handle the combination of layers and is able to write the file. If no plugins offer napari_get_writer() for that combination of layers then the default napari_get_writer() will create a folder and call napari_write_<layer_type> for each layer using the Layer.name variable to modify the path such that the layers are written to unique files in the folder.

If plugin is provided and a single layer is targeted, then we call the napari_write_<layer_type> for that plugin, and if it fails we error.

If plugin is provided and multiple layers are targeted, then we call we call napari_get_writer() for that plugin, and if it doesn’t return a WriterFunction we error, otherwise we call it and if that fails if it we error.

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

  • selected (bool) – Optional flag to only save selected layers. False by default.

  • 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

select_all()[source]

Selects all layers.

select_next(shift=False)[source]

Selects next item from list.

select_previous(shift=False)[source]

Selects previous item from list.

property selected

List of selected layers.

toggle_selected_visibility()[source]

Toggle visibility of selected layers

unselect_all(ignore=None)[source]

Unselects all layers expect any specified in ignore.

Parameters

ignore (Layer | None) – Layer that should not be unselected if specified.

napari.components.viewer_model module

class ViewerModel(title='napari', ndisplay=2, order=None, axis_labels=None)[source]

Bases: napari.components.add_layers_mixin.AddLayersMixin, napari.utils.key_bindings.KeymapHandler, napari.utils.key_bindings.KeymapProvider

Viewer containing the rendered scene, layers, and controlling elements including dimension sliders, and control bars for color limits.

Parameters
  • title (string) – The title of the viewer window.

  • ndisplay ({2, 3}) – Number of displayed dimensions.

  • order (tuple of int) – Order in which dimensions are displayed where the last two or last three dimensions correspond to row x column or plane x row x column if ndisplay is 2 or 3.

  • = list of str (axis_labels) – Dimension names.

window

Parent window.

Type

Window

layers

List of contained layers.

Type

LayerList

dims

Contains axes, indices, dimensions and sliders.

Type

Dimensions

themes

Preset color palettes.

Type

dict of str: dict of str: str

property active_layer

index of active_layer

Type

int

class_keymap = {}
property cursor

String identifying cursor displayed over canvas.

Type

string

property cursor_size

Size of cursor if custom. None is yields default size

Type

int | None

property grid_size

Size of grid

Type

tuple

grid_view(n_row=None, n_column=None, stride=1)[source]

Arrange the current layers is a 2D grid.

Default behaviour is to make a square 2D grid.

Parameters
  • n_row (int, optional) – Number of rows in the grid.

  • n_column (int, optional) – Number of column in the grid.

  • stride (int, optional) – Number of layers to place in each grid square before moving on to the next square. The default ordering is to place the most visible layer in the top left corner of the grid. A negative stride will cause the order in which the layers are placed in the grid to be reversed.

property help

String that can be displayed to the user in the status bar with helpful usage tips.

Type

string

property interactive

Determines if canvas pan/zoom interactivity is enabled or not.

Type

bool

property palette

Color palette with which to style the viewer.

Type

dict of str

Type

str

reset_view(event=None)[source]

Resets the camera’s view using event.rect a 4-tuple of the x, y corner position followed by width and height of the camera

stack_view()[source]

Arrange the current layers is a stack.

property status

Status string

Type

string

property theme

Preset color palette.

Type

string or None

themes = {'dark': {'background': 'rgb(38, 41, 48)', 'canvas': 'black', 'console': 'rgb(0, 0, 0)', 'current': 'rgb(0, 122, 204)', 'folder': 'dark', 'foreground': 'rgb(65, 72, 81)', 'highlight': 'rgb(106, 115, 128)', 'icon': 'rgb(209, 210, 212)', 'primary': 'rgb(90, 98, 108)', 'secondary': 'rgb(134, 142, 147)', 'syntax_style': 'native', 'text': 'rgb(240, 241, 242)', 'warning': 'rgb(153, 18, 31)'}, 'light': {'background': 'rgb(239, 235, 233)', 'canvas': 'white', 'console': 'rgb(255, 255, 255)', 'current': 'rgb(253, 240, 148)', 'folder': 'light', 'foreground': 'rgb(214, 208, 206)', 'highlight': 'rgb(163, 158, 156)', 'icon': 'rgb(107, 105, 103)', 'primary': 'rgb(188, 184, 181)', 'secondary': 'rgb(150, 146, 144)', 'syntax_style': 'default', 'text': 'rgb(59, 58, 57)', 'warning': 'rgb(255, 18, 31)'}}
property title

String that is displayed in window title.

Type

string

Module contents

napari.components provides the public-facing models for widgets and other utilities that the user will be able to programmatically interact with.

Classes

Dims

Current indices along each data dimension, together with which dimensions are being displayed, projected, sliced…

LayerList

List of layers currently present in the viewer.

ViewerModel

Data viewer displaying the currently rendered scene and layer-related controls.