def __init__(self, ax, button=3): self.canvas = ax.figure.canvas self.Npts = len(self.xys) self.lasso = LassoSelector(ax, onselect=self.onselect, button=[button]) self.ind = []
class SelectFromCollection(object): """Use the lasso selector tool.""" def __init__(self, ax, collection, alpha_other=0.3): """The lasso.""" self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.fcl = collection.get_facecolors() if not self.fcl.any(): raise ValueError('Collection must have a facecolor') elif len(self.fcl) == 1: self.fcl = np.tile(self.fcl, (len(self.xys), 1)) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] def onselect(self, verts): """Begin lasso.""" path = Path(verts) self.ind = np.nonzero(path.contains_points(self.xys))[0] self.fcl[:, -1] = self.alpha_other self.fcl[self.ind, -1] = 1 self.collection.set_facecolors(self.fcl) self.canvas.draw_idle() def disconnect(self): """End lasso.""" self.lasso.disconnect_events() self.fcl[:, -1] = 1 self.collection.set_facecolors(self.fcl) self.canvas.draw_idle()
class SelectFromCollection(object): def __init__(self, ax, collection, alpha_other=0.3): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, (self.Npts, 1)) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] def onselect(self, verts): path = Path(verts) self.ind = np.nonzero(path.contains_points(self.xys))[0] self.fc[:, -1] = self.alpha_other self.fc[self.ind, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() def disconnect(self): self.lasso.disconnect_events() self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle()
def label_chart(self, csv_path): """Show and Label the Chart. Call this method. """ # Create axis for the price and technical indicator graph ax1 = self.fig.add_suplot(211) # Turn on axes and background lines self.path = csv_path plt.axis('on') self.df.plot(x=self.col_label, y=self.row_label, ax=ax1, label='price', color='black') # Plot Technical Indicators if self.tech_inds: for col_name in self.tech_inds: ti_df = self.df[['time', col_name]].copy() ti_df.plot(x='time', y=col_name, ax=ax1, label=col_name) # 1 = left mouse, 2 = scroll wheel, 3 = right mouse lsso_sell = LassoSelector(ax=self.ax, onselect=self.onSelectSell, lineprops=self.lineprops_sell, button=1) lsso_buy = LassoSelector(ax=self.ax, onselect=self.onSelectBuy, lineprops=self.lineprops_buy, button=3) lsso_clear = LassoSelector(ax=self.ax, onselect=self.onSelectClear, lineprops=self.lineprops_clear, button=2) # On Keyboard Enter press, export the labelled data to .csv self.fig.canvas.mpl_connect('key_press_event', self.enter_press_export_event) plt.show()
class SelectFromCollection(object): """Select indices from a matplotlib collection using `LassoSelector`. Selected indices are saved in the `ind` attribute. This tool fades out the points that are not part of the selection (i.e., reduces their alpha values). If your collection has alpha < 1, this tool will permanently alter the alpha values. Note that this tool selects collection objects based on their *origins* (i.e., `offsets`). Parameters ---------- ax : :class:`~matplotlib.axes.Axes` Axes to interact with. collection : :class:`matplotlib.collections.Collection` subclass Collection you want to select from. alpha_other : 0 <= float <= 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to `alpha_other`. """ def __init__(self, ax, collection, cb_onselect, alpha_other=0.3): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) self.cb_onselect = cb_onselect # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, (self.Npts, 1)) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] hello = True def onselect(self, verts): path = Path(verts) self.ind = np.nonzero(path.contains_points(self.xys))[0] self.cb_onselect(self) self.fc[:, -1] = 1 self.fc[self.ind, -1] = 0.5 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() def disconnect(self): self.lasso.disconnect_events() self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle()
class SelectFromCollection(object): """Select indices from a matplotlib collection using `LassoSelector`. Selected indices are saved in the `ind` attribute. This tool highlights selected points by fading them out (i.e., reducing their alpha values). If your collection has alpha < 1, this tool will permanently alter them. Note that this tool selects collection objects based on their *origins* (i.e., `offsets`). Parameters ---------- ax : :class:`~matplotlib.axes.Axes` Axes to interact with. collection : :class:`matplotlib.collections.Collection` subclass Collection you want to select from. alpha_other : 0 < = float < = 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to `alpha_other`. """ def __init__(self, ax, collection,parent): '''Docstring''' self.ax = ax self.canvas = ax.figure.canvas self.collection = collection self.xys = collection self.Npts = len(self.xys) self.parent = parent self.lasso = LassoSelector(ax, onselect = self.onselect) self.ind = [] def onselect(self, verts): '''Docstring''' if self.parent._active == "ZOOM" or self.parent._active == "PAN": return path = Path(verts) self.ind.extend(np.nonzero([path.contains_point(xy) for xy in self.xys])[0]) self.ind = list(np.unique(self.ind)) for line in self.ax.axes.lines: if line.get_gid() == 'node': line.remove() self.ax.plot(self.xys[self.ind,0], self.xys[self.ind,1], 'r.', gid='node') self.canvas.draw_idle() def disconnect(self): '''Docstring''' self.lasso.disconnect_events() self.canvas.draw_idle()
def __init__(self, tracker, ax, collection, alpha, alpha_other=0.2): self.tracker = tracker self.ax = ax self.collection = collection self.fc = collection.get_facecolors() self.alpha = alpha self.alpha_other = alpha_other self.lasso = LassoSelector(ax, onselect=self.on_select) self.is_connected = True self.toggle()
def __init__(self, ax, collection, parent): self.ax = ax self.canvas = ax.figure.canvas self.collection = collection self.xys = collection self.Npts = len(self.xys) self.parent = parent self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = []
def __init__(self, ax, implot, color=[1,1,1]): self.canvas = ax.figure.canvas self.implot = implot self.array = implot.get_array() xv, yv = np.meshgrid(np.arange(self.array.shape[1]),np.arange(self.array.shape[0])) self.pix = np.vstack( (xv.flatten(), yv.flatten()) ).T self.ind = [] self.im_bool = np.zeros((self.array.shape[0], self.array.shape[1])) self.color = color self.lasso = LassoSelector(ax, onselect=self.onselect)
class SelectFromCollection(object): """Select indices from a matplotlib collection using `LassoSelector`. Selected indices are saved in the `ind` attribute. This tool fades out the points that are not part of the selection (i.e., reduces their alpha values). If your collection has alpha < 1, this tool will permanently alter the alpha values. Note that this tool selects collection objects based on their *origins* (i.e., `offsets`). Parameters ---------- ax : :class:`~matplotlib.axes.Axes` Axes to interact with. collection : :class:`matplotlib.collections.Collection` subclass Collection you want to select from. alpha_other : 0 <= float <= 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to `alpha_other`. """ def __init__(self, ax, collection, alpha_other=0.3): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, (self.Npts, 1)) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] def onselect(self, verts): path = Path(verts) self.ind = np.nonzero(path.contains_points(self.xys))[0] self.fc[:, -1] = self.alpha_other self.fc[self.ind, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() def disconnect(self): self.lasso.disconnect_events() self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle()
class SelectFromCollection: """ Select indices from a matplotlib collection using `LassoSelector`. Modified from https://matplotlib.org/gallery/widgets/lasso_selector_demo_sgskip.html Selected indices are saved in the `ind` attribute. This tool fades out the points that are not part of the selection (i.e., reduces their alpha values). If your collection has alpha < 1, this tool will permanently alter the alpha values. Note that this tool selects collection objects based on their *origins* (i.e., `offsets`). """ def __init__(self, ax, collection, alpha_other=0.3, on_select=None): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.n_pts = len(self.xys) self._on_select = on_select # Ensure that we have separate colors for each object self.facecolors = collection.get_facecolors() if not len(self.facecolors): raise ValueError('Collection must have a facecolor') if len(self.facecolors) == 1: self.facecolors = np.tile(self.facecolors, (self.n_pts, 1)) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] def onselect(self, verts): try: path = Path(verts) self.ind = np.nonzero(path.contains_points(self.xys))[0] self.facecolors[:, -1] = self.alpha_other self.facecolors[self.ind, -1] = 1 self.collection.set_facecolors(self.facecolors) self.canvas.draw_idle() if self._on_select is not None: self._on_select(self.ind) except Exception: pass def disconnect(self): self.lasso.disconnect_events() self.facecolors[:, -1] = 1 self.collection.set_facecolors(self.facecolors) self.canvas.draw_idle()
def __init__(self, x, y, canvas, figure, data, xlabel, ylabel): self.canvas = canvas self.ax = figure self.ax.clear() self.collection = data self.xlabel = xlabel self.ylabel = ylabel self.xys = self.collection.get_offsets() self.x = x self.y = y self.ax.scatter(x, y, color='blue') self.ind = [] self.lasso = LassoSelector(self.ax, onselect=self.onselect)
def __init__(self, ax, collection, alpha_other=0.3): """The lasso.""" self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.fcl = collection.get_facecolors() if not self.fcl.any(): raise ValueError('Collection must have a facecolor') elif len(self.fcl) == 1: self.fcl = np.tile(self.fcl, (len(self.xys), 1)) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = []
def init_df(self, df): self.exclude = set() self.mean_line = None self.initial_df = df.set_index(['lon', 'lat']) self.df = df.reset_index().drop_duplicates( ['lon', 'lat', 'time']).set_index(['lon', 'lat']) collection = self.scatter_ax.scatter(self.df.time, self.df.temperature, 1) self.lola = lola = df.drop_duplicates( ['lon', 'lat']).reset_index().set_index(['lon', 'lat']) lola['index'] = np.arange(len(lola)) map_collection = self.map_ax.scatter(lola.index.get_level_values(0), lola.index.get_level_values(1), s=1, transform=ccrs.PlateCarree()) self.collection = collection self.map_collection = map_collection self.xys = collection.get_offsets() self.Npts = len(self.xys) self.map_xys = map_collection.get_offsets() self.map_Npts = len(self.map_xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, (self.Npts, 1)) # Ensure that we have separate colors for each object self.map_fc = map_collection.get_facecolors() if len(self.map_fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.map_fc) == 1: self.map_fc = np.tile(self.map_fc, (self.map_Npts, 1)) self.lasso = LassoSelector(self.scatter_ax, onselect=self.onselect) self.map_lasso = LassoSelector(self.map_ax, onselect=self.map_onselect) self.plot_band_mean() self.ind = [] self.map_ind = [] self.refresh_table()
def choosePolygon(self, event=None): ''' Activates matplotlib widget LassoSelector. ''' from matplotlib.widgets import LassoSelector if hasattr(self, '_cidRect'): self.disconnectRect() self.printOutput( 'Select polygon is active. Add points with leftclick. Finish with rightclick.' ) self._cidPoly = None self._cidPoly = self.ax.figure.canvas.mpl_connect( 'button_press_event', self._onpress) self._lasso = LassoSelector(self.ax, self._onselect_verts) return self._lasso
def on_selectcircle_toggled(self, button): if button.get_active(): self.set_sensitive(False, 'Ellipse selection not ready', ['new_button', 'save_button', 'saveas_button', 'open_button', 'undo_button', 'selectrectangle_button', 'selectpolygon_button', 'pixelhunting_button', 'loadexposure_expander', 'close_button', self.plot2d.toolbar, self.plot2d.settings_expander]) while self.plot2d.toolbar.mode != '': # turn off zoom, pan, etc. modes. self.plot2d.toolbar.zoom() self._selector = EllipseSelector(self.plot2d.axis, self.on_ellipse_selected, rectprops={'facecolor': 'white', 'edgecolor': 'none', 'alpha': 0.7, 'fill': True, 'zorder': 10}, button=[1, ], interactive=False, lineprops={'zorder': 10}) self._selector.state.add('square') self._selector.state.add('center') else: assert isinstance(self._selector, EllipseSelector) self._selector.set_active(False) self._selector.set_visible(False) self._selector = None self.plot2d.replot(keepzoom=False) self.set_sensitive(True)
def create_baseplot(self): self.fig = plt.figure() self.fig.suptitle("Interactive Dimension Reduction RoI Selection") self.ax1 = plt.axes([0.12, 0.2, 0.4, 0.75]) self.ax1.set_title("Embedding") self.ax1.set_xlabel("Dimension A") self.ax1.set_ylabel("Dimension B") self.ax1.set_xlim([self.ax1_xmin, self.ax1_xmax]) self.ax1.set_ylim([self.ax1_ymin, self.ax1_ymax]) self.pts = self.ax1.scatter(self.embedding[:, 0], self.embedding[:, 1], s=10, c="blue") self.ax1.set_aspect('equal') self.ax2 = plt.axes([0.55, 0.2, 0.4, 0.75]) self.ax2.axis("off") self.ax2.set_title('RoI Area:') self.ax2.imshow(self.img, vmax=1) self.lsso = LassoSelector(ax=self.ax1, onselect=self.onselect, lineprops=self.toggle_props[self.toggle]) plt.subplots_adjust(bottom=0.1) self.ax3 = plt.axes([0.25, 0.05, 0.12, 0.065]) self.resetbutton = Button(self.ax3, "Reset") self.resetbutton.on_clicked(self.reset) self.ax4 = plt.axes([0.45, 0.05, 0.12, 0.065]) self.roibutton = Button(self.ax4, "Set RoI") self.roibutton.on_clicked(self.exportroi) self.ax5 = plt.axes([0.65, 0.05, 0.22, 0.065]) self.returnbutton = Button(self.ax5, "Return and Close") self.returnbutton.on_clicked(self.return_rois)
def reset(self, event): self.lsso = LassoSelector(ax=self.ax1, onselect=self.onselect, lineprops=self.toggle_props["roi"]) self.pts.remove() self.adjust_variables() self.adjust_plots()
def close(): lasso = LassoSelector(ax1, onselect) # associated with subplot 1 plt.show() return array
def setTarget(self, event): #lassoの対象をclickから決定する if not len(event.ind): return True if not self.lassoTarget == None: #初回のclickでない場合は先に選択されていたものを元に戻す self.lassoTarget.set_alpha(self.pre_alpha) try: #あったら掃除 多分いつもある self.selectedLine.remove() except: pass self.selectedIndices = set() self.unselectedIndices = set() #plotの設定を保存 self.lassoTarget = event.artist self.pre_alpha = self.lassoTarget.get_alpha() self.pre_settings = self.getSettings(self.lassoTarget) #alphaの調整とselectedLineの描画 まだinvisible データの取得 self.lassoTarget.set_alpha(self.ALPHA_OTHER) self.selectedLine, = self.lassoTarget.axes.plot([], [], visible=False, linestyle='None', **self.pre_settings) self.lasso = LassoSelector(self.lassoTarget.axes, onselect=self.onselect) self.xys = np.array([[x, y] for x, y in zip( self.lassoTarget.get_xdata(), self.lassoTarget.get_ydata())]) self.canvas.draw()
def __init__(self, axes, roi_type): self.axes = axes self.roi_type = roi_type self.patch = None self.lasso_switch = False self.verts = None self.title = 'N/A' self.annotate = None self.intensity = 0 self.global_switch = False if self.roi_type == 'rectangle': self.roi = RectangleSelector(self.axes, self.onselect, drawtype='box', interactive=True) elif self.roi_type == 'ellipse': self.roi = EllipseSelector(self.axes, self.onselect, drawtype='box', interactive=True) else: self.roi = LassoSelector(self.axes, onselect=self.lasso_select)
def __init__(self, ax, collection, alpha_other=0.2): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = []
def draw_mask( tif_file, out_tif=None, n_masks=1, ): image = tifffile.imread(tif_file) if len(image.shape) > 2: image = find_xy_image(image) if type(out_tif) == type(None): out_tif = tif_file.replace('.tif', '_single_mask.tif') y, x = np.mgrid[:image.shape[0], :image.shape[1]] points = np.transpose((x.ravel(), y.ravel())) mask = np.zeros(image.shape, dtype='uint16') for mask_idx in range(n_masks): fig, ax = plt.subplots(figsize=(9, 9)) plot_image = image.copy() plot_image[np.where(mask)] = image.max() ax.imshow(plot_image, cmap='gray', vmax=image.mean() + 3 * image.std()) lasso = LassoSelector(ax, onselect) plt.show() plt.close() verts = np.asarray(pd.read_csv('_verts.txt', sep='\t', header=None)) path = Path(verts, closed=True) new_mask = path.contains_points(points).reshape(image.shape[0], \ image.shape[1]).astype('uint16') mask += new_mask tifffile.imsave(out_tif, mask) return mask, path
def __init__(self, directory): self.directory = directory self.sampleArray = self.directory.sampleFits.arrays self.openArray = self.directory.openFits.arrays self.im = self.sampleArray[sliderInd] self.frame = tk.Toplevel() self.fig = Figure(figsize=(7, 7)) self.ax = self.fig.add_subplot(111) self.strainButton = tk.Button(self.frame, text="do", command=self.strainMap) self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame) self.canvas.show() self.canvas.get_tk_widget().grid(row=0) self.canvas.mpl_connect('key_press_event', self.onKey) self.strainButton.grid(row=1) self.mask = np.zeros((512, 512)) self.pix = np.arange(512) self.XX, self.YY = np.meshgrid(self.pix, self.pix) self.pix = np.vstack((self.XX.flatten(), self.YY.flatten())).T self.lasso = LassoSelector(self.ax, self.onselect)
def __init__(self, ax, collection, mmc, img): self.colornormalizer = Normalize(vmin=0, vmax=1, clip=False) self.scat = plt.scatter(img[:, 0], img[:, 1], c=mmc.classvec) plt.gray() plt.setp(ax.get_yticklabels(), visible=False) ax.yaxis.set_tick_params(size=0) plt.setp(ax.get_xticklabels(), visible=False) ax.xaxis.set_tick_params(size=0) self.img = img self.canvas = ax.figure.canvas self.collection = collection #self.alpha_other = alpha_other self.mmc = mmc self.prevnewclazz = None self.xys = collection self.Npts = len(self.xys) self.lockedset = set([]) self.lasso = LassoSelector(ax, onselect=self.onselect)#, lineprops = {:'prism'}) self.lasso.disconnect_events() self.lasso.connect_event('button_press_event', self.lasso.onpress) self.lasso.connect_event('button_release_event', self.onrelease) self.lasso.connect_event('motion_notify_event', self.lasso.onmove) self.lasso.connect_event('draw_event', self.lasso.update_background) self.lasso.connect_event('key_press_event', self.onkeypressed) #self.lasso.connect_event('button_release_event', self.onrelease) self.ind = [] self.slider_axis = plt.axes(slider_coords, visible = False) self.slider_axis2 = plt.axes(obj_fun_display_coords, visible = False) self.in_selection_slider = None newws = list(set(range(len(self.collection))) - self.lockedset) self.mmc.new_working_set(newws) self.lasso.line.set_visible(False)
def reset_selection(self): """Reset lasso selection """ self.xy_compute() self.ind = [] self.selected = controller.get_view_mask(controller.slice).flatten() self.lasso = LassoSelector(self.main_ax, onselect=self.onselect)
def lasso_select(self, verts): if self.global_switch is False: del self.roi self.roi = LassoSelector(self.axes, onselect=self.lasso_select) self.axes.figure.canvas.draw() return if self.lasso_switch is True: self.patch.remove() self.verts = verts self.p = path.Path(verts, closed=True) self.patch = patches.PathPatch(self.p, facecolor=(1, 0, 0, 0.3), lw=2) self.axes.add_patch(self.patch) self.lasso_switch = True if self.annotate != None: self.annotate.remove() self.label(self.title)
def show(self): self.fig = plt.figure() ax = self.fig.add_subplot(111) ax.axis("off") lo = np.nanmin(self.xy, axis=0) hi = np.nanmax(self.xy, axis=0) center = (hi + lo) / 2 w, h = hi - lo ampl = 1.3 w *= ampl h *= ampl ax.set_xlim(center[0] - w / 2, center[0] + w / 2) ax.set_ylim(center[1] - h / 2, center[1] + h / 2) ax.imshow(self.image) ax.scatter(*self.xy.T, s=self.cfg["dotsize"]**2) ax.add_collection(self.lines) ax.invert_yaxis() self.lasso = LassoSelector(ax, onselect=self.on_select) ax_clear = self.fig.add_axes([0.85, 0.55, 0.1, 0.1]) ax_export = self.fig.add_axes([0.85, 0.45, 0.1, 0.1]) self.clear_button = Button(ax_clear, "Clear") self.clear_button.on_clicked(self.clear) self.export_button = Button(ax_export, "Export") self.export_button.on_clicked(self.export) self.fig.canvas.mpl_connect("pick_event", self.on_pick) plt.show()
def LassoSelection(img): from matplotlib.widgets import LassoSelector from matplotlib import path import matplotlib.pyplot as plt global nROI, ROI, ROI_color, points dims = img.shape nROI = 0 ROI = np.zeros((dims[0], dims[1])) ROI_color = np.zeros((dims[0], dims[1], 3)) points = np.fliplr(np.array(np.nonzero(np.ones((dims[0], dims[1])))).T) fig = plt.figure(1, figsize=(14, 7)) ax1 = plt.subplot(121) f1 = ax1.imshow(imNormalize(img, 99), cmap=plt.get_cmap('gray')) ax2 = plt.subplot(122) f2 = ax2.imshow(ROI_color, cmap=plt.get_cmap('gray')) points_poly = [] def onselectf(verts): global nROI, ROI, ROI_color, points nROI += 1 p = path.Path(verts) points_poly = np.where(p.contains_points(points, radius=1))[0] tmp = np.zeros((dims[0], dims[1])) tmp[points[points_poly, 1], points[points_poly, 0]] = 1 tmp[np.where(ROI > 0)] = 0 ROI = ROI + tmp * nROI ROI_color = ROI_color + np.tile(tmp[:, :, None], (1, 1, 3)) f2.set_data(ROI_color) fig.canvas.draw() print('ROI', nROI, 'drawn') lasso = LassoSelector(ax1, onselect=onselectf) plt.show() cnum = 0 while True: select = fig.ginput(1) if not select: break else: xy = (np.asarray(select)[0]).astype(int) if xy.min() >= 1 and xy[1] < dims[0] and xy[0] < dims[1]: cnum = 1 print('ROI selection done') return nROI, ROI
class SelectFromImage(object): """ Class used to draw the lassos on the images with two methods: - onselect: save the pixels inside the selection - disconnect: stop drawing lassos on the image Copied with permission from CoastSat (KV, 2020) https://github.com/kvos/CoastSat """ # initialize lasso selection class def __init__(self, ax, implot, color=[1, 1, 1]): self.canvas = ax.figure.canvas self.implot = implot self.array = implot.get_array() xv, yv = np.meshgrid(np.arange(self.array.shape[1]), np.arange(self.array.shape[0])) self.pix = np.vstack((xv.flatten(), yv.flatten())).T self.ind = [] self.im_bool = np.zeros((self.array.shape[0], self.array.shape[1])) self.color = color self.lasso = LassoSelector(ax, onselect=self.onselect) def onselect(self, verts): # find pixels contained in the lasso p = path.Path(verts) self.ind = p.contains_points(self.pix, radius=1) # color selected pixels array_list = [] for k in range(self.array.shape[2]): array2d = self.array[:, :, k] lin = np.arange(array2d.size) new_array2d = array2d.flatten() new_array2d[lin[self.ind]] = self.color[k] array_list.append(new_array2d.reshape(array2d.shape)) self.array = np.stack(array_list, axis=2) self.implot.set_data(self.array) self.canvas.draw_idle() # update boolean image with selected pixels vec_bool = self.im_bool.flatten() vec_bool[lin[self.ind]] = 1 self.im_bool = vec_bool.reshape(self.im_bool.shape) def disconnect(self): self.lasso.disconnect_events()
def __init__(self, ax, collection, eventids, runnum, total_hpol_delays,total_vpol_delays,alpha_other=0.3): self.canvas = ax.figure.canvas self.eventids = eventids self.runnum = runnum self.id = numpy.array(list(zip(self.runnum,self.eventids))) self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] self.total_hpol_delays = total_hpol_delays self.total_vpol_delays = total_vpol_delays
class SelectFromCollection(object): def __init__(self, ax, collection, alpha_other=0.2): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] def onselect(self, verts): path = Path(verts) self.ind = np.nonzero([path.contains_point(xy) for xy in self.xys])[0] # This is an older code that would reset the colors and the alpha values for the # selected objects #self.fc[:, -1] = self.alpha_other #self.fc[self.ind, -1] = 1 #print self.fc[self.ind] #self.collection.set_facecolors(self.fc) # However currently, we plot the points that are selected with black dots. n_points = len(self.ind) ax.scatter(outlier_z_spec, outlier_z_phot, s=30, c=outlier_snr_colors, edgecolor='None') zspec, zphot = make_into_points(self.xys[self.ind]) ax.scatter(zspec, zphot, s=5, color='black') # And now we plot the inset. plot_point_properties(self.xys[self.ind]) self.canvas.draw_idle() def disconnect(self): self.lasso.disconnect_events() self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle()
def create_lassos(): lassos = matts_admin_functions.create_empty_list(number_of_planes) lasso_functions = create_lasso_functions() for plane in range(number_of_planes): axis = main.region_figures[plane].get_axes() lassos[plane] = LassoSelector(axis[0], lasso_functions[plane]) return lassos
def __init__(self, fig, mmc, img, collection, windowsize = 0): #Initialize the main axis ax = fig.add_axes([0.1,0.1,0.8,0.8]) ax.set_yticklabels([]) ax.yaxis.set_tick_params(size = 0) ax.set_xticklabels([]) ax.xaxis.set_tick_params(size = 0) self.imdata = ax.imshow(img) #Initialize LassoSelector on the main axis self.lasso = LassoSelector(ax, onselect = self.onselect) self.lasso.connect_event('key_press_event', self.onkeypressed) self.lasso.line.set_visible(False) self.mmc = mmc self.img = img self.img_orig = img.copy() self.collection = collection self.selectedset = set([]) self.lockedset = set([]) self.windowsize = windowsize #Initialize the fraction slider self.slider_axis = fig.add_axes([0.2, 0.06, 0.6, 0.02]) self.in_selection_slider = Slider(self.slider_axis, 'Fraction slider', 0., 1, valinit = len(np.nonzero(self.mmc.classvec_ws)[0]) / len(mmc.working_set)) def sliderupdate(val): val = int(val * len(mmc.working_set)) nonzeroc = len(np.nonzero(self.mmc.classvec_ws)[0]) if val > nonzeroc: claims = val - nonzeroc newclazz = 1 elif val < nonzeroc: claims = nonzeroc - val newclazz = 0 else: return print('Claimed', claims, 'points for class', newclazz) self.claims = claims mmc.claim_n_points(claims, newclazz) self.redrawall() self.in_selection_slider.on_changed(sliderupdate) #Initialize the display for the RLS objective funtion self.objfun_display_axis = fig.add_axes([0.1, 0.96, 0.8, 0.02]) self.objfun_display_axis.imshow(mmc.compute_steepness_vector()[np.newaxis, :], cmap = plt.get_cmap("Oranges")) self.objfun_display_axis.set_aspect('auto') self.objfun_display_axis.set_yticklabels([]) self.objfun_display_axis.yaxis.set_tick_params(size = 0)
def __init__(self, ax, collection, alpha_other=0.3): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = []
def __init__(self, ax, collection, color_other="k", onselection=None): self.canvas = ax.figure.canvas self.collection = collection self.color_other = colorConverter.to_rgba(color_other) self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError("Collection must have a facecolor") elif len(self.fc) == 1: self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1) self.sfc = self.fc.copy() self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] self.onselection = onselection
def on_selectpolygon_toggled(self, button): if button.get_active(): self.set_sensitive(False, 'Polygon selection not ready', ['new_button', 'save_button', 'saveas_button', 'open_button', 'undo_button', 'selectrectangle_button', 'selectcircle_button', 'pixelhunting_button', 'loadexposure_expander', 'close_button', self.plot2d.toolbar, self.plot2d.settings_expander]) while self.plot2d.toolbar.mode != '': # turn off zoom, pan, etc. modes. self.plot2d.toolbar.zoom() self._selector = LassoSelector(self.plot2d.axis, self.on_polygon_selected, lineprops={'color': 'white', 'zorder': 10}, button=[1, ], ) else: self._selector.set_active(False) self._selector.set_visible(False) self._selector = None self.plot2d.replot(keepzoom=False) self.set_sensitive(True)
def __init__(self, ax, collection,selected_color=(0,0,1,1),unselected_color=(1,0,0,1)): self.canvas = ax.figure.canvas self.collection = collection self.unselected_color = unselected_color self.selected_color = selected_color self.shift_is_held = False self.xys = collection.get_offsets() self.Npts = len(self.xys) self.canvas.mpl_connect('key_press_event', self.on_key_press) self.canvas.mpl_connect('key_release_event', self.on_key_release) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1) lineprops = dict(color='black', linestyle='-',linewidth = 2, alpha=1) self.lasso = LassoSelector(ax, onselect=self.onselect,lineprops=lineprops) self.ind = []
class MaskEditor(ToolWindow, DoubleFileChooserDialog): def __init__(self, *args, **kwargs): self.mask = None self._undo_stack = [] self._im = None self._selector = None self._cursor = None self.exposureloader = None self.plot2d = None ToolWindow.__init__(self, *args, **kwargs) DoubleFileChooserDialog.__init__( self, self.widget, 'Open mask file...', 'Save mask file...', [('Mask files', '*.mat'), ('All files', '*')], self.instrument.config['path']['directories']['mask'], os.path.abspath(self.instrument.config['path']['directories']['mask']), ) def init_gui(self, *args, **kwargs): self.exposureloader = ExposureLoader(self.instrument) self.builder.get_object('loadexposure_expander').add(self.exposureloader) self.exposureloader.connect('open', self.on_loadexposure) self.plot2d = PlotImageWidget() self.builder.get_object('plotbox').pack_start(self.plot2d.widget, True, True, 0) self.builder.get_object('toolbar').set_sensitive(False) def on_loadexposure(self, exposureloader: ExposureLoader, im: Exposure): if self.mask is None: self.mask = im.mask self._im = im self.plot2d.set_image(im.intensity) self.plot2d.set_mask(self.mask) self.builder.get_object('toolbar').set_sensitive(True) def on_new(self, button): if self._im is None or self.mask is None: return False self.mask = np.ones_like(self.mask) self.plot2d.set_mask(self.mask) self.set_last_filename(None) def on_open(self, button): filename = self.get_open_filename() if filename is not None: mask = loadmat(filename) self.mask = mask[[k for k in mask.keys() if not k.startswith('__')][0]] self.plot2d.set_mask(self.mask) def on_save(self, button): filename = self.get_last_filename() if filename is None: return self.on_saveas(button) maskname = os.path.splitext(os.path.split(filename)[1])[0] savemat(filename, {maskname: self.mask}) def on_saveas(self, button): filename = self.get_save_filename(None) if filename is not None: self.on_save(button) def suggest_filename(self): return 'mask_dist_{0.year:d}{0.month:02d}{0.day:02d}.mat'.format(datetime.date.today()) def on_selectcircle_toggled(self, button): if button.get_active(): self.set_sensitive(False, 'Ellipse selection not ready', ['new_button', 'save_button', 'saveas_button', 'open_button', 'undo_button', 'selectrectangle_button', 'selectpolygon_button', 'pixelhunting_button', 'loadexposure_expander', 'close_button', self.plot2d.toolbar, self.plot2d.settings_expander]) while self.plot2d.toolbar.mode != '': # turn off zoom, pan, etc. modes. self.plot2d.toolbar.zoom() self._selector = EllipseSelector(self.plot2d.axis, self.on_ellipse_selected, rectprops={'facecolor': 'white', 'edgecolor': 'none', 'alpha': 0.7, 'fill': True, 'zorder': 10}, button=[1, ], interactive=False, lineprops={'zorder': 10}) self._selector.state.add('square') self._selector.state.add('center') else: assert isinstance(self._selector, EllipseSelector) self._selector.set_active(False) self._selector.set_visible(False) self._selector = None self.plot2d.replot(keepzoom=False) self.set_sensitive(True) def on_ellipse_selected(self, pos1, pos2): # pos1 and pos2 are mouse button press and release events, with xdata and ydata carrying # the two opposite corners of the bounding box of the circle. These are NOT the exact # button presses and releases! row = np.arange(self.mask.shape[0])[:, np.newaxis] column = np.arange(self.mask.shape[1])[np.newaxis, :] row0 = 0.5 * (pos1.ydata + pos2.ydata) col0 = 0.5 * (pos1.xdata + pos2.xdata) r2 = ((pos2.xdata - pos1.xdata) ** 2 + (pos2.ydata - pos1.ydata) ** 2) / 8 tobemasked = (row - row0) ** 2 + (column - col0) ** 2 <= r2 self._undo_stack.append(self.mask) if self.builder.get_object('mask_button').get_active(): self.mask &= ~tobemasked elif self.builder.get_object('unmask_button').get_active(): self.mask |= tobemasked elif self.builder.get_object('invertmask_button').get_active(): self.mask[tobemasked] = ~self.mask[tobemasked] else: pass self.builder.get_object('selectcircle_button').set_active(False) self.plot2d.set_mask(self.mask) def on_selectrectangle_toggled(self, button): if button.get_active(): self.set_sensitive(False, 'Rectangle selection not ready', ['new_button', 'save_button', 'saveas_button', 'open_button', 'undo_button', 'selectcircle_button', 'selectpolygon_button', 'pixelhunting_button', 'loadexposure_expander', 'close_button', self.plot2d.toolbar, self.plot2d.settings_expander]) while self.plot2d.toolbar.mode != '': # turn off zoom, pan, etc. modes. self.plot2d.toolbar.zoom() self._selector = RectangleSelector(self.plot2d.axis, self.on_rectangle_selected, rectprops={'facecolor': 'white', 'edgecolor': 'none', 'alpha': 0.7, 'fill': True, 'zorder': 10}, button=[1, ], interactive=False, lineprops={'zorder': 10}) else: self._selector.set_active(False) self._selector.set_visible(False) self._selector = None self.plot2d.replot(keepzoom=False) self.set_sensitive(True) def on_rectangle_selected(self, pos1, pos2): # pos1 and pos2 are mouse button press and release events, with xdata and ydata # carrying the two opposite corners of the bounding box of the rectangle. These # are NOT the exact button presses and releases! row = np.arange(self.mask.shape[0])[:, np.newaxis] column = np.arange(self.mask.shape[1])[np.newaxis, :] tobemasked = ((row >= min(pos1.ydata, pos2.ydata)) & (row <= max(pos1.ydata, pos2.ydata)) & (column >= min(pos1.xdata, pos2.xdata)) & (column <= max(pos1.xdata, pos2.xdata))) self._undo_stack.append(self.mask) if self.builder.get_object('mask_button').get_active(): self.mask = self.mask & (~tobemasked) elif self.builder.get_object('unmask_button').get_active(): self.mask = self.mask | tobemasked elif self.builder.get_object('invertmask_button').get_active(): self.mask[tobemasked] = ~self.mask[tobemasked] else: pass self.builder.get_object('selectrectangle_button').set_active(False) self.plot2d.set_mask(self.mask) def on_selectpolygon_toggled(self, button): if button.get_active(): self.set_sensitive(False, 'Polygon selection not ready', ['new_button', 'save_button', 'saveas_button', 'open_button', 'undo_button', 'selectrectangle_button', 'selectcircle_button', 'pixelhunting_button', 'loadexposure_expander', 'close_button', self.plot2d.toolbar, self.plot2d.settings_expander]) while self.plot2d.toolbar.mode != '': # turn off zoom, pan, etc. modes. self.plot2d.toolbar.zoom() self._selector = LassoSelector(self.plot2d.axis, self.on_polygon_selected, lineprops={'color': 'white', 'zorder': 10}, button=[1, ], ) else: self._selector.set_active(False) self._selector.set_visible(False) self._selector = None self.plot2d.replot(keepzoom=False) self.set_sensitive(True) def on_polygon_selected(self, vertices): path = Path(vertices) col, row = np.meshgrid(np.arange(self.mask.shape[1]), np.arange(self.mask.shape[0])) points = np.vstack((col.flatten(), row.flatten())).T tobemasked = path.contains_points(points).reshape(self.mask.shape) self._undo_stack.append(self.mask) if self.builder.get_object('mask_button').get_active(): self.mask = self.mask & (~tobemasked) elif self.builder.get_object('unmask_button').get_active(): self.mask = self.mask | tobemasked elif self.builder.get_object('invertmask_button').get_active(): self.mask[tobemasked] = ~self.mask[tobemasked] else: pass self.plot2d.set_mask(self.mask) self.builder.get_object('selectpolygon_button').set_active(False) def on_mask_toggled(self, button): pass def on_unmask_toggled(self, button): pass def on_invertmask_toggled(self, button): pass def on_pixelhunting_toggled(self, button): if button.get_active(): self._cursor = Cursor(self.plot2d.axis, useblit=False, color='white', lw=1) self._cursor.connect_event('button_press_event', self.on_cursorclick) while self.plot2d.toolbar.mode != '': # turn off zoom, pan, etc. modes. self.plot2d.toolbar.zoom() else: self._cursor.disconnect_events() self._cursor = None self._undo_stack.append(self.mask) self.plot2d.replot(keepzoom=False) def on_cursorclick(self, event): if (event.inaxes == self.plot2d.axis) and (self.plot2d.toolbar.mode == ''): self.mask[round(event.ydata), round(event.xdata)] ^= True self._cursor.disconnect_events() self._cursor = None self.plot2d.replot(keepzoom=True) self.on_pixelhunting_toggled(self.builder.get_object('pixelhunting_button')) def cleanup(self): super().cleanup() self._undo_stack = [] def on_undo(self, button): try: self.mask = self._undo_stack.pop() except IndexError: return self.plot2d.set_mask(self.mask)
class SelectFromCollection(object): def __init__(self, ax, collection, mmc, img): self.colornormalizer = Normalize(vmin=0, vmax=1, clip=False) self.scat = plt.scatter(img[:, 0], img[:, 1], c=mmc.classvec) plt.gray() plt.setp(ax.get_yticklabels(), visible=False) ax.yaxis.set_tick_params(size=0) plt.setp(ax.get_xticklabels(), visible=False) ax.xaxis.set_tick_params(size=0) self.img = img self.canvas = ax.figure.canvas self.collection = collection #self.alpha_other = alpha_other self.mmc = mmc self.prevnewclazz = None self.xys = collection self.Npts = len(self.xys) self.lockedset = set([]) self.lasso = LassoSelector(ax, onselect=self.onselect)#, lineprops = {:'prism'}) self.lasso.disconnect_events() self.lasso.connect_event('button_press_event', self.lasso.onpress) self.lasso.connect_event('button_release_event', self.onrelease) self.lasso.connect_event('motion_notify_event', self.lasso.onmove) self.lasso.connect_event('draw_event', self.lasso.update_background) self.lasso.connect_event('key_press_event', self.onkeypressed) #self.lasso.connect_event('button_release_event', self.onrelease) self.ind = [] self.slider_axis = plt.axes(slider_coords, visible = False) self.slider_axis2 = plt.axes(obj_fun_display_coords, visible = False) self.in_selection_slider = None newws = list(set(range(len(self.collection))) - self.lockedset) self.mmc.new_working_set(newws) self.lasso.line.set_visible(False) def onselect(self, verts): self.path = Path(verts) self.ind = np.nonzero(self.path.contains_points(self.xys))[0] print 'Selected '+str(len(self.ind))+' points' newws = list(set(self.ind) - self.lockedset) self.mmc.new_working_set(newws) self.redrawall() def onpress(self, event): if self.lasso.ignore(event) or event.inaxes != self.ax: return self.lasso.line.set_data([[], []]) self.lasso.verts = [(event.xdata, event.ydata)] self.lasso.line.set_visible(True) def onrelease(self, event): if self.lasso.ignore(event): return if self.lasso.verts is not None: if event.inaxes == self.lasso.ax: self.lasso.verts.append((event.xdata, event.ydata)) self.lasso.onselect(self.lasso.verts) self.lasso.verts = None def onkeypressed(self, event): print 'You pressed', event.key if event.key == '1': print 'Assigned all selected points to class 1' newclazz = 1 mmc.claim_all_points_in_working_set(newclazz) if event.key == '0': print 'Assigned all selected points to class 0' newclazz = 0 mmc.claim_all_points_in_working_set(newclazz) if event.key == 'a': print 'Selected all points' newws = list(set(range(len(self.collection))) - self.lockedset) self.mmc.new_working_set(newws) self.lasso.line.set_visible(False) if event.key == 'c': changecount = mmc.cyclic_descent_in_working_set() print 'Performed ', changecount, 'cyclic descent steps' if event.key == 'l': print 'Locked the class labels of selected points' self.lockedset = self.lockedset | set(self.ind) newws = list(set(self.ind) - self.lockedset) self.mmc.new_working_set(newws) #print newws if event.key == 'u': print 'Unlocked the selected points' self.lockedset = self.lockedset - set(self.ind) newws = list(set(self.ind) - self.lockedset) self.mmc.new_working_set(newws) self.redrawall() def redrawall(self, newslider = True): if newslider: nozeros = np.nonzero(self.mmc.classvec_ws)[0] self.slider_axis.cla() del self.slider_axis del self.slider_axis2 self.slider_axis = plt.axes(slider_coords) self.slider_axis2 = plt.axes(obj_fun_display_coords) steepness_vector = mmc.compute_steepness_vector() X = [steepness_vector, steepness_vector] #right = left+width #self.slider_axis2.imshow(X, interpolation='bicubic', cmap=plt.get_cmap("Oranges"), alpha=1) self.slider_axis2.imshow(X, cmap=plt.get_cmap("Oranges")) self.slider_axis2.set_aspect('auto') plt.setp(self.slider_axis2.get_yticklabels(), visible=False) self.slider_axis2.yaxis.set_tick_params(size=0) del self.in_selection_slider self.in_selection_slider = None self.in_selection_slider = Slider(self.slider_axis, 'Fraction slider', 0., len(mmc.working_set), valinit=len(nozeros)) def sliderupdate(val): val = int(val) nonzeroc = len(np.nonzero(self.mmc.classvec_ws)[0]) if val > nonzeroc: claims = val - nonzeroc newclazz = 1 elif val < nonzeroc: claims = nonzeroc - val newclazz = 0 else: return print 'Claimed', claims, 'points for class', newclazz #val, nonzeroc, claims self.claims = claims mmc.claim_n_points(claims, newclazz) steepness_vector = mmc.compute_steepness_vector() X = [steepness_vector, steepness_vector] self.slider_axis2.imshow(X, cmap=plt.get_cmap("Oranges")) self.slider_axis2.set_aspect('auto') self.redrawall(newslider = False) #HACK! self.prevnewclazz = newclazz self.in_selection_slider.on_changed(sliderupdate) oneclazz = np.nonzero(self.mmc.classvec)[0] col_row = self.collection[oneclazz] rowcs, colcs = col_row[:, 1], col_row[:, 0] #self.img[rowcs, colcs, :] = 0 #self.img[rowcs, colcs, 0] = 255 zeroclazz = np.nonzero(self.mmc.classvec - 1)[0] col_row = self.collection[zeroclazz] rowcs, colcs = col_row[:, 1], col_row[:, 0] #self.img[rowcs, colcs, :] = img_orig[rowcs, colcs, :] #self.imdata.set_data(self.img) scatcolors = self.scat.get_facecolors() scatcolors[:,0] = mmc.classvec scatcolors[:,1] = mmc.classvec scatcolors[:,2] = mmc.classvec self.scat.set_facecolors(scatcolors) if self.lasso.useblit: self.lasso.canvas.restore_region(self.lasso.background) self.lasso.ax.draw_artist(self.lasso.line) self.lasso.canvas.blit(self.lasso.ax.bbox) else: self.lasso.canvas.draw_idle() plt.draw() print_instructions() def disconnect(self): self.lasso.disconnect_events() self.canvas.draw_idle()
class CollectionSelector(object): """Select indices from a matplotlib collection using `LassoSelector`. Selected indices are saved in the `ind` attribute. This tool highlights selected points by fading them out (i.e., reducing their alpha values). If your collection has alpha < 1, this tool will permanently alter them. Note that this tool selects collection objects based on their *origins* (i.e., `offsets`). Parameters ---------- ax : :class:`~matplotlib.axes.Axes` Axes to interact with. collection : :class:`matplotlib.collections.Collection` subclass Collection you want to select from. alpha_other : 0 <= float <= 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to `alpha_other`. """ def __init__(self, ax, collection, color_other="k", onselection=None): self.canvas = ax.figure.canvas self.collection = collection self.color_other = colorConverter.to_rgba(color_other) self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError("Collection must have a facecolor") elif len(self.fc) == 1: self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1) self.sfc = self.fc.copy() self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] self.onselection = onselection def updateselection(self): self.sfc[:, :] = self.fc[:, :] if len(self.ind) > 0: self.sfc[self.ind, :] = self.color_other self.collection.set_facecolors(self.sfc) self.canvas.draw_idle() def selectall(self): self.ind = range(self.Npts) self.updateselection() def reset(self): self.ind = [] self.updateselection() def onselect(self, verts): path = Path(verts) self.ind = list(np.nonzero([path.contains_point(xy) for xy in self.xys])[0]) self.updateselection() if self.onselection is not None: self.onselection(self.ind) def disconnect(self): self.lasso.disconnect_events() # self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle()
class SelectFromCollection(object): """Interactive RLS classifier interface for image segmentation Parameters ---------- fig : matplotlib.figure.Figure The Figure object on which the interface is drawn. mmc : rlscore.learner.interactive_rls_classifier.InteractiveRlsClassifier Interactive RLS classifier object img : numpy.array Array consisting of image data collection : numpy.array, shape = [n_pixels, 2] array consisting of the (x,y) coordinates of all usable pixels in the image windowsize : int Determines the size of a window around grid points (2 * windowsize + 1) """ def __init__(self, fig, mmc, img, collection, windowsize = 0): #Initialize the main axis ax = fig.add_axes([0.1,0.1,0.8,0.8]) ax.set_yticklabels([]) ax.yaxis.set_tick_params(size = 0) ax.set_xticklabels([]) ax.xaxis.set_tick_params(size = 0) self.imdata = ax.imshow(img) #Initialize LassoSelector on the main axis self.lasso = LassoSelector(ax, onselect = self.onselect) self.lasso.connect_event('key_press_event', self.onkeypressed) self.lasso.line.set_visible(False) self.mmc = mmc self.img = img self.img_orig = img.copy() self.collection = collection self.selectedset = set([]) self.lockedset = set([]) self.windowsize = windowsize #Initialize the fraction slider self.slider_axis = fig.add_axes([0.2, 0.06, 0.6, 0.02]) self.in_selection_slider = Slider(self.slider_axis, 'Fraction slider', 0., 1, valinit = len(np.nonzero(self.mmc.classvec_ws)[0]) / len(mmc.working_set)) def sliderupdate(val): val = int(val * len(mmc.working_set)) nonzeroc = len(np.nonzero(self.mmc.classvec_ws)[0]) if val > nonzeroc: claims = val - nonzeroc newclazz = 1 elif val < nonzeroc: claims = nonzeroc - val newclazz = 0 else: return print('Claimed', claims, 'points for class', newclazz) self.claims = claims mmc.claim_n_points(claims, newclazz) self.redrawall() self.in_selection_slider.on_changed(sliderupdate) #Initialize the display for the RLS objective funtion self.objfun_display_axis = fig.add_axes([0.1, 0.96, 0.8, 0.02]) self.objfun_display_axis.imshow(mmc.compute_steepness_vector()[np.newaxis, :], cmap = plt.get_cmap("Oranges")) self.objfun_display_axis.set_aspect('auto') self.objfun_display_axis.set_yticklabels([]) self.objfun_display_axis.yaxis.set_tick_params(size = 0) def onselect(self, verts): #Select a new working set self.path = Path(verts) self.selectedset = set(np.nonzero(self.path.contains_points(self.collection))[0]) print('Selected ' + str(len(self.selectedset)) + ' points') newws = list(self.selectedset - self.lockedset) self.mmc.new_working_set(newws) self.redrawall() def onkeypressed(self, event): print('You pressed', event.key) if event.key == '1': print('Assigned all selected points to class 1') newclazz = 1 mmc.claim_all_points_in_working_set(newclazz) if event.key == '0': print('Assigned all selected points to class 0') newclazz = 0 mmc.claim_all_points_in_working_set(newclazz) if event.key == 'a': print('Selected all points') newws = list(set(range(len(self.collection))) - self.lockedset) self.mmc.new_working_set(newws) self.lasso.line.set_visible(False) if event.key == 'c': changecount = mmc.cyclic_descent_in_working_set() print('Performed ', changecount, 'cyclic descent steps') if event.key == 'l': print('Locked the class labels of selected points') self.lockedset = self.lockedset | self.selectedset newws = list(self.selectedset - self.lockedset) self.mmc.new_working_set(newws) if event.key == 'u': print('Unlocked the selected points') self.lockedset = self.lockedset - self.selectedset newws = list(self.selectedset - self.lockedset) self.mmc.new_working_set(newws) if event.key == 'p': print('Compute predictions and AUC on data') preds = self.mmc.predict(Xmat) print(auc(mmc.Y[:, 0], preds[:, 0])) self.redrawall() def redrawall(self): #Color all class one labeled pixels red oneclazz = np.nonzero(self.mmc.classvec)[0] col_row = self.collection[oneclazz] rowcs, colcs = col_row[:, 1], col_row[:, 0] red = np.array([255, 0, 0]) for i in range(-self.windowsize, self.windowsize + 1): for j in range(-self.windowsize, self.windowsize + 1): self.img[rowcs+i, colcs+j, :] = red #Return the original color of the class zero labeled pixels zeroclazz = np.nonzero(self.mmc.classvec - 1)[0] col_row = self.collection[zeroclazz] rowcs, colcs = col_row[:, 1], col_row[:, 0] for i in range(-self.windowsize, self.windowsize + 1): for j in range(-self.windowsize, self.windowsize + 1): self.img[rowcs+i, colcs+j, :] = self.img_orig[rowcs+i, colcs+j, :] self.imdata.set_data(self.img) #Update the slider position according to labeling of the current working set sliderval = 0 if len(mmc.working_set) > 0: sliderval = len(np.nonzero(self.mmc.classvec_ws)[0]) / len(mmc.working_set) self.in_selection_slider.set_val(sliderval) #Update the RLS objective function display self.objfun_display_axis.imshow(mmc.compute_steepness_vector()[np.newaxis, :], cmap=plt.get_cmap("Oranges")) self.objfun_display_axis.set_aspect('auto') #Final stuff self.lasso.canvas.draw_idle() plt.draw() print_instructions()
kp_y = [kp[1] for kp in kp_coord[showside]] fig, ax = plt.subplots(figsize = (12, 12)) fig.suptitle('calibration: %s' % showside) fig.canvas.manager.set_window_title('Press any key to finish mask selection') ax.imshow( calib[showside], cmap = mpl.cm.gray, zorder = 1) # ax.plot(kp_x, kp_y, 'ro', mfc = 'None', mec = 'red', ms = 20, zorder = 10) # plt.grid(True) # plt.xlim(xmin = 0) #, xmax = 325) # plt.ylim(ymax = 0) #, ymax = 375) lasso = LassoSelector(ax = ax, onselect = onselect, useblit = True, lineprops = dict(color = 'yellow', linewidth = 7, linestyle = 'dashed', marker = 'None')) print "Press any key to finish mask selection" while True: buttonpressed = plt.waitforbuttonpress(timeout = -1) if buttonpressed: break lasso.disconnect_events() fig.canvas.manager.set_window_title('Mask selection DONE') plt.show() # <codecell> %%script python
class SelectFromCollection(object): """Select indices from a matplotlib collection using `LassoSelector`. Selected indices are saved in the `ind` attribute. This tool highlights selected points by fading them out (i.e., reducing their alpha values). If your collection has alpha < 1, this tool will permanently alter them. Note that this tool selects collection objects based on their *origins* (i.e., `offsets`). Parameters ---------- ax : :class:`~matplotlib.axes.Axes` Axes to interact with. collection : :class:`matplotlib.collections.Collection` subclass Collection you want to select from. alpha_other : 0 <= float <= 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to `alpha_other`. """ def __init__(self, ax, collection,selected_color=(0,0,1,1),unselected_color=(1,0,0,1)): self.canvas = ax.figure.canvas self.collection = collection self.unselected_color = unselected_color self.selected_color = selected_color self.shift_is_held = False self.xys = collection.get_offsets() self.Npts = len(self.xys) self.canvas.mpl_connect('key_press_event', self.on_key_press) self.canvas.mpl_connect('key_release_event', self.on_key_release) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1) lineprops = dict(color='black', linestyle='-',linewidth = 2, alpha=1) self.lasso = LassoSelector(ax, onselect=self.onselect,lineprops=lineprops) self.ind = [] def on_key_press(self, event): if event.key == 'shift': self.shift_is_held = True def on_key_release(self, event): if event.key == 'shift': self.shift_is_held = False def onselect(self, verts): path = Path(verts) old_ind = self.ind self.ind = np.nonzero([path.contains_point(xy) for xy in self.xys])[0] if self.shift_is_held: self.ind = np.unique(np.append(self.ind, old_ind)) self.fc[:, :] = self.unselected_color self.fc[self.ind, :] = self.selected_color self.collection.set_facecolors(self.fc) self.canvas.draw_idle() def disconnect(self): self.lasso.disconnect_events() self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle()