Exemplo n.º 1
0
Add named or unnamed vispy colormaps to existing layers.
"""

import numpy as np
import vispy.color
from skimage import data
import napari


histo = data.astronaut() / 255
rch, gch, bch = np.transpose(histo, (2, 0, 1))
red = vispy.color.Colormap([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
green = vispy.color.Colormap([[0.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
blue = vispy.color.Colormap([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]])

v = napari.Viewer()

rlayer = v.add_image(rch, name='red channel')
rlayer.blending = 'additive'
rlayer.colormap = 'red', red
glayer = v.add_image(gch, name='green channel')
glayer.blending = 'additive'
glayer.colormap = green  # this will appear as [unnamed colormap]
blayer = v.add_image(bch, name='blue channel')
blayer.blending = 'additive'
blayer.colormap = {'blue': blue}

if __name__ == '__main__':
    napari.run()
Exemplo n.º 2
0
def view_plate(
    image_data,
    label_data=None,
    image_settings=None,
    label_settings=None,
    well_measurements=None,
    well_shape=None,
    zero_based=True,
    well_spacing=16,
    site_spacing=4,
    show=True,
):
    """Visualize data from a multi-well plate using napari.

    Args:
        image_data dict[str, [dict[str, list[np.array]]]]: list of image sources,
            each list contains a dict which maps the well names (e.g. A1, B3) to
            the image data for this well (one array per well position)
        label_data dict[str, [dict[str, list[np.array]]]]: list of label sources,
            each list contains a dict which maps the well names (e.g. A1, B3) to
            the label data for this well (one array per well position) (default: None)
        image_settings dict[str, dict]: image settings for the channels (default: None)
        label_settings dict[str, dict]: settings for the label channels (default: None)
        well_measurements dict[str, dict[str, [float, int, str]]]: measurements associated with the wells
        well_shape tuple[int]: the 2D shape of a well in terms of images, if not given will be derived.
            Well shape can only be derived for square wells and must be passed otherwise (default: None)
        zero_based bool: whether the well indexing is zero-based (default: True)
        well_sources int: spacing between wells, in pixels (default: 12)
        site_spacing int: spacing between sites, in pixels (default: 4)
        show bool: whether to show the viewer (default: True)
    """
    # find the number of positions per well
    first_channel_sources = next(iter(image_data.values()))
    pos_per_well = len(next(iter(first_channel_sources.values())))

    # find the well shape
    if well_shape is None:  # well shape can only be derived for square wells
        assert pos_per_well in (1, 4, 9, 25, 36,
                                49), f"well is not square: {pos_per_well}"
        well_len = int(np.sqrt(pos_per_well))
        well_shape = (well_len, well_len)
    else:
        assert len(well_shape) == 2
        pos_per_well_exp = np.prod(list(well_shape))
        assert pos_per_well_exp == pos_per_well, f"{pos_per_well_exp} != {pos_per_well}"

    def process_sources(sources, well_names):
        for well_sources in sources.values():
            # make sure all wells have the same number of label
            n_pos_well = [len(sources) for sources in well_sources.values()]
            assert all(
                n_pos == pos_per_well
                for n_pos in n_pos_well), f"{pos_per_well} != {n_pos_well}"
            well_names.extend(list(well_sources.keys()))
        return well_names

    # find the well names for all sources
    well_names = process_sources(image_data, [])
    if label_data is not None:
        well_names = process_sources(label_data, well_names)
    well_names = list(set(well_names))
    well_names.sort()

    # compute the well extent and well positions
    well_positions, well_start, well_stop = parse_wells(well_names, zero_based)
    assert len(well_positions) == len(well_names)

    # start the veiwer and add all sources
    viewer = napari.Viewer()
    shape = add_grid_sources(image_data, well_positions, well_shape,
                             well_spacing, site_spacing, viewer.add_image,
                             image_settings)
    if label_data is not None:
        add_grid_sources(label_data, well_positions, well_shape, well_spacing,
                         site_spacing, viewer.add_labels, label_settings)

    # add shape layer corresponding to the well positions
    add_plate_layout(viewer,
                     well_names,
                     well_positions,
                     well_shape,
                     well_spacing,
                     site_spacing,
                     shape,
                     measurements=well_measurements)

    # set the camera so that the initial view is centered around the existing wells
    # and zoom out so that the central well is fully visible
    set_camera(viewer, well_start, well_stop, well_shape, well_spacing,
               site_spacing, shape)

    if show:
        napari.run()
    return viewer
Exemplo n.º 3
0
def run_cli(args):
    LI = calciumcharacterisation.LazyImarisTSReader(args.imarisfile[0])

    v = napari.Viewer()
    l = v.add_image(LI.daskseries(), multiscale=False, name=args.imarisfile[0])
    napari.run()
Exemplo n.º 4
0
def _run():
    from napari import run, view_path
    from napari.settings import get_settings

    """Main program."""
    args, kwargs = parse_sys_argv()

    # parse -v flags and set the appropriate logging level
    levels = [logging.WARNING, logging.INFO, logging.DEBUG]
    level = levels[min(2, args.verbose)]  # prevent index error
    logging.basicConfig(
        level=level,
        format="%(asctime)s %(levelname)s %(message)s",
        datefmt='%H:%M:%S',
    )

    if args.reset:
        if args.settings_path:
            settings = get_settings(path=args.settings_path)
        else:
            settings = get_settings()
        settings.reset()
        settings.save()
        sys.exit("Resetting settings to default values.\n")

    if args.plugin:
        # make sure plugin is only used when files are specified
        if not args.paths:
            sys.exit(
                "error: The '--plugin' argument is only valid "
                "when providing a file name"
            )
        # I *think* that Qt is looking in sys.argv for a flag `--plugins`,
        # which emits "WARNING: No such plugin for spec 'builtins'"
        # so remove --plugin from sys.argv to prevent that warningz
        sys.argv.remove('--plugin')

    if any(p.endswith('.py') for p in args.paths):
        # we're running a script
        if len(args.paths) > 1:
            sys.exit(
                'When providing a python script, only a '
                'single positional argument may be provided'
            )

        # run the file
        mod = runpy.run_path(args.paths[0])

        from napari_plugin_engine.markers import HookImplementationMarker

        # if this file had any hook implementations, register and run as plugin
        if any(isinstance(i, HookImplementationMarker) for i in mod.values()):
            _run_plugin_module(mod, os.path.basename(args.paths[0]))

    else:
        if args.with_:
            from .plugins import plugin_manager

            # if a plugin widget has been requested, this will fail immediately
            # if the requested plugin/widget is not available.
            plugin_manager.discover_widgets()
            pname, *wnames = args.with_
            if wnames:
                for wname in wnames:
                    _npe2.get_widget_contribution(
                        pname, wname
                    ) or plugin_manager.get_widget(pname, wname)
            else:
                _npe2.get_widget_contribution(
                    pname
                ) or plugin_manager.get_widget(pname)

        from napari._qt.widgets.qt_splash_screen import NapariSplashScreen

        splash = NapariSplashScreen()
        splash.close()  # will close once event loop starts

        # viewer is unused but _must_  be kept around.
        # it will be referenced by the global window only
        # once napari has finished starting
        # but in the meantime if the garbage collector runs;
        # it will collect it and hang napari at start time.
        # in a way that is machine, os, time (and likely weather dependant).
        viewer = view_path(  # noqa: F841
            args.paths,
            stack=args.stack,
            plugin=args.plugin,
            layer_type=args.layer_type,
            **kwargs,
        )

        if args.with_:
            pname, *wnames = args.with_
            if wnames:
                for wname in wnames:
                    viewer.window.add_plugin_dock_widget(pname, wname)
            else:
                viewer.window.add_plugin_dock_widget(pname)

        # only necessary in bundled app, but see #3596
        from napari.utils.misc import (
            install_certifi_opener,
            running_as_bundled_app,
        )

        if running_as_bundled_app:
            install_certifi_opener()
        run(gui_exceptions=True)