Python matplotlib.patches.Rectangle() Examples
The following are 30
code examples of matplotlib.patches.Rectangle().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.patches
, or try the search function
.
Example #1
Source File: mpl_gui_selection.py From FRETBursts with GNU General Public License v2.0 | 6 votes |
def on_press(event): if event.inaxes != GSel.ax: return GSel.pressed = True GSel.xs, GSel.ys = event.xdata, event.ydata #print 'PRESS button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % ( # event.button, event.x, event.y, event.xdata, event.ydata) if hasattr(GSel, 'r'): GSel.r.set_height(0); GSel.r.set_width(0) GSel.r.set_xy((GSel.xs,GSel.ys)) GSel.e.height = 0; GSel.e.width = 0 GSel.e.center = (GSel.xs,GSel.ys) else: GSel.r = Rectangle(xy=(GSel.xs,GSel.ys), height=0, width=0, fill=False, lw=2, alpha=0.6, color='blue') GSel.e = Ellipse(xy=(GSel.xs,GSel.ys), height=0, width=0, fill=False, lw=2, alpha=0.6, color='blue') GSel.ax.add_artist(GSel.r) GSel.r.set_clip_box(GSel.ax.bbox); GSel.r.set_zorder(10) GSel.ax.add_artist(GSel.e) GSel.e.set_clip_box(GSel.ax.bbox); GSel.e.set_zorder(10) GSel.fig.canvas.draw() GSel.id_motion = GSel.fig.canvas.mpl_connect('motion_notify_event', on_motion)
Example #2
Source File: common_config.py From Datasets2Darknet with MIT License | 6 votes |
def show_img(img, object_lb_x1, object_lb_y1, object_width, object_height): fig, ax = plt.subplots(1) ax.imshow(img) rect = patches.Rectangle( (object_lb_x1, object_lb_y1), object_width, object_height, linewidth=1, edgecolor='r', facecolor='none' ) ax.add_patch(rect) plt.show() # CHeck for the case 3_11_20 is in 3_11_n # This method converts the specific obj_class to the common one # using traffic_sign_classes data structure.
Example #3
Source File: _base.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
def _gen_axes_patch(self): """ Returns ------- Patch The patch used to draw the background of the axes. It is also used as the clipping path for any data elements on the axes. In the standard axes, this is a rectangle, but in other projections it may not be. Notes ----- Intended to be overridden by new projection types. """ return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0)
Example #4
Source File: yolo_image.py From ai-platform with MIT License | 6 votes |
def draw_boxes(filename, v_boxes, v_labels, v_scores, output_photo_name): # load the image data = pyplot.imread(filename) # plot the image pyplot.imshow(data) # get the context for drawing boxes ax = pyplot.gca() # plot each box for i in range(len(v_boxes)): box = v_boxes[i] # get coordinates y1, x1, y2, x2 = box.ymin, box.xmin, box.ymax, box.xmax # calculate width and height of the box width, height = x2 - x1, y2 - y1 # create the shape rect = Rectangle((x1, y1), width, height, fill=False, color='white') # draw the box ax.add_patch(rect) # draw text and score in top left corner label = "%s (%.3f)" % (v_labels[i], v_scores[i]) pyplot.text(x1, y1, label, color='white') # show the plot #pyplot.show() pyplot.savefig(output_photo_name)
Example #5
Source File: segment_bbox_only.py From COCO-Style-Dataset-Generator-GUI with Apache License 2.0 | 6 votes |
def read_JSON_file(f): with open(f, 'r') as g: d = json.loads(g.read()) img_paths = [x['file_name'] for x in d['images']] rects = [{'bbox': x['segmentation'][0], 'class': x['category_id'], 'image_id': x['image_id']} for x in d['annotations']] annotations = defaultdict(list) for rect in rects: r = rect['bbox'] x0, y0 = min(r[0], r[2], r[4], r[6]), min(r[1], r[3], r[5], r[7]) x1, y1 = max(r[0], r[2], r[4], r[6]), max(r[1], r[3], r[5], r[7]) r = patches.Rectangle((x0,y0),x1-x0,y1-y0,linewidth=1,edgecolor='g',facecolor='g', alpha=0.4) annotations[img_paths[rect['image_id']]].append({'bbox': r, 'cls': d['classes'][rect['class']-1]}) return d['classes'], img_paths, annotations
Example #6
Source File: plotter.py From quantumsim with GNU General Public License v3.0 | 6 votes |
def _plot_box_with_label(self, time_start, time_end, n_qubit_start, n_qubit_end, label, **kwargs): """ Parameters ---------- time_start : float time_end : float n_qubit_start : int n_qubit_end : int label : str kwargs """ box_y = n_qubit_start - 0.5 * _golden_mean box_dy = n_qubit_end - n_qubit_start + _golden_mean box_x = time_start + 0.5*self.gate_offset box_dx = time_end - time_start - self.gate_offset rect = Rectangle((box_x, box_y), box_dx, box_dy, **kwargs) self.ax.add_patch(rect) if label is not None: self.ax.text(box_x + 0.5 * box_dx, box_y + 0.5 * box_dy, label, ha='center', va='center', zorder=self.zorders['text'])
Example #7
Source File: anchored_artists.py From Computable with MIT License | 6 votes |
def __init__(self, transform, size, label, loc, pad=0.1, borderpad=0.1, sep=2, prop=None, frameon=True, **kwargs): """ Draw a horizontal bar with the size in data coordinate of the give axes. A label will be drawn underneath (center-aligned). pad, borderpad in fraction of the legend font size (or prop) sep in points. """ self.size_bar = AuxTransformBox(transform) self.size_bar.add_artist(Rectangle((0,0), size, 0, fc="none")) self.txt_label = TextArea(label, minimumdescent=False) self._box = VPacker(children=[self.size_bar, self.txt_label], align="center", pad=0, sep=sep) AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=self._box, prop=prop, frameon=frameon, **kwargs)
Example #8
Source File: gui_selection.py From FRETBursts with GNU General Public License v2.0 | 6 votes |
def on_press_draw(self): if 'r' in self.__dict__: self.r.set_height(0) self.r.set_width(0) self.r.set_xy((self.xs, self.ys)) self.e.height = 0 self.e.width = 0 self.e.center = (self.xs, self.ys) else: self.r = Rectangle(xy=(self.xs, self.ys), height=0, width=0, fill=False, lw=2, alpha=0.5, color='blue') self.e = Ellipse(xy=(self.xs, self.ys), height=0, width=0, fill=False, lw=2, alpha=0.6, color='blue') self.ax.add_artist(self.r) self.ax.add_artist(self.e) self.r.set_clip_box(self.ax.bbox) self.r.set_zorder(10) self.e.set_clip_box(self.ax.bbox) self.e.set_zorder(10)
Example #9
Source File: burst_plot.py From FRETBursts with GNU General Public License v2.0 | 6 votes |
def _plot_bursts(d, i, tmin_clk, tmax_clk, pmax=1e3, pmin=0, color="#999999", ytext=20): """Highlights bursts in a timetrace plot.""" b = d.mburst[i] if b.num_bursts == 0: return burst_mask = (tmin_clk < b.start) * (b.start < tmax_clk) bs = b[burst_mask] burst_indices = np.where(burst_mask)[0] start = bs.start * d.clk_p end = bs.stop * d.clk_p R = [] width = end - start ax = gca() for b, bidx, s, w, sign, va in zip(bs, burst_indices, start, width, cycle([-1, 1]), cycle(['top', 'bottom'])): r = Rectangle(xy=(s, pmin), height=pmax - pmin, width=w) r.set_clip_box(ax.bbox) r.set_zorder(0) R.append(r) ax.text(s, sign * ytext, _burst_info(d, i, bidx), fontsize=6, rotation=45, horizontalalignment='center', va=va) ax.add_artist(PatchCollection(R, lw=0, color=color))
Example #10
Source File: show_labels.py From 3d-vehicle-tracking with BSD 3-Clause "New" or "Revised" License | 6 votes |
def box2rect(self, box2d): """generate individual bounding box from label""" x1 = box2d['x1'] y1 = box2d['y1'] x2 = box2d['x2'] y2 = box2d['y2'] # Pick random color for each box box_color = random_color() # Draw and add one box to the figure return mpatches.Rectangle( (x1, y1), x2 - x1, y2 - y1, linewidth=3 * self.scale, edgecolor=box_color, facecolor='none', fill=False, alpha=0.75 )
Example #11
Source File: electrodes.py From pulse2percept with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, x, y, z): if isinstance(x, (Sequence, np.ndarray)): raise TypeError("x must be a scalar, not %s." % (type(x))) if isinstance(y, (Sequence, np.ndarray)): raise TypeError("y must be a scalar, not %s." % type(y)) if isinstance(z, (Sequence, np.ndarray)): raise TypeError("z must be a scalar, not %s." % type(z)) self.x = x self.y = y self.z = z # A matplotlib.patches object (e.g., Circle, Rectangle) that can be # used to plot the electrode: self.plot_patch = None # Any keyword arguments that should be passed to the call above: # (e.g., {'radius': 5}): self.plot_kwargs = {}
Example #12
Source File: test_electrodes.py From pulse2percept with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_SquareElectrode(): with pytest.raises(TypeError): SquareElectrode(0, 0, 0, [1, 2]) with pytest.raises(TypeError): SquareElectrode(0, np.array([0, 1]), 0, 1) # Invalid radius: with pytest.raises(ValueError): SquareElectrode(0, 0, 0, -5) # Check params: electrode = SquareElectrode(0, 1, 2, 100) npt.assert_almost_equal(electrode.x, 0) npt.assert_almost_equal(electrode.y, 1) npt.assert_almost_equal(electrode.z, 2) npt.assert_almost_equal(electrode.a, 100) # Slots: npt.assert_equal(hasattr(electrode, '__slots__'), True) npt.assert_equal(hasattr(electrode, '__dict__'), False) # Plots: ax = electrode.plot() npt.assert_equal(len(ax.texts), 0) npt.assert_equal(len(ax.patches), 1) npt.assert_equal(isinstance(ax.patches[0], Rectangle), True)
Example #13
Source File: utils.py From NeuralBabyTalk with MIT License | 5 votes |
def vis_detections(ax, class_name, dets, color_i, rest_flag=0): """Visual debugging of detections.""" bbox = tuple(int(np.round(x)) for x in dets[:4]) score = dets[-1] if rest_flag == 0: ax.add_patch( patches.Rectangle( (bbox[0], bbox[1]), bbox[2]-bbox[0], bbox[3]-bbox[1], fill=False, # remove background lw=3, color=color_pad[color_i] ) ) ax.text(bbox[0]+5, bbox[1] + 13, '%s' % (class_name) , fontsize=9, fontweight='bold', backgroundcolor=color_pad[color_i]) else: ax.add_patch( patches.Rectangle( (bbox[0], bbox[1]), bbox[2]-bbox[0], bbox[3]-bbox[1], fill=False, # remove background lw=2, color='grey' ) ) ax.text(bbox[0]+5, bbox[1] + 13, '%s' % (class_name) , fontsize=9, fontweight='bold', backgroundcolor='grey') return ax
Example #14
Source File: parse_svg.py From pylustrator with GNU General Public License v3.0 | 5 votes |
def patch_rect(node: minidom.Element, trans: mtransforms.Transform, style: dict, ids: dict) -> mpatches.Rectangle: """ draw a svg rectangle node as a rectangle patch element into the figure (with the given transformation and style) """ if node.getAttribute("d") != "": return patch_path(node, trans, style, ids) return mpatches.Rectangle(xy=(float(node.getAttribute("x")), float(node.getAttribute("y"))), width=float(node.getAttribute("width")), height=float(node.getAttribute("height")), transform=trans)
Example #15
Source File: gui_selection.py From FRETBursts with GNU General Public License v2.0 | 5 votes |
def on_press_draw(self): if 'r' in self.__dict__: self.r.set_width(0) self.r.set_xy((self.xs, self.ax.get_ylim()[0])) self.r.set_height(self.ax.get_ylim()[1] - self.ax.get_ylim()[0]) else: self.r = Rectangle(xy=(self.xs, self.ax.get_ylim()[0]), height=self.ax.get_ylim()[1] - \ self.ax.get_ylim()[0], width=0, fill=True, lw=2, alpha=0.5, color='blue') self.ax.add_artist(self.r) self.r.set_clip_box(self.ax.bbox) self.r.set_zorder(10)
Example #16
Source File: matplotlib_gui_select.py From FRETBursts with GNU General Public License v2.0 | 5 votes |
def on_press(event): global id_motion, xs, ys, r print 'INAXES: ', event.inaxes if event.inaxes!=ax: return xs, ys = event.xdata, event.ydata print 'PRESS button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % ( event.button, event.x, event.y, event.xdata, event.ydata) r = Rectangle(xy=(xs,ys), height=0, width=0, fill=False, lw=2, alpha=0.2) ax.add_artist(r) r.set_clip_box(ax.bbox) draw() id_motion = fig.canvas.mpl_connect('motion_notify_event', on_motion)
Example #17
Source File: label.py From smashscan with MIT License | 5 votes |
def show_frame(self): self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame_num) _, frame = self.capture.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) self.ax.imshow(frame) if self.is_recording: current_width = self.br_record[0] - self.tl_record[0] current_height = self.br_record[1] - self.tl_record[1] self.rect_patch = patches.Rectangle(self.tl_record, current_width, current_height, linewidth=1, edgecolor='r', facecolor='none') self.ax.add_patch(self.rect_patch) plt.draw() # Function called when left mouse button is clicked and released.
Example #18
Source File: find_wally_pretty.py From HereIsWally with MIT License | 5 votes |
def draw_box(box, image_np): #expand the box by 50% box += np.array([-(box[2] - box[0])/2, -(box[3] - box[1])/2, (box[2] - box[0])/2, (box[3] - box[1])/2]) fig = plt.figure() ax = plt.Axes(fig, [0., 0., 1., 1.]) fig.add_axes(ax) #draw blurred boxes around box ax.add_patch(patches.Rectangle((0,0),box[1]*image_np.shape[1], image_np.shape[0],linewidth=0,edgecolor='none',facecolor='w',alpha=0.8)) ax.add_patch(patches.Rectangle((box[3]*image_np.shape[1],0),image_np.shape[1], image_np.shape[0],linewidth=0,edgecolor='none',facecolor='w',alpha=0.8)) ax.add_patch(patches.Rectangle((box[1]*image_np.shape[1],0),(box[3]-box[1])*image_np.shape[1], box[0]*image_np.shape[0],linewidth=0,edgecolor='none',facecolor='w',alpha=0.8)) ax.add_patch(patches.Rectangle((box[1]*image_np.shape[1],box[2]*image_np.shape[0]),(box[3]-box[1])*image_np.shape[1], image_np.shape[0],linewidth=0,edgecolor='none',facecolor='w',alpha=0.8)) return fig, ax
Example #19
Source File: parse_svg.py From pylustrator with GNU General Public License v3.0 | 5 votes |
def clone_patch(patch: mpatches.Patch) -> mpatches.Patch: """ clone a patch element with the same properties as the given patch """ if isinstance(patch, mpatches.Rectangle): return mpatches.Rectangle(xy=patch.get_xy(), width=patch.get_width(), height=patch.get_height()) if isinstance(patch, mpatches.Circle): return mpatches.Circle(xy=patch.get_xy(), radius=patch.get_radius()) if isinstance(patch, mpatches.Ellipse): return mpatches.Ellipse(xy=patch.get_xy(), width=patch.get_width(), height=patch.get_height()) if isinstance(patch, mpatches.PathPatch): return mpatches.PathPatch(patch.get_path())
Example #20
Source File: legend.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def get_frame(self): ''' Return the `~.patches.Rectangle` instances used to frame the legend. ''' return self.legendPatch
Example #21
Source File: vis.py From lost with MIT License | 5 votes |
def _boxes(img, bb_list, lbls=None, figsize=(15,15), fontsize=15, label_offset=(0, 15)): '''Draw bboxes on into an matplotlib figures Args: img (str or array): Path to an image file or an image as numpy rgb array. bb_list (list): List of bboxes in format, [ [xc, yc, width, height], [...] ] Values are considered to be relative. lbls (list): List of labels corresponding to bb_list figsize (tuple): Size of the matplotlib figure. Returns: Matplotlib figure ''' fig,ax = plt.subplots(1, figsize=figsize) if isinstance(img, str): img = skimage.io.imread(img) ax.imshow(img) for idx, bb in enumerate(bb_list): if not np.isnan(bb[0]): w = bb[2] * img.shape[1] h = bb[3] * img.shape[0] x = bb[0] * img.shape[1] - w/2.0 y = bb[1] *img.shape[0] - h/2.0 bbox = patches.Rectangle((x,y),w,h,linewidth=2,edgecolor='r',facecolor='none') ax.add_patch(bbox) if lbls is not None: try: if lbls[idx] is not None: ax.text(x-label_offset[0], y-label_offset[1], lbls[idx], color='r', fontsize=fontsize) except IndexError: pass fig.tight_layout() return fig
Example #22
Source File: legend_handler.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): p = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) self.update_prop(p, orig_handle, legend) p.set_transform(trans) return [p]
Example #23
Source File: legend_handler.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def _create_patch(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize): if self._patch_func is None: p = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) else: p = self._patch_func(legend=legend, orig_handle=orig_handle, xdescent=xdescent, ydescent=ydescent, width=width, height=height, fontsize=fontsize) return p
Example #24
Source File: shapes.py From viznet with MIT License | 5 votes |
def rectangle(xy, size, angle, roundness, **kwargs): '''width is relative width with respect to height.''' if np.ndim(size) == 0: size = (size, size) width, height = 2*size[0], 2*size[1] xy_ = xy[0] - width / 2., xy[1] - height / 2. if roundness!=0: pad = roundness c = patches.FancyBboxPatch(xy_+np.array([pad,pad]), width-pad*2, height-pad*2, boxstyle=patches.BoxStyle("Round", pad=pad), **_fix(kwargs)) else: c = patches.Rectangle(xy_, width, height, **_fix(kwargs)) return [c] ########################## Derived types #############################
Example #25
Source File: plot_localization_tutorial.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 5 votes |
def convert_points_to_box(points, color, alpha): upper_left_point = (points[:, 0].min(), points[:, 1].min()) width = points[:, 0].max() - points[:, 0].min() height = points[:, 1].max() - points[:, 1].min() return Rectangle(upper_left_point, width, height, ec=color, fc=color, alpha=alpha) # Show the original image
Example #26
Source File: plot_single_localization.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 5 votes |
def convert_points_to_box(points, color, alpha): upper_left_point = (points[:, 0].min(), points[:, 1].min()) width = points[:, 0].max() - points[:, 0].min() height = points[:, 1].max() - points[:, 1].min() return Rectangle(upper_left_point, width, height, ec=color, fc=color, alpha=alpha)
Example #27
Source File: plot_multiple_localization.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 5 votes |
def convert_gmm_to_box(gmm, color, alpha): midpoint = gmm.means_ std = 3 * np.sqrt(clf.covars_) width = std[:, 0] height = std[:, 1] upper_left_point = (midpoint[:, 0] - width // 2, midpoint[:, 1] - height // 2) return Rectangle(upper_left_point, width, height, ec=color, fc=color, alpha=alpha)
Example #28
Source File: mondrian.py From Ensemble-Bayesian-Optimization with MIT License | 5 votes |
def visualize(self): if self.leaves is None or self.X.shape[1] != 2: print 'error: x shape is wrong or leaves is none.' # visaulize 2d mondrians import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib font = {'size': 20} matplotlib.rc('font', **font) mondrian_colors = np.array([[255, 240, 1], [48, 48, 58], [255, 1, 1], [1, 1, 253], [249, 249, 249]]) mondrian_colors = mondrian_colors / 255.0 fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') print('number of leaves = {}'.format(len(self.leaves))) for node in self.leaves: xy = node.x_range[0] xylen = node.x_range[1] - node.x_range[0] c = mondrian_colors[4] p = patches.Rectangle( xy, xylen[0], xylen[1], facecolor=c, linewidth=1, edgecolor='k' ) ax.add_patch(p) for x in self.X: c = '#fdbf6f' p = patches.Circle( x, 0.01, facecolor=c, linewidth=0 ) ax.add_patch(p) return ax, fig
Example #29
Source File: legend.py From Computable with MIT License | 5 votes |
def get_frame(self): 'return the Rectangle instance used to frame the legend' return self.legendPatch
Example #30
Source File: legend_handler.py From Computable with MIT License | 5 votes |
def _create_patch(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize): if self._patch_func is None: p = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) else: p = self._patch_func(legend=legend, orig_handle=orig_handle, xdescent=xdescent, ydescent=ydescent, width=width, height=height, fontsize=fontsize) return p