How to use napari - 10 common examples

To help you get started, we’ve selected a few napari examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github constantinpape / elf / test / wrapper / test_resized_volume.py View on Github external
x = np.concatenate(256 * [x[None]], axis=0)

        out_shape = 3 * (128,)
        order = 0
        out1 = vigra.sampling.resize(x, shape=out_shape, order=order)
        out2 = ResizedVolume(x, shape=out_shape, order=order)
        out3 = resize(x, out_shape, order=0, preserve_range=True, anti_aliasing=False)
        assert out1.shape == out2.shape == out_shape
        # bb = np.s_[:64, :, 64:]
        bb = np.s_[:]
        o1 = out1[bb]
        o2 = out2[bb]
        o3 = out3[bb]
        import napari
        with napari.gui_qt():
            viewer = napari.Viewer()
            viewer.add_image(o1, name='elf')
            viewer.add_image(o2, name='vigra')
            viewer.add_image(o3, name='skimage')
            # viewer.add_labels(diff, name='pix-diff')
github napari / napari / napari / _qt / qt_about_keybindings.py View on Github external
self.layout = QVBoxLayout()

        self.setWindowTitle('Keybindings')
        self.setWindowModality(Qt.NonModal)
        self.setLayout(self.layout)

        # stacked keybindings widgets
        self.textEditBox = QTextEdit()
        self.textEditBox.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.textEditBox.setMinimumWidth(360)
        # Can switch to a normal dict when our minimum Python is 3.7
        self.keybindings_strs = OrderedDict()
        self.keybindings_strs[self.ALL_ACTIVE_KEYBINDINGS] = ''
        col = self.viewer.palette['secondary']
        layers = [
            napari.layers.Image,
            napari.layers.Labels,
            napari.layers.Points,
            napari.layers.Shapes,
            napari.layers.Surface,
            napari.layers.Vectors,
        ]
        for layer in layers:
            if len(layer.class_keymap) == 0:
                text = 'No keybindings'
            else:
                text = get_keybindings_summary(layer.class_keymap, col=col)
            self.keybindings_strs[f"{layer.__name__} layer"] = text

        # layer type selection
        self.layerTypeComboBox = QComboBox()
        for name in self.keybindings_strs:
github napari / napari / napari / layers / shapes / shapes.py View on Github external
self._drag_start = None
        self._drag_box = None
        self._is_selecting = False
        self._fixed_vertex = None
        self._value = (None, None)
        self._moving_value = (None, None)
        if self._is_creating is True and self._mode == Mode.ADD_PATH:
            vertices = self._data_view.displayed_vertices[
                self._data_view.displayed_index == index
            ]
            if len(vertices) <= 2:
                self._data_view.remove(index)
            else:
                data_full = self.expand_shape(vertices)
                self._data_view.edit(index, data_full[:-1])
        if self._is_creating is True and self._mode == Mode.ADD_POLYGON:
            vertices = self._data_view.displayed_vertices[
                self._data_view.displayed_index == index
            ]
            if len(vertices) <= 2:
                self._data_view.remove(index)
        self._is_creating = False
        self._update_dims()
github napari / napari / napari / layers / shapes / shapes.py View on Github external
vertices = self._data_view.displayed_vertices[indices]
                        vertices[vertex] = coord
                        data_full = self.expand_shape(vertices)
                        self._data_view.edit(
                            index, data_full, new_type=new_type
                        )
                        shapes = self.selected_data
                        self._selected_box = self.interaction_box(shapes)
                        self.refresh()
            else:
                self._is_selecting = True
                if self._drag_start is None:
                    self._drag_start = coord
                self._drag_box = np.array([self._drag_start, coord])
                self._set_highlight()
        elif self._mode in [Mode.VERTEX_INSERT, Mode.VERTEX_REMOVE]:
            if len(self.selected_data) > 0:
                pass
            else:
                self._is_selecting = True
                if self._drag_start is None:
                    self._drag_start = coord
                self._drag_box = np.array([self._drag_start, coord])
                self._set_highlight()
github napari / napari / napari / layers / shapes / shapes.py View on Github external
def _finish_drawing(self):
        """Reset properties used in shape drawing."""
        index = copy(self._moving_value[0])
        self._is_moving = False
        self.selected_data = []
        self._drag_start = None
        self._drag_box = None
        self._is_selecting = False
        self._fixed_vertex = None
        self._value = (None, None)
        self._moving_value = (None, None)
        if self._is_creating is True and self._mode == Mode.ADD_PATH:
            vertices = self._data_view.displayed_vertices[
                self._data_view.displayed_index == index
            ]
            if len(vertices) <= 2:
                self._data_view.remove(index)
            else:
                data_full = self.expand_shape(vertices)
                self._data_view.edit(index, data_full[:-1])
        if self._is_creating is True and self._mode == Mode.ADD_POLYGON:
            vertices = self._data_view.displayed_vertices[
                self._data_view.displayed_index == index
            ]
            if len(vertices) <= 2:
                self._data_view.remove(index)
        self._is_creating = False
        self._update_dims()
github napari / napari / napari / _qt / qt_dims_slider.py View on Github external
def work(self):
        # if loop_mode is once and we are already on the last frame,
        # return to the first frame... (so the user can keep hitting once)
        if self.loop_mode == LoopMode.ONCE:
            if self.step > 0 and self.current >= self.max_point - 1:
                self.frame_requested.emit(self.axis, self.min_point)
            elif self.step < 0 and self.current <= self.min_point + 1:
                self.frame_requested.emit(self.axis, self.max_point)
            self.timer.singleShot(self.interval, self.advance)
        else:
            # immediately advance one frame
            self.advance()
        self.started.emit()
github napari / napari / napari / _qt / qt_viewer.py View on Github external
def _update_palette(self, palette):
        # template and apply the primary stylesheet
        themed_stylesheet = template(self.raw_stylesheet, **palette)
        self.console.style_sheet = themed_stylesheet
        self.console.syntax_style = palette['syntax_style']
        bracket_color = QtGui.QColor(*str_to_rgb(palette['highlight']))
        self.console._bracket_matcher.format.setBackground(bracket_color)
        self.setStyleSheet(themed_stylesheet)
        self.aboutKeybindings.setStyleSheet(themed_stylesheet)
        self.canvas.bgcolor = palette['canvas']
github napari / napari / napari / _version.py View on Github external
def git_versions_from_keywords(keywords, tag_prefix, verbose):
    """Get version information from git keywords."""
    if not keywords:
        raise NotThisMethod("no keywords at all, weird")
    date = keywords.get("date")
    if date is not None:
        # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
        # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
        # -like" string, which we must then edit to make compliant), because
        # it's been around since git-1.5.3, and it's too difficult to
        # discover which version we're using, or to work around using an
        # older one.
        date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
    refnames = keywords["refnames"].strip()
    if refnames.startswith("$Format"):
        if verbose:
            print("keywords are unexpanded, not using")
        raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
    refs = set([r.strip() for r in refnames.strip("()").split(",")])
    # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
github napari / napari / napari / _version.py View on Github external
if not keywords:
        raise NotThisMethod("no keywords at all, weird")
    date = keywords.get("date")
    if date is not None:
        # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
        # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
        # -like" string, which we must then edit to make compliant), because
        # it's been around since git-1.5.3, and it's too difficult to
        # discover which version we're using, or to work around using an
        # older one.
        date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
    refnames = keywords["refnames"].strip()
    if refnames.startswith("$Format"):
        if verbose:
            print("keywords are unexpanded, not using")
        raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
    refs = set([r.strip() for r in refnames.strip("()").split(",")])
    # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
    # just "foo-1.0". If we see a "tag: " prefix, prefer those.
    TAG = "tag: "
    tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)])
    if not tags:
        # Either we're using git < 1.8.3, or there really are no tags. We use
        # a heuristic: assume all version tags have a digit. The old git %d
        # expansion behaves like git log --decorate=short and strips out the
        # refs/heads/ and refs/tags/ prefixes that would let us distinguish
        # between branches and tags. By ignoring refnames without digits, we
        # filter out many common branch names like "release" and
        # "stabilization", as well as "HEAD" and "master".
        tags = set([r for r in refs if re.search(r'\d', r)])
        if verbose:
            print("discarding '%s', no digits" % ",".join(refs - tags))
github napari / napari / napari / _version.py View on Github external
def get_versions():
    """Get version information or return default if unable to do so."""
    # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
    # __file__, we can work backwards from there to the root. Some
    # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
    # case we can only use expanded keywords.

    cfg = get_config()
    verbose = cfg.verbose

    try:
        return git_versions_from_keywords(
            get_keywords(), cfg.tag_prefix, verbose
        )
    except NotThisMethod:
        pass

    try:
        root = os.path.realpath(__file__)
        # versionfile_source is the relative path from the top of the source
        # tree (where the .git directory might live) to this file. Invert
        # this to find the root from __file__.
        for i in cfg.versionfile_source.split('/'):
            root = os.path.dirname(root)
    except NameError:
        return {
            "version": "0+unknown",
            "full-revisionid": None,
            "dirty": None,
            "error": "unable to find root of source tree",
            "date": None,