Python matplotlib.widgets.RectangleSelector() Examples

The following are 20 code examples of matplotlib.widgets.RectangleSelector(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.widgets , or try the search function .
Example #1
Source File: label.py    From smashscan with MIT License 6 votes vote down vote up
def show(self):

        self.fig, self.ax = plt.subplots(1, figsize=(11, 8.5))
        _, frame = self.capture.read()
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        self.ax.imshow(frame)

        toggle_selector.RS = RectangleSelector(
            self.ax, self.line_select_callback,
            drawtype='box', useblit=True,
            button=[1], minspanx=5, minspany=5,
            spancoords='pixels', interactive=True,
        )
        self.fig.canvas.mpl_connect('key_press_event', toggle_selector)
        self.fig.canvas.mpl_connect('key_press_event', self.onkeypress)
        plt.tight_layout()
        plt.show()


    # The keybindings attached to the LabelPlot. 
Example #2
Source File: test_widgets.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def check_rectangle(**kwargs):
    ax = get_ax()

    def onselect(epress, erelease):
        ax._got_onselect = True
        assert epress.xdata == 100
        assert epress.ydata == 100
        assert erelease.xdata == 199
        assert erelease.ydata == 199

    tool = widgets.RectangleSelector(ax, onselect, **kwargs)
    do_event(tool, 'press', xdata=100, ydata=100, button=1)
    do_event(tool, 'onmove', xdata=199, ydata=199, button=1)

    # purposely drag outside of axis for release
    do_event(tool, 'release', xdata=250, ydata=250, button=1)

    if kwargs.get('drawtype', None) not in ['line', 'none']:
        assert_allclose(tool.geometry,
            [[100., 100, 199, 199, 100], [100, 199, 199, 100, 100]],
            err_msg=tool.geometry)

    assert ax._got_onselect 
Example #3
Source File: test_widgets.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def check_rectangle(**kwargs):
    ax = get_ax()

    def onselect(epress, erelease):
        ax._got_onselect = True
        assert epress.xdata == 100
        assert epress.ydata == 100
        assert erelease.xdata == 199
        assert erelease.ydata == 199

    tool = widgets.RectangleSelector(ax, onselect, **kwargs)
    do_event(tool, 'press', xdata=100, ydata=100, button=1)
    do_event(tool, 'onmove', xdata=199, ydata=199, button=1)

    # purposely drag outside of axis for release
    do_event(tool, 'release', xdata=250, ydata=250, button=1)

    if kwargs.get('drawtype', None) not in ['line', 'none']:
        assert_allclose(tool.geometry,
                        [[100., 100, 199, 199, 100],
                         [100, 199, 199, 100, 100]],
                        err_msg=tool.geometry)

    assert ax._got_onselect 
Example #4
Source File: test_widgets.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_rectangle(**kwargs):
    ax = get_ax()

    def onselect(epress, erelease):
        ax._got_onselect = True
        assert epress.xdata == 100
        assert epress.ydata == 100
        assert erelease.xdata == 199
        assert erelease.ydata == 199

    tool = widgets.RectangleSelector(ax, onselect, **kwargs)
    do_event(tool, 'press', xdata=100, ydata=100, button=1)
    do_event(tool, 'onmove', xdata=199, ydata=199, button=1)

    # purposely drag outside of axis for release
    do_event(tool, 'release', xdata=250, ydata=250, button=1)

    if kwargs.get('drawtype', None) not in ['line', 'none']:
        assert_allclose(tool.geometry,
                        [[100., 100, 199, 199, 100],
                         [100, 199, 199, 100, 100]],
                        err_msg=tool.geometry)

    assert ax._got_onselect 
Example #5
Source File: select_crop_parameters.py    From DeepLabCut with GNU Lesser General Public License v3.0 6 votes vote down vote up
def show_image(self):
        self.figure, self.axes, self.canvas = self.image_panel.getfigure()
        self.ax = self.axes.imshow(self.image)
        self.figure.canvas.draw()
        self.cid = RectangleSelector(
            self.axes,
            self.line_select_callback,
            drawtype="box",
            useblit=False,
            button=[1],
            minspanx=5,
            minspany=5,
            spancoords="pixels",
            interactive=True,
        )
        self.canvas.mpl_connect("key_press_event", self.cid) 
Example #6
Source File: interactivefigure.py    From ray-optics with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, fig, **kwargs):
        def on_release(press_event, release_event):
            bbox = np.array([[press_event.xdata, press_event.ydata],
                             [release_event.xdata, release_event.ydata]])
            fig.set_view_bbox(bbox)
            fig.canvas.draw_idle()
            self.rubber_box.disconnect_events()
            fig.connect_events(self.saved_events)
            fig.action_complete()

        self.saved_events = fig.disconnect_events()
        rectprops = dict(edgecolor=fig._rgb['foreground'], fill=False)
        self.rubber_box = widgets.RectangleSelector(
            fig.ax, on_release, drawtype='box', useblit=False,
            button=[1, 3],  # don't use middle button
            minspanx=5, minspany=5, spancoords='pixels', rectprops=rectprops,
            interactive=False) 
Example #7
Source File: PDS_Compute_MTF.py    From PDS_Compute_MTF with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, filename):
        self.filename = filename
        self.image_data = cv2.imread(filename, 0)
        fig_image, current_ax = plt.subplots()
        plt.imshow(self.image_data, cmap='gray')
        eh = EventHandler(self.filename)
        rectangle_selector = RectangleSelector(current_ax,
                                               eh.line_select_callback,
                                               drawtype='box',
                                               useblit=True,
                                               button=[1, 2, 3],
                                               minspanx=5, minspany=5,
                                               spancoords='pixels',
                                               interactive=True)
        plt.connect('key_press_event', eh.event_exit_manager)
        plt.show() 
Example #8
Source File: filter.py    From picasso with MIT License 5 votes vote down vote up
def plot(self):
        # Prepare the data
        x = self.locs[self.field_x]
        y = self.locs[self.field_y]
        valid = np.isfinite(x) & np.isfinite(y)
        x = x[valid]
        y = y[valid]
        # Prepare the figure
        self.figure.clear()
        # self.canvas.figure = self.figure
        axes = self.figure.add_subplot(111)
        # Start hist2 version
        bins_x = lib.calculate_optimal_bins(x, 1000)
        bins_y = lib.calculate_optimal_bins(y, 1000)
        counts, x_edges, y_edges, image = axes.hist2d(
            x, y, bins=[bins_x, bins_y], norm=LogNorm()
        )
        x_range = x.ptp()
        axes.set_xlim([bins_x[0] - 0.05 * x_range, x.max() + 0.05 * x_range])
        y_range = y.ptp()
        axes.set_ylim([bins_y[0] - 0.05 * y_range, y.max() + 0.05 * y_range])
        self.figure.colorbar(image, ax=axes)
        axes.grid(False)
        axes.get_xaxis().set_label_text(self.field_x)
        axes.get_yaxis().set_label_text(self.field_y)
        self.selector = RectangleSelector(
            axes,
            self.on_rect_select,
            useblit=False,
            rectprops=dict(facecolor="green", alpha=0.2, fill=True),
        )
        self.canvas.draw() 
Example #9
Source File: test_widgets.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_rectangle_handles():
    ax = get_ax()

    def onselect(epress, erelease):
        pass

    tool = widgets.RectangleSelector(ax, onselect=onselect,
                                     maxdist=10, interactive=True)
    tool.extents = (100, 150, 100, 150)

    assert tool.corners == (
        (100, 150, 150, 100), (100, 100, 150, 150))
    assert tool.extents == (100, 150, 100, 150)
    assert tool.edge_centers == (
        (100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150))
    assert tool.extents == (100, 150, 100, 150)

    # grab a corner and move it
    do_event(tool, 'press', xdata=100, ydata=100)
    do_event(tool, 'onmove', xdata=120, ydata=120)
    do_event(tool, 'release', xdata=120, ydata=120)
    assert tool.extents == (120, 150, 120, 150)

    # grab the center and move it
    do_event(tool, 'press', xdata=132, ydata=132)
    do_event(tool, 'onmove', xdata=120, ydata=120)
    do_event(tool, 'release', xdata=120, ydata=120)
    assert tool.extents == (108, 138, 108, 138)

    # create a new rectangle
    do_event(tool, 'press', xdata=10, ydata=10)
    do_event(tool, 'onmove', xdata=100, ydata=100)
    do_event(tool, 'release', xdata=100, ydata=100)
    assert tool.extents == (10, 100, 10, 100) 
Example #10
Source File: test_widgets.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_rectangle_handles():
    ax = get_ax()

    def onselect(epress, erelease):
        pass

    tool = widgets.RectangleSelector(ax, onselect=onselect,
                                     maxdist=10, interactive=True)
    tool.extents = (100, 150, 100, 150)

    assert tool.corners == (
        (100, 150, 150, 100), (100, 100, 150, 150))
    assert tool.extents == (100, 150, 100, 150)
    assert tool.edge_centers == (
        (100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150))
    assert tool.extents == (100, 150, 100, 150)

    # grab a corner and move it
    do_event(tool, 'press', xdata=100, ydata=100)
    do_event(tool, 'onmove', xdata=120, ydata=120)
    do_event(tool, 'release', xdata=120, ydata=120)
    assert tool.extents == (120, 150, 120, 150)

    # grab the center and move it
    do_event(tool, 'press', xdata=132, ydata=132)
    do_event(tool, 'onmove', xdata=120, ydata=120)
    do_event(tool, 'release', xdata=120, ydata=120)
    assert tool.extents == (108, 138, 108, 138)

    # create a new rectangle
    do_event(tool, 'press', xdata=10, ydata=10)
    do_event(tool, 'onmove', xdata=100, ydata=100)
    do_event(tool, 'release', xdata=100, ydata=100)
    assert tool.extents == (10, 100, 10, 100) 
Example #11
Source File: frame_extraction_toolbox.py    From DeepLabCut with GNU Lesser General Public License v3.0 5 votes vote down vote up
def CheckCropping(self):
        """ Display frame at time "time" for video to check if cropping is fine.
        Select ROI of interest by adjusting values in myconfig.py

        USAGE for cropping:
        clip.crop(x1=None, y1=None, x2=None, y2=None, width=None, height=None, x_center=None, y_center=None)

        Returns a new clip in which just a rectangular subregion of the
        original clip is conserved. x1,y1 indicates the top left corner and
        x2,y2 is the lower right corner of the cropped region.

        All coordinates are in pixels. Float numbers are accepted.
        """

        videosource = self.video_source
        self.x1 = int(self.cfg["video_sets"][videosource]["crop"].split(",")[0])
        self.x2 = int(self.cfg["video_sets"][videosource]["crop"].split(",")[1])
        self.y1 = int(self.cfg["video_sets"][videosource]["crop"].split(",")[2])
        self.y2 = int(self.cfg["video_sets"][videosource]["crop"].split(",")[3])

        if self.cropping == True:
            # Select ROI of interest by drawing a rectangle
            self.cid = RectangleSelector(
                self.axes,
                self.line_select_callback,
                drawtype="box",
                useblit=False,
                button=[1],
                minspanx=5,
                minspany=5,
                spancoords="pixels",
                interactive=True,
            )
            self.canvas.mpl_connect("key_press_event", self.cid) 
Example #12
Source File: widgets.py    From ImageFusion with MIT License 5 votes vote down vote up
def set_active(self, active):
        """
        Use this to activate / deactivate the RectangleSelector
        from your program with an boolean parameter *active*.
        """
        self.active = active 
Example #13
Source File: widgets.py    From Computable with MIT License 5 votes vote down vote up
def set_active(self, active):
        """
        Use this to activate / deactivate the RectangleSelector
        from your program with an boolean parameter *active*.
        """
        self.active = active 
Example #14
Source File: test_widgets.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_rectangle_handles():
    ax = get_ax()

    def onselect(epress, erelease):
        pass

    tool = widgets.RectangleSelector(ax, onselect=onselect,
                                     maxdist=10, interactive=True)
    tool.extents = (100, 150, 100, 150)

    assert tool.corners == (
        (100, 150, 150, 100), (100, 100, 150, 150))
    assert tool.extents == (100, 150, 100, 150)
    assert tool.edge_centers == (
        (100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150))
    assert tool.extents == (100, 150, 100, 150)

    # grab a corner and move it
    do_event(tool, 'press', xdata=100, ydata=100)
    do_event(tool, 'onmove', xdata=120, ydata=120)
    do_event(tool, 'release', xdata=120, ydata=120)
    assert tool.extents == (120, 150, 120, 150)

    # grab the center and move it
    do_event(tool, 'press', xdata=132, ydata=132)
    do_event(tool, 'onmove', xdata=120, ydata=120)
    do_event(tool, 'release', xdata=120, ydata=120)
    assert tool.extents == (108, 138, 108, 138)

    # create a new rectangle
    do_event(tool, 'press', xdata=10, ydata=10)
    do_event(tool, 'onmove', xdata=100, ydata=100)
    do_event(tool, 'release', xdata=100, ydata=100)
    assert tool.extents == (10, 100, 10, 100) 
Example #15
Source File: rectangle_selector.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def toggle_selector(event):
    print(' Key pressed.')
    if event.key in ['Q', 'q'] and toggle_selector.RS.active:
        print(' RectangleSelector deactivated.')
        toggle_selector.RS.set_active(False)
    if event.key in ['A', 'a'] and not toggle_selector.RS.active:
        print(' RectangleSelector activated.')
        toggle_selector.RS.set_active(True) 
Example #16
Source File: widgets.py    From neural-network-animation with MIT License 5 votes vote down vote up
def set_active(self, active):
        """
        Use this to activate / deactivate the RectangleSelector
        from your program with an boolean parameter *active*.
        """
        self.active = active 
Example #17
Source File: helper_functions.py    From pylustrator with GNU General Public License v3.0 5 votes vote down vote up
def selectRectangle(axes: Axes = None):
    """ add a rectangle selector to the given axes """
    if axes is None:
        axes = plt.gca()

    def onselect(eclick, erelease):
        'eclick and erelease are matplotlib events at press and release'
        print(' startposition : (%f, %f)' % (eclick.xdata, eclick.ydata))
        print(' endposition   : (%f, %f)' % (erelease.xdata, erelease.ydata))
        print(' used button   : ', eclick.button)

    from matplotlib.widgets import RectangleSelector
    rect_selector = RectangleSelector(axes, onselect)
    return rect_selector 
Example #18
Source File: widgets.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def set_active(self, active):
        """
        Use this to activate / deactivate the RectangleSelector
        from your program with an boolean parameter *active*.
        """
        self.active = active 
Example #19
Source File: auxfun_videos.py    From DeepLabCut with GNU Lesser General Public License v3.0 4 votes vote down vote up
def draw_bbox(video):
    import matplotlib.pyplot as plt
    from matplotlib.widgets import RectangleSelector, Button

    clip = cv2.VideoCapture(video)
    if not clip.isOpened():
        print("Video could not be opened. Skipping...")
        return

    success = False
    # Read the video until a frame is successfully read
    while not success:
        success, frame = clip.read()

    bbox = [0, 0, frame.shape[1], frame.shape[0]]

    def line_select_callback(eclick, erelease):
        bbox[:2] = int(eclick.xdata), int(eclick.ydata)  # x1, y1
        bbox[2:] = int(erelease.xdata), int(erelease.ydata)  # x2, y2

    def validate_crop(*args):
        fig.canvas.stop_event_loop()

    def display_help(*args):
        print(
            "1. Use left click to select the region of interest. A red box will be drawn around the selected region. \n\n2. Use the corner points to expand the box and center to move the box around the image. \n\n3. Click "
        )

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.imshow(frame[:, :, ::-1])
    ax_help = fig.add_axes([0.9, 0.2, 0.1, 0.1])
    ax_save = fig.add_axes([0.9, 0.1, 0.1, 0.1])
    crop_button = Button(ax_save, "Crop")
    crop_button.on_clicked(validate_crop)
    help_button = Button(ax_help, "Help")
    help_button.on_clicked(display_help)

    rs = RectangleSelector(
        ax,
        line_select_callback,
        drawtype="box",
        minspanx=5,
        minspany=5,
        interactive=True,
        spancoords="pixels",
        rectprops=dict(facecolor="red", edgecolor="black", alpha=0.3, fill=True),
    )
    plt.show()

    # import platform
    # if platform.system() == "Darwin":  # for OSX use WXAgg
    #    fig.canvas.start_event_loop(timeout=-1)
    # else:
    fig.canvas.start_event_loop(timeout=-1)  # just tested on Ubuntu I also need this.
    #    #fig.canvas.stop_event_loop()

    plt.close(fig)
    return bbox 
Example #20
Source File: spypylab.py    From spectral with MIT License 4 votes vote down vote up
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)