def __init__(self, parentPlot, ax, x, y): self._parentPlot = parentPlot self.ax = ax self.canvas = ax.figure.canvas self.x, self.y = x, y # mask will be set in self.setData if x and y: self.mask = np.zeros(x.shape, dtype=bool) else: self.mask = None markerSize = 50 self._highlight = ax.scatter([], [], s=markerSize, color='yellow', zorder=10) # here self is setting the callback and calls __call__ #self.selector = RectangleSelector(ax, self, useblit=True, interactive=False) self.selector = RectangleSelector(ax, self._HighlighterReleasedEvent, button=[1], useblit=True, interactive=False) self.mouseDownEvent = None self.keyIsDown = None self.ax.figure.canvas.mpl_connect('key_press_event', self._keyPressEvent) self.ax.figure.canvas.mpl_connect('key_release_event', self._keyReleaseEvent) # remember, sanpyPlugin is installing for key press and on pick self.keepOnMotion = self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion) self.keepMouseDown = self.ax.figure.canvas.mpl_connect('button_press_event', self.on_button_press)
def _setUp(self): self.ax.tick_params(direction='out', length=4, width=1, colors='black', grid_color='black', labelsize=self.axis_tick_font, grid_alpha=0.5) self.fig.tight_layout() self.chart = FigureCanvasTkAgg(self.fig, self.frame) self.chart.mpl_connect('button_press_event', self.doubleClkChart) rectprops = dict(facecolor='white', edgecolor='black', alpha=0.2, fill=True) self.RS = RectangleSelector( self.ax, self.selector, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True, rectprops=rectprops) self.RS.set_active(True) self.chart.get_tk_widget().pack(side=TOP)
def __init__(self): self.fig = plt.figure(num='Layout Analysed Image') #self.fig.suptitle("Layout Analysed figure") self.ax = self.fig.add_subplot(111) self.point = self.ax.plot([],[], marker="o", color="crimson") #clear button self.axclear = plt.axes([0.3, 0.01, 0.09,0.06]) self.bnclear = Button(self.axclear, 'Clear All') self.bnclear.color = "orange" #undo button self.axundo = plt.axes([0.4, 0.01, 0.09,0.06]) self.bnundo = Button(self.axundo, 'UNDO') self.bnundo.color = "red" #proceedbutton self.axproceed = plt.axes([0.5, 0.01, 0.095, 0.06]) self.bnproceed = Button(self.axproceed, 'PROCEED') self.bnproceed.color = "green" #usage 1 self.usg1 =plt.figtext(0.26, 0.96, 'PRESS "ENTER" AFTER SELECTING TO CONFIRM THE SELECTION') self.usg1.set_color('brown') self.usg1.set_weight('bold') #usage 2 self.usg2 = plt.figtext(0.3, 0.93, 'CLICK ON THE DRAWN RECTANGLES TO DELETE IT') self.usg2.set_color('brown') self.usg2.set_weight('bold') self.rect = [] self.rs = RectangleSelector(self.ax,self.line_select_callback, drawtype='box', useblit=False, button=[1], minspanx=2, minspany=2, spancoords='pixels', interactive=True)
def run(self): """ Create original line, movable line, background "line" (just points), and fitted curve lines. Create figure and subplot, register the callbacks, and show the plot. The movable line and the curve lines are in the regions. """ self._process_args() self._io_manager = io.Manager(self._args) # Read the data sets outside of Regions so we can discover the x, y # range of the data to use for the initial GUI size: self._input_data_sets = self._io_manager.get_movable_data_sets() self._background_data_sets = self._io_manager.get_background_data_sets( ) self._setup_GUI() self._regions = regions.Regions(ax=self._ax, args=self._args, input_data_sets=self._input_data_sets, xy_limits=self._xy_limits, io_manager=self._io_manager) self._register_callbacks() self._print_keymap() # Create rectangle selector for selecting multiple points self._selector = RectangleSelector( self._ax, self.line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button spancoords='pixels') self._selector.set_active(False) # Main routine: display all figures and block until all figures have # been closed: pyplot.show()
def boxes(): global files, directory,images_per_channel for f in files: if 'C2' in f: x = 1 y = 1 fig = pyplt.figure ax = pyplt.subplot(111) ax.plot(x,y) red_image_path = os.path.join(directory, f) img = PIL.Image.open(os.path.join(directory, f)) try: img.seek(images_per_channel-1) except: pass currentAxis = pyplt.gca() for coord1, coord2 in zip(start_coords, end_coords): x,y1 = coord1 x1,y = coord2 upper_left = (x,y1) width = x1-x height = y-y1 currentAxis.add_patch(Rectangle(upper_left, width, height, facecolor="none")) figManager = pyplt.get_current_fig_manager() figManager.window.showMaximized() pyplt.imshow(img) toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='box')
def draw_bbox(video): import matplotlib.pyplot as plt from matplotlib.widgets import RectangleSelector, Button clip = VideoWriter(video) frame = None # Read the video until a frame is successfully read while frame is None: frame = clip.read_frame() 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
def logplot(self, show_sliceplots=True): from zoom_colorbar import zoom_colorbar x_min = self.params['x_min'] x_max = self.params['x_max'] y_min = self.params['y_min'] y_max = self.params['y_max'] self.show_data = zeros( (self.params['x_steps'], self.params['y_steps'])) self.minimum_intensity = inf for j in range(self.params['y_steps']): for i in range(self.params['x_steps']): avg = self.bin_data[i, j, 3] if avg > 0.0: self.show_data[i, j] = avg else: self.show_data[i, j] = 0.0 if (avg < self.minimum_intensity and avg > 0): self.minimum_intensity = avg #self.show_data = transpose(log(self.show_data + self.minimum_intensity / 2.0)) fig = figure() self.fig = fig connect('pick_event', self.log_lin_select) if show_sliceplots: ax = fig.add_subplot(221, label='qxqz_plot') fig.sx = fig.add_subplot(222, label='sx', picker=True) fig.sx.xaxis.set_picker(True) fig.sx.yaxis.set_picker(True) fig.sz = fig.add_subplot(223, label='sz', picker=True) fig.sz.xaxis.set_picker(True) fig.sz.yaxis.set_picker(True) self.RS = RectangleSelector(ax, self.onselect, drawtype='box', useblit=True) fig.slice_overlay = None else: ax = fig.add_subplot(111, label='qxqz_plot') fig.ax = ax ax.set_title(self.params['description']) connect('key_press_event', self.toggle_selector) transformed_show_data = transpose( log(self.show_data + self.minimum_intensity / 2.0)) im = ax.imshow(transformed_show_data, interpolation='nearest', aspect='auto', origin='lower', cmap=cm.jet, extent=(x_min, x_max, y_min, y_max)) fig.im = im ax.set_xlabel(self.xlabel) ax.set_ylabel(self.ylabel) zoom_colorbar(im) figure(fig.number) fig.canvas.draw() return im
def _imshow_tfr(ax, ch_idx, tmin, tmax, vmin, vmax, onselect, ylim=None, tfr=None, freq=None, x_label=None, y_label=None, colorbar=False, cmap=('RdBu_r', True), yscale='auto', mask=None, mask_style="both", mask_cmap="Greys", mask_alpha=0.1, is_jointplot=False): """Show time-frequency map as two-dimensional image.""" from matplotlib import pyplot as plt from matplotlib.widgets import RectangleSelector if yscale not in ['auto', 'linear', 'log']: raise ValueError("yscale should be either 'auto', 'linear', or 'log'" ", got {}".format(yscale)) cmap, interactive_cmap = cmap times = np.linspace(tmin, tmax, num=tfr[ch_idx].shape[1]) img, t_end = _plot_masked_image(ax, tfr[ch_idx], times, mask, picks=None, yvals=freq, cmap=cmap, vmin=vmin, vmax=vmax, mask_style=mask_style, mask_alpha=mask_alpha, mask_cmap=mask_cmap, yscale=yscale) if x_label is not None: ax.set_xlabel(x_label) if y_label is not None: ax.set_ylabel(y_label) if colorbar: if isinstance(colorbar, DraggableColorbar): cbar = colorbar.cbar # this happens with multiaxes case else: cbar = plt.colorbar(mappable=img) if interactive_cmap: ax.CB = DraggableColorbar(cbar, img) ax.RS = RectangleSelector(ax, onselect=onselect) # reference must be kept return t_end
def create_main_frame(self): self.main_frame = QWidget() # Set up the matplotlib figure. self.fig = Figure(figsize=(self.width, self.height), dpi=self.dpi) self.fig_canvas = FigureCanvas(self.fig) self.fig_canvas.setParent(self.main_frame) self.fig_canvas.setFocusPolicy(Qt.ClickFocus) self.fig_canvas.setFocus() self.axs = self.fig.gca() # Get Current Axes self.fig_canvas.mpl_connect('key_press_event', self.on_key) self.fig_canvas.mpl_connect('key_press_event', self.on_key) # Put an image in the figure at startup. self.compute_initial_figure(self.disp_file) # Allow for the widget to expand/contract with the main widget. self.fig_canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.fig_canvas.updateGeometry() # Set up another figure for plotting (can be used for focus plot). self.plotfigure = plt.figure() self.plotdisp = FigureCanvas(self.plotfigure) self.plotdisp.setMaximumHeight(150) layout = QVBoxLayout(self.main_frame) layout.addWidget(self.fig_canvas) layout.addWidget(self.plotdisp) self.main_frame.setLayout(layout) self.setCentralWidget(self.main_frame) self.setWindowTitle(self.disp_file) self.rs = RectangleSelector( self.axs, self.line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=False) print(type(self.rs)) self.show() # Offset each new ImageDisplay window by 20,20 pixels until # we get to 200,200, then reset back to 0,0. geo = self.geometry() self.move(geo.x() + ImageDisplay.xoffset, geo.y() + ImageDisplay.yoffset) ImageDisplay.xoffset = ImageDisplay.xoffset + 20 ImageDisplay.yoffset = ImageDisplay.yoffset + 20 if (ImageDisplay.xoffset > 200): ImageDisplay.xoffset = 0 if (ImageDisplay.yoffset > 200): ImageDisplay.yoffset = 0
def setupSelector(self): self.rectSelect = RectangleSelector(self.ax, self.onselect, drawtype='box', rectprops=dict(facecolor='red', edgecolor='white', alpha=0.5, fill=False))
def __init__(self, fig, axes, patient_id): self.fig = fig self.ax = axes self.patient_id = patient_id self.roi = RectangleSelector(self.ax, self.start_end_select, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True)
def mpl_setup(self): def onselect(eclick, erelease): print("eclick: {}, erelease: {}".format(eclick, erelease)) self.rs = RectangleSelector(self.axes, onselect, drawtype='box', useblit=True)
def onrelease(self,event): self.rs = RectangleSelector(self.ax[0], self.line_select_callback, drawtype='box', useblit=False, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True) self.fig.canvas.mpl_disconnect(self.onclck) self.fig.canvas.mpl_disconnect(self.evtrelease) self.colors=self.oldcolor.copy()
def __init__(self, image, fig_xsize=None, fig_ysize=None, cmap=plt.cm.gist_gray, vmin=None, vmax=None ): display(Markdown(f"<text style=color:blue><b>Area of Interest Selector Tips:\n</b></text>")) display(Markdown(f'<text style=color:blue>- This plot uses "matplotlib notebook", whereas the other plots in this notebook use "matplotlib inline".</text>')) display(Markdown(f'<text style=color:blue>- If you run this cell out of sequence and the plot is not interactive, rerun the "%matplotlib notebook" code cell.</text>')) display(Markdown(f'<text style=color:blue>- Use the pan tool to pan with the left mouse button.</text>')) display(Markdown(f'<text style=color:blue>- Use the pan tool to zoom with the right mouse button.</text>')) display(Markdown(f'<text style=color:blue>- You can also zoom with a selection box using the zoom to rectangle tool.</text>')) display(Markdown(f'<text style=color:blue>- To turn off the pan or zoom to rectangle tool so you can select an AOI, click the selected tool button again.</text>')) display(Markdown(f'<text style=color:darkred><b>IMPORTANT!</b></text>')) display(Markdown(f'<text style=color:darkred>- Upon loading the AOI selector, the selection tool is already active.</text>')) display(Markdown(f'<text style=color:darkred>- Click, drag, and release the left mouse button to select an area.</text>')) display(Markdown(f'<text style=color:darkred>- The square tool icon in the menu is <b>NOT</b> the selection tool. It is the zoom tool.</text>')) display(Markdown(f'<text style=color:darkred>- If you select any tool, you must toggle it off before you can select an AOI</text>')) self.image = image self.x1 = None self.y1 = None self.x2 = None self.y2 = None if not vmin: self.vmin = np.nanpercentile(self.image, 1) else: self.vmin = vmin if not vmax: self.vmax=np.nanpercentile(self.image, 99) else: self.vmax = vmax if fig_xsize and fig_ysize: self.fig, self.current_ax = plt.subplots(figsize=(fig_xsize, fig_ysize)) else: self.fig, self.current_ax = plt.subplots() self.fig.suptitle('Area-Of-Interest Selector', fontsize=16) self.current_ax.imshow(self.image, cmap=plt.cm.gist_gray, vmin=self.vmin, vmax=self.vmax) def toggle_selector(self, 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) toggle_selector.RS = RectangleSelector(self.current_ax, self.line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', rectprops = dict(facecolor='red', edgecolor = 'yellow', alpha=0.3, fill=True), interactive=True) plt.connect('key_press_event', toggle_selector)
def selectROI(matrice_immagine, titolo='Immagine', contour_plot_flag: bool = False): ''' input: ax --> axis su cui fare la selezione della roi output: (xi,yi,dx,dy) ''' (t_lim_inf, t_lim_sup) = set_cmap(matrice_immagine) _, ax = plt.subplots() if contour_plot_flag: alpha = 0.5 matrice_immagine = matrice_immagine.copy() (dx, dy) = matrice_immagine.shape N = dx * dy istogramma = np.zeros(N) istogramma = np.sort(np.reshape(matrice_immagine, N)) footprint = np.matrix([[1, 1, 1], [1, 2, 1], [1, 1, 1]]) levels = [ istogramma[int(0.2 * N)], istogramma[int(0.6 * N)], istogramma[int(0.8 * N)], istogramma[int(0.9 * N)], istogramma[int(0.95 * N)] ] matrice_immagine = ndimage.gaussian_filter(matrice_immagine, sigma=2) matrice_immagine = ndimage.grey_erosion(matrice_immagine, footprint=footprint) matrice_immagine = ndimage.grey_dilation(matrice_immagine, footprint=footprint) CS = ax.contour(np.arange(dy), np.arange(dx), matrice_immagine, levels, cmap='inferno') ax.clabel(CS, inline=True, fontsize=10) else: alpha = 1 ax.imshow(matrice_immagine, cmap='inferno', clim=[t_lim_inf, t_lim_sup], alpha=alpha) ax.set(title=titolo) __toggle_selector.RS = RectangleSelector( ax, __onselect, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True) plt.connect('key_press_event', __toggle_selector) plt.show() return cordinate
def plot_slice(self, z, z_lower, z_upper, NewBox, FinishCurrentBox, label, sigma=2, R=10): time1 = time.time() a = self.volume # Smooth if sigma == 0: a_smooth = a else: a_smooth = smooth(a, sigma) # Get image img = a_smooth[:, :, z] plt.rcParams['figure.figsize'] = self.figsize self.current_ax.imshow(img, cmap=self.cmap) # Change box color based on lower and upper bound of z box_c = 'green' if z <= z_lower or z >= z_upper: box_c = 'red' # Store label and bounding box info when done with the current box if FinishCurrentBox: coordinates = toggle_selector.RS.extents # Return (xmin, xmax, ymin, ymax) coordinates = coordinates * 5 xmin = coordinates[0] xmax = coordinates[1] ymin = coordinates[2] ymax = coordinates[3] boxInfo = [ xmin, ymin, z_lower, xmax - xmin, ymax - ymin, z_upper - z_lower ] self.annotations[label] = boxInfo # Adding a new bounding box if NewBox: toggle_selector.RS = RectangleSelector( self.current_ax, self.line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True, rectprops=dict(edgecolor=box_c, alpha=1, fill=False)) plt.connect('key_press_event', toggle_selector) print('plot_slice time', time.time() - time1)
def __get_roi(img, loc_names, output_folder): """ The GUI interface for selecting regions of interest in a provided image. :param img: ndarray. The image to be used for selecting ROIs. :param loc_names: list. Name describing each ROI. (i.e. ['top', 'bot']) :param output_folder: str. Location to save out coordinates. :return: """ if not os.path.isdir(output_folder): os.makedirs(output_folder) nroi = len(loc_names) colors = ['r', 'g', 'b', 'k', 'c', 'm', 'y'] plt.rcParams['image.cmap'] = 'gray' # ROI selection callback. def onselect(eclick, erelease): print(loc_names[idx] + ' ROI selected.' + ' Change or close window to continue.') # Make a new window to choose each ROI. selectors = [] for idx in range(nroi): fig = plt.figure(figsize=(20, 20)) ax = fig.add_subplot(1, 1, 1) ax.imshow(img) selector = RectangleSelector(ax, onselect, drawtype='box', interactive=True) plt.title('Choose ' + loc_names[idx] + ' ROI.') plt.show() selectors.append(selector) # Plot all selections. fig = plt.figure(figsize=(20, 20)) ax = fig.add_subplot(1, 1, 1) ax.imshow(img) for idx, selector in enumerate(selectors): rect = plt.Rectangle( [selector.corners[0][0], selector.corners[1][0]], selector.corners[0][2] - selector.corners[0][0], selector.corners[1][2] - selector.corners[1][0], fill=None, color=colors[idx]) ax.add_patch(rect) plt.savefig(output_folder + '/roi_summary.pdf') plt.show() slices = [] for selector in selectors: x0 = int(selector.corners[1][0]) - 1 x0 = 0 if x0 < 0 else x0 x = slice(x0, int(selector.corners[1][2])) x0 = int(selector.corners[0][0]) - 1 x0 = 0 if x0 < 0 else x0 y = slice(x0, int(selector.corners[0][2])) slices.append([x, y]) return slices
def draw(self): (self.coord, self.stats, title, showLegend) = self.inputPorts stds, corrs = self.stats.values[:, 0], self.stats.values[:, 1] self.Xs = stds * corrs self.Ys = stds * np.sin(np.arccos(corrs)) colors = pylab.cm.jet(np.linspace(0, 1, len(self.stats.ids))) pylab.clf() fig = pylab.figure(str(self)) dia = taylor_diagram.TaylorDiagram(stds[0], corrs[0], fig=fig, label=self.stats.labels[0]) dia.samplePoints[0].set_color( colors[0]) # Mark reference point as a red star if self.stats.ids[0] in self.selectedIds: dia.samplePoints[0].set_markeredgewidth(3) # add models to Taylor diagram for i, (_id, stddev, corrcoef) in enumerate( zip(self.stats.ids[1:], stds[1:], corrs[1:])): label = self.stats.labels[i + 1] size = 3 if _id in self.selectedIds else 1 dia.add_sample( stddev, corrcoef, marker='o', #self.markers[i], ls='', mfc=colors[i + 1], mew=size, label=label) # Add grid dia.add_grid() # Add RMS contours, and label them contours = dia.add_contours(levels=5, colors='0.5') # 5 levels in grey pylab.clabel(contours, inline=1, fontsize=10, fmt='%.1f') # Add a figure legend and title if showLegend: fig.legend(dia.samplePoints, [p.get_label() for p in dia.samplePoints], numpoints=1, prop=dict(size='small'), loc='upper right') fig.suptitle(title, size='x-large') # Figure title self.figManager.canvas.draw() self.rectSelector = RectangleSelector(pylab.gca(), self.onselect, drawtype='box', rectprops=dict( alpha=0.4, facecolor='yellow')) self.rectSelector.set_active(True)
def __init__(self, ax, data, flags): from matplotlib.widgets import RectangleSelector self._rs = RectangleSelector(ax, self._onselect, drawtype='box', interactive=True) # plt.connect('key_press_event', self._toggle) self.data = data self.flags = flags
def show_image(self): self.figure,self.axes,self.canvas = self.image_panel.getfigure() #frame=cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB) #frame=cv2.imread(self.image)[...,::-1] frame=self.image self.ax = self.axes.imshow(frame) 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)
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, frame.shape[1], 0, 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() if platform.system() == 'Darwin': #for OSX use WXAgg fig.canvas.start_event_loop(timeout=-1) else: fig.canvas.stop_event_loop() plt.close(fig) return bbox
def __init__(self, ax, x, y): self.ax = ax self.canvas = ax.figure.canvas self.x, self.y = x, y self.mask = np.zeros(x.shape, dtype=bool) self._highlight = ax.scatter([], [], s=1, color='yellow', zorder=10) self.selector = RectangleSelector(ax, self, useblit=True)
def create_selector(self): """Create the :attr:`selector` to enable :attr:`colpic` selection""" self.selector = RectangleSelector(self.main_ax, self.update_image, interactive=True) if self.colpic_extents is not None: self.selector.extents = self.colpic_extents self.key_press_cid = self.main_canvas.mpl_connect( 'key_press_event', self.update_image)
def connect(self): self.controller.fovLoaded.connect(self.on_load_fov) self.controller.indexChanged.connect(self.on_change_cell) self.controller.cellUpdated.connect(self.on_change_cell) self.mpl_connect('button_release_event', self.on_release) rectProps = {"alpha": 0.5, "facecolor": "#E5FF00"} spanArgs = {"useblit": True, "button": 1, "rectprops": rectProps} self.zoomSpan = RectangleSelector(self.axFOV, self.on_zoom, **spanArgs)
def create_rectangle_ax(self, ax): rectprops = dict(facecolor = 'red', edgecolor = 'black', alpha = 0.1, fill = True, linewidth = 1, linestyle= '-') self._rectangle_selector = RectangleSelector(ax, self._callback_rectangle, drawtype= 'box', useblit= True, rectprops= rectprops, button= [1,3], minspanx = 5, minspany=5, spancoords='pixels', interactive=True) self._disable_rectangle()
def PostInit(self, ts): self.unselected = ts.data.transpose() ax = self.add_subplot(111) ax.set_title('%s data for station %s' % (ts.variable, ts.station_id)) self.unselected_points, = ax.plot(self.unselected[0,:], self.unselected[1,:], 'bo', picker=5) # 5 points tolerance self.selected_points, = ax.plot([], [], 'ro', zorder=5) self.canvas.mpl_connect('pick_event', self.OnPick) self.rs = RectangleSelector(ax, self.OnSelect, drawtype='box', button=3) self.canvas.mpl_connect('key_press_event', self.OnKeyPress)
def __init__(self, ax, imgplot, img_slider): print('ini') self.ROI = RectangleSelector(ax, self.onselectfun, drawtype='box', interactive=True) self.imgplot = imgplot self.img_slider = img_slider self.saveInt = np.zeros(259) self.saveROI = np.zeros([259, 4])
def _interactive(self): if self._ax and self.interactive: self._selector = RectangleSelector( self._ax, onselect=self._onselect, rectprops={'alpha':0.2, 'color':'grey'}, useblit = True) else: self._selector = None
def _interactive(self): if self._ax and self.interactive: self._selector = RectangleSelector(self._ax, onselect=self._onselect, rectprops=dict(facecolor='none', edgecolor='blue', linewidth=2), useblit=True) else: self._selector = None
def updateSelector(self, data_axis): ''' Updates the selector of the axes with a new selector data_axis [DataAxis] ''' if data_axis.axisExists(): self.selector = RectangleSelector(data_axis.getAxis(), self._selector_callback_plot, drawtype='box')