class PeakFinder(object): def __init__(self, ax, canvas): self.rectProps = dict(facecolor='red', edgecolor = 'white', alpha=0.5, fill=True) self.indicatorProps = dict(facecolor='white', edgecolor='black', alpha=0.5, fill=True) self.__selector = RectangleSelector(ax, self.onSelect, drawtype='box', rectprops=self.rectProps) self.__axes = ax self.__canvas = canvas def onSelect(self, epress, erelease): start = map(int, (epress.xdata, epress.ydata)) stop = map(int, (erelease.xdata, erelease.ydata)) ################### ax = self.__axes dataMatrix = ax.get_axes().get_images()[0].get_array() clipMatrix = dataMatrix[start[1]:(stop[1]+1), start[0]:(stop[0]+1)] peakPos = nonzero(clipMatrix == clipMatrix.max()) peakPos = (peakPos[1][0] + start[0], peakPos[0][0] + start[1]) print peakPos circle = Circle(peakPos, 4, **self.indicatorProps) ax.add_patch(circle) self.__canvas.show() ################### def activate(self): self.__selector.set_active(True) def deactivate(self): self.__selector.set_active(False) @property def isActivate(self): return self.__selector.active
def __init__(self, ax, on_move=None, on_release=None, on_enter=None, maxdist=10, rect_props=None): CanvasToolBase.__init__(self, ax, on_move=on_move, on_enter=on_enter, on_release=on_release) props = dict(edgecolor=None, facecolor="r", alpha=0.15) props.update(rect_props if rect_props is not None else {}) if props["edgecolor"] is None: props["edgecolor"] = props["facecolor"] RectangleSelector.__init__(self, ax, lambda *args: None, rectprops=props, useblit=self.useblit) # Alias rectangle attribute, which is initialized in RectangleSelector. self._rect = self.to_draw self._rect.set_animated(True) self.maxdist = maxdist self.active_handle = None self._extents_on_press = None if on_enter is None: def on_enter(extents): print("(xmin=%.3g, xmax=%.3g, ymin=%.3g, ymax=%.3g)" % extents) self.callback_on_enter = on_enter props = dict(mec=props["edgecolor"]) self._corner_order = ["NW", "NE", "SE", "SW"] xc, yc = self.corners self._corner_handles = ToolHandles(ax, xc, yc, marker_props=props) self._edge_order = ["W", "N", "E", "S"] xe, ye = self.edge_centers self._edge_handles = ToolHandles(ax, xe, ye, marker="s", marker_props=props) self._artists = [self._rect, self._corner_handles.artist, self._edge_handles.artist]
class SeriesWidget(MplWidget): def __init__(self, parent=None): MplWidget.__init__(self, parent) def draw(self): (self.coord, series, title, xlabel, ylabel, showLegend) = self.inputPorts colors = pylab.cm.jet(np.linspace(0,1, series.values.shape[0])) pylab.clf() pylab.title(title) ll = pylab.plot(series.values.T, linewidth=1) for pos, _ids in enumerate(series.ids): ll[pos].set_color(colors[pos]) if _ids in self.selectedIds: ll[pos].set_linewidth(3) pylab.xlabel(xlabel) pylab.ylabel(ylabel) if showLegend: pylab.legend(pylab.gca().get_lines(), series.labels, numpoints=1, prop=dict(size='small'), loc='upper right') 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 updateSelection(self, selectedIds): self.selectedIds = selectedIds self.updateContents(); def onselect(self, eclick, erelease): pass
def __init__(self, lines, drawtype='box', minspanx=None, minspany=None, useblit=False, lineprops=None, rectprops=None, spancoords='data', button=None, maxdist=10, marker_props=None, interactive=False, state_modifier_keys=None): self.verbose = True self.lines = flatten(lines) ax = self.lines[0].axes RectangleSelector.__init__( self, ax, self.select_lines, drawtype, minspanx, minspany, useblit, lineprops, rectprops, spancoords, button, maxdist, marker_props, interactive, state_modifier_keys) hprops = dict(linewidth=10, alpha=0.5, linestyle='-') # marker='s' self.selection = [ np.zeros(l.get_xdata().shape, bool) for l in self.lines ] #Create Line2D for highlighting selected sections self.highlighted = [] for line in self.lines: hline, = ax.plot([], [], color=line.get_color(), **hprops) self.highlighted.append( hline ) self.artists.append( hline ) #enable blitting for the highlighted segments
def __init__( self, ax, onselect, button=None, minspanx=None, minspany=None, useblit=True, lineprops=None, rectprops=dict(facecolor="red", edgecolor="black", alpha=0.5, fill=True), proxy=5, ): RectangleSelector.__init__( self, ax=ax, onselect=onselect, drawtype="box", spancoords="data", minspanx=minspanx, minspany=minspany, useblit=useblit, lineprops=lineprops, rectprops=rectprops, button=button, ) self.fixedSize = None self.prevEvents = None self.proxy = max( self.ax.transData.transform_point((proxy / 100, proxy / 100)) - self.ax.transData.transform_point((0, 0)) )
def _press(self, event): if event.button == 1: pass if event.button == 2: self.restart() self.canvas.draw() #TODO: blit return RectangleSelector._press(self, event)
def on_mouse_press(self, event): if event.button != 1 or not self.ax.in_axes(event): return self._set_active_handle(event) if self.active_handle is None: # Clear previous rectangle before drawing new rectangle. self.set_visible(False) self.redraw() self.set_visible(True) RectangleSelector.press(self, event)
def onmove(self, ev): if self.eventpress is None or self.ignore(ev): return if self.fixedSize and self.prevEvents: # Panning mode. Modify the existing ROI. Do the shift. ev.xdata += self.wdata ev.ydata += self.hdata self.eventpress.xdata = ev.xdata - 2 * self.wdata self.eventpress.ydata = ev.ydata - 2 * self.hdata RectangleSelector.onmove(self, ev)
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, 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 = RectangleSelector(ax, onselect=self.onselect) # Sprememba glede na originalno kodo self.ind = [] def onselect(self, verts): path = Path(verts) self.ind = np.nonzero([path.contains_point(xy) for xy in 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 on_mouse_release(self, event): if event.button != 1: return if not self.ax.in_axes(event): self.eventpress = None return RectangleSelector.release(self, event) self._extents_on_press = None # Undo hiding of rectangle and redraw. self.set_visible(True) self.redraw() self.callback_on_release(self.geometry)
def press(self, ev): if self.ignore(ev): return h = self.close_to_handles(ev) if not self.fixedSize and self.prevEvents and h: # Not fixed size and active roi. # Clicked on the corner -> modify mode x, y = self.opposite_corner(h) self.to_draw.set_visible(self.visible) self.eventpress = ev self.eventpress.xdata = x self.eventpress.ydata = y return False else: RectangleSelector.press(self, ev)
def release(self, ev): if self.eventpress is None or self.ignore(ev): return if self.fixedSize and self.prevEvents: # Panning mode. Modify the existing ROI. Do the shift. ev.xdata += self.wdata ev.ydata += self.hdata self.eventpress.xdata = ev.xdata - 2 * self.wdata self.eventpress.ydata = ev.ydata - 2 * self.hdata self.prevEvents = (self.eventpress, ev) pe, re = self.prevEvents self.wdata = (pe.xdata - re.xdata) / 2 self.hdata = (pe.ydata - re.ydata) / 2 RectangleSelector.release(self, ev)
def __init__(self, ax, canvas): self.rectProps = dict(facecolor='red', edgecolor = 'white', alpha=0.5, fill=True) self.indicatorProps = dict(facecolor='white', edgecolor='black', alpha=0.5, fill=True) self.__selector = RectangleSelector(ax, self.onSelect, drawtype='box', rectprops=self.rectProps) self.__axes = ax self.__canvas = canvas
def __init__(self,artist): self.artist = artist self.selector = RectangleSelector(self.artist.axes,self.on_select, button=3, minspanx=5, minspany=5, spancoords='pixels', rectprops = dict(facecolor='red', edgecolor = 'red', alpha=0.3, fill=True)) self.coords = []
def init_plot(self, new): y, x = self.model.get_image_shape() if new: self.figure = Figure(figsize=(x*2/72.0, y*2/72.0), dpi=72) self.canvas = FigureCanvasWxAgg(self.scroll, -1, self.figure) self.canvas.SetBackgroundColour('grey') self.axes = self.figure.add_axes([0.0, 0.0, 1.0, 1.0]) self.axes.set_axis_off() self.axes.imshow(self.model.get_image(), aspect='auto') # aspect='auto' sets image aspect to match the size of axes self.axes.set_autoscale_on(False) # do not apply autoscaling on plot commands - VERY IMPORTANT! self.mpl_bindings() y, = self.scroll.GetSizeTuple()[-1:] iHt, = self.model.get_image_shape()[:-1] self.aspect = (float(y)/float(iHt)) self.controller.resize_image() # Set the RectangleSelector so that the user can drag zoom when enabled rectprops = dict(facecolor='white', edgecolor = 'white', alpha=0.25, fill=True) self.toggle_selector = RectangleSelector(self.axes, self.zoom_controller.on_zoom, drawtype='box', useblit=True, rectprops=rectprops, button=[1], # Left mouse button minspanx=1, minspany=1, spancoords='data') self.toggle_selector.set_active(False)
def __init__(self, viewer, on_move=None, on_release=None, on_enter=None, maxdist=10, rect_props=None): self._rect = None props = dict(edgecolor=None, facecolor='r', alpha=0.15) props.update(rect_props if rect_props is not None else {}) if props['edgecolor'] is None: props['edgecolor'] = props['facecolor'] RectangleSelector.__init__(self, viewer.ax, lambda *args: None, rectprops=props) CanvasToolBase.__init__(self, viewer, on_move=on_move, on_enter=on_enter, on_release=on_release) # Events are handled by the viewer try: self.disconnect_events() except AttributeError: # disconnect the events manually (hack for older mpl versions) [self.canvas.mpl_disconnect(i) for i in range(10)] # Alias rectangle attribute, which is initialized in RectangleSelector. self._rect = self.to_draw self._rect.set_animated(True) self.maxdist = maxdist self.active_handle = None self._extents_on_press = None if on_enter is None: def on_enter(extents): print("(xmin=%.3g, xmax=%.3g, ymin=%.3g, ymax=%.3g)" % extents) self.callback_on_enter = on_enter props = dict(mec=props['edgecolor']) self._corner_order = ['NW', 'NE', 'SE', 'SW'] xc, yc = self.corners self._corner_handles = ToolHandles(self.ax, xc, yc, marker_props=props) self._edge_order = ['W', 'N', 'E', 'S'] xe, ye = self.edge_centers self._edge_handles = ToolHandles(self.ax, xe, ye, marker='s', marker_props=props) self.artists = [self._rect, self._corner_handles.artist, self._edge_handles.artist] viewer.add_tool(self)
def __init__(self, ax=None): if ax is None: ax=gca() self.ax = ax # drawtype is 'box' or 'line' or 'none' self.selector = RectangleSelector(self.ax, self._callback, drawtype='box',useblit=True, minspanx=5,minspany=5,spancoords='pixels') self.selector.set_active(False) self.block = BlockingInput(self.ax.figure)
class ROISelector(object): def __init__(self,artist): self.artist = artist self.selector = RectangleSelector(self.artist.axes,self.on_select, button=3, minspanx=5, minspany=5, spancoords='pixels', rectprops = dict(facecolor='red', edgecolor = 'red', alpha=0.3, fill=True)) self.coords = [] def on_select(self,click,release): x1,y1 = int(click.xdata),int(click.ydata) x2,y2 = int(release.xdata),int(release.ydata) self.coords =[(x1,y1),(x2,y2)] def activate(self): self.selector.set_active(True) def deactivate(self): self.selector.set_active(False)
def _line_selector(self): try: self.rs.disconnect_events() DraggableResizeableRectangle.lock = True print('Rectangles are locked') except: print('Rectangles could not be locked') print(self.__class__.__name__, ": Connecting Line Selector") DraggableResizeableLine.lock = None self.ls = RectangleSelector(self.axes_selector, self.line_selector_func, drawtype='line', useblit=True, button=[3])
def __init__(self, fitsfile, ax, mags, frms, all_axes, buttons, use_hjd=False, display_class=LightcurveDisplay): self.fitsfile = fitsfile self.ax = ax self.mags = mags self.frms = frms self.all_axes = all_axes self.buttons = buttons self.use_hjd = use_hjd self.display_class = display_class self.selector = RectangleSelector(self.ax, self.on_event, drawtype='box') self.l = None
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)
def __init__(self, ax, canvas): self.rectProps = dict(facecolor='red', edgecolor = 'white', alpha=0.5, fill=True) self.indicatorProps = dict(facecolor='white', edgecolor='black', alpha=0.5, fill=True) self.__selector = RectangleSelector(ax, self._on_select, drawtype='box', rectprops=self.rectProps) self.__axes = ax self.__canvas = canvas self.mode = None # mode: # None or 'rect': get the selected rect region # 'peak': get the peak point in the selected rect region self.__rect = None self.__peakpos = None self.__callback = None
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)
def add_selector(axes, callback, button=None, interactive=True, **kwargs): kwargs = { "button": button, "interactive": interactive, "rectprops": { "facecolor": "none", "edgecolor": "w", "fill": False, }, **kwargs, } return RectangleSelector(axes, callback, useblit=True, spancoords="data", **kwargs)
def _imshow_tfr(ax, ch_idx, tmin, tmax, vmin, vmax, onselect, ylim=None, tfr=None, freq=None, vline=None, x_label=None, y_label=None, colorbar=False, picker=True, cmap='RdBu_r', title=None): """ Aux function to show time-freq map on topo """ import matplotlib.pyplot as plt from matplotlib.widgets import RectangleSelector extent = (tmin, tmax, freq[0], freq[-1]) img = ax.imshow(tfr[ch_idx], extent=extent, aspect="auto", origin="lower", vmin=vmin, vmax=vmax, picker=picker, cmap=cmap) if isinstance(ax, plt.Axes): if x_label is not None: ax.set_xlabel(x_label) if y_label is not None: ax.set_ylabel(y_label) else: if x_label is not None: plt.xlabel(x_label) if y_label is not None: plt.ylabel(y_label) if colorbar: plt.colorbar(mappable=img) if title: plt.title(title) if not isinstance(ax, plt.Axes): ax = plt.gca() ax.RS = RectangleSelector(ax, onselect=onselect) # reference must be kept
def setup_plot(self): self.ax = self.figure_signal.add_subplot(2, 1, 1) self.vl = self.ax.axvline(self.signal_t[0], color='r', linewidth=3) '''Hard coded for WrenchStamped change later''' # TODO functionality to change topic type fx = np.array([element.wrench.force.x for element in self.signal]) fy = np.array([element.wrench.force.y for element in self.signal]) fz = np.array([element.wrench.force.z for element in self.signal]) tx = [element.wrench.torque.x for element in self.signal] ty = [element.wrench.torque.y for element in self.signal] tz = [element.wrench.torque.z for element in self.signal] t = np.array(self.signal_t) self.ax.plot(t, fx) self.ax.plot(t, fy) self.ax.plot(t, fz) self.ax.axis("Off") # self.ax.plot(t,tx,'k') # self.ax.plot(t,ty,'k') # self.ax.plot(t,tz,'k') self.RS = RectangleSelector( self.ax, self.line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button interactive=True) self.ax_timeline = self.figure_signal.add_subplot(2, 1, 2) self.vl_timeline = self.ax_timeline.axvline(self.signal_t[0], color='r', linewidth=3) self.label_names = list(set(self.labels)) plotResult_colorbars(self.labels, self.labels_t, ax=self.ax_timeline, labelNames=self.label_names) self.ax.set_xlim([t[0], t[-1]]) self.ax_timeline.set_xlim([t[0], t[-1]]) self.signalplot.draw()
def manual_matplotlib_crop(fullImage): ''' Manually crop part of the image. @param fullImage: Image to crop @return: the cropped image. ''' def line_select_callback(eclick, erelease): ''' Get x1, y1 when cliked and x2,y2 when released. ''' x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata def toggle_selector(event): ''' (de) Activate the selector. ''' 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) fig, ax = plt.subplots(1, 1, figsize=(15, 10)) ax.imshow(fullImage) toggle_selector.RS = RectangleSelector(ax, line_select_callback, drawtype='box', useblit=True, button=[1, 3], minspanx=5, minspany=5, spancoords='pixels', interactive=True) plt.connect('key_pressed_event', toggle_selector) plt.show() cropCoords = [int(x) for x in toggle_selector.RS.extents] croopedIm = fullImage[cropCoords[2]:cropCoords[3], cropCoords[0]:cropCoords[1]] return croopedIm
def select_point(x, y, axes, outfile_name, step): '''https://matplotlib.org/3.3.2/api/widgets_api.html#matplotlib.widgets.RectangleSelector''' def line_select_callback(eclick, erelease): '''Called by RectangleSelector. eclick and erelease are the press and release events''' global x1, x2, y1, y2 x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2)) # print(" The button you used were: %s %s" % (eclick.button, erelease.button)) 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) tellme('draw a rectangle around point of interest') toggle_selector.RS = RectangleSelector( axes, line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True) print(mpl.is_interactive()) plt.connect('key_press_event', toggle_selector) print(mpl.is_interactive()) plt.show() x = (x1 + x2) / 2. y = (y1 + y2) / 2. dx = abs(x1 - x2) / 2. dy = abs(y1 - y2) / 2. print(x, y, dx, dy) with open(outfile_name, 'a') as outfile: outfile.write('%10d %16.9e %16.9e %16.9e %16.9e\n' % (step, x, y, dx, dy)) plt.cla()
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 = RectangleSelector(ax, onselect=self.onselect) # Sprememba glede na originalno kodo self.ind = []
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 = self.ax.scatter( [], [], color='purple', zorder=2, picker=5, alpha=0.5) self.rectangle_selector = RectangleSelector( self.ax, self, useblit=True) ax_sa_button = self.ax.figure.add_axes([0.8, 0.01, 0.1, 0.05]) self.select_all_button = Button(ax_sa_button, label='select all') self.select_all_button.on_clicked(self.select_all) self.canvas.mpl_connect('pick_event', self.onpick)
def __init__(self, plotter: LinePlots, exporter: Any): """ See KeyHandler for parameter descriptions """ super().__init__(plotter, exporter) ax = plotter.image_axes self._selector = RectangleSelector( ax, self._on_rectangle_selected, drawtype='box', useblit=False, # rectangle persists on button release button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True)
def add_selector(self, mpl_ax, axes): self._update_data_lim(mpl_ax, axes) for ax in axes: if ax not in self.coords: self.coords[ax] = [0, 200] selector = RectangleSelector( mpl_ax, self.make_callback(axes), drawtype="box", useblit=False, rectprops=dict(facecolor="red", edgecolor="red", alpha=0.4, fill=False), interactive=True, ) self.selectors.append((selector, axes))
def show_selector(ROI_instance): fig_image, current_ax = plt.subplots() plt.imshow(ROI_instance.img_arr, cmap='gray') eh = EventHandler(ROI_instance.filename, ROI_instance.along_track) rect_select = RectangleSelector(current_ax, eh.line_select_callback, drawtype='box', useblit=True, button=[1, 2, 3], minspanx=5, minspany=5, spancoords='pixels', interactive=True) print("Rectangle Selector center:",rect_select.center) plt.connect('key_press_event', eh.event_exit_manager) plt.title('Original raw image') plt.colorbar() plt.show()
def plot_trigger(self, on_of): """ Function that load the previously pre-processed STA/LTA file as a dictionary file. Notice that in order to make this function work, it must be pre-processed using the included CLI, specifically, the make_stalta.sh script A own dictionary from another picking file, BUT with the following fields are also possible: 'data' -> (the seismic data we want to process as a Numpy Array) 'on of' -> an activation vector with triggers on and off times 'fm' -> the sampling frequency we are working with. Args: on_of : tuple The tuple of activation times for the times """ time_Vector = np.linspace(0, self.active_trace.data.shape[0] / self.fm, num=self.active_trace.data.shape[0]) # create an axis self.ax = self.figura_traza.add_subplot(111) # discards the old graph self.ax.cla() self.ax.plot(time_Vector, self.active_trace) self.ax.toolbar_trace = NavigationToolbar(self.canvas_traza, self) self.selector = RectangleSelector(self.ax, self.line_select_callback, drawtype='box', useblit=True, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True) ymin, ymax = self.ax.get_ylim() self.ax.vlines(on_of[:, 0] / self.fm, ymin, ymax, color='r', linewidth=1) self.ax.axvline(self.first_ticked, color='green', linestyle='solid') self.ax.axvline(self.last_ticked, color='magenta', linestyle='dashed') self.canvas_traza.draw()
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()
class BlockingRectangleSelector: """ Blocking rectangle selector selects once then continues with script. """ def __init__(self, ax=None): if ax is None: ax = gca() self.ax = ax # drawtype is 'box' or 'line' or 'none' self.selector = RectangleSelector(self.ax, self._callback, drawtype='box', useblit=True, minspanx=5, minspany=5, spancoords='pixels') self.selector.set_active(False) self.block = BlockingInput(self.ax.figure) def _callback(self, event1, event2): """ Selection callback. event1 and event2 are the press and release events """ x1, y1 = event1.xdata, event1.ydata x2, y2 = event2.xdata, event2.ydata if x1 > x2: x1, x2 = x2, x1 if y1 > y2: y1, y2 = y2, y1 self.x1, self.x2, self.y1, self.y2 = x1, x2, y1, y2 print 'stopping event loop' self.ax.figure.canvas.stop_event_loop_default() def select(self): """ Wait for box to be selected on the axes. """ # Wait for selector to complete self.selector.set_active(True) self.ax.figure.canvas.draw_idle() self.block() self.selector.set_active(False) # Make sure the graph is redrawn next time the event loop is shown self.ax.figure.canvas.draw_idle() def remove(self): """ Remove the selector from the axes. Note: this currently does nothing since matplotlib doesn't allow widgets to be removed from axes. """ pylab.close('all')
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 draw(self): """draw(fig: Figure) ->None code using matplotlib. Use self.fig and self.figManager """ (self.coord, self.matrix, title) = self.inputPorts # for faster access id2pos = {idd: pos for (pos, idd) in enumerate(self.matrix.ids)} circleSize = np.ones(len(self.matrix.ids)) for selId in self.selectedIds: circleSize[id2pos[selId]] = 4 pylab.clf() pylab.axis("off") pylab.title(title) pylab.scatter( self.matrix.values[:, 0], self.matrix.values[:, 1], # c=colors, cmap=pylab.cm.Spectral, s=40, linewidth=circleSize, marker="o", ) # draw labels if self.showLabels and self.matrix.labels is not None: for label, xy in zip(self.matrix.labels, self.matrix.values): pylab.annotate( str(label), xy=xy, xytext=(5, 5), textcoords="offset points", bbox=dict(boxstyle="round,pad=0.2", fc="yellow", alpha=0.5), ) self.figManager.canvas.draw() # Set Selectors self.rectSelector = RectangleSelector( pylab.gca(), self.onselect, drawtype="box", rectprops=dict(alpha=0.4, facecolor="yellow") ) self.rectSelector.set_active(True)
def func2(filename2=filename): print(filename) doc2 = pdf.convert_from_path("{}.pdf".format(filename2), 500) print(doc2[0]) doc2[0].save("{}.png".format(filename2)) doc = cv2.imread("{}.png".format(filename2)) print(doc) fig, ax = plt.subplots() plt.imshow(doc) coords = pd.DataFrame(columns=['blx', 'bly', 'trx', 'try']) TrainingRegions = [] def line_select_callback(eclick, erelease): global ix ix += 1 x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata rect = plt.Rectangle((min(x1, x2), min(y1, y2)), np.abs(x1 - x2), np.abs(y1 - y2), alpha=0.3) coords.at[ix, 'blx'] = int(x1) coords.at[ix, 'bly'] = int(y1) coords.at[ix, 'trx'] = int(x2) coords.at[ix, 'try'] = int(y2) print(ix) ax.add_patch(rect) rs = RectangleSelector(ax, line_select_callback, drawtype='box', useblit=False, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True) fig_manager = plt.get_current_fig_manager() fig_manager.window.showMaximized() cursor = Cursor(ax, useblit=True, color='red', linewidth=1) plt.tight_layout() plt.show() for i in range(0, len(coords)): TrainingRegions.append(doc[coords.at[i, 'blx']:coords.at[i, 'trx'], coords.at[i, 'bly']:coords.at[i, 'try']]) # Change from TestImagesTemp to TestImages when function is working os.chdir(local_repo_path + '\Data\TestImagesTemp') if not coords.empty: for j in range(0, len(TrainingRegions)): sm.imsave('{}_{}.png'.format(filename2, j), TrainingRegions[j])
def plot_rect(x, y): fig, current_ax = plt.subplots() plt.plot(x, y) plt.xlabel('Tiempo') plt.ylabel('|B| (nT)') plt.title('Seleccionar ') print("\n click --> release") toggle_selector.RS = RectangleSelector( current_ax, line_select_callback, 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)
def show_and_select(self): """ show the screenshot and allow user to select area """ _, current_ax = plt.subplots() # make a new plotting range plt.imshow(self.screenshot()) print("\n click --> release") # drawtype is 'box' or 'line' or 'none' self.toggle_selector.RS = RectangleSelector( 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) plt.connect('key_press_event', self.toggle_selector) plt.show()
def plot(self): self.profImshow() def toggle_selector(event): 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.ax, self.rectangle_callback, drawtype='box', useblit=True, button=[1, 3], minspanx=5, minspany=5, spancoords='pixels', interactive=True) plt.connect('key_press_event', toggle_selector)
def __init__(self): self.cropfig = plt.figure(num='Crop Image') #self.fig.suptitle("Layout Analysed figure") self.cropax = self.cropfig.add_subplot(111) self.croppoint = self.cropax.plot([],[], marker="o", color="crimson") self.axcrop = plt.axes([0.4, 0.01, 0.09,0.06]) self.bncrop = Button(self.axcrop, 'Crop') self.bncrop.color = "white" self.img = 0 self.cropx1 = 0 self.cropy1 = 0 self.cropx2 = 0 self.cropy2 = 0 self.cr = RectangleSelector(self.cropax,self.crop_select, drawtype='box', useblit=False, button=[1], minspanx=2, minspany=2, spancoords='pixels', interactive=True)
def onpressrect(self, event): ''' Create lasso when button pressed on active canvas/axes allegedly rectangleselector (and lassoselector) behave differently than lasso these require manual disconnect''' print('Started rectangle selection') # ensure that current dataset is active self.xys = self.parent.xys # pixels list passed from plotter (parent) # does not need to be initialized with starting point ''' doesn't seem to react self.rect = RectangleSelector(event.inaxes, self.callbackrect) # this also doesn't respond self.rect = RectangleSelector(event.inaxes, onselect=self.callbackrect, drawtype='box', interactive='True') ''' self.rect = RectangleSelector(self.canvas, onselect=self.callbackrect, drawtype='box', interactive='True')
def select_roi(img): fig, current_ax = plt.subplots() plt.title("Select ROI, press any key to continue.") plt.imshow(img, cmap='gray') # show the first image in the stack toggle_selector.RS = RectangleSelector(current_ax, line_select_callback, 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() # # some IDE's (pycharm, jupyter) move on to plt.close(fig) instead of waiting for the callback to finish # # if that is the case, uncomment the next three lines keyboardClick = False while not keyboardClick: keyboardClick = plt.waitforbuttonpress() plt.close(fig)
def __init__(self, doc, parent=None, mdi=None): QtWidgets.QMainWindow.__init__(self, parent) uic.loadUi('ui/document.ui', self) self.mdi = mdi self.parent = parent self.fig = Figure((400, 400)) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.centralwidget) self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus) self.canvas.setFocus() self.canvas.updateGeometry() self.grid = [0, 0, 20, 20] self.mpl_toolbar = NavigationToolbar(self.canvas, self.centralwidget) self.verticalLayout.addWidget(self.canvas) self.verticalLayout.addWidget(self.mpl_toolbar) self.plt = self.fig.gca() self.doc = doc self.updatePlot() self.actionProperties.triggered.connect(self.updateProperties) self.actionImport.triggered.connect(self.importObject) #self.cur = Cursor(self.plt, useblit=True) self.cursor = SnaptoCursor(self, useblit=True) self.selector = RectangleSelector(self.plt, self.onselect, drawtype='box', rectprops=dict(facecolor='white', edgecolor='black', alpha=0.5, fill=False, linestyle='--'), useblit=True, button=3, state_modifier_keys={ 'center': 'None', 'None': 'space', 'clear': 'escape', 'square': 'shift' })
def onclick(event): xcord = event.xdata ycord = event.ydata for j in range(self.df.shape[0]): if (between(xcord, self.df.loc[j]['xleft'], self.df.loc[j]['xleft'] + self.df.loc[j]['width']) and between( ycord, self.df.loc[j]['yleft'], self.df.loc[j]['yleft'] + self.df.loc[j]['height'])): top = Toplevel() top.geometry('200x120+' + str(np.random.randint(low=100, high=200)) + '+' + str(np.random.randint(low=100, high=200))) top.title('Edit Object') button1 = Button(top, text="Delete", bg='red', command=partial(deleteObj, j)) button1.pack() entry = Entry(top, textvariable=self.s) self.s.set(root.df.loc[j]['label']) entry.pack() button2 = Button(top, text="Save", bg='green', command=partial(saveObj, j)) button2.pack() else: if event.dblclick: toggle_selector.RS = RectangleSelector( self.ax, line_select_callback, drawtype='box', useblit=True, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True)
def func2(filename2=filename): os.chdir("Data/TestImages") # Reading the image as an array. img = cv2.imread("{}.png".format(filename2)) # Using fig, ax to make the interactive bit work. fig, ax = plt.subplots() plt.imshow(img) coords = pd.DataFrame(columns=['blx', 'bly', 'trx', 'try']) def line_select_callback(eclick, erelease): global ix ix += 1 x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata rect = plt.Rectangle((min(x1, x2), min(y1, y2)), np.abs(x1 - x2), np.abs(y1 - y2), alpha=0.3) coords.at[ix, 'blx'] = int(x1) coords.at[ix, 'bly'] = int(y1) coords.at[ix, 'trx'] = int(x2) coords.at[ix, 'try'] = int(y2) print(ix) ax.add_patch(rect) rs = RectangleSelector(ax, line_select_callback, drawtype='box', useblit=False, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True) fig_manager = plt.get_current_fig_manager() fig_manager.window.showMaximized() cursor = Cursor(ax, useblit=True, color='red', linewidth=1) plt.show() os.chdir(local_repo_path + '\Data\TestCoords') if not coords.empty: coords.to_csv('{}.csv'.format(filename2), index=False)
class BlockingRectangleSelector: """ Blocking rectangle selector selects once then continues with script. """ def __init__(self, ax=None): if ax is None: ax=gca() self.ax = ax # drawtype is 'box' or 'line' or 'none' self.selector = RectangleSelector(self.ax, self._callback, drawtype='box',useblit=True, minspanx=5,minspany=5,spancoords='pixels') self.selector.set_active(False) self.block = BlockingInput(self.ax.figure) def _callback(self, event1, event2): """ Selection callback. event1 and event2 are the press and release events """ x1, y1 = event1.xdata, event1.ydata x2, y2 = event2.xdata, event2.ydata if x1>x2: x1,x2 = x2,x1 if y1>y2: y1,y2 = y2,y1 self.x1,self.x2,self.y1,self.y2 = x1,x2,y1,y2 print 'stopping event loop' self.ax.figure.canvas.stop_event_loop_default() def select(self): """ Wait for box to be selected on the axes. """ # Wait for selector to complete self.selector.set_active(True) self.ax.figure.canvas.draw_idle() self.block() self.selector.set_active(False) # Make sure the graph is redrawn next time the event loop is shown self.ax.figure.canvas.draw_idle() def remove(self): """ Remove the selector from the axes. Note: this currently does nothing since matplotlib doesn't allow widgets to be removed from axes. """ pylab.close('all')
def selector_function(img, count): fig, current_ax = plt.subplots() plt.imshow(img) print("\n Frame %d" % count) # drawtype is 'box' or 'line' or 'none' toggle_selector.RS = RectangleSelector( current_ax, line_select_callback, 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
def _selector_callback(self, eclick, erelease): self.ax_main.clear() super(CEST_MRI, self)._display_image(self.ax_main) x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata dx = [eclick.xdata, erelease.xdata] dy = [eclick.ydata, erelease.ydata] roi = ROI.ROI(self._ref_img) rec_patch = roi.rectangle((x1, y1), x2 - x1, y2 - y1) self.select_map[self._c_indx] = roi self.box_draw[self._c_indx] = rec_patch self.eval_mask() self.ax_cest.clear() for i, spec in enumerate(self.cest): k = {3: 'r', 0: 'b', 1: 'g', 2: 'k'}[i] self.ax_cest.plot(spec, k) self.ax_main.clear() super(CEST_MRI, self)._display_image(self.ax_main) kc = {3: 'r', 0: 'b', 1: 'g', 2: 'k'} for k in self.select_map.keys(): s = self.box_draw[k] s.set_ec(kc[k]) self.ax_main.add_patch(s) self._fig.canvas.draw() self._selector = RectangleSelector( self.ax_main, self._selector_callback, drawtype='box', useblit=False, button=[1], # don't use middle button minspanx=5, minspany=5, spancoords='pixels') self.dump_data()
def __init__(self, fig, ax): self.x1 = 0 self.x2 = 0 self.y1 = 0 self.y2 = 0 self.fig = fig self.ax = ax self.RS = RectangleSelector( self.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) self.fig.canvas.mpl_connect('key_press_event', self.toggle_selector)
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 try: 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]) except KeyError: self.x1, self.x2, self.y1, self.y2 = map( int, self.cfg["video_sets_original"][videosource] ["crop"].split(",")) if self.cropping: # 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)
def __init__(self, image, coords=None): self.image = image self.coords = coords if coords is not None: # then testing return self.isDone = False self.fig, ax = plt.subplots() self.widget = RectangleSelector(ax, self._onselect, drawtype='box', interactive=True, useblit=True) axDone = plt.axes([0.81, 0.05, 0.1, 0.075]) self.doneButton = Button(axDone, 'Done') self.doneButton.on_clicked(self.done) ax.imshow(self.image) plt.connect('key_press_event', self.widget) plt.show()
def show(self, use_widgets, **kwargs): if self._fig: plt.close(self._fig) self.plotted_lines = [] if use_widgets: self._create_widgets() else: self._fig = plt.figure() self._axes = self._fig.add_subplot(111) self._dx = 0 self._last_update = time.time() calibrated_image = CalibratedKymographChannel.from_kymo(self._kymo, self._channel) calibrated_image.plot(interpolation="nearest", **kwargs) if self.axis_aspect_ratio: self._axes.set_xlim( [ 0, self.axis_aspect_ratio * calibrated_image.to_seconds(calibrated_image.data.shape[0]), ] ) # Prevents the axes from resetting every time new lines are drawn self._axes.autoscale(enable=False) plt.tight_layout() self._area_selector = RectangleSelector( self._axes, self.track_kymo, useblit=True, button=[3], minspanx=5, minspany=5, spancoords="pixels", interactive=False, ) self.update_lines() self._connect_drag_callback() self._connect_line_callback() self._select_state({"value": "mode", "old": "", "new": "Track lines"})
def Deblend(spectrum, **kwargs): ''' Remove feature from `spectrum` via division. The user manually selects regions in the `spectrum` and a `line` is fit to and subtracted. The original `spectrum` object is modified. If `spectrum` is actually a Spectrum object (Spectrum.Spectrum), a `SPlot` figure is created for it (without a label). Alternatively, a SPlot object can be directly given. ''' if type(spectrum) is Spectrum: # create a SPlot object out of the spectrum spectrum = SPlot(spectrum) elif type(spectrum) is not SPlot: raise MeasureError('From Deblend(), argument must be either of type ' 'Spectrum or SPlot!') # make spectrum window active spectrum.draw() # pass off spectrum to global plot object global plot global regions plot = spectrum domain = ' Select a region, the press enter: ' # while domain: selector = RectangleSelector(plot.ax, OnSelect_Deblend, minspanx=1, minspany=1) #connect('key_press_event', toggle_selector) # selector = RectangleSelector(plot.ax, OnSelect_Deblend, # drawtype='box', useblit=True, # button=[1,3], # don't use middle button # minspanx=5, minspany=5, # spancoords='pixels') #domain = input(domain) #print('Region -> ', regions[-1]) #print('Select regions for continuum fitting: <press enter when done>') return plot
def __init__(self, slice_plot, canvas, ws_title): self.slice_plot = slice_plot self._canvas = canvas self._ws_title = ws_title self._en_unit = slice_plot.get_slice_cache().energy_axis.e_unit self._en_from_meV = EnergyUnits(self._en_unit).factor_from_meV() self.horizontal = None self.connect_event = [None, None, None, None] # We need to access the CutPlotterPresenter instance of the particular CutPlot (window) we are using # But there is no way to get without changing the active category then calling the GlobalFigureManager. # So we create a new temporary here. After the first time we plot a 1D plot, the correct category is set # and we can get the correct CutPlot instance and its CutPlotterPresenter self._cut_plotter_presenter = CutPlotterPresenter() self._is_initial_cut_plotter_presenter = True self._rect_pos_cache = [0, 0, 0, 0, 0, 0] self.rect = RectangleSelector(self._canvas.figure.gca(), self.plot_from_mouse_event, drawtype='box', useblit=True, button=[1, 3], spancoords='pixels', interactive=True) self.connect_event[3] = self._canvas.mpl_connect('draw_event', self.redraw_rectangle) self._canvas.draw()
return start_java_bridge() image4d = readfile(filename) [nx, ny, nz, nt] = image4d.shape if timepts == []: timepts = range(0, nt) # set time points used for correlation ''' select area used as reference waveform ''' fig = pyplot.figure(2) ax = pyplot.gca() REFimg = ax.imshow(np.mean(image4d[:, :, 0, :], axis=2), interpolation='none') RS = RectangleSelector(ax, onselect) RS.coords = np.array([0, 0, ny-1, nx-1]) # image and plot reverse axes pyplot.show() RS.coords = RS.coords.astype(int) RS.dims = np.array([RS.coords[2]-RS.coords[0], RS.coords[3]-RS.coords[1]]) # generate signal wave Ipxtimeseries = np.reshape(image4d[:, :, 0, :], (nx*ny, nt)) I = Ipxtimeseries[:, timepts] mI = np.mean(I, axis=1) sI = np.std(I, axis=1) # generate reference wave REFimg = image4d[RS.coords[0]:RS.coords[2], RS.coords[1]:RS.coords[3], 0, :] REFpxtimeseries = np.reshape(REFimg, (RS.dims[0]*RS.dims[1], nt))
def f(e): if e.button != 1: return True else: return RectangleSelector.ignore(self.selector, e)
class View(wx.Frame): def __init__(self, controller, model): self.controller = controller self.model = model self.zoom_controller = zoom_controller.Controller(controller, self, model) self.aspect = 1.0 self.toolbar_ids = {} self.menubar_ids = {} self.connect_ids = [] self.ov_axes = '' self.toggle_selector = None self.figure = None wx.Frame.__init__(self, parent=None, title="Coral X-Ray Viewer", size=(850, 750), pos=(0,0)) self.SetMinSize((100, 100)) self.scroll = wx.ScrolledWindow(self, -1) self.scroll.SetBackgroundColour('grey') self.create_menubar() self.create_toolbar() self.create_statusbar() self.scroll.Bind(wx.EVT_SCROLLWIN, self.controller.on_scroll) # scroll event self.scroll.Bind(wx.EVT_SCROLL, self.on_scroll) self.Bind(wx.EVT_SIZE, self.controller.on_resize) self.Bind(wx.EVT_ACTIVATE, self.controller.cleanup) self.Bind(wx.EVT_CLOSE, self.controller.on_quit) self.Bind(wx.EVT_CONTEXT_MENU, self.controller.on_show_popup) self.Center() self.Show() def on_scroll(self, event): event.Skip() self.controller.state_changed(True) def create_menubar(self): self.menubar = wx.MenuBar() for name in self.menu_names(): menu = wx.Menu() for each in self.menu_options()[self.menu_names().index(name)]: self.add_menu_option(menu, *each) self.menubar.Append(menu, name) self.SetMenuBar(self.menubar) def add_menu_option(self, menu, label, accel, handler, enabled, has_submenu, submenu): if not label: menu.AppendSeparator() else: menu_id = wx.NewId() self.menubar_ids[label] = menu_id if has_submenu: if label == 'Filter Plugins': option = menu.AppendMenu(menu_id, label, self.plugin_submenu()) else: option = menu.AppendMenu(menu_id, label, submenu) else: option = menu.Append(menu_id, label) option.Enable(enabled) if accel: wx.AcceleratorTable([ (accel[0], ord(accel[1]), option.GetId()) ]) self.Bind(wx.EVT_MENU, handler, option) def menu_names(self): return ('File', 'Tools', 'Help') def menu_options(self): """ ('TEXT', (ACCELERATOR), HANDLER, ENABLED, HAS_SUBMENU, SUBMENU METHOD """ return ( [ # File ('&Open...\tCtrl+O', (wx.ACCEL_CTRL, 'O'), self.controller.on_open, True, False, None), ('&Save\tCtrl+S', (wx.ACCEL_CTRL, 'S'), self.controller.on_save, False, False, None), ('Save As...', (), self.controller.on_save_as, False, False, None), ('', '', '', True, False, None), ('Export', (), self.controller.on_export, False, False, None), ('', '', '', True, False, None), ('&Quit\tCtrl+Q', (wx.ACCEL_CTRL, 'Q'), self.controller.on_quit, True, False, None) ], [ # Tools ('Image Overview', (), self.controller.on_overview, False, False, None), ('Image Information', (), self.controller.on_image_info, False, False, None), ('', '', '', True, False, None), # ('Rotate Image', (), self.controller.on_rotate_image, False, False, None), ('Pan Image', (), self.controller.on_pan_image_menu, False, False, None), ('Rotate Image', (), self.controller.on_rotate, False, False, None), ('Zoom In', (), self.zoom_controller.on_zoom_in_menu, False, False, None), ('Zoom Out', (), self.zoom_controller.on_zoom_out, False, False, None), ('', '', '', True, False, None), # ('Adjust Contrast', (), self.controller.on_contrast, False, False, None), # ('', '', '', True, False, None), ('Adjust Target Area', (), self.controller.on_coral_menu, False, False, None), ('', '', '', True, False, None), ('Filtered Overlays', (), self.controller.on_overlay, False, False, None), ('Filter Plugins', (), self.controller.on_plugin, True, True, None), ('', '', '', True, False, None), ('Adjust Calibration Region', (), self.controller.on_calibrate_menu, False, False, None), ('Set Calibration Parameters', (), self.controller.on_density_params, False, False, None), ('Show Density Chart', (), self.controller.on_show_density_chart, False, False, None), ('', '', '', True, False, None), ('Draw Polylines', (), self.controller.on_polyline_menu, False, False, None), ], [ # Help ('Help', (), self.controller.on_help, True, False, None), ('About', (), self.controller.on_about, True, False, None) ] ) def plugin_submenu(self): """ Creates the plugin submenu in the menubar which displays all plugins and allows the user to specify a secondary plugin directory. """ menu = wx.Menu() """ # Add a plugin from another directory to the default directory addPlugin = wx.MenuItem(menu, wx.ID_ANY, 'Add Plugin') menu.AppendItem(addPlugin) self.Bind(wx.EVT_MENU, self.controller.on_add_plugin, addPlugin) """ # Set directory where extra plugins are held props = wx.MenuItem(menu, wx.ID_ANY, 'Set Directory') menu.AppendItem(props) self.Bind(wx.EVT_MENU, self.controller.on_plugin_properties, props) menu.AppendSeparator() # Get the default plugin directory, using XML path = os.path.expanduser('~') xml = xml_controller.Controller(path + '\.cxvrc.xml') xml.load_file() if os.path.exists(os.path.expanduser('~') + os.sep + "plugins"): default_dir = os.path.expanduser('~') + os.sep + "plugins" else: default_dir = self.get_main_dir() + os.sep + "plugins" if xml.get_plugin_directory() == "" or xml.get_plugin_directory() is None: directory = [default_dir] else: directory = [default_dir, xml.get_plugin_directory()] # Load the plugins from the specified plugin directory/s. manager = PluginManager() manager.setPluginPlaces(directory) manager.setPluginInfoExtension('plugin') manager.collectPlugins() for plugin in manager.getAllPlugins(): item = wx.MenuItem(menu, wx.ID_ANY, plugin.name) menu.AppendItem(item) self.better_bind(wx.EVT_MENU, item, self.controller.on_about_filter, plugin) return menu def better_bind(self, evt_type, instance, handler, *args, **kwargs): self.Bind(evt_type, lambda event: handler(event, *args, **kwargs), instance) def create_toolbar(self): self.toolbar = self.CreateToolBar() for each in self.toolbar_data(): self.add_tool(self.toolbar, *each) self.toolbar.Realize() def add_tool(self, toolbar, tool_type, label, bmp, handler, enabled): if tool_type == 'separator': toolbar.AddSeparator() elif tool_type == 'control': toolbar.AddControl(label) else: bmp = wx.Image(self.get_main_dir() + os.sep + bmp, wx.BITMAP_TYPE_ANY).ConvertToBitmap() tool_id = wx.NewId() self.toolbar_ids[label] = tool_id if tool_type == 'toggle': tool = toolbar.AddCheckTool(tool_id, bmp, wx.NullBitmap, label, '') elif tool_type == 'simple': tool = toolbar.AddSimpleTool(tool_id, bmp, label, '') toolbar.EnableTool(tool_id, enabled) self.Bind(wx.EVT_MENU, handler, tool) def toolbar_data(self): aspects = ['100%', '75%', '50%', '25%', '10%', 'Zoom to fit'] self.aspect_cb = wx.ComboBox(self.toolbar, -1, '100%', choices=aspects, style=wx.CB_DROPDOWN) self.aspect_cb.SetValue('Zoom to fit') self.Bind(wx.EVT_COMBOBOX, self.controller.on_aspect, self.aspect_cb) self.Bind(wx.EVT_TEXT_ENTER, self.controller.on_aspect, self.aspect_cb) self.aspect_cb.Disable() return (# tool type, description text, icon directory, handler ('simple', '&Open...\tCtrl+O', 'images' + os.sep + 'open.png', self.controller.on_open, True), ('simple', '&Save\tCtrl+S', 'images' + os.sep + 'save.png', self.controller.on_save, False), ('separator', '', '', '', ''), ('simple', 'Image Overview', 'images' + os.sep + 'overview.png', self.controller.on_overview, False), ('simple', 'Image Information', 'images' + os.sep + 'info.png', self.controller.on_image_info, False), ('separator', '', '', '', ''), # ('simple', 'Rotate Image', 'images' + os.sep + 'rotate_counter-clock.png', self.controller.on_rotate_image, False), ('toggle', 'Pan Image', 'images' + os.sep + 'cursor_hand.png', self.controller.on_pan_image, False), ('simple', 'Rotate Image', 'images' + os.sep + 'rotate_image.png', self.controller.on_rotate, False), ('toggle', 'Zoom In', 'images' + os.sep + 'zoom_in_toolbar.png', self.zoom_controller.on_zoom_in, False), ('simple', 'Zoom Out', 'images' + os.sep + 'zoom_out_toolbar.png', self.zoom_controller.on_zoom_out, False), ('control', self.aspect_cb, '', '', ''), ('separator', '', '', '', ''), # ('simple', 'Adjust Contrast', 'images' + os.sep + 'contrast.png', self.controller.on_contrast, False), # ('separator', '', '', '', ''), ('toggle', 'Adjust Target Area', 'images' + os.sep + 'coral.png', self.controller.on_coral, False), # ('simple', 'Lock Target Area', 'images' + os.sep + 'lock_coral.png', self.controller.on_lock_coral, False), # ('separator', '', '', '', ''), ('simple', 'Filtered Overlays', 'images' + os.sep + 'overlay.png', self.controller.on_overlay, False), ('separator', '', '', '', ''), ('toggle', 'Adjust Calibration Region', 'images' + os.sep + 'calibrate.png', self.controller.on_calibrate, False), ('toggle', 'Set Calibration Parameters', 'images' + os.sep + 'density.png', self.controller.on_density_params, False), ('simple', 'Show Density Chart', 'images' + os.sep + 'chart_line.png', self.controller.on_show_density_chart, False), ('separator', '', '', '', ''), ('toggle', 'Draw Polylines', 'images' + os.sep + 'polyline.png', self.controller.on_polyline, False), ) def create_statusbar(self): self.statusbar = self.CreateStatusBar() self.statusbar.SetFieldsCount(2) self.statusbar.SetStatusWidths([-5, -5]) def mpl_bindings(self): for each in self.mpl_binds(): self.connect(*each) def connect(self, event, handler): cid = self.canvas.mpl_connect(event, handler) self.connect_ids.append(cid) def disconnect(self): for cid in self.connect_ids: self.canvas.mpl_disconnect(cid) self.connect_ids = [] # matplotlib events def mpl_binds(self): return [ ('motion_notify_event', self.controller.on_mouse_motion), ('figure_leave_event', self.controller.on_figure_leave), ('button_press_event', self.controller.on_mouse_press), ('button_release_event', self.controller.on_mouse_release), ('key_press_event', self.controller.on_key_press), ('key_release_event', self.controller.on_key_release) ] def init_plot(self, new): y, x = self.model.get_image_shape() if new: self.figure = Figure(figsize=(x*2/72.0, y*2/72.0), dpi=72) self.canvas = FigureCanvasWxAgg(self.scroll, -1, self.figure) self.canvas.SetBackgroundColour('grey') self.axes = self.figure.add_axes([0.0, 0.0, 1.0, 1.0]) self.axes.set_axis_off() self.axes.imshow(self.model.get_image(), aspect='auto') # aspect='auto' sets image aspect to match the size of axes self.axes.set_autoscale_on(False) # do not apply autoscaling on plot commands - VERY IMPORTANT! self.mpl_bindings() y, = self.scroll.GetSizeTuple()[-1:] iHt, = self.model.get_image_shape()[:-1] self.aspect = (float(y)/float(iHt)) self.controller.resize_image() # Set the RectangleSelector so that the user can drag zoom when enabled rectprops = dict(facecolor='white', edgecolor = 'white', alpha=0.25, fill=True) self.toggle_selector = RectangleSelector(self.axes, self.zoom_controller.on_zoom, drawtype='box', useblit=True, rectprops=rectprops, button=[1], # Left mouse button minspanx=1, minspany=1, spancoords='data') self.toggle_selector.set_active(False) def main_is_frozen(self): return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") or # old py2exe imp.is_frozen("__main__")) # tools/freeze def get_main_dir(self): if self.main_is_frozen(): return os.path.dirname(sys.executable) return os.path.dirname(sys.argv[0])