def init_callbacks(self):
        '''Creates the object's callback registry and default callbacks.'''
        from spectral import settings
        from matplotlib.cbook import CallbackRegistry

        self.callbacks = CallbackRegistry()

        # callbacks_common may have been set to a shared external registry
        # (e.g., to the callbacks_common member of another ImageView object). So
        # don't create it if it has already been set.
        if self.callbacks_common is None:
            self.callbacks_common = CallbackRegistry()

        # Keyboard callback
        self.cb_mouse = ImageViewMouseHandler(self)
        self.cb_mouse.connect()

        # Mouse callback
        self.cb_keyboard = ImageViewKeyboardHandler(self)
        self.cb_keyboard.connect()

        # Class update event callback
        def updater(*args, **kwargs):
            if self.classes is None:
                self.set_classes(args[0].classes)
            self.refresh()

        callback = MplCallback(registry=self.callbacks_common,
                               event='spy_classes_modified',
                               callback=updater)
        callback.connect()
        self.cb_classes_modified = callback

        if settings.imshow_enable_rectangle_selector is False:
            return
        try:
            from matplotlib.widgets import RectangleSelector
            self.selector = RectangleSelector(self.axes,
                                              self._select_rectangle,
                                              button=1,
                                              useblit=True,
                                              spancoords='data',
                                              drawtype='box',
                                              rectprops = \
                                                  self.selector_rectprops)
            self.selector.set_active(False)
        except:
            self.selector = None
            msg = 'Failed to create RectangleSelector object. Interactive ' \
              'pixel class labeling will be unavailable.'
            warn(msg)
Пример #2
0
    def __init__(self, ax, x, y, pickradius=5, which_button=1, **kwargs):
        """
        Create the scatter plot and selection machinery.

        Parameters
        ----------
        ax : Axes
            The Axes on which to make the scatter plot
        x, y : float or array-like, shape (n, )
            The data positions.
        pickradius : float
            Pick radius, in points.
        which_button : int, default: 1
            Where 1=left, 2=middle, 3=right

        Other Parameters
        ----------------
        **kwargs : arguments to scatter
            Other keyword arguments are passed directly to the ``ax.scatter`` command

        """
        super().__init__(ax)
        self.scatter = ax.scatter(x, y, **kwargs, picker=True)
        self.scatter.set_pickradius(pickradius)
        self._observers = CallbackRegistry()
        self._x = x
        self._y = y
        self._button = which_button
        self.connect_event("pick_event", self._on_pick)
        self._init_val()
Пример #3
0
    def __init__(self,
                 artists,
                 *,
                 multiple=False,
                 highlight=False,
                 hover=False,
                 bindings=default_bindings):
        """Construct a cursor.

        Parameters
        ----------

        artists : List[Artist]
            A list of artists that can be selected by this cursor.

        multiple : bool
            Whether multiple artists can be "on" at the same time (defaults to
            False).

        highlight : bool
            Whether to also highlight the selected artist.  If so,
            "highlighter" artists will be placed as the first item in the
            :attr:`extras` attribute of the `Selection`.

        bindings : dict
            A mapping of button and keybindings to actions.  Valid entries are:

            =================== ===============================================
            'select'            mouse button to select an artist (default: 1)
            'deselect'          mouse button to deselect an artist (default: 3)
            'left'              move to the previous point in the selected
                                path, or to the left in the selected image
                                (default: shift+left)
            'right'             move to the next point in the selected path, or
                                to the right in the selected image
                                (default: shift+right)
            'up'                move up in the selected image
                                (default: shift+up)
            'down'              move down in the selected image
                                (default: shift+down)
            'toggle_visibility' toggle visibility of all cursors (default: d)
            'toggle_enabled'    toggle whether the cursor is active
                                (default: t)
            =================== ===============================================

        hover : bool
            Whether to select artists upon hovering instead of by clicking.
        """

        artists = list(artists)
        # Be careful with GC.
        self._artists = [weakref.ref(artist) for artist in artists]

        for artist in artists:
            type(self)._keep_alive.setdefault(artist, []).append(self)

        self._multiple = multiple
        self._highlight = highlight

        self._axes = {artist.axes for artist in artists}
        self._enabled = True
        self._selections = []
        self._callbacks = CallbackRegistry()

        connect_pairs = [("key_press_event", self._on_key_press)]
        if hover:
            if multiple:
                raise ValueError("`hover` and `multiple` are incompatible")
            connect_pairs += [("motion_notify_event",
                               self._on_select_button_press)]
        else:
            connect_pairs += [("button_press_event", self._on_button_press)]
        self._disconnect_cids = [
            partial(canvas.mpl_disconnect, canvas.mpl_connect(*pair))
            for pair in connect_pairs
            for canvas in {artist.figure.canvas
                           for artist in artists}
        ]

        bindings = {**default_bindings, **bindings}
        if set(bindings) != set(default_bindings):
            raise ValueError("Unknown bindings")
        actually_bound = {k: v for k, v in bindings.items() if v is not None}
        if len(set(actually_bound.values())) != len(actually_bound):
            raise ValueError("Duplicate bindings")
        self._bindings = bindings
Пример #4
0
    def __init__(self,
                 artists,
                 *,
                 multiple=False,
                 highlight=False,
                 hover=False,
                 bindings=None,
                 annotation_kwargs=None,
                 annotation_positions=None,
                 highlight_kwargs=None):
        """Construct a cursor.

        Parameters
        ----------

        artists : List[Artist]
            A list of artists that can be selected by this cursor.

        multiple : bool, optional
            Whether multiple artists can be "on" at the same time (defaults to
            False).

        highlight : bool, optional
            Whether to also highlight the selected artist.  If so,
            "highlighter" artists will be placed as the first item in the
            :attr:`extras` attribute of the `Selection`.

        hover : bool, optional
            Whether to select artists upon hovering instead of by clicking.
            (Hovering over an artist while a button is pressed will not trigger
            a selection; right clicking on an annotation will still remove it.)

        bindings : dict, optional
            A mapping of button and keybindings to actions.  Valid entries are:

            ================ ==================================================
            'select'         mouse button to select an artist
                             (default: 1)
            'deselect'       mouse button to deselect an artist
                             (default: 3)
            'left'           move to the previous point in the selected path,
                             or to the left in the selected image
                             (default: shift+left)
            'right'          move to the next point in the selected path, or to
                             the right in the selected image
                             (default: shift+right)
            'up'             move up in the selected image
                             (default: shift+up)
            'down'           move down in the selected image
                             (default: shift+down)
            'toggle_enabled' toggle whether the cursor is active
                             (default: e)
            'toggle_visible' toggle default cursor visibility and apply it to
                             all cursors (default: v)
            ================ ==================================================

            Missing entries will be set to the defaults.  In order to not
            assign any binding to an action, set it to ``None``.

        annotation_kwargs : dict, optional
            Keyword argments passed to the `annotate
            <matplotlib.axes.Axes.annotate>` call.

        annotation_positions : List[dict], optional
            List of positions tried by the annotation positioning algorithm.

        highlight_kwargs : dict, optional
            Keyword arguments used to create a highlighted artist.
        """

        artists = list(artists)
        # Be careful with GC.
        self._artists = [weakref.ref(artist) for artist in artists]

        for artist in artists:
            type(self)._keep_alive.setdefault(artist, set()).add(self)

        self._multiple = multiple
        self._highlight = highlight

        self._visible = True
        self._enabled = True
        self._selections = []
        self._last_auto_position = None
        self._callbacks = CallbackRegistry()

        connect_pairs = [("key_press_event", self._on_key_press)]
        if hover:
            if multiple:
                raise ValueError("'hover' and 'multiple' are incompatible")
            connect_pairs += [
                ("motion_notify_event", self._hover_handler),
                ("button_press_event", self._hover_handler),
            ]
        else:
            connect_pairs += [("button_press_event", self._nonhover_handler)]
        self._disconnectors = [
            partial(canvas.mpl_disconnect, canvas.mpl_connect(*pair))
            for pair in connect_pairs
            for canvas in {artist.figure.canvas
                           for artist in artists}
        ]

        bindings = dict(
            ChainMap(bindings if bindings is not None else {},
                     _default_bindings))
        unknown_bindings = set(bindings) - set(_default_bindings)
        if unknown_bindings:
            raise ValueError("Unknown binding(s): {}".format(", ".join(
                sorted(unknown_bindings))))
        duplicate_bindings = [
            k for k, v in Counter(list(bindings.values())).items() if v > 1
        ]
        if duplicate_bindings:
            raise ValueError("Duplicate binding(s): {}".format(", ".join(
                sorted(map(str, duplicate_bindings)))))
        self.bindings = bindings

        self.annotation_kwargs = (annotation_kwargs
                                  if annotation_kwargs is not None else
                                  copy.deepcopy(_default_annotation_kwargs))
        self.annotation_positions = (
            annotation_positions if annotation_positions is not None else
            copy.deepcopy(_default_annotation_positions))
        self.highlight_kwargs = (highlight_kwargs
                                 if highlight_kwargs is not None else
                                 copy.deepcopy(_default_highlight_kwargs))
"""
cbook即为cookbook,是一些小工具组成的库

"""
from matplotlib.cbook import CallbackRegistry

callbacks = CallbackRegistry()
sum = lambda x, y: print(f'{x}+{y}={x + y}')
mul = lambda x, y: print(f"{x} * {y}={x * y}")
id_sum = callbacks.connect("sum", sum)
id_mul = callbacks.connect("mul", mul)
callbacks.process('sum', 3, 4)
callbacks.process("mul", 5, 6)
callbacks.disconnect(id_sum)
callbacks.process("sum", 7, 8)
Пример #6
0
    def __init__(self, data, parent, id, *args, **kwargs):
        global DEFAULT_WIN_SIZE
        self.kwargs = kwargs
        self.size = kwargs.get('size', DEFAULT_WIN_SIZE)
        self.title = kwargs.get('title', 'ND Window')

        #
        # Forcing a specific style on the window.
        #   Should this include styles passed?
        style = wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE
        super(NDWindow, self).__init__(parent, id,
                                       self.title, wx.DefaultPosition,
                                       wx.Size(*self.size), style, self.title)

        self.gl_initialized = False
        attribs = (glcanvas.WX_GL_RGBA, glcanvas.WX_GL_DOUBLEBUFFER,
                   glcanvas.WX_GL_DEPTH_SIZE, settings.WX_GL_DEPTH_SIZE)
        self.canvas = glcanvas.GLCanvas(self, attribList=attribs)
        self.canvas.context = wx.glcanvas.GLContext(self.canvas)

        self._have_glut = False
        self.clear_color = (0, 0, 0, 0)
        self.show_axes_tf = True
        self.point_size = 1.0
        self._show_unassigned = True
        self._refresh_display_lists = False
        self._click_tolerance = 1
        self._display_commands = []
        self._selection_box = None
        self._rgba_indices = None
        self.mouse_panning = False
        self.win_pos = (100, 100)
        self.fovy = 60.
        self.znear = 0.1
        self.zfar = 10.0
        self.target_pos = [0.0, 0.0, 0.0]
        self.camera_pos_rtp = [7.0, 45.0, 30.0]
        self.up = [0.0, 0.0, 1.0]

        self.quadrant_mode = None
        self.mouse_handler = MouseHandler(self)

        # Set the event handlers.
        self.canvas.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background)
        self.Bind(wx.EVT_SIZE, self.on_resize)
        self.canvas.Bind(wx.EVT_PAINT, self.on_paint)
        self.canvas.Bind(wx.EVT_LEFT_DOWN, self.mouse_handler.left_down)
        self.canvas.Bind(wx.EVT_LEFT_UP, self.mouse_handler.left_up)
        self.canvas.Bind(wx.EVT_MOTION, self.mouse_handler.motion)
        self.canvas.Bind(wx.EVT_CHAR, self.on_char)
        self.canvas.Bind(wx.EVT_RIGHT_DOWN, self.right_click)
        self.canvas.Bind(wx.EVT_CLOSE, self.on_event_close)

        self.data = data
        self.classes = kwargs.get('classes', np.zeros(data.shape[:-1], np.int))
        self.features = kwargs.get('features', list(range(6)))
        self.labels = kwargs.get('labels', list(range(data.shape[-1])))
        self.max_menu_class = int(np.max(self.classes.ravel() + 1))

        from matplotlib.cbook import CallbackRegistry
        self.callbacks = CallbackRegistry()
Пример #7
0
    def __init__(self,
                 artists,
                 *,
                 multiple=False,
                 bindings=None,
                 annotation_kwargs=None,
                 annotation_positions=None):
        """Construct a cursor.

        Parameters
        ----------

        artists : List[Artist]
            A list of artists that can be selected by this cursor.

        multiple : bool, optional
            Whether multiple artists can be "on" at the same time (defaults to
            False).

        bindings : dict, optional
            A mapping of button and keybindings to actions.  Valid entries are:

            ================ ==================================================
            'select'         mouse button to select an artist
                             (default: 1)
            'deselect'       mouse button to deselect an artist
                             (default: 3)
            'left'           move to the previous point in the selected path,
                             or to the left in the selected image
                             (default: shift+left)
            'right'          move to the next point in the selected path, or to
                             the right in the selected image
                             (default: shift+right)
            'up'             move up in the selected image
                             (default: shift+up)
            'down'           move down in the selected image
                             (default: shift+down)
            'toggle_enabled' toggle whether the cursor is active
                             (default: e)
            'toggle_visible' toggle default cursor visibility and apply it to
                             all cursors (default: v)
            ================ ==================================================

            Missing entries will be set to the defaults.  In order to not
            assign any binding to an action, set it to ``None``.

        annotation_kwargs : dict, optional
            Keyword argments passed to the `annotate
            <matplotlib.axes.Axes.annotate>` call.

        annotation_positions : List[dict], optional
            List of positions tried by the annotation positioning algorithm.
        """

        self._artists = artists

        self._multiple = multiple

        self._visible = True
        self._enabled = True
        self._selections = []
        self._last_auto_position = None
        self._last_active_selection = -1
        self._callbacks = CallbackRegistry()

        connect_pairs = [
            ('key_press_event', self._on_key_press),
            ('button_press_event', self._mouse_click_handler),
            ('pick_event', self._pick_event_handler)
        ]
        self._disconnectors = [
            partial(canvas.mpl_disconnect, canvas.mpl_connect(*pair))
            for pair in connect_pairs
            for canvas in {artist.figure.canvas for artist in self._artists}
        ]

        if bindings is not None:
            unknown_bindings = set(bindings) - set(_default_bindings)
            if unknown_bindings:
                raise ValueError("Unknown binding(s): {}".format(", ".join(sorted(unknown_bindings))))
            duplicate_bindings = [k for k, v in Counter(list(bindings.values())).items() if v > 1]
            if duplicate_bindings:
                raise ValueError("Duplicate binding(s): {}".format(", ".join(sorted(map(str, duplicate_bindings)))))
            self.bindings = copy.deepcopy(_default_bindings)
            for key, value in bindings.items():
                self.bindings[key] = value
        else:
            self.bindings = _default_bindings

        self.annotation_kwargs = copy.deepcopy(_default_annotation_kwargs)
        if annotation_kwargs is not None:
            for key, value in annotation_kwargs.items():
                self.annotation_kwargs[key] = value
        self.annotation_positions = copy.deepcopy(_default_annotation_positions)
        if annotation_positions is not None:
            for key, value in annotation_positions.items():
                self.annotation_positions[key] = value