def draw_rectangle(self, lower, upper, node): r = Rectangle(lower, upper[0] - lower[0], upper[1]-lower[1], edgecolor='k', facecolor = (0,0,0)) self.ax.add_patch(r) if node.is_leaf(): rx, ry = r.get_xy() cx = rx + r.get_width()/2.0 cy = ry + r.get_height()/2.0 r.set_facecolor( node.get_colour()) self.ax.annotate(node.get_weight(), (cx, cy), color=(0,0,0), fontsize = 10, ha='center', va='center') print node.name, rx, ry, cx, cy
def add_box(ax,box_bounds,clrs, fill = False, linewidth = 2): # lonmin,lonmax, latmin, latmax from matplotlib.patches import Rectangle for ii, box in enumerate(box_bounds): p = Rectangle( (box[0], box[2]), box[1]-box[0], box[3]-box[2], linewidth=linewidth,fill=False,color=clrs[ii], zorder = 3) ax.add_patch(p) rx, ry = p.get_xy() cx = rx + p.get_width()/2.0 cy = ry + p.get_height()/2.0
def demo(self): model = self.model() model.load_weights('./checkpoints/model') test_dataset = self.database.get_tf_dataset(partition='test', batch_size=1, all_info=True) for i, item in enumerate(test_dataset): img, annot, orig_img, y1, y2, x1, x2 = item x1 = x1[0, ...].numpy() x2 = x2[0, ...].numpy() y1 = y1[0, ...].numpy() y2 = y2[0, ...].numpy() prediction = model.predict(img) prediction = 1 / (1 + np.exp(prediction)) prediction = prediction[0, 0] if annot == 1: prediction = 1 - prediction text = f'with_mask\n{prediction:0.2f}' else: text = f'no_mask\n{prediction:0.2f}' if prediction > 0.5: color = 'g' else: color = 'r' rect = Rectangle((y1, x1), y2 - y1, x2 - x1, fill=False, linewidth=4, edgecolor=color) position = list(rect.get_xy()) position[0] += rect.get_width() / 2 position[1] -= 20 plt.imshow(orig_img[0, ...]) plt.gca().add_patch(rect) plt.gca().annotate(text, position, color='w', weight='bold', fontsize=18, ha='center', va='center') plt.show()
def draw_trip(base_line, start, duration, color, text): rect_w = duration * 0.1 rect_h = 0.08 x = start * 0.1 y = base_line + 0.1 rect = Rectangle((x, y), rect_w, rect_h, alpha=1, facecolor=color) rx, ry = rect.get_xy() cx = rx + rect.get_width() / 2.0 cy = ry + rect.get_height() / 2.0 currentAxis.annotate(str(start), (cx, cy), color='w', weight='bold', fontsize=6, ha='center', va='center') currentAxis.add_patch(rect)
def draw_days(base_line, number): rect_w = 0.1 rect_h = 0.08 for day in range(0, number): x = day * 0.1 y = base_line rect = Rectangle((x, y), rect_w, rect_h, alpha=1, fill=None) rx, ry = rect.get_xy() cx = rx + rect.get_width() / 2.0 cy = ry + rect.get_height() / 2.0 currentAxis.annotate(day, (cx, cy), color='b', weight='bold', fontsize=6, ha='center', va='center') currentAxis.add_patch(rect)
def draw_rectangle(self, lower, upper, node): r = Rectangle(lower, upper[0] - lower[0], upper[1] - lower[1], edgecolor='k', facecolor=node.get_color(), label=node.name) self.ax.add_patch(r) rx, ry = r.get_xy() rw = r.get_width() rh = r.get_height() cx = rx + rw / 2.0 cy = ry + rh / 2.0 if isinstance(node, PathNode): t = node.name if rw * 3 < rh: t += ", " else: t += "\n" t += str(node.size) + ", " + node.stype c = 'w' if rw < rh: o = "vertical" else: o = "horizontal" else: t = node.name if node.isfile: c = 'k' o = 45 else: return self.ax.annotate(t, (cx, cy), color=c, weight='bold', ha='center', va='center', rotation=o)
def draw_rectangle(self, lower, upper, node): r = Rectangle( lower, upper[0]-lower[0], upper[1] - lower[1], edgecolor='k', facecolor= node.get_color(), label=node.name) self.ax.add_patch(r) rx, ry = r.get_xy() rw = r.get_width() rh = r.get_height() cx = rx + rw/2.0 cy = ry + rh/2.0 if isinstance(node, PathNode): t = node.name if rw * 3 < rh: t += ", " else: t += "\n" t += str(node.size) + ", " + node.stype c='w' if rw < rh: o = "vertical" else: o = "horizontal" else: t = node.name if node.isfile: c='k' o = 45 else: return self.ax.annotate( t, (cx,cy), color=c, weight='bold', ha='center', va='center', rotation=o )
def plot_rectangle(startTime, endTime, low, high, color, text): #print("plot rectangle: startTime {} endTime {} low {} high {} color {}".format(startTime, endTime, low, high, color)) from matplotlib.patches import Rectangle #convert to matplotlib date representation start = mdates.date2num(startTime) end = mdates.date2num(endTime) width = (end - start) height = high - low rect = Rectangle((start, low), width, height, color=color, alpha=0.4) rx, ry = rect.get_xy() cx = rx + rect.get_width() / 2.0 cy = ry + rect.get_height() / 2.0 ax = plt.gca() ax.annotate(text, (cx, cy), color='w', weight='bold', fontsize=6, ha='center', va='center') ax.add_patch(rect)
def run_sim(scenario_str): # see second answer of https://stackoverflow.com/questions/25175530/can-rpy2-code-be-run-in-parallel on why it starts different # R instances print ("Working on scenario " + scenario_str) all_data = {} scenario = scenarios[scenario_str] for dp in departements: all_data[dp] = DeptData() r_source = robjects.r['source'] r_options = robjects.r['options'] r_options(warn=-1) robjects.r('scenario <- "' + scenario_str + '"') robjects.r('nsim <- ' + str(nsim)) robjects.r('t_vacc_start <- list()') robjects.r('t_vacc_end <- list()') robjects.r('p1d_reg <- list()') robjects.r('r_v_year <- list()') for dp in departements: robjects.r('t_vacc_start${} <- "'.format(dp.replace('-','_')) + str(scenario.t_vacc_start[dp]) + '"') robjects.r('t_vacc_end${} <- "'.format(dp.replace('-','_')) + str(scenario.t_vacc_end[dp]) + '"') robjects.r('p1d_reg${} <- '.format(dp.replace('-','_')) + str(scenario.p1d_reg[dp])) robjects.r('r_v_year${} <- '.format(dp.replace('-','_')) + str(scenario.r_v_year[dp])) robjects.r('cases_ext <- ' + str(scenario.ve)) r_source('scripts/forecast_all_dept.R') temp = robjects.r['sim_stochastic'] for dp in departements: for comp in compartments: all_data[dp].q05[comp] = temp[temp['variable'] == comp + dp.replace('-','_')][temp['isdata']=='simulation']['q05'].values all_data[dp].q50[comp] = temp[temp['variable'] == comp + dp.replace('-','_')][temp['isdata']=='simulation']['q50'].values all_data[dp].q95[comp] = temp[temp['variable'] == comp + dp.replace('-','_')][temp['isdata']=='simulation']['q95'].values all_data['Ouest'].q05['cases'][:datetime.date(2017,6,10)] = np.nan all_data['Ouest'].q50['cases'][:datetime.date(2017,6,10)] = np.nan all_data['Ouest'].q95['cases'][:datetime.date(2017,6,10)] = np.nan print ("Finished run of scenario " + scenario_str) # Save results dir_name = 'output/Results/' + scenario_str + '/' try: os.makedirs(dir_name) print("Directory " , dir_name , " Created ") except FileExistsError: print("Directory " , dir_name , " already exists, writing into.") save_result(all_data, scenario_str, folder_name = dir_name) # Do figure ti = input_parameters['t_start'] tf = t_for fig, axes = plt.subplots((len(all_data))//2, 2, figsize=(15,15), squeeze = True, dpi = 200) fig.patch.set_facecolor('white') axes = axes.flat for i, dp in enumerate(departements): axt = axes[i].twinx() axes[i].plot(cases[dp][t_start:][ti:tf], marker='.', linestyle='-',color='black', linewidth=0, markersize=3 ) axes[i].fill_between(all_data[dp].q05['cases'][ti:tf].index, all_data[dp].q05['cases'][ti:tf], all_data[dp].q95['cases'][ti:tf], alpha = .5, color = 'darkblue', linewidth = 0) axes[i].plot(all_data[dp].q50['cases'][ti:tf], alpha = 1,linestyle='-', linewidth = 2, color = 'darkblue') axt.bar(pd.date_range(ti,tf, freq='W-SAT').date, rain[dp].resample('W-SAT').sum()[ti:tf], label = r'Rainfall', color = 'darkblue', width=7, alpha = 1) axes[i].set_title(dp) axes[i].set_ylim(0, 500) axt.set_ylim(1000, 0) #axt.set_ylim(4*max(rain[dp].resample('W-SAT').sum()[t_start:t_for]),0) # check if only reverse y axes[i].set_xlim(ti, tf) if i%5 == 4: axt.set_ylabel('Rainfall [mm/week]') axes[i].get_yaxis().set_visible(False) elif i%5 == 0: axes[i].set_ylabel('Reported cholera cases') if i%5 != 4: axt.get_yaxis().set_visible(False) if (dp not in scenario.not_dep) and (scenario_str != 'S0'): # convert to matplotlib date representation start = mdates.date2num(scenario.t_vacc_start[dp]) end = mdates.date2num(scenario.t_vacc_end[dp]) width = end - start rect = Rectangle((start, 0), width, 1000, color='orange', alpha= 0.1) axes[i].add_patch(rect) axes[i].add_artist(rect) rx, ry = rect.get_xy() for ax in axes: ax.label_outer() fig.autofmt_xdate() fig.tight_layout() plt.savefig('output/Results/' + scenario_str + '.png', bbox_inches='tight')
def plot_peptides(pm, ax, wrap=None, color=True, labels=False, cbar=False, intervals='corrected', cmap='jet', **kwargs): """ TODO: needs to be checked if intervals (start, end) are still accurately taking inclusive, exclusive into account Plots peptides as rectangles in the provided axes Parameters ---------- pm wrap ax color labels cmap kwargs Returns ------- """ wrap = wrap or autowrap(pm.data['start'], pm.data['end']) rect_kwargs = {'linewidth': 1, 'linestyle': '-', 'edgecolor': 'k'} rect_kwargs.update(kwargs) cmap = mpl.cm.get_cmap(cmap) norm = mpl.colors.Normalize(vmin=0, vmax=1) i = -1 for p_num, e in enumerate(pm.data): if i < -wrap: i = -1 if color: c = cmap(norm(e['rfu'])) else: c = '#707070' if intervals == 'corrected': start, end = 'start', 'end' elif intervals == 'original': start, end = '_start', '_end' else: raise ValueError( f"Invalid value '{intervals}' for keyword 'intervals', options are 'corrected' or 'original'" ) width = e[end] - e[start] rect = Rectangle((e[start] - 0.5, i), width, 1, facecolor=c, **rect_kwargs) ax.add_patch(rect) if labels: rx, ry = rect.get_xy() cy = ry cx = rx ax.annotate(str(p_num), (cx, cy), color='k', fontsize=6, va='bottom', ha='right') i -= 1 if cbar: scalar_mappable = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) plt.colorbar(scalar_mappable, label='Percentage D') ax.set_ylim(-wrap, 0) end = pm.interval[1] ax.set_xlim(0, end) ax.set_yticks([])
class RectangleInteractor(QObject): epsilon = 5 showverts = True mySignal = pyqtSignal(str) modSignal = pyqtSignal(str) def __init__(self,ax,corner,width,height=None,angle=0.): super().__init__() from matplotlib.patches import Rectangle from matplotlib.lines import Line2D # from matplotlib.artist import Artist # To avoid crashing with maximum recursion depth exceeded import sys sys.setrecursionlimit(10000) # 10000 is 10x the default value if height is None: self.type = 'Square' height = width else: self.type = 'Rectangle' self.ax = ax self.angle = angle/180.*np.pi self.width = width self.height = height self.rect = Rectangle(corner,width,height,edgecolor='Lime',facecolor='none',angle=angle,fill=False,animated=True) self.ax.add_patch(self.rect) self.canvas = self.rect.figure.canvas x,y = self.compute_markers() self.line = Line2D(x, y, marker='o', linestyle=None, linewidth=0., markerfacecolor='g', animated=True) self.ax.add_line(self.line) self.cid = self.rect.add_callback(self.rectangle_changed) self._ind = None # the active point self.connect() self.aperture = self.rect self.press = None self.lock = None def compute_markers(self): theta0 = self.rect.angle / 180.*np.pi w0 = self.rect.get_width() h0 = self.rect.get_height() x0,y0 = self.rect.get_xy() c, s = np.cos(-theta0), np.sin(-theta0) R = np.matrix('{} {}; {} {}'.format(c, s, -s, c)) x = [0.5*w0, w0, 0.5*w0] y = [0.5*h0, 0.5*h0, h0] self.xy = [] x_ = [] y_ = [] for dx,dy in zip(x,y): (dx_,dy_), = np.array(np.dot(R,np.array([dx,dy]))) self.xy.append((dx_+x0,dy_+y0)) x_.append(dx_+x0) y_.append(dy_+y0) return x_,y_ def connect(self): self.cid_draw = self.canvas.mpl_connect('draw_event', self.draw_callback) self.cid_press = self.canvas.mpl_connect('button_press_event', self.button_press_callback) self.cid_release = self.canvas.mpl_connect('button_release_event', self.button_release_callback) self.cid_motion = self.canvas.mpl_connect('motion_notify_event', self.motion_notify_callback) self.cid_key = self.canvas.mpl_connect('key_press_event', self.key_press_callback) self.canvas.draw_idle() def disconnect(self): self.canvas.mpl_disconnect(self.cid_draw) self.canvas.mpl_disconnect(self.cid_press) self.canvas.mpl_disconnect(self.cid_release) self.canvas.mpl_disconnect(self.cid_motion) self.canvas.mpl_disconnect(self.cid_key) self.rect.remove() self.line.remove() self.canvas.draw_idle() self.aperture = None def draw_callback(self, event): self.background = self.canvas.copy_from_bbox(self.ax.bbox) self.ax.draw_artist(self.rect) self.ax.draw_artist(self.line) def rectangle_changed(self, rect): 'this method is called whenever the polygon object is called' # only copy the artist props to the line (except visibility) vis = self.line.get_visible() Artist.update_from(self.line, rect) self.line.set_visible(vis) def get_ind_under_point(self, event): 'get the index of the point if within epsilon tolerance' x, y = zip(*self.xy) d = np.hypot(x - event.xdata, y - event.ydata) indseq, = np.nonzero(d == d.min()) ind = indseq[0] if d[ind] >= self.epsilon: ind = None return ind def button_press_callback(self, event): 'whenever a mouse button is pressed' if not self.showverts: return if event.inaxes is None: return if event.button != 1: return self._ind = self.get_ind_under_point(event) x0, y0 = self.rect.get_xy() w0, h0 = self.rect.get_width(), self.rect.get_height() theta0 = self.rect.angle/180*np.pi self.press = x0, y0, w0, h0, theta0, event.xdata, event.ydata self.xy0 = self.xy self.lock = "pressed" def key_press_callback(self, event): 'whenever a key is pressed' if not event.inaxes: return if event.key == 't': self.showverts = not self.showverts self.line.set_visible(self.showverts) if not self.showverts: self._ind = None elif event.key == 'd': #self.disconnect() #self.rect = None #self.line = None self.mySignal.emit('rectangle deleted') self.canvas.draw_idle() def button_release_callback(self, event): 'whenever a mouse button is released' if not self.showverts: return if event.button != 1: return self._ind = None self.press = None self.lock = "released" self.background = None # To get other aperture redrawn self.canvas.draw_idle() def motion_notify_callback(self, event): 'on mouse movement' if not self.showverts: return if self._ind is None: return if event.inaxes is None: return if event.button != 1: return x0, y0, w0, h0, theta0, xpress, ypress = self.press self.dx = event.xdata - xpress self.dy = event.ydata - ypress self.update_rectangle() # Redraw rectangle and points self.canvas.restore_region(self.background) self.ax.draw_artist(self.rect) self.ax.draw_artist(self.line) self.canvas.update() self.canvas.flush_events() # Notify callback self.modSignal.emit('rectangle modified') def update_rectangle(self): x0, y0, w0, h0, theta0, xpress, ypress = self.press dx, dy = self.dx, self.dy if self.lock == "pressed": if self._ind == 0: self.lock = "move" else: self.lock = "resizerotate" elif self.lock == "move": if x0+dx < 0: xn = x0 dx = 0 else: xn = x0+dx if y0+dy < 0: yn = y0 dy = 0 else: yn = y0+dy self.rect.set_xy((xn,yn)) # update line self.xy = [(i+dx,j+dy) for (i,j) in self.xy0] # Redefine line self.line.set_data(zip(*self.xy)) # otherwise rotate and resize elif self.lock == 'resizerotate': xc,yc = self.xy0[0] # center is conserved in the markers dtheta = np.arctan2(ypress+dy-yc,xpress+dx-xc)-np.arctan2(ypress-yc,xpress-xc) theta_ = (theta0+dtheta) * 180./np.pi c, s = np.cos(theta0), np.sin(theta0) R = np.matrix('{} {}; {} {}'.format(c, s, -s, c)) (dx_,dy_), = np.array(np.dot(R,np.array([dx,dy]))) # Avoid to pass through the center if self._ind == 1: w_ = w0+2*dx_ if (w0+2*dx_) > 0 else w0 if self.type == 'Square': h_ = w_ else: h_ = h0 elif self._ind == 2: h_ = h0+2*dy_ if (h0+2*dy_) > 0 else h0 if self.type == 'Square': w_ = h_ else: w_ = w0 # update rectangle self.rect.set_width(w_) self.rect.set_height(h_) self.rect.angle = theta_ # update markers self.updateMarkers() def updateMarkers(self): # update points x,y = self.compute_markers() self.line.set_data(x,y)
def handle_event(): global command global command_meta global main_pic global history global patch global patches global click_handlers global G if command=="horizontal_line" or command=="vertical_line": h,w = main_pic.shape[:2] if patch is not None: w1,h1 = patch.get_xy() if command=="horizontal_line": line = Line(0,int(h1),w,int(h1), int(patch.get_height()), magenta) else: line = Line(int(w1),0,int(w1),h, int(patch.get_width()), magenta) main_pic = draw_line_on_picture(main_pic, line) patch=None else: if command=="horizontal_line": patch = Rectangle((0,0), w, 1, edgecolor='magenta', alpha=1) else: patch = Rectangle((0,0), 1, h, edgecolor='magenta', alpha=1) if command=="needle" or command=="angle_needle": G["needle"]["active"] = True just_added_patch = False if "pt1" in G["needle"] and "pt2" in G["needle"]: if patch is None: print "Drawing needle patch" pt1 = G["needle"]["pt1"] pt2 = G["needle"]["pt2"] if command=="needle": patch = Rectangle((pt1[0], pt1[1]), abs(pt2[0]-pt1[0]), abs(pt2[1]-pt1[1]), edgecolor='magenta', alpha=1, facecolor='magenta') else: patch = Polygon(np.array([pt1, pt2, p(pt1), p(pt2)]), closed=False, edgecolor='magenta', alpha=1, facecolor='magenta') angle = get_angle(pt1, pt2) print ("Angle :{}".format(angle)) # how to add text? just_added_patch = True if patch is not None and not just_added_patch: if isinstance(patch, Polygon): patches.append(patch) patch=None else: print "finalize" w1,h1 = patch.get_xy() w = patch.get_width() h = patch.get_height() if w>h: print("horizontal patch") line = Line(int(w1),int(h1),int(w1+w),int(h1), 3, magenta) else: line = Line(int(w1),int(h1),int(w1),int(h1+h), 3, magenta) main_pic = draw_line_on_picture(main_pic, line) G["needle"] = {} if command == "divide": divide(command_meta.xdata, command_meta.ydata) if command == "brighten": main_pic = do_brighten(main_pic) if command == "mirror": main_pic = np.fliplr(main_pic) if command == "zoom": click_handlers = not click_handlers if command == "darken": main_pic = do_darken(main_pic) if command == "edge": main_pic = edge_detect(main_pic) if command == "resize_patch": if patch is not None: h = patch.get_height() w = patch.get_width() patch.set_width(int(w * 0.9)) patch.set_height(int(h * 0.9)) if command == "crop": if patch is not None: # apply patch # crop main_pic h = patch.get_height() w = patch.get_width() w1,h1 = patch.get_xy() main_pic = main_pic[slice(h1,h1+h),slice(w1,w1+w),slice(None)] patch=None else: # create patch # TODO: can read this from settings :)) portrait_ratio = 14.8/20.8 if orientation=="portrait": w_to_h = portrait_ratio else: w_to_h = 1.0/portrait_ratio shape = main_pic.shape border = 15 hp = shape[0] - border wp = shape[1] - border if w_to_h * hp >wp: tw = wp th = wp / w_to_h else: th = hp tw = w_to_h * hp print th,tw patch = Rectangle((0,0), tw, th, edgecolor='magenta', alpha=1, facecolor='none') if command == "undo": print "Undoing" print len(history) if len(history)>=2: main_pic,cmd = history[-2] print cmd history = history[:-1] if command!="undo": history.append((np.copy(main_pic),command)) if command not in ["crop","horizontal_line","vertical_line","needle","angle_needle","resize_patch"]: patch = None command = None command_meta = None plot(patch=patch, click_handlers=click_handlers) if command is not None: handle_event()
class PixelInteractor(QObject): epsilon = 10 showverts = True mySignal = pyqtSignal(str) modSignal = pyqtSignal(str) def __init__(self,ax,corner,width,angle=0.): super().__init__() from matplotlib.patches import Rectangle from matplotlib.lines import Line2D # from matplotlib.artist import Artist # To avoid crashing with maximum recursion depth exceeded import sys sys.setrecursionlimit(10000) # 10000 is 10x the default value self.type = 'Pixel' height = width self.ax = ax self.angle = angle self.width = width self.height = width # print('corner is ', corner) self.rect = Rectangle(corner,width,height,edgecolor='Lime',facecolor='none',angle=angle,fill=False,animated=True) self.ax.add_patch(self.rect) self.canvas = self.rect.figure.canvas x,y = self.compute_markers() self.line = Line2D(x, y, marker='s', linestyle=None, linewidth=0., markerfacecolor='g', animated=True) self.ax.add_line(self.line) self.cid = self.rect.add_callback(self.rectangle_changed) self._ind = None # the active point self.connect() self.aperture = self.rect self.press = None self.lock = None def compute_markers(self): # theta0 = self.rect.angle / 180.*np.pi w0 = self.rect.get_width() # h0 = self.rect.get_height() x0,y0 = self.rect.get_xy() angle0 = self.rect.angle x = [x0+w0/np.sqrt(2.)*np.sin((45.-angle0)*np.pi/180.)] y = [y0+w0/np.sqrt(2.)*np.cos((45.-angle0)*np.pi/180.)] self.xy = [(x,y)] return x, y def connect(self): self.cid_draw = self.canvas.mpl_connect('draw_event', self.draw_callback) self.cid_press = self.canvas.mpl_connect('button_press_event', self.button_press_callback) self.cid_release = self.canvas.mpl_connect('button_release_event', self.button_release_callback) self.cid_motion = self.canvas.mpl_connect('motion_notify_event', self.motion_notify_callback) self.cid_key = self.canvas.mpl_connect('key_press_event', self.key_press_callback) self.canvas.draw_idle() def disconnect(self): self.canvas.mpl_disconnect(self.cid_draw) self.canvas.mpl_disconnect(self.cid_press) self.canvas.mpl_disconnect(self.cid_release) self.canvas.mpl_disconnect(self.cid_motion) self.canvas.mpl_disconnect(self.cid_key) self.rect.remove() self.line.remove() self.canvas.draw_idle() self.aperture = None def draw_callback(self, event): self.background = self.canvas.copy_from_bbox(self.ax.bbox) self.ax.draw_artist(self.rect) self.ax.draw_artist(self.line) def rectangle_changed(self, rect): 'this method is called whenever the polygon object is called' # only copy the artist props to the line (except visibility) vis = self.line.get_visible() Artist.update_from(self.line, rect) self.line.set_visible(vis) def get_ind_under_point(self, event): 'get the index of the point if within epsilon tolerance' x, y = self.xy[0] d = np.hypot(x - event.xdata, y - event.ydata) if d >= self.epsilon: ind = None else: ind = 0 return ind def button_press_callback(self, event): 'whenever a mouse button is pressed' if not self.showverts: return if event.inaxes is None: return if event.button != 1: return self._ind = self.get_ind_under_point(event) x0, y0 = self.rect.get_xy() w0, h0 = self.rect.get_width(), self.rect.get_height() theta0 = self.rect.angle/180*np.pi self.press = x0, y0, w0, h0, theta0, event.xdata, event.ydata self.xy0 = self.xy self.lock = "pressed" def key_press_callback(self, event): 'whenever a key is pressed' if not event.inaxes: return if event.key == 't': self.showverts = not self.showverts self.line.set_visible(self.showverts) if not self.showverts: self._ind = None elif event.key == 'd': self.mySignal.emit('rectangle deleted') self.canvas.draw_idle() def button_release_callback(self, event): 'whenever a mouse button is released' if not self.showverts: return if event.button != 1: return self._ind = None self.press = None self.lock = "released" self.background = None # To get other aperture redrawn self.canvas.draw_idle() def motion_notify_callback(self, event): 'on mouse movement' if not self.showverts: return if self._ind is None: return if event.inaxes is None: return if event.button != 1: return x0, y0, w0, h0, theta0, xpress, ypress = self.press self.dx = event.xdata - xpress self.dy = event.ydata - ypress self.update_rectangle() # Redraw rectangle and points self.canvas.restore_region(self.background) self.ax.draw_artist(self.rect) self.ax.draw_artist(self.line) self.canvas.update() self.canvas.flush_events() # alternative (slower) # self.canvas.draw_idle() # Notify callback self.modSignal.emit('rectangle modified') def update_rectangle(self): x0, y0, w0, h0, theta0, xpress, ypress = self.press dx, dy = self.dx, self.dy if self.lock == "pressed": self.lock = "move" elif self.lock == "move": if x0+dx < 0: xn = x0 dx = 0 else: xn = x0+dx if y0+dy < 0: yn = y0 dy = 0 else: yn = y0+dy self.rect.set_xy((xn,yn)) # update line self.xy = [(i+dx,j+dy) for (i,j) in self.xy0] # Redefine line self.line.set_data(zip(*self.xy)) self.updateMarkers() def updateMarkers(self): # update points x,y = self.compute_markers() self.line.set_data(x,y)
def get_xy(self): xy = Rectangle.get_xy(self) return xy[0] + self.d / 2, xy[1] + self.d / 2
class usb1Windows(QWidget): def __del__(self): if hasattr(self, "camera"): self.camera.release() # 释放资源 def init_fun(self): self.window = Ui_Form() self.window.setupUi(self) self.timer = QTimer() # 定义一个定时器对象 self.timer.timeout.connect(self.timer_fun) #计时结束调用方法 # 1. open usb and show self.window.pushButton_2.clicked.connect(self.timer_start) # 2. catch one picture self.window.pushButton.clicked.connect(self.catch_picture) self.window.comboBox.currentIndexChanged.connect( self.set_width_and_height) self.window.checkBox.clicked.connect(self.get_faces_flag_fun) self.window.pushButton_5.clicked.connect(self.preview_picture) self.window.pushButton_4.clicked.connect(self.save_picture) self.window.pic_figure.canvas.mpl_connect('button_press_event', self.on_press) self.window.pic_figure.canvas.mpl_connect('button_release_event', self.on_release) self.getface_flag = False fm = open("./identiffun/faces.conf", 'r') self.names = fm.read().split(";") fm.close() self.my_get_face = Get_Faces(self.names) def on_press(self, event): self.on_x0 = event.xdata self.on_y0 = event.ydata if not hasattr(self, "rectload"): self.rectload = Rectangle((0, 0), 0, 0, linestyle='solid', fill=False, edgecolor='red') self.window.pic_figaxes.add_patch(self.rectload) def on_release(self, event): self.on_x1 = event.xdata self.on_y1 = event.ydata x_start = int(min(self.on_x0, self.on_x1)) x_end = int(max(self.on_x0, self.on_x1)) y_start = int(min(self.on_y0, self.on_y1)) y_end = int(max(self.on_y0, self.on_y1)) self.rectload.set_xy((x_start, y_start)) self.rectload.set_height(y_end - y_start + 1) self.rectload.set_width(x_end - x_start + 1) self.window.pic_figaxes.figure.canvas.draw() def save_picture(self): if hasattr(self, 'preview_res'): tmp_save_picture = self.preview_res else: if hasattr(self, 'raw_frame'): tmp_save_picture = self.raw_frame else: return # no pic cv2.imwrite("./image/save.jpg", tmp_save_picture) if hasattr(self, "rectload"): x, y = self.rectload.get_xy() w = self.rectload.get_width() h = self.rectload.get_height() cv2.imwrite("./image/ret.jpg", tmp_save_picture[y:y + h, x:x + w]) # filename, filetype = QFileDialog.getSaveFileName(self, "save", "jpg Files(*.jpg)::All Files(*)") # if filename: # cv2.imwrite(filename, tmp_save_picture) def preview_picture(self): if hasattr(self, 'raw_frame'): width = self.window.spinBox.value() height = self.window.spinBox_2.value() # self.raw_frame.reszie((width, height)) self.preview_res = cv2.resize(self.raw_frame, (width, height), interpolation=cv2.INTER_CUBIC) self.showimg2figaxes2(self.preview_res) def get_faces_flag_fun(self): if self.window.checkBox.isChecked(): self.getface_flag = True else: self.getface_flag = False # print(self.getface_flag) def set_width_and_height(self): # print(self.window.comboBox.currentText()) width, height = self.window.comboBox.currentText().split('*') if hasattr(self, "camera"): self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, int(width)) self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, int(height)) def catch_picture(self): if hasattr(self, "camera") and self.camera.isOpened(): ret, frame = self.camera.read() if ret: self.raw_frame = copy.deepcopy(frame) if hasattr(self, 'preview_res'): del self.preview_res self.showimg2figaxes2(frame) else: pass # get faild def timer_fun(self): ret, frame = self.camera.read() if ret: self.showimg2figaxes(frame) else: self.timer.stop() def timer_start(self): if hasattr(self, "camera"): if not self.camera.isOpened(): self.camera.open(0) # self.camera = cv2.VideoCapture(0) else: self.camera = cv2.VideoCapture(0) if self.camera.isOpened(): pass else: self.camera.open(0) # get width = self.camera.get(cv2.CAP_PROP_FRAME_WIDTH) print(width) height = self.camera.get(cv2.CAP_PROP_FRAME_HEIGHT) print(int(height)) self.window.comboBox.setCurrentText("%d*%d" % (int(width), int(height))) fps = self.camera.get(cv2.CAP_PROP_FPS) if fps == float('inf'): pass else: print(fps) brightness = self.camera.get(cv2.CAP_PROP_BRIGHTNESS) if brightness == float('inf'): self.window.doubleSpinBox_2.setValue(0.0) else: self.window.doubleSpinBox_2.setValue(brightness) contrast = self.camera.get(cv2.CAP_PROP_CONTRAST) if contrast == float('inf'): self.window.doubleSpinBox.setValue(0.0) else: self.window.doubleSpinBox.setValue(contrast) hue = self.camera.get(cv2.CAP_PROP_HUE) if hue == float('inf'): self.window.doubleSpinBox_3.setValue(0.0) else: self.window.doubleSpinBox_3.setValue(hue) exposure = self.camera.get(cv2.CAP_PROP_EXPOSURE) if exposure == float('inf'): self.window.doubleSpinBox_4.setValue(0.0) else: self.window.doubleSpinBox_4.setValue(exposure) # inf saturation = self.camera.get(cv2.CAP_PROP_SATURATION) if saturation == float('inf'): self.window.doubleSpinBox_5.setValue(0.0) else: self.window.doubleSpinBox_5.setValue(saturation) # inf self.timer.start(101) #设置计时间隔并启动 def showimg2figaxes2(self, frame): b, g, r = cv2.split(frame) imgret = cv2.merge([r, g, b]) if hasattr(self, "rectload"): self.rectload.remove() del self.rectload self.window.pic_figaxes.clear() self.window.pic_figaxes.imshow(imgret) self.window.pic_figure.canvas.draw() def showimg2figaxes(self, img): if self.getface_flag: tmp_img = self.my_get_face.get_face_fun(img) else: tmp_img = img b, g, r = cv2.split(tmp_img) imgret = cv2.merge([r, g, b]) # 这个就是前面说书的,OpenCV和matplotlib显示不一样,需要转换 self.window.video_figaxes.clear() self.window.video_figaxes.imshow(imgret) self.window.video_figure.canvas.draw()
class InteractiveCanvas(FigureCanvas): """An interactive matplotlib figure that allows for the plotting of data on a log-log axis with interactive matplotlib.patches.Rectangle drawing """ def __init__(self, xdata, ydata, parent=None, xlabel='x label', ylabel='y label', linestyle='--', marker='o', dpi=150, hold=False, alpha=0.5, colors=None): """Initialization method. Executes every time initialization occurs Parameters ---------- xdata: `np.array.float64` Array of the input data to be plotted on the x-axis ydata: np.array.float64 Array of the input data to be plotted on the y-axis parent: None Parent object of the class xlabel: str Label for the x-axis of the plot ylabel: str Label for the y-axis of the plot linestyle: str Matplotlib linestyle to be used to draw the line on the graph marker: str Matplotlib marker type to be used to draw the points on the graph dpi: int Dots per inch of the desired figure hold: bool Boolean that desides whether or not the plot should hold on the axes during instantiation/drawing alpha: float Transparency level of the rectangles that are drawn onto the figure canvas colors: list List of matplotlib acceptable color keys to be used in generation of the rectangles. Typically matches the table rows Notes ----- This class implements the matplotlib Qt5 backend to allow for insertion of the resultant figure into a Qt application. The class allows for interactive generation of rectangles over a log/log axes plot. """ # Save figure input parameters as class properties self.xdata = xdata self.ydata = ydata self.xlabel = xlabel self.ylabel = ylabel self.linestyle = linestyle self.marker = marker self.dpi = dpi self.hold = hold self.alpha = alpha self.colors = colors # Initialize empty list to store mpl rectangles and their coordinates self.rectCoordinates = [] self.mplRectangles = [] # Initialize a figure, axis, and axes self.fig = Figure(dpi=self.dpi) self.ax = plt.gca() self.ax.set_xlabel(xlabel) self.ax.set_ylabel(ylabel) self.axes = self.fig.add_subplot(111) self.axes.hold(self.hold) # Initialize a FigureCanvas from the figure FigureCanvas.__init__(self, self.fig) self.setParent(self.ax.figure.canvas) self.initFigure(self.xdata, self.ydata) # Allow the FigureCanvas to adjust with Main window using mpl Qt5 API FigureCanvas.setSizePolicy( self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) # Connect the mouse/trackpad to the FigureCanvas self.ax.figure.canvas.mpl_connect( 'button_press_event', self.onPress) self.ax.figure.canvas.mpl_connect( 'button_release_event', self.onRelease) # Super from the class for Qt super(InteractiveCanvas, self).__init__(self.fig) def initFigure(self, xdata, ydata): """Initialize the figure Parameters ---------- xdata: `np.array` A flat numpy array of x values for the plot ydata: `np.array` A flat numpy array of y values for the plot Notes ----- The plot will not have a tight layout until data has been passed in. This is currently the source of the semi-unsightly bug of misaligned axes on start up. Plotting the data "fixes" the bug. """ if xdata is None or ydata is None: return # Currently ydata is longer than xdata with schlumberger, so handle # that if it makes it this far into the program if len(xdata) != len(ydata): if len(ydata) > len(xdata): xdata = xdata[:len(ydata)] else: ydata = ydata[:len(xdata)] # Set up an empty rectangle for drawing and plot the x/y data self.rect = Rectangle( (0, 0), 0, 0, alpha=self.alpha, color='grey') self.addPointsAndLine(xdata, ydata, draw=False) # Create an mpl axis and set the labels, add the rectangle self.ax = plt.gca() self.ax.set_xlabel(self.xlabel) self.ax.set_ylabel(self.ylabel) self.ax.add_patch(self.rect) self.ax.figure.canvas.draw() # Draw extant rectangles if applicable if self.mplRectangles: self.drawRectangles() # Update the figure object/property self.fig = plt.gcf() self.fig.tight_layout() def drawRectangles(self): """Adds rectangles to the plot if they are currently stored""" # Iterate through the mpl Rectangles to draw them with the proper color for i, rectangle in enumerate(self.rectCoordinates): color = self.colors[i * 4] xy, width, height = rectangle rect = Rectangle( xy, width, height, alpha=self.alpha, color=color) self.ax.add_patch(rect) def addPointsAndLine(self, xdata, ydata, color='#003366', draw=True): """Adds the points and a line to the figure Parameters ---------- xdata: `np.array` A flat numpy array of x values for the plot ydata: `np.array` A flat numpy array of y values for the plot color: str Hex code or other matplotlib accepted color key for the points/line draw: bool If True, the plot will be drawn. If False, it will not. Mainly a product of the test code """ # Currently ydata is longer than xdata with schlumberger, so handle # that if it makes it this far into the program if len(xdata) != len(ydata): if len(ydata) > len(xdata): xdata = xdata[:len(ydata)] else: ydata = ydata[:len(xdata)] # log/log plot of x and y data plt.loglog( xdata, ydata, linestyle=self.linestyle, marker=self.marker, color=color) # Draw the updates if draw: self.fig.tight_layout() self.ax.figure.canvas.draw() def onPress(self, event): """Handle mouse press events on the matplotlib figure cavas Parameters ---------- event: matplotlib.event The matplotlib event definition. In this case, a mouse click. """ self.x0 = event.xdata self.y0 = event.ydata def onRelease(self, event): """Handles release of mouse button events on the matplotlib canvas Parameters ---------- event: matplotlib.event The matplotlib event definition. In this case, a mouse release. """ try: self.x1 = event.xdata self.y1 = event.ydata # Create a rectangle on the plot self.rect.set_width(self.x1 - self.x0) self.rect.set_height(self.y1 - self.y0) self.rect.set_xy((self.x0, self.y0)) self.ax.figure.canvas.draw() # Store and return the rectangle attributes as a tuple self.rectxy = ( self.rect.get_xy(), self.rect._width, self.rect._height) return self.rectxy except TypeError: pass
def handle_event(): global command global command_meta global main_pic global history global patch global patches global click_handlers global G if command == "horizontal_line" or command == "vertical_line": h, w = main_pic.shape[:2] if patch is not None: w1, h1 = patch.get_xy() if command == "horizontal_line": line = Line(0, int(h1), w, int(h1), int(patch.get_height()), magenta) else: line = Line(int(w1), 0, int(w1), h, int(patch.get_width()), magenta) main_pic = draw_line_on_picture(main_pic, line) patch = None else: if command == "horizontal_line": patch = Rectangle((0, 0), w, 1, edgecolor='magenta', alpha=1) else: patch = Rectangle((0, 0), 1, h, edgecolor='magenta', alpha=1) if command == "needle" or command == "angle_needle": G["needle"]["active"] = True just_added_patch = False if "pt1" in G["needle"] and "pt2" in G["needle"]: if patch is None: print "Drawing needle patch" pt1 = G["needle"]["pt1"] pt2 = G["needle"]["pt2"] if command == "needle": patch = Rectangle((pt1[0], pt1[1]), abs(pt2[0] - pt1[0]), abs(pt2[1] - pt1[1]), edgecolor='magenta', alpha=1, facecolor='magenta') else: patch = Polygon(np.array([pt1, pt2, p(pt1), p(pt2)]), closed=False, edgecolor='magenta', alpha=1, facecolor='magenta') angle = get_angle(pt1, pt2) print("Angle :{}".format(angle)) # how to add text? just_added_patch = True if patch is not None and not just_added_patch: if isinstance(patch, Polygon): patches.append(patch) patch = None else: print "finalize" w1, h1 = patch.get_xy() w = patch.get_width() h = patch.get_height() if w > h: print("horizontal patch") line = Line(int(w1), int(h1), int(w1 + w), int(h1), 3, magenta) else: line = Line(int(w1), int(h1), int(w1), int(h1 + h), 3, magenta) main_pic = draw_line_on_picture(main_pic, line) G["needle"] = {} if command == "divide": divide(command_meta.xdata, command_meta.ydata) if command == "brighten": main_pic = do_brighten(main_pic) if command == "mirror": main_pic = np.fliplr(main_pic) if command == "zoom": click_handlers = not click_handlers if command == "darken": main_pic = do_darken(main_pic) if command == "edge": main_pic = edge_detect(main_pic) if command == "resize_patch": if patch is not None: h = patch.get_height() w = patch.get_width() patch.set_width(int(w * 0.9)) patch.set_height(int(h * 0.9)) if command == "crop": if patch is not None: # apply patch # crop main_pic h = patch.get_height() w = patch.get_width() w1, h1 = patch.get_xy() main_pic = main_pic[slice(h1, h1 + h), slice(w1, w1 + w), slice(None)] patch = None else: # create patch # TODO: can read this from settings :)) portrait_ratio = 14.8 / 20.8 if orientation == "portrait": w_to_h = portrait_ratio else: w_to_h = 1.0 / portrait_ratio shape = main_pic.shape border = 15 hp = shape[0] - border wp = shape[1] - border if w_to_h * hp > wp: tw = wp th = wp / w_to_h else: th = hp tw = w_to_h * hp print th, tw patch = Rectangle((0, 0), tw, th, edgecolor='magenta', alpha=1, facecolor='none') if command == "undo": print "Undoing" print len(history) if len(history) >= 2: main_pic, cmd = history[-2] print cmd history = history[:-1] if command != "undo": history.append((np.copy(main_pic), command)) if command not in [ "crop", "horizontal_line", "vertical_line", "needle", "angle_needle", "resize_patch" ]: patch = None command = None command_meta = None plot(patch=patch, click_handlers=click_handlers) if command is not None: handle_event()