napari.layers.Image#
- class napari.layers.Image(data, *, affine=None, attenuation=0.05, axis_labels=None, blending='translucent', cache=True, colormap='gray', contrast_limits=None, custom_interpolation_kernel_2d=None, depiction='volume', experimental_clipping_planes=None, gamma=1.0, interpolation2d='nearest', interpolation3d='linear', iso_threshold=None, metadata=None, multiscale=None, name=None, opacity=1.0, plane=None, projection_mode='none', rendering='mip', rgb=None, rotate=None, scale=None, shear=None, translate=None, units=None, visible=True)[source]#
Bases:
IntensityVisualizationMixin
,ScalarFieldBase
Image layer.
- Parameters:
data (array or list of array) – Image data. Can be N >= 2 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. 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.
attenuation (float) – Attenuation rate for attenuated maximum intensity projection.
axis_labels (tuple of str) – Dimension names of the layer data. If not provided, axis_labels will be set to (…, ‘axis -2’, ‘axis -1’).
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 {‘translucent’, ‘translucent_no_depth’, ‘additive’, ‘minimum’, ‘opaque’}.
cache (bool) – Whether slices of out-of-core datasets should be cached upon retrieval. Currently, this only applies to dask arrays.
colormap (str, napari.utils.Colormap, tuple, dict) – Colormaps to use for luminance images. If a string, it can be the name of a supported colormap from vispy or matplotlib or the name of a vispy color or a hexadecimal RGB color representation. 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,)) – Intensity value limits to be used for determining the minimum and maximum colormap bounds for luminance images. If not passed, they will be calculated as the min and max intensity value of the image.
custom_interpolation_kernel_2d (np.ndarray) – Convolution kernel used with the ‘custom’ interpolation mode in 2D rendering.
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.
gamma (float) – Gamma correction for determining colormap linearity; defaults to 1.
interpolation2d (str) – Interpolation mode used by vispy for rendering 2d data. Must be one of our supported modes. (for list of supported modes see Interpolation enum) ‘custom’ is a special mode for 2D interpolation in which a regular grid of samples is taken from the texture around a position using ‘linear’ interpolation before being multiplied with a custom interpolation kernel (provided with ‘custom_interpolation_kernel_2d’).
interpolation3d (str) – Same as ‘interpolation2d’ but for 3D rendering.
iso_threshold (float) – Threshold for isosurface.
metadata (dict) – Layer metadata.
multiscale (bool) – Whether the data is a multiscale image or not. Multiscale data is represented by a list of array-like image data. If not specified by the user and if the data is a list of arrays that decrease in shape, then it will be taken to be multiscale. The first image in the list should be the largest. Please note multiscale rendering is only supported in 2D. In 3D, only the lowest resolution scale is displayed.
name (str) – Name of the layer.
opacity (float) – Opacity of the layer visual, between 0.0 and 1.0.
plane (dict or SlicingPlane) – Properties defining plane rendering in 3D. Properties are defined in data coordinates. Valid dictionary keys are {‘position’, ‘normal’, ‘thickness’, and ‘enabled’}.
projection_mode (str) – How data outside the viewed dimensions, but inside the thick Dims slice will be projected onto the viewed dimensions. Must fit to ImageProjectionMode
rendering (str) – Rendering mode used by vispy. Must be one of our supported modes.
rgb (bool, optional) – Whether the image is RGB or RGBA if rgb. If not specified by user, but 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.
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.
units (tuple of str or pint.Unit, optional) – Units of the layer data in world coordinates. If not provided, the default units are assumed to be pixels.
visible (bool) – Whether the layer visual is currently being displayed.
- data#
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. Please note multiscale rendering is only supported in 2D. In 3D, only the lowest resolution scale is displayed.
- Type:
array or list of array
- rgb#
Whether the image is rgb RGB or RGBA if rgb. 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.
- Type:
- 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:
- mode#
Interactive mode. The normal, default mode is PAN_ZOOM, which allows for normal interactivity with the canvas.
In TRANSFORM mode the image can be transformed interactively.
- Type:
- colormap#
The first is the name of the current colormap, and the second value is the colormap. Colormaps are used for luminance images, if the image is rgb the colormap is ignored.
- Type:
2-tuple of str, napari.utils.Colormap
- contrast_limits#
Color limits to be used for determining the colormap bounds for luminance images. If the image is rgb the contrast_limits is ignored.
- contrast_limits_range#
Range for the color limits for luminance images. If the image is rgb the contrast_limits_range is ignored.
- interpolation2d#
Interpolation mode used by vispy. Must be one of our supported modes. ‘custom’ is a special mode for 2D interpolation in which a regular grid of samples are taken from the texture around a position using ‘linear’ interpolation before being multiplied with a custom interpolation kernel (provided with ‘custom_interpolation_kernel_2d’).
- Type:
- plane#
Properties defining plane rendering in 3D. Valid dictionary keys are {‘position’, ‘normal’, ‘thickness’}.
- Type:
SlicingPlane or dict
- experimental_clipping_planes#
Clipping planes defined in data coordinates, used to clip the volume.
- Type:
ClippingPlaneList
- custom_interpolation_kernel_2d#
Convolution kernel used with the ‘custom’ interpolation mode in 2D rendering.
- Type:
np.ndarray
Notes
- _data_viewarray (N, M), (N, M, 3), or (N, M, 4)
Image data for the currently viewed slice. Must be 2D image data, but can be multidimensional for RGB or RGBA images if multidimensional is True.
Methods
as_layer_data_tuple
()bind_key
(key_bind[, func, overwrite])Bind a key combination to a keymap.
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_to_world
(position)Convert from data coordinates to world coordinates.
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.
Calculate the length of the projection of a line between two mouse clicks onto a vector (or array of vectors) in data coordinates.
refresh
([event, thumbnail, data_displayed, ...])Refresh all layer data based on current view slice.
reset_contrast_limits
([mode])Scale contrast limits to data range
reset_contrast_limits_range
([mode])Scale contrast limits range to data type if dtype is an integer, or use the current maximum data range otherwise.
save
(path[, plugin])Save this layer to
path
with default (or specified) plugin.set_view_slice
()update_transform_box_visibility
(visible)world_to_data
(position)Convert from world coordinates to data coordinates.
Attributes
ModeCallable
alias of
Callable
[[Layer
,Event
],None
|Generator
[None
,None
,None
]]Extra affine transform to go from physical to world coordinates.
attenuation rate for attenuated_mip rendering.
tuple of axis labels for the layer.
Determines how RGB and alpha values get mixed.
bounding_box
class_keymap
colormap for luminance images.
names of available colormaps.
Limits to use for the colormap.
The current valid range of the contrast limits.
String identifying cursor displayed over canvas.
Size of cursor if custom.
Data, possibly in multiscale wrapper.
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.
displayed in status bar bottom right.
interactive
Return current interpolation mode.
threshold for isosurface.
keymap
Shapes of each level of the multiscale or just of image.
True if this layer is fully loaded in memory, False otherwise.
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.
Opacity value between 0.0 and 1.0.
Mode of projection of the thick slice onto the viewed dimensions.
Return current rendering mode.
Rotation matrix in world coordinates.
Anisotropy factors to scale data into world coordinates.
Shear matrix in world coordinates.
source
Integer array of thumbnail for the layer
Factors to shift the layer by in units of world coordinates.
Unique ID of the layer.
List of units for the layer.
Whether the visual is currently being displayed.
Details
- bind_key(key_bind: ~app_model.types._keys._keybindings.KeyBinding | str | int | ellipsis, func=<object object>, *, overwrite=False)#
Bind a key combination to a keymap.
- Parameters:
keymap (dict of str: callable) – Keymap to modify.
key_bind (keybinding-like 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: str#
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
- click_plane_from_click_data(click_position: npt.ArrayLike, view_direction: npt.ArrayLike, dims_displayed: list[int]) tuple[np.ndarray, np.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[int]) – 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 colormap#
colormap for luminance images.
- Type:
- property contrast_limits_range#
The current valid range of the contrast limits.
- classmethod create(data: Any, 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: LayerDataProtocol | MultiScaleData#
Data, possibly in multiscale wrapper. Obeys LayerDataProtocol.
- property data_raw: LayerDataProtocol | Sequence[LayerDataProtocol]#
Data, exactly as provided by the user.
- 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.
For image-like layers, these coordinates are the locations of the pixels in Layer.data which are treated like sample points that are centered in the rendered version of those pixels. For other layers, these coordinates are the points or vertices stored in Layer.data. Lower and upper bounds are inclusive.
- get_ray_intersections(position: npt.ArrayLike, view_direction: npt.ArrayLike, dims_displayed: list[int], world: bool = True) tuple[np.ndarray | None, np.ndarray | 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 (List[int]) – 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: npt.ArrayLike | None = None, *, view_direction: npt.ArrayLike | None = None, dims_displayed: list[int] | None = None, world: bool = False) dict #
Status message information of the data at a coordinate position.
- 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:
source_info – Dictionary containing a information that can be used as a status update.
- Return type:
- get_value(position: npt.ArrayLike, *, view_direction: npt.ArrayLike | None = None, dims_displayed: list[int] | None = None, world: bool = False) tuple | None #
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 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’, ‘cubic’, ‘linear’, ‘blackman’, ‘catrom’, ‘gaussian’, ‘hamming’, ‘hanning’, ‘hermite’, ‘kaiser’, ‘lanczos’, ‘mitchell’, ‘nearest’, ‘spline16’, ‘spline36’
- Returns:
The current interpolation mode
- Return type:
- property level_shapes: ndarray#
Shapes of each level of the multiscale or just of image.
- Type:
array
- property loaded: bool#
True if this layer is fully loaded in memory, False otherwise.
Layers that only support sync slicing are always fully loaded. Layers that support async slicing can be temporarily not loaded while slicing is occurring.
- property mode: str#
Interactive mode
Interactive mode. The normal, default mode is PAN_ZOOM, which allows for normal interactivity with the canvas.
TRANSFORM allows for manipulation of the layer transform.
- Type:
- projected_distance_from_mouse_drag(start_position: npt.ArrayLike, end_position: npt.ArrayLike, view_direction: npt.ArrayLike, vector: np.ndarray, dims_displayed: list[int]) npt.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 (List[int]) – (3,) list of currently displayed dimensions
- Returns:
projected_distance
- Return type:
(1, ) or (n, ) np.ndarray of float
- property projection_mode#
Mode of projection of the thick slice onto the viewed dimensions.
The sliced data is described by an n-dimensional bounding box (“thick slice”), which needs to be projected onto the visible dimensions to be visible. The projection mode controls the projection logic.
- refresh(event: Event | None = None, *, thumbnail: bool = True, data_displayed: bool = True, highlight: bool = True, extent: bool = True, force: bool = False) 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 untilthe result is opaque.
mip
: maximum intensity projection. Cast a ray and display themaximum value that was encountered.
minip
: minimum intensity projection. Cast a ray and display theminimum value that was encountered.
attenuated_mip
: attenuated maximum intensity projection. Cast aray 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.
additive
: voxel colors are added along the view ray untilthe result is saturated.
iso
: isosurface. Cast a ray until a certain threshold isencountered. At that location, lighning calculations are performed to give the visual appearance of a surface.
average
: average intensity projection. Cast a ray and display theaverage of values that were encountered.
- Returns:
The current rendering mode
- Return type:
- reset_contrast_limits(mode=None)#
Scale contrast limits to data range
- reset_contrast_limits_range(mode=None)#
Scale contrast limits range to data type if dtype is an integer, or use the current maximum data range otherwise.
- property rotate: npt.NDArray#
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 scale: npt.NDArray#
Anisotropy factors to scale data into world coordinates.
- Type:
array
- property shear: npt.NDArray#
Shear matrix in world coordinates.
- Type:
array
- property thumbnail: npt.NDArray[np.uint8]#
Integer array of thumbnail for the layer
- Type:
array
- property translate: npt.NDArray#
Factors to shift the layer by in units of world coordinates.
- Type:
array
- property unique_id: Hashable#
Unique ID of the layer.
This is guaranteed to be unique to this specific layer instance over the lifetime of the program.
- world_to_data(position: npt.ArrayLike) npt.NDArray #
Convert from world coordinates to data coordinates.