impy.viewer package

Subpackages

Submodules

impy.viewer.keybinds module

impy.viewer.keybinds.focus_next(viewer: napari.viewer.Viewer)[source]
impy.viewer.keybinds.focus_previous(viewer: napari.viewer.Viewer)[source]
impy.viewer.keybinds.hide_others(viewer: napari.viewer.Viewer)[source]

Make selected layers visible and others invisible.

impy.viewer.keybinds.reset_view(viewer: napari.viewer.Viewer)[source]

Reset translate/scale parameters to the initial value.

impy.viewer.keybinds.reslice(viewer: napari.viewer.Viewer)[source]

2D Reslice with currently selected lines/paths and images.

impy.viewer.keybinds.to_front(viewer: napari.viewer.Viewer)[source]

Let selected layers move to front.

impy.viewer.menus module

impy.viewer.menus.add_crop_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_duplicate_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_explorer_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_filter(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_get_props_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_imread_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_imsave_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_label_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_layer_to_labels_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_note_widget(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_plane_clipper(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_proj_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_read_csv_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_rectangle_editor(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_regionprops(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_rotator(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_text_layer_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_threshold(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.add_time_stamper_menu(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.function_handler(viewer: napari.viewer.Viewer)[source]
impy.viewer.menus.layer_template_matcher(viewer: napari.viewer.Viewer)[source]

impy.viewer.mouse module

impy.viewer.utils module

class impy.viewer.utils.ColorCycle(cmap='rainbow')[source]

Bases: object

impy.viewer.utils.add_dask(viewer: napari.viewer.Viewer, img: impy.arrays.lazy.LazyImgArray, **kwargs)[source]
impy.viewer.utils.add_labeledarray(viewer: napari.viewer.Viewer, img: impy.arrays.labeledarray.LabeledArray, **kwargs)[source]
impy.viewer.utils.add_labels(viewer: napari.Viewer, labels: Label, opacity: float = 0.3, name: str | list[str] = None, **kwargs)[source]
impy.viewer.utils.add_paths(viewer: napari.Viewer, paths: PathFrame, **kwargs)[source]
impy.viewer.utils.add_points(viewer: napari.viewer.Viewer, points, **kwargs)[source]
impy.viewer.utils.add_table(viewer: napari.viewer.Viewer, data=None, columns=None, name=None)[source]
impy.viewer.utils.add_tracks(viewer: napari.Viewer, track: TrackFrame, **kwargs)[source]
impy.viewer.utils.copy_layer(layer)[source]
impy.viewer.utils.crop_rectangle(img: impy.arrays.labeledarray.LabeledArray, crds: numpy.ndarray, dims='yx') tuple[impy.arrays.labeledarray.LabeledArray, numpy.ndarray][source]
impy.viewer.utils.crop_rotated_rectangle(img: impy.arrays.labeledarray.LabeledArray, crds: numpy.ndarray, dims='yx')[source]
impy.viewer.utils.front_image(viewer: napari.viewer.Viewer)[source]

From list of image layers return the most front visible image.

impy.viewer.utils.get_a_selected_layer(viewer: napari.viewer.Viewer)[source]
impy.viewer.utils.get_viewer_scale(viewer: napari.viewer.Viewer)[source]
impy.viewer.utils.image_tuple(input: napari.layers.image.image.Image, out: impy.arrays.imgarray.ImgArray, translate='inherit', **kwargs)[source]
impy.viewer.utils.iter_layer(viewer: napari.viewer.Viewer, layer_type: str)[source]

Iterate over layers and yield only certain type of layers.

Parameters

layer_type (str, {"shape", "image", "point"}) – Type of layer.

Yields

napari.layers – Layers specified by layer_type

impy.viewer.utils.iter_selected_layer(viewer: napari.Viewer, layer_type: str | list[str])[source]
impy.viewer.utils.label_tuple(input: napari.layers.labels.labels.Labels, out: impy.arrays.label.Label, translate='inherit', **kwargs)[source]
impy.viewer.utils.layer_to_impy_object(viewer: napari.viewer.Viewer, layer)[source]

Convert layer to real data.

Parameters

layer (napari.layers.Layer) – Input layer.

Returns

Return type

ImgArray, Label, MarkerFrame or TrackFrame, or Shape features.

impy.viewer.utils.make_world_scale(obj)[source]
impy.viewer.utils.to_labels(layer: napari.layers.shapes.shapes.Shapes, labels_shape, zoom_factor=1)[source]
impy.viewer.utils.upon_add_layer(event)[source]
impy.viewer.utils.viewer_imread(viewer: napari.viewer.Viewer, path: str)[source]

impy.viewer.viewer module

class impy.viewer.viewer.napariViewers

Bases: object

The controller of napari.Viewer``s from ``impy. Always access by ip.gui.

add(obj: Optional[ImpyObject] = None, **kwargs)

Add images, points, labels, tracks etc to viewer.

Parameters

obj (ImpyObject) – Object to add.

add_parameter_container(f: Callable)

Make a parameter container widget from a function. Essentially same as magicgui’s method. These parameters are accessible via ip.gui.param.

Parameters

f (Callable) – The function from which parameter types will be inferred.

add_surface(image3d: impy.arrays.labeledarray.LabeledArray, level: Optional[float] = None, step_size: int = 1, mask=None, **kwargs)

Add a surface layer from a 3D image.

Parameters
  • image3d (LabeledArray) – 3D image from which surface will be generated

  • level – Passed to skimage.measure.marching_cubes

  • step_size – Passed to skimage.measure.marching_cubes

  • mask – Passed to skimage.measure.marching_cubes

add_table(data=None, columns=None, name=None) impy.viewer.widgets.table.TableWidget

Add table widget in the viewer.

Parameters
  • data (array-like, optional) – Initial data to add in the table. If not given, an empty table will be made.

  • columns (sequence, optional) – Column names of the table.

  • name (str, optional) – Name of the table widget.

Returns

Pointer to the table widget.

Return type

TabelWidget

property axes: str

Axes information of current viewer. Defined to make compatible with ImgArray.

axisof(symbol: str) int
bind(func=None, key: str = 'F1', use_logger: bool = False, use_plt: bool = True, allowed_dims: int | tuple[int, ...] = (1, 2, 3))

Decorator that makes it easy to call custom function on the viewer. Every time “F1” is pushed, func(self, ...) will be called. Returned values will be appeded to self.results if exists.

Parameters
  • func (callable) – Function to be called when key is pushed. This function must accept func(self, **kwargs). Docstring of this function will be displayed on the top of the parameter container as a tooltip.

  • key (str, default is "F1") – Key binding.

  • use_logger (bool, default is False) – If True, all the texts that are printed out will be displayed in the log widget. In detail, sys.stdout and sys.stderr are substituted to the log widget during function call.

  • use_plt (bool, default is True) – If True, the backend of matplotlib is set to “impy.viewer._plt” during function call. All the plot functions such as plt.plot will update the figure canvas inside the viewer. If plt.figure or other figure generation function is not called, the figure canvas will not be refreshed so that new results will drawn over the old ones.

  • allowed_dims (int or tuple of int, default is (1, 2, 3)) – Function will not be called if the number of displayed dimensions does not match it.

Examples

  1. Calculate mean intensity of images.

    >>> @ip.gui.bind
    >>> def measure(gui):
    >>>     return gui.get("image").mean()
    
  2. Plot line scan of 2D image.

    >>> @ip.gui.bind
    >>> def profile(gui)
    >>>     img = gui.get("image")
    >>>     line = gui.get("line")
    >>>     scan = img.reslice(line)
    >>>     plt.plot(scan)
    >>>     return None
    
bind_protocol(func: Callable = None, key1: str = 'F1', key2: str = 'F2', use_logger: bool = False, use_plt: bool = True, allowed_dims: int | tuple[int, ...] = (1, 2, 3), exit_with_error: bool = False)

Decorator that makes it easy to make protocol (series of function call) on the viewer. Unlike bind method, input function func must yield callable objects, from which parameter container will be generated. Simply, bind-like method is called for every yielded function and each time parameter container will be renewed. Two keys, key1 and key2, are useful when you want to distinguish “repeat same function” and “proceed to next step”. For instance, if in the first step you should add multiple points in the viewer as many as you want, it is hard for the protocol function to “know” whether you finish adding points. In this case, you can assign key “F1” to “add point” and key “F2” to “finish adding point” and inside the protocol function these different event can be distinguished by check whether gui.proceed is True or not. See examples for details.

Parameters
  • func (callable) – Protocol function. This function must accept func(self) and yield functions that accept f(self, **kwargs) . Docstring of the yielded functions will be displayed on the top of the parameter container as a tooltip. Therefore it would be very useful if you write procedure of the protocol as docstrings.

  • key1 (str, default is "F1") – First key binding. When this key is pushed, returned value will be appended to ip.gui.results and attribute proceed will be False.

  • key2 (str, default is "F2") – Second key binding. When this key is pushed, returned value will be discarded and attribute proceed will be True.

  • use_logger (bool, default is False) – If True, all the texts that are printed out will be displayed in the log widget. In detail, sys.stdout and sys.stderr are substituted to the log widget during function call.

  • use_plt (bool, default is True) – If True, the backend of matplotlib is set to “impy.viewer._plt” during function call. All the plot functions such as plt.plot will update the figure canvas inside the viewer. If plt.figure or other figure generation function is not called, the figure canvas will not be refreshed so that new results will drawn over the old ones.

  • allowed_dims (int or tuple of int, default is (1, 2, 3)) – Function will not be called if the number of displayed dimensions does not match it.

  • exit_with_error (bool default is False) – If True, protocol will quit whenever exception is raised and key binding will be released. If False, protocol continues from the same step.

Examples

  1. Draw a 3-D path and get the line scan.

    >>> @ip.gui.bind_protocol
    >>> def add_line(gui):
    >>>     def func(gui):
    >>>         '''
    >>>         Push F1 to add line.
    >>>         Push F2 to finish.
    >>>         '''
    >>>         return gui.cursor_pos
    >>>     while not gui.proceed:
    >>>         yield func
    >>>     line = np.stack(gui.results)
    >>>     img = gui.get("image")
    >>>     gui.register_shape(line, shape_type="path")
    >>>     plt.plot(img.reslice(line))
    >>>     plt.show()
    
  2. 3-D cropper.

    >>> @ip.gui.bind_protocol
    >>> def crop(gui):
    >>>     img = gui.get("image")
    >>>     layer = gui.viewer.add_shapes()
    >>>     layer.mode = "add_rectangle"
    >>>     def draw_rectangle(gui):
    >>>         '''draw a rectangle'''
    >>>         rect = gui.get("rectangle")[:,-2:]
    >>>         rect[:,0] /= img.scale["y"]
    >>>         rect[:,1] /= img.scale["x"]
    >>>         return rect.astype(np.int64)
    >>>     yield draw_rectangle
    >>>     def read_z(gui):
    >>>         '''set z borders'''
    >>>         return gui.stepof("z")
    >>>     yield read_z        # get one z-border coordinate
    >>>     yield read_z        # get the other z-border coordinate
    >>>     rect, z0, z1 = gui.results
    >>>     x0, _, _, x1 = sorted(rect[:, 1]) # get x-border coordinate
    >>>     y0, _, _, y1 = sorted(rect[:, 0]) # get y-border coordinate
    >>>     z0, z1 = sorted([z0, z1])
    >>>     gui.add(img[f"z={z0}:{z1+1};y={y0}:{y1+1};x={x0}:{x1+1}"])
    
property current_slice: tuple[slice | int, ...]

Return a tuple of slicer that corresponds to current field of view. For instance, when the viewer is displaying yx-plane at t=1, then this property returns (1, slice(None), slice(None)).

property cursor_pos: numpy.ndarray

Return cursor position. Scale is considered.

cursor_to_pixel(ref: 'napari.layers.Image' | int | str | LabeledArray | LazyImgArray, ndim: int = None) np.ndarray

With cursor position and a layer as inputs, this function returns the cursor “pixel” coordinates on the given layer. This function is useful when you want to get such as pixel value at the cursor position.

Parameters
  • ref (napari.layers.Image, int, str, LabeledArray or LazyImgArray) –

    Reference layer or its identifier. To determine the reference layer, this parameter is interpreted in different ways depending on its type:

    • napari.layers.Image … layer itself

    • int … the index of layer list

    • str … the name of layer list

    • LabeledArray or LazyImgArray … layer that has same object as data

  • ndim (int, optional) – If specified, the last ndim coordinates will be returned.

Returns

1-D, int64 array of cursor position along each dimension.

Return type

np.ndarray

property fig

matplotlib.figure.Figure object bound to the viewer.

get(kind: str = 'image', layer_state: str = 'visible', returns: str = 'last') ImpyObject | list[ImpyObject]

Simple way to get impy object from viewer.

Parameters
  • kind (str, optional) –

    Kind of layers/shapes to return.

    • ”image”: Image layer.

    • ”labels”: Labels layer

    • ”points”: Points layer.

    • ”shapes”: Shapes layer.

    • ”tracks”: Tracks layer.

    • ”vectors”: Vectors layer.

    • ”surface”: Surface layer.

    • ”line”: Line shapes in Shapes layer.

    • ”rectangle”: Rectangle shapes in Shapes layer.

    • ”path”: Path shapes in Shapes layer.

    • ”polygon”: Polygon shapes in Shapes layer.

    • ”ellipse”: Ellipse shapes in Shapes layer.

  • layer_state ({"selected", "visible", "any"}, default is "any") –

    How to filter layer list.

    • ”selected”: Only selected layers will be searched.

    • ”visible”: Only visible layers will be searched.

    • ”any”: All the layers will be searched.

  • returns ({"first", "last", "all"}) –

    What will be returned in case that there are multiple layers/shapes.

    • ”first”: Only the first object will be returned.

    • ”last”: Only the last object will be returned.

    • ”all”: All the objects will be returned as a list.

Returns

impy object(s) that satisfies the options.

Return type

ImgArray, Label, MarkerFrame or TrackFrame, np.ndarray, or list of one of them.

Examples

  1. Get the front image.

    >>> ip.gui.get("image")
    
  2. Get all the selected images as a list.

    >>> ip.gui.get("image", layer_state="selected", returns="all")
    
  3. Get all the lines from the front visible shapes layer.

    >>> ip.gui.get("line", layer_state="visible")
    
goto(**kwargs) tuple[int, ...]

Change the current step of the viewer.

Examples

  1. Go to t=3.

    >>> ip.gui.goto(t=3)
    
  2. Go to t=3 and last z.

    >>> ip.gui.goto(t=3, z=-1)
    
property layers: napari.components.layerlist.LayerList

Napari layer list. Identical to ip.gui.viewer.layers.

property log: impy.viewer.widgets.log.LoggerWidget
property params: dict
preview(path: str, downsample_factor: int = 4, dims: str | int = None, **kwargs)

Preview a large image with a strided image.

Parameters
  • path (str) – Path to the image file.

  • downsample_factor (int, default is 4) – Image value is sampled every downsample_factor pixels.

  • dims (str or int, optional) – Axes along which values will be down-sampled.

register_point(data='cursor position', size: Optional[float] = None, face_color=None, edge_color=None, properties: Optional[dict] = None, **kwargs)

Register a point in a points layer, and link it to a table widget. Similar to “ROI Manager” in ImageJ. New points layer will be created when the first point is added.

Parameters
  • data (array, optional) – Point coordinate. By default the cursor position willbe added.

  • size (float, optional) – Point size.

  • face_color (str or array, optional) – Face color of point.

  • edge_color (str or array, optional) – Edge color of the point.

  • properties (dict, optional) – Propertied of the point. Values in this parameter is also added to table.

register_shape(data, shape_type='rectangle', face_color=None, edge_color=None, properties=None, **kwargs)

Register a shape in a shapes layer, and link it to a table widget. Similar to “ROI Manager” in ImageJ. New shapes layer will be created when the first shape is added.

Parameters
  • data (array, optional) – Shape data.

  • shape_type (str, default is "rectangle") – Shape type of the new one.

  • face_color (str or array, optional) – Face color of point.

  • edge_color (str or array, optional) – Edge color of the point.

  • properties (dict, optional) – Propertied of the point. Values in this parameter is also added to table.

property results: impy.viewer.widgets.results.ResultStackView

Temporary results stored in the viewer.

property scale: dict[str, float]

Scale information of current viewer. Defined to make compatible with ImgArray.

property selection: list[typing.NewType.<locals>.new_type]

Return selected layers’ data as a list of impy objects.

start(key: str = 'impy')

Create a napari window with name key.

stepof(symbol: str) int

Get the current step of certain axis.

Parameters

symbol (str) – Axis symbol

property table: impy.viewer.widgets.table.TableWidget
use_logger() impy.viewer.viewer.setLogger

Return a context manager that all the texts will be printed in the logger.

Examples

>>> import logging
>>> with ip.gui.use_logger():
>>>     # both will be printed in the viewer's logger widget
>>>     print("something")
>>>     logging.warning("WARNING")
property viewer: napari.viewer.Viewer

The most front viewer you’re using

class impy.viewer.viewer.setLogger(gui=None)

Bases: object

Module contents