slope4 = slope_square - 90 slope5 = slope_square slope3 = math.radians(slope3) x_second = x_center + length * math.cos(slope3) y_second = y_center + length * math.sin(slope3) slope4 = math.radians(slope4) x_third = x_center + length * math.cos(slope4) y_third = y_center + length * math.sin(slope4) slope5 = math.radians(slope5) x_fourth = x_center + length * math.cos(slope5) y_fourth = y_center + length * math.sin(slope5) pt1 = [x_var, y_var] pt2 = [x_second, y_second] pt3 = [x_third, y_third] pt4 = [x_fourth, y_fourth] circle = plt.Polygon([pt1, pt2, pt4, pt3], color='b', fill=False, lw=2) ax = plt.gca() ax.add_patch(circle) plt.axis('scaled') elif detected_shape == 'Triangle': slope_tri = math.atan(f) slope_tri = math.degrees(slope_tri) slope3 = slope_tri + 60 slope4 = slope_tri - 60 slope3 = math.radians(slope3) x_second = x_center + length * math.cos(slope3) y_second = y_center + length * math.sin(slope3) slope4 = math.radians(slope4) x_third = x_center + length * math.cos(slope4) y_third = y_center + length * math.sin(slope4) pt1 = [x_var, y_var]
# Points of equilateral triangles A = np.array([0.0, 0.0]) B = np.array([1.0, 0.0]) C = np.array([0.5, 0.5*np.sqrt(3)]) r = 0.15 N = 2 angles = [] # Plotting graph plt.gca() plt.scatter(A[0], A[1], s=50, marker='o', color='r') plt.scatter(B[0], B[1], s=50, marker='o', color='r') plt.scatter(C[0], C[1], s=50, marker='o', color='r') t = plt.Polygon([A, B, C], fill=False, edgecolor='r', linestyle='--', alpha=0.65, linewidth=2) plt.gca().add_patch(t) colors = itertools.cycle(cm.hsv(np.linspace(0, 1, N*N*N))) for thetaA in np.linspace(0.0, (1.0/3.0)*2.0*np.pi, N): for thetaB in np.linspace((1.0/3.0)*2.0*np.pi, (2.0/3.0)*2.0*np.pi, N): for thetaC in np.linspace((2.0/3.0)*2.0*np.pi, 2.0*np.pi, N): A1, B1, C1 = wiggle(r, thetaA, thetaB, thetaC, A, B, C) plt.scatter(A1[0], A1[1], s=15, marker='o', color='b') plt.scatter(B1[0], B1[1], s=15, marker='o', color='b') plt.scatter(C1[0], C1[1], s=15, marker='o', color='b') t = plt.Polygon([A1, B1, C1], fill=False, edgecolor='b') plt.gca().add_patch(t) # angles.extend(get_angles(A1, B1, C1))
if step>1: for i in range(step-1): f.readline() l=f.readline() #print(data.shape) f.close() fig = plt.figure() fig.set_dpi(100) fig.set_size_inches(7, 6.5) size=int(sum(data[0][-DIM:])) ax = plt.axes(xlim=(-size, size), ylim=(-size, size)) polygon = plt.Polygon(vertices, fc='b') trail, = ax.plot([], [], lw=1, c='g') if interactive: mass = plt.Circle((0, 0), 0.2, fc='r') rope = patches.FancyArrowPatch(posA=(0, 0), posB=(0, 0), ls='solid', lw='1') def init(): mass.center = data[0][-DIM:] ax.add_patch(mass) rope.set_positions(data[0][-2*DIM:-DIM], data[0][-DIM:]) ax.add_patch(rope) ax.add_patch(polygon) trail.set_data(data[0][-2], data[0][-1]) return mass, rope, polygon, trail,
def vis_image(img, boxes=None, label_names=None, scores=None, colors=None, image_id=None, polygons=None,showfig=False): """Visualize a color image. Args: img: (PIL.Image/tensor) image to visualize boxes: (tensor) bounding boxes, sized [#obj, 4], format: x1y1x2y2 label_names: (list) label names scores: (list) confidence scores colors: (list) colors of boxes image_id: show this image_id as axes caption polygon: (tensor) quadrilateral defining the transformations [#obj, 8] showfig: (bool) - flag showing whether to call plt.show() at the end (e.g., stopping the script) Reference: https://github.com/kuangliu/torchcv/blob/master/torchcv/visualizations/vis_image.py """ # Plot image fig = plt.figure() ax = fig.add_subplot(1, 1, 1) if isinstance(img, torch.Tensor): img = torchvision.transforms.ToPILImage()(img.cpu()) ax.imshow(img) # Plot boxes if boxes is not None: for i, bb in enumerate(boxes): xy = (bb[0], bb[1]) width = bb[2] - bb[0] + 1 height = bb[3] - bb[1] + 1 box_color = 'red' if colors is None else colors[i] ax.add_patch(plt.Rectangle( xy, width, height, fill=False, edgecolor=box_color, linewidth=2)) caption = [] if label_names is not None: if label_names[i]: try: # if label_names is a pytorch vector n = label_names[i].item() except (KeyboardInterrupt, SystemExit): raise except: # if scores is a list n = label_names[i] caption.append(str(n)) if scores is not None: try: # if scores is a pytorch vector s = scores[i].item() except (KeyboardInterrupt, SystemExit): raise except: # if scores is a list s = scores[i] if not np.isnan(s): caption.append('{:.4f}'.format(s)) if len(caption) > 0: ax.text(bb[0], bb[1], ': '.join(caption), style='italic', fontsize=8, bbox={'facecolor': 'white', 'alpha': 0.7, 'pad': 2}) # plot polygons in x1, y1, x2, y2, x3, y3, x4, y4 format if polygons is not None: for i, polygon in enumerate(polygons): xy = polygon.numpy() xy = xy.reshape((4,2)) xy = xy[[0,2,3,1], :] ax.add_patch(plt.Polygon( xy, fill=False, edgecolor='red', linewidth=1)) # Caption with image_id if image_id is not None: ax.set_title('Image {0}'.format(image_id)) # turne off axes plt.axis('off') # Show if showfig: plt.show() return fig
def cla(self): """Clear projection.""" self.fig.clear() self.ax = self.fig.add_subplot(111) self.ax.format_coord = self.format_coord self.ax.set_aspect("equal") self.ax.set_autoscale_on(False) triangle = np.c_[self.A, self.B, self.C, self.A] n = 10 tick_size = 0.2 margin = 0.05 self.ax.set_axis_off() plt.axis([ self.A[0] - margin, self.B[0] + margin, self.C[1] - margin, self.A[1] + margin, ]) # projection triangle bg = plt.Polygon([self.A, self.B, self.C], color="w", edgecolor=None) self.ax.add_patch(bg) self.ax.plot(triangle[0], triangle[1], "k", lw=2) self.ax.text(self.A[0] - 0.02, self.A[1], "P", ha="right", va="bottom", fontsize=14) self.ax.text(self.B[0] + 0.02, self.B[1], "G", ha="left", va="bottom", fontsize=14) self.ax.text(self.C[0], self.C[1] - 0.02, "R", ha="center", va="top", fontsize=14) if self.grid: for l in np.arange(0.1, 1, 0.1): self.triplot([l, l], [0, 1 - l], [1 - l, 0], "k:") self.triplot([0, 1 - l], [l, l], [1 - l, 0], "k:") self.triplot([0, 1 - l], [1 - l, 0], [l, l], "k:") # ticks if self.ticks: r = np.linspace(0, 1, n + 1) tick = tick_size * (self.B - self.C) / n x = self.A[0] * (1 - r) + self.B[0] * r x = np.vstack((x, x + tick[0])) y = self.A[1] * (1 - r) + self.B[1] * r y = np.vstack((y, y + tick[1])) self.ax.plot(x, y, "k", lw=1) tick = tick_size * (self.C - self.A) / n x = self.B[0] * (1 - r) + self.C[0] * r x = np.vstack((x, x + tick[0])) y = self.B[1] * (1 - r) + self.C[1] * r y = np.vstack((y, y + tick[1])) self.ax.plot(x, y, "k", lw=1) tick = tick_size * (self.A - self.B) / n x = self.A[0] * (1 - r) + self.C[0] * r x = np.vstack((x, x + tick[0])) y = self.A[1] * (1 - r) + self.C[1] * r y = np.vstack((y, y + tick[1])) self.ax.plot(x, y, "k", lw=1) self.ax.set_title("Fabric plot") self.draw()
def plot_lines(geom, plt): points = geom.GetPoints() line = [[p[0], p[1]] for p in points] l = plt.Polygon(line, closed=False, fill=False, edgecolor='blue') plt.gca().add_line(l)
def drawPolygonNoFill(points, color): polygon = plt.Polygon(points, color=color, fill=False) plt.gca().add_patch(polygon)
def encode(self, gt_data, debug=False): """Encode ground truth polygones to segments and links for local classification and regression. # Arguments gt_data: shape (boxes, 4 xy + classes) # Return shape (priors, 2 segment_labels + 5 segment_offsets + 2*8 inter_layer_links_labels + 2*4 cross_layer_links_labels) """ rboxes = [] polygons = [] for word in gt_data: xy = np.reshape(word[:8], (-1, 2)) xy = np.copy(xy) * (self.image_w, self.image_h) polygons.append(xy) rbox = polygon_to_rbox(xy) rboxes.append(rbox) rboxes = self.gt_rboxes = np.array(rboxes) polygnos = self.gt_polygons = np.array(polygons) # compute segments for i in range(len(self.prior_maps)): m = self.prior_maps[i] # compute priors #m.compute_priors() num_priors = len(m.priors) # assigne gt to priors a_l = m.minmax_size[0] match_indices = np.full(num_priors, -1, dtype=np.int32) min_lhs_eq_11 = np.full(num_priors, 1e6, dtype=np.float32) for j in range(len(rboxes)): # ~12.9 ms cx, cy, w, h, theta = rboxes[j] c = rboxes[j,:2] # constraint on ratio between box size and word height, equation (11) lhs_eq_11 = max(a_l/h, h/a_l) if lhs_eq_11 <= 1.5: R = rot_matrix(theta) for k in range(num_priors): # hurts # is center of prior is in gt rbox d = np.abs(np.dot(m.priors_xy[k]-c, R.T)) if d[0] < w/2. and d[1] < h/2.: # is lhs of equation (11) minimal for prior if lhs_eq_11 < min_lhs_eq_11[k]: min_lhs_eq_11[k] = lhs_eq_11 match_indices[k] = j m.match_indices = match_indices segment_mask = match_indices != -1 # segment labels m.segment_labels = np.empty((num_priors, 2), dtype=np.int8) m.segment_labels[:, 0] = np.logical_not(segment_mask) m.segment_labels[:, 1] = segment_mask # compute offsets only for assigned boxes m.segment_offsets = np.zeros((num_priors, 5)) pos_segment_idxs = np.nonzero(segment_mask)[0] for j in pos_segment_idxs: # box_idx # ~4 ms gt_idx = match_indices[j] rbox = rboxes[gt_idx] polygon = polygons[gt_idx] cx, cy, w, h, theta = rbox R = rot_matrix(theta) prior_x, prior_y = m.priors_xy[j] prior_w, prior_h = m.priors_wh[j] # step 2 figuer 5, rotate word anticlockwise around the center of prior d = rbox[:2] - m.priors_xy[j] #poly_loc = rbox_to_polygon([*d, w, h, theta]) poly_loc = rbox_to_polygon(list(d) + [w, h, theta]) poly_loc_easy = polygon - m.priors_xy[j] poly_loc_rot = np.dot(poly_loc, R.T) # step 3 figure 5, crop word to left and right of prior poly_loc_croped = np.copy(poly_loc_rot) poly_loc_croped[:,0] = np.clip(poly_loc_croped[:,0], -prior_w/2., prior_w/2.) # step 4 figure 5, rotate croped word box clockwisely poly_loc_rot_back = np.dot(poly_loc_croped, R) rbox_loc_rot_back = polygon_to_rbox(poly_loc_rot_back) # encode, solve (3) to (7) to get local offsets #offset = np.array([*(rbox_loc_rot_back[:2]/a_l), # *(np.log(rbox_loc_rot_back[2:4]/a_l)), # rbox_loc_rot_back[4]]) offset = np.array(list(rbox_loc_rot_back[:2]/a_l) + list(np.log(rbox_loc_rot_back[2:4]/a_l)) + [rbox_loc_rot_back[4]]) offset[:4] /= m.priors[j,-4:] # variances m.segment_offsets[j] = offset # for debugging local geometry if debug: prior_poly_loc = np.array([[-prior_w, +prior_h], [+prior_w, +prior_h], [+prior_w, -prior_h], [-prior_w, -prior_h]])/2. plt.figure(figsize=[10]*2) ax = plt.gca() ax.add_patch(plt.Polygon(prior_poly_loc, fill=False, edgecolor='r', linewidth=1)) ax.add_patch(plt.Polygon(poly_loc, fill=False, edgecolor='b', linewidth=1)) ax.add_patch(plt.Polygon(np.dot(poly_loc, R.T), fill=False, edgecolor='k', linewidth=1)) #ax.add_patch(plt.Polygon(poly_loc_easy, fill=False, edgecolor='r', linewidth=1)) #ax.add_patch(plt.Polygon(np.dot(poly_loc_easy, R.T), fill=False, edgecolor='y', linewidth=1)) ax.add_patch(plt.Polygon(poly_loc_croped, fill=False, edgecolor='c', linewidth=1)) ax.add_patch(plt.Polygon(poly_loc_rot_back, fill=False, edgecolor='y', linewidth=1)) lim = 50; plt.xlim(-lim,lim); plt.ylim(-lim,lim); plt.grid() plt.show() break # compute link labels m.inter_layer_links_labels = np.zeros((num_priors,16), dtype=np.int8) m.cross_layer_links_labels = np.zeros((num_priors,8), dtype=np.int8) if i > 0: previous_map = self.prior_maps[i-1] # we only have to check neighbors if we are positive for idx in pos_segment_idxs: neighbor_idxs = m.inter_layer_neighbors_idxs[idx] for n, neighbor_idx in enumerate(neighbor_idxs): # valid neighbors if m.inter_layer_neighbors_valid[idx,n]: # neighbor matched to the same word if match_indices[idx] == match_indices[neighbor_idx]: # since we are positive and match to the same word, neighbor has to be positive m.inter_layer_links_labels[idx, n*2+1] = 1 # would be nice, but we refere to invalid neighbors #label = m.inter_layer_neighbors_valid[idx] & (match_indices[neighbor_idxs] == match_indices[idx]) #m.inter_layer_links_labels[idx, 1::2] = label if i > 0: neighbor_idxs = m.cross_layer_neighbors_idxs[idx] for n, neighbor_idx in enumerate(neighbor_idxs): # cross layer neighbors are always valid if match_indices[idx] == previous_map.match_indices[neighbor_idx]: m.cross_layer_links_labels[idx, n*2+1] = 1 m.inter_layer_links_labels[:,::2] = np.logical_not(m.inter_layer_links_labels[:,1::2]) m.cross_layer_links_labels[:,::2] = np.logical_not(m.cross_layer_links_labels[:,1::2]) # collect encoded ground truth maps = self.prior_maps segment_labels = np.concatenate([m.segment_labels for m in maps]) segment_offsets = np.concatenate([m.segment_offsets for m in maps]) inter_layer_links_labels = np.concatenate([m.inter_layer_links_labels for m in maps]) cross_layer_links_labels = np.concatenate([m.cross_layer_links_labels for m in maps]) return np.concatenate([segment_labels, segment_offsets, inter_layer_links_labels, cross_layer_links_labels], axis=1)
def plot_rbox(box, color='r', linewidth=1): xy_rec = rbox_to_polygon(box) ax = plt.gca() ax.add_patch(plt.Polygon(xy_rec, fill=False, edgecolor=color, linewidth=linewidth))
def draw_triangle(): X = np.array([[0, 0], [0, 1], [1, 0]]) t1 = plt.Polygon(X, fill=False) plt.gca().add_patch(t1)
def draw_poly_frame(self, x0, y0, r): # TODO: use transforms to convert (x, y) to (r, theta) verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta] return plt.Polygon(verts, closed=True, edgecolor='k')
def plot_xy_on_gamut(xy_base_vectors, label="", saveto=None): """ Plot the xy base vectors of any number of colour spaces on the xy plane. If possible, use colorio's function to plot the human eye and sRGB gamuts. """ saveto = plot._convert_to_path(saveto) try: from colorio._tools import plot_xy_gamut except ImportError: print("Could not import colorio, using simple gamut plot.") plt.xlim(0, 0.8) plt.ylim(0, 0.8) plt.xlabel("x") plt.ylabel("y") sRGB_triangle = plt.Polygon([[0.64, 0.33], [0.30, 0.60], [0.15, 0.06]], fill=True, linestyle="-", label="sRGB") plt.gca().add_patch(sRGB_triangle) else: plot_xy_gamut() # Check if a single set of base vectors was given or multiple if len(xy_base_vectors[0]) != 3: # A single set of base vectors xy_base_vectors = [xy_base_vectors] label = [label] plt.title(f"{label[0]} colour space\ncompared to sRGB") else: # If multiple sets were given nr_sets = len(xy_base_vectors) # If no or insufficient labels were provided, warn the user, and provide empty strings instead if len(label) != nr_sets: print( f"{len(label)} labels were provided for {nr_sets} data sets. Using empty labels instead." ) label = [""] * nr_sets plt.title(f"Colour spaces\ncompared to sRGB") # kwargs to make triangles look distinct kwargs = [{ "linestyle": "dashed" }, { "linestyle": "dotted" }, { "linestyle": "dashdot" }, { "linestyle": "solid", "linewidth": 0.5 }] triangles = [ plt.Polygon(base_vectors, fill=False, label=label_single, **kwargs_single) for base_vectors, label_single, kwargs_single in zip( xy_base_vectors, label, kwargs) ] for triangle in triangles: plt.gca().add_patch(triangle) plt.legend(loc="upper right") plot._saveshow(saveto)
horizontalalignment='left', verticalalignment='center', fontsize=14, color='w') #ax2.grid() # add rectangle import matplotlib.dates as mdates start = mdates.date2num(XLIM[0]) end = mdates.date2num(XLIM[1]) width = end - start rect_x = [start, end, end, start, start] rect_y = [0, 0, 52, 52, 0] rect = zip(rect_x, rect_y) Rgon = plt.Polygon(rect, color=np.multiply([1.0, 1.0, 1.0], .7), alpha=0.0, hatch='/') ax2.add_patch(Rgon) # add zoomed rectangle ## start = mdates.date2num(pd.Timestamp('2010-03-02 03:00:00')) ## end = mdates.date2num(pd.Timestamp('2010-03-02 09:00:00')) ## rect_x = [start, end, end, start, start] ## rect_y = [83, 83, 53, 53, 83] ## rect = zip(rect_x, rect_y) ## Rgon2 = plt.Polygon(rect, color='k', ls='--', lw=1, alpha=1, fill=False) ## #Rgon = plt.Polygon(rect,color='none', edgecolor='red', facecolor="red", hatch='/') ## ax2.add_patch(Rgon2) fig.set_size_inches(w=8, h=5) fig.set_dpi(150)
def draw_landscape(regions, duprange, lossrange, filename=None, log=False): """ Plot the landscape. The x-axis represents dup cost and the y-axis represents the loss cost (both relative to unit cost of deep coalescence). """ from rasmus import plotting import matplotlib.pyplot as plt # axes dup_min, dup_max = duprange loss_min, loss_max = lossrange if log: plt.xscale('log') plt.yscale('log') plt.axis('scaled') plt.axis([dup_min, dup_max, loss_min, loss_max]) plt.xlabel("relative duplication cost") plt.ylabel("relative loss cost") # legend legend_handles = [] legend_labels = [] # color map n = len(regions) colormap = plotting.rainbow_color_map(low=0, high=n - 1) # plot regions for i, (cv, region) in enumerate(regions.iteritems()): # output label = str(cv) color = colormap.get(i) if isinstance(region, geometry.Polygon): # non-degenerate coords = list(region.exterior.coords) h = plt.gca().add_patch(plt.Polygon(coords, color=color)) elif isinstance(region, geometry.LineString): # degenerate coords = list(region.coords) h, = plt.plot([coords[0][0], coords[1][0]], [coords[0][1], coords[1][1]], linewidth=4, color=color) elif isinstance(region, geometry.Point): # degenerate coords = list(region.coords) h, = plt.plot(coords[0][0], coords[0][1], 'o', markersize=4, color=color) else: # non-degenerate (collection) raise Exception("count vector (%s) has invalid region (%s)" % (cv, dumps(region))) legend_handles.append(h) legend_labels.append(label) # legend leg = plt.legend(legend_handles, legend_labels, numpoints=1, fontsize=10, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) # save if filename: plt.savefig(filename, format="pdf", bbox_extra_artists=(leg, ), bbox_inches='tight') else: plt.show() plt.close()
def draw_bars(out_value, features, feature_type, width_separators, width_bar): """Draw the bars and separators.""" rectangle_list = [] separator_list = [] pre_val = out_value for index, features in zip(range(len(features)), features): if feature_type == 'positive': left_bound = float(features[0]) right_bound = pre_val pre_val = left_bound separator_indent = np.abs(width_separators) separator_pos = left_bound colors = ['#FF0D57', '#FFC3D5'] else: left_bound = pre_val right_bound = float(features[0]) pre_val = right_bound separator_indent = - np.abs(width_separators) separator_pos = right_bound colors = ['#1E88E5', '#D1E6FA'] # Create rectangle if index == 0: if feature_type == 'positive': points_rectangle = [[left_bound, 0], [right_bound, 0], [right_bound, width_bar], [left_bound, width_bar], [left_bound + separator_indent, (width_bar / 2)] ] else: points_rectangle = [[right_bound, 0], [left_bound, 0], [left_bound, width_bar], [right_bound, width_bar], [right_bound + separator_indent, (width_bar / 2)] ] else: points_rectangle = [[left_bound, 0], [right_bound, 0], [right_bound + separator_indent * 0.90, (width_bar / 2)], [right_bound, width_bar], [left_bound, width_bar], [left_bound + separator_indent * 0.90, (width_bar / 2)]] line = plt.Polygon(points_rectangle, closed=True, fill=True, facecolor=colors[0], linewidth=0) rectangle_list += [line] # Create seperator points_separator = [[separator_pos, 0], [separator_pos + separator_indent, (width_bar / 2)], [separator_pos, width_bar]] line = plt.Polygon(points_separator, closed=None, fill=None, edgecolor=colors[1], lw=3) separator_list += [line] return rectangle_list, separator_list
import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1, 1, 1) rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3) circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3) pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]], color='g', alpha=0.5) ax.add_patch(rect) ax.add_patch(circ) ax.add_patch(pgon) plt.show()
def get_triangle(x, y, z, c, s): """Draws a triangle with center (x, y), color c, size s and z-order of z.""" points = np.array([[0, 0], [s, s * math.sqrt(3.0)], [s * 2.0, 0]]) tri = plt.Polygon(points + [x - s, y - s], fc=c, zorder=z) return tri
def plot_gmm(self, dim=None, color=[1, 0, 0], alpha=0.5, linewidth=1, markersize=6, batch_idx=0, ax=None, empty=False, edgecolor=None, edgealpha=None, border=False, nb=1, center=True, zorder=20, equal=True, sess=None, feed_dict={}, axis=0): if sess is None: sess = tf.compat.v1.get_default_session() loc, cov = sess.run([self._loc, self._cov], feed_dict) if loc.ndim == 3: loc = loc[batch_idx] if axis == 0 else loc[:, batch_idx] if cov.ndim == 4: cov = cov[batch_idx] if axis == 0 else cov[:, batch_idx] if loc.ndim == 1: loc = loc[None] if cov.ndim == 2: cov = cov[None] nb_states = loc.shape[0] if dim: loc = loc[:, dim] cov = cov[np.ix_(range(cov.shape[0]), dim, dim)] if isinstance( dim, list) else cov[:, dim, dim] if not isinstance(color, list) and not isinstance(color, np.ndarray): color = [color] * nb_states elif not isinstance(color[0], str) and not isinstance( color, np.ndarray): color = [color] * nb_states if not isinstance(alpha, np.ndarray): alpha = [alpha] * nb_states else: alpha = np.clip(alpha, 0.1, 0.9) rs = tf.linalg.sqrtm(cov).eval() pointss = np.einsum('aij,js->ais', rs, np.array([np.cos(self._t), np.sin(self._t)])) pointss += loc[:, :, None] for i, c, a in zip(range(0, nb_states, nb), color, alpha): points = pointss[i] if edgecolor is None: edgecolor = c polygon = plt.Polygon(points.transpose().tolist(), facecolor=c, alpha=a, linewidth=linewidth, zorder=zorder, edgecolor=edgecolor) if edgealpha is not None: plt.plot(points[0, :], points[1, :], color=edgecolor) if ax: ax.add_patch(polygon) # Patch l = None if center: a = alpha[i] else: a = 0. ax.plot(loc[i, 0], loc[i, 1], '.', color=c, alpha=a) # Mean if border: ax.plot(points[0, :], points[1, :], color=c, linewidth=linewidth, markersize=markersize) # Contour if equal: ax.set_aspect('equal') else: if empty: plt.gca().grid('off') # ax[-1].set_xlabel('x position [m]') plt.gca().set_axis_bgcolor('w') plt.axis('off') plt.gca().add_patch(polygon) # Patch l = None if center: a = alpha[i] else: a = 0.0 l, = plt.plot(loc[i, 0], loc[i, 1], '.', color=c, alpha=a) # Mean # plt.plot(points[0,:], points[1,:], color=c, linewidth=linewidth , markersize=markersize) # Contour if equal: plt.gca().set_aspect('equal') return l
def drawPolygon(points): polygon = plt.Polygon(points) plt.gca().add_patch(polygon)
def draw_xsect(self, save=False): # Initiate figures and axes fig, ax = plt.subplots() # Create and draw HAND cross-section polygon # Generate origin for plotting (note: must be done prior to for loop) hand_xsect = scipy.array([[0, 0]]) for h in range(len(self.handstage)): # Retrieve top-width data for this height step print self.handwidth delta_w = self.handwidth[h] / 2.0 # Collect negative and positive widths for this height step neg = scipy.array([[-delta_w, h]]) pos = scipy.array([[delta_w, h]]) # Organize final data as LHS, origin, RHS hand_xsect = scipy.concatenate([neg, hand_xsect, pos]) # Draw HAND cross-section hand_poly = plt.Polygon(hand_xsect, closed=None, fill=None, edgecolor='b', linewidth=5, label='HAND X-Sect') ax.add_artist(hand_poly) usgs_max_height = 0 usgs_max_width = 0 # Create and draw USGS cross-section polygon for usgsid in self.usgsids: # Generate origin for plotting (note: must be done within for loop) usgs_xsect = scipy.array([[0, 0]]) # Retrieve dictionary with USGS data d = self.get_usgs_geometry(usgsid) # Retrieve Gage height at Zero Flow (GZF) gzf = self.get_usgs_gzf(usgsid) # Collect indices of most recent rating number only ratings = [(ind, float(r)) for ind, r in enumerate(d['current_rating_nu']) if filter(None, r)] # Find index of latest occurence of most recent rating number rnos = zip(*ratings)[1] most_recent = ratings[rnos.index(rnos[-1])][0] # Collect height and width data (note: divide width by 2 for one-sided width), # while removing pairs missing one element and taking only most recent rating number ratings = [ float(r) for r in d['current_rating_nu'] if filter(None, r) ] data = [(float(w)/2.0,float(h)-gzf)\ for w,h,r in zip(d['chan_width'],d['gage_height_va'],d['current_rating_nu'])\ if filter(None,w) and filter(None,h) and filter(None,r) and float(r) == ratings[-1]] # Sort data: ascending height and ascending width pos = scipy.array(sorted(data, key=operator.itemgetter(1, 0))) # Sort data: ascending height and descending width neg = scipy.array( sorted(data, key=operator.itemgetter(1, 0), reverse=True)) neg[:, 0] = -neg[:, 0] # change widths to negative for plotting # Organize final data as LHS, origin, RHS usgs_xsect = scipy.concatenate([neg, usgs_xsect, pos]) # Draw USGS cross-section usgs_poly = plt.Polygon(usgs_xsect, closed=None, fill=None, edgecolor='g', linewidth=5, label='USGS X-Sect') ax.add_artist(usgs_poly) # Customize plot fig.set_size_inches(20, 16, forward=True) plt.gca().set_xlim(left=-self.handwidth[-1], right=self.handwidth[-1]) plt.gca().set_ylim(bottom=self.handstage[0], top=self.handstage[-1]) # Manually over-ride HAND limits plt.gca().set_xlim(left=-self.handwidth[11], right=self.handwidth[11]) plt.gca().set_ylim(bottom=-1, top=pos[-1][1] + 1) # 1 above USGS height ax.set_xticks(ax.get_xticks()[::2]) ax.set_yticks(ax.get_yticks()[::2]) title = 'COMID {0}'.format(self.comid) ax.set_title(title, y=1.04, fontsize=56) plt.xlabel('Width (ft)', fontsize=56) plt.ylabel('Height (ft)', fontsize=56) plt.rc('font', size=56) # plt.legend(loc='upper left',fontsize=40) plt.legend([hand_poly, usgs_poly], ['hand', 'usgs']) plt.tick_params(axis='both', labelsize=56) plt.grid() if save: fig.savefig(save) plt.clf() if not save: # mng = plt.get_current_fig_manager() # mng.resize(*mng.window.maxsize()) plt.show() plt.clf()
if pos == start: p3 = sf["back"]["射水市5"][:i + 1] if pos == end: p4 = sf["back"]["射水市5"][i:] if p1[0] == p2[0]: p1 = p2[::-1] + p1 elif p1[0] == p2[-1]: p1 = p2 + p1 elif p1[-1] == p2[0]: p1 += p2 elif p1[-1] == p2[-1]: p1 += p2[::-1] if p3[0] == p4[0]: p3 = p4[::-1] + p3 elif p3[0] == p4[-1]: p3 = p4 + p3 elif p3[-1] == p4[0]: p3 += p4 elif p3[-1] == p4[-1]: p3 += p4[::-1] if p1[-1] == p3[0]: p1 += p3 elif p1[-1] == p3[-1]: p1 += p3[::-1] fig, ax = plt.subplots() poly = plt.Polygon(p1, fc="b") ax.add_patch(poly) plt.xlim([136, 138]) plt.ylim([36, 37]) plt.show()
def draw_poly_patch(self): # rotate theta such that the first axis is at the top verts = unit_poly_verts(theta + np.pi / 2) return plt.Polygon(verts, closed=True, edgecolor='k')
def update_figure(self): saved_tree = False # Plot the bounding boxes, their text annotations and direction arrow plotted_objects = [] for track_ind in self.ids_for_frame[self.current_frame]: track = self.tracks[track_ind] track_id = track["trackId"] static_track_information = self.static_info[track_id] initial_frame = static_track_information["initialFrame"] current_index = self.current_frame - initial_frame object_class = static_track_information["class"] is_vehicle = object_class in ["car", "truck_bus", "motorcycle"] bounding_box = track["bboxVis"][ current_index] / self.scale_down_factor center_points = track["centerVis"] / self.scale_down_factor center_point = center_points[current_index] color = self.colors[ object_class] if object_class in self.colors else self.colors[ "default"] if self.config["plotBoundingBoxes"] and is_vehicle: rect = plt.Polygon(bounding_box, True, facecolor=color, **self.rect_style) self.ax.add_patch(rect) plotted_objects.append(rect) if self.config["plotDirectionTriangle"] and is_vehicle: # Add triangles that display the direction of the cars triangle_factor = 0.75 a_x = bounding_box[3, 0] + ( (bounding_box[2, 0] - bounding_box[3, 0]) * triangle_factor) b_x = bounding_box[0, 0] + ( (bounding_box[1, 0] - bounding_box[0, 0]) * triangle_factor) c_x = bounding_box[2, 0] + ( (bounding_box[1, 0] - bounding_box[2, 0]) * 0.5) triangle_x_position = np.array([a_x, b_x, c_x]) a_y = bounding_box[3, 1] + ( (bounding_box[2, 1] - bounding_box[3, 1]) * triangle_factor) b_y = bounding_box[0, 1] + ( (bounding_box[1, 1] - bounding_box[0, 1]) * triangle_factor) c_y = bounding_box[2, 1] + ( (bounding_box[1, 1] - bounding_box[2, 1]) * 0.5) triangle_y_position = np.array([a_y, b_y, c_y]) # Differentiate between vehicles that drive on the upper or lower lanes triangle_info = np.array( [triangle_x_position, triangle_y_position]) polygon = plt.Polygon(np.transpose(triangle_info), True, **self.triangle_style) self.ax.add_patch(polygon) plotted_objects.append(polygon) if self.config["plotTrackingLines"]: plotted_centroid = plt.Circle( (center_points[current_index][0], center_points[current_index][1]), facecolor=color, **self.centroid_style) self.ax.add_patch(plotted_centroid) plotted_objects.append(plotted_centroid) if center_points.shape[0] > 0: # Calculate the centroid of the vehicles by using the bounding box information # Check track direction plotted_centroids = self.ax.plot( center_points[0:current_index + 1][:, 0], center_points[0:current_index + 1][:, 1], color=color, **self.track_style) plotted_objects.append(plotted_centroids) if self.config["plotFutureTrackingLines"]: # Check track direction plotted_centroids_future = self.ax.plot( center_points[current_index:][:, 0], center_points[current_index:][:, 1], **self.track_style_future) plotted_objects.append(plotted_centroids_future) if self.config[ "showTextAnnotation"] and self.agent_id is None or self.agent_id == track_id: # Plot the text annotation annotation_text = "ID{}".format(track_id) if self.config["showClassLabel"]: if annotation_text != '': annotation_text += '|' annotation_text += "{}".format(object_class[0]) if self.config["showVelocityLabel"]: if annotation_text != '': annotation_text += '|' current_velocity = np.sqrt( track["xVelocity"][current_index]**2 + track["yVelocity"][current_index]**2) * 3.6 current_velocity = abs(float(current_velocity)) annotation_text += "{:.2f}km/h".format(current_velocity) if self.config["showRotationsLabel"]: if annotation_text != '': annotation_text += '|' current_rotation = track["heading"][current_index] annotation_text += "Deg%.2f" % current_rotation if self.config["showAgeLabel"]: if annotation_text != '': annotation_text += '|' age = static_track_information["age"] annotation_text += "Age%d/%d" % (current_index + 1, age) if (self.goal_recogniser is not None and self.episode.agents[track_id].num_frames < 25 * 120 and object_class[0] == 'c'): initial_frame = static_track_information["initialFrame"] frames = self.episode.frames[initial_frame:self. current_frame + 1] goal_probabilities = self.goal_recogniser.goal_probabilities( frames, track_id) for goal_idx, prob in enumerate(goal_probabilities): if prob > 0: annotation_text += '\nG{}: {:.3f}'.format( goal_idx, prob) if self.agent_id is not None: assert isinstance(self.goal_recogniser, DecisionTreeGoalRecogniser) goal_idx = 0 goal_type = 'turn-right' pydot_tree = self.goal_recogniser.decision_trees[ goal_idx][goal_type].pydot_tree() pydot_tree.write_png( get_img_dir() + '/video_tree/{}.png'.format( self.current_frame, self.agent_id, goal_idx, goal_type)) saved_tree = True # Differentiate between using an empty background image and using the virtual background target_location = (center_point[0], (center_point[1])) text_location = ((center_point[0] + 45), (center_point[1] - 20)) text_patch = self.ax.annotate(annotation_text, xy=target_location, xytext=text_location, bbox={ "fc": color, **self.text_box_style }, **self.text_style) plotted_objects.append(text_patch) # Add listener to figure self.fig.canvas.mpl_connect('pick_event', self.display_features_on_click) # Save the plotted objects in a list self.plotted_objects = plotted_objects if saved_tree: plt.savefig(get_img_dir() + '/video_road/{}.png'.format(self.current_frame))
def colorMap(BM, stateFPs, countyFpToLeDict): """ Description: Colors counties on a map. Iterates through all counties and changes their color. Input: BM (basemap object): Please refer to draw_us_map stateFPs (list(str)): Please refer to draw_us_map Output: None: TODO: 1) Sety individual county colors. Right now everything is set to blue, but you need to open and read the life expectancy data to get this information. 2) handle alaska and Hawaii data. You need to draw counties for them and fix an issue where alaska being fucksy when you draw it. """ ax = plt.gca() for i, county in enumerate(BM.counties_info): countyname = county["NAME"] try: statename = stateFPs[int(county["STATEFP"])] except IndexError: # print(countyname, "has out-of-index statefp of", county["STATEFP"]) continue # The file has no results for Puerto Rico and Alaska. if statename in ["Puerto Rico", "Alaska", "Hawaii"]: # TODO there is data for alaska and hawaii but plotting them is difficult. # print("nothing for Alaska") continue if not statename: # print("No state for", countyname) continue countystate = "%s, %s" % (countyname, statename) try: ccolor = countyFpToLeDict[county["GEOID"]][1] # colAlpha = 1#float(countyFpToLeDict[county["GEOID"]][1]) # colAlpha = 0 except KeyError: print("No match for", countystate) continue # No exact match; try for a fuzzy match # colAlpha = 0 # fuzzyname = fuzzy_find(countystate, county_colors.keys()) # if fuzzyname: # ccolor = county_colors[fuzzyname] # county_colors[countystate] = ccolor # else: # print("No match for", countystate) # continue countyseg = BM.counties[i] # Move Hawaii and Alaska: # http://stackoverflow.com/questions/39742305/how-to-use-basemap-python-to-plot-us-with-50-states # Offset Alaska and Hawaii to the lower-left corner. if statename == 'Alaska': # Alaska is too big. Scale it down to 35% first, then transate it. countyseg = list( map(lambda xy: (0.25 * xy[0] + 400000, 0.25 * xy[1] - 1000000), countyseg)) # countyseg =countyseg elif statename == 'Hawaii': # countyseg = countyseg countyseg = list( map(lambda xy: (xy[0] + 6000000, xy[1] - 1500000), countyseg)) # countyseg = BM.counties[i] poly = plt.Polygon(countyseg, facecolor=ccolor) # edgecolor="white" ax.add_patch(poly)
def draw_poly_patch(self): verts = unit_poly_verts(theta) return plt.Polygon(verts, closed=True, edgecolor='k')
def render( self, title=None, n_frame=10, show_before=False, task_num=0, save_viz=False, iteration=0, **kargs, ): t_delta = 0.001 if self.num_agents == 1: colors = ["#000075"] elif self.num_agents == 2: colors = ["#000075", "#e6194B"] else: colors = ["#000075", "#e6194B", "#3cb44b"] curr_state = self._state show_state = self._state if n_frame != 1: show_state = self._last_state for i_frame in range(n_frame): # Refresh if self._fig is None: self._fig = plt.figure(figsize=(8, 8), dpi=80) else: self._fig.clear() ax = plt.gca() # Object visualization show_state = show_state + (curr_state - show_state) / n_frame xs, ys, gxs, gys, angles, _ = self.get_pos_gpos(show_state) if self.num_agents == 2: object_plt = plt.Line2D( xs, ys, lw=10.0, ls="-", marker=".", color="grey", markersize=0, markerfacecolor="r", markeredgecolor="r", markerfacecoloralt="k", alpha=0.7, ) ax.add_line(object_plt) elif self.num_agents == 3: object_plt = plt.Polygon(list(map(list, zip(xs, ys))), alpha=0.7, color="grey") ax.add_line(object_plt) for i, c in zip(range(self.num_agents), colors): plt.scatter(xs[i], ys[i], c=c, marker="o", s=140, zorder=10, alpha=0.7) # Before adaptation visualization if show_before: if self.num_agents == 2: object_plt = plt.Line2D( before_xs, before_ys, lw=10.0, ls="-", marker=".", color="grey", markersize=0, markerfacecolor="r", markeredgecolor="r", markerfacecoloralt="k", alpha=0.35, ) ax.add_line(object_plt) elif self.num_agents == 3: object_plt = plt.Polygon( list(map(list, zip(before_xs, before_ys))), alpha=0.35, color="grey", ) ax.add_line(object_plt) for i, c in zip(range(self.num_agents), colors): plt.scatter( before_xs[i], before_ys[i], c=c, marker="o", s=140, zorder=10, alpha=0.35, ) # Goal visualization markers = ["$" + s + "$" for s in "ABC"[:self.num_agents]] sm_marker = 50 lg_marker = 80 if gxs is not None and gys is not None: gxs += [gxs[0]] gys += [gys[0]] ax.plot(gxs, gys, ":", lw=2, alpha=1, color="grey") if self.num_agents == 2: goal_plt = plt.Line2D( gxs, gys, lw=10.0, ls="-", marker=".", color="grey", markersize=0, markerfacecolor="r", markeredgecolor="r", markerfacecoloralt="k", alpha=0.3, ) else: goal_plt = plt.Polygon(list(map(list, zip(gxs, gys))), alpha=0.3, color="grey") ax.add_line(goal_plt) for i, c in zip(range(self.num_agents), colors): plt.scatter(gxs[i], gys[i], c=c, marker="o", s=140, zorder=10, alpha=0.3) # Action visualization fs = self._last_actions F_xs, F_ys, F_rs = [], [], [] if fs is not None: F_xs, F_ys, F_rs = self._convert_f_xyr(self._last_state, fs) fs_const = 0.3 F_xs *= fs_const F_ys *= fs_const lengths = np.sqrt(np.square(F_xs) + np.square(F_ys)) for i in range(self.num_agents): plt.arrow( xs[i], ys[i], F_xs[i], F_ys[i], fc=colors[i], ec="none", alpha=0.7, width=0.06, head_width=0.1, head_length=0.2, zorder=8, ) sns.despine(offset=10, trim=True) ax.set_xlim([-(PAPER_FIX_DIST + 0.75), (PAPER_FIX_DIST + 0.75)]) ax.set_ylim([-(PAPER_FIX_DIST + 0.75), (PAPER_FIX_DIST + 0.75)]) plt.xticks(fontsize=15) plt.yticks(fontsize=15) plt.axis("off") for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontname("Times New Roman") if save_viz: if not self._fig_folder: self._fig_folder = "figures/stick-{s}-{date:%Y-%m-%d %H:%M:%S}".format( s=self.num_agents, date=datetime.datetime.now()).replace(" ", "_") os.makedirs(self._fig_folder, exist_ok=True) self._fig.savefig( os.path.join( self._fig_folder, "stick{}_task{}_itr{}_frame{:04d}.png".format( self.num_agents, task_num, iteration, self._step_count * n_frame + i_frame, ), )) self._fig.show() plt.pause(t_delta / n_frame)
# tri dislocation parameters pr = 0.25 ss = -1. ts = 0. ds = 0. N = 30 sx, sy, sz = np.meshgrid( np.linspace(0, 100, N), np.linspace(0, 100, N), 0) sxr = sx.ravel(order='F') syr = sy.ravel(order='F') szr = sz.ravel(order='F') X = np.array([40., 60., 40.]) Y = np.array([50., 50., 30.]) Z = np.array([0., 0., 20.]) S = tde.calc_tri_strains(sxr, syr, szr, X, Y, Z, pr, ss, ts, ds) U = tde.calc_tri_displacements(sxr, syr, szr, X, Y, Z, pr, ss, ts, ds) plt.figure() plt.gca().add_patch(plt.Polygon( np.array([X,Y]).T)) plt.quiver(sxr, syr, U['x']*0.5, U['y']*0.5) plt.show()
def holiday_input_plots(paramfile, infile, indices): indata = h5py.File(infile, 'r') gp_input = indata['parameter_density'] simtools.PARAMS = toml.load(paramfile) print('Index list') print('index', 'start', 'duration', sep='\t') for i, ix in enumerate(gp_input['holiday_parameters']): print(i, *ix, sep='\t') fig, axs = plt.subplots() fig.set_size_inches(6, 8) for i, style in zip(indices, STYLE_CYCLE): time_axis = gp_input['time_axis'][i, :] growth_rate = gp_input['growth_rate'][i, :] holiday_params = gp_input['holiday_parameters'][i, :] axs.plot(time_axis, growth_rate, color='k', linewidth='1', linestyle=style) axs.axvline(time_axis[holiday_params[0]], linewidth=0.5, color='lightgrey') axs.axvline(time_axis[holiday_params[0] + holiday_params[1]], linewidth=0.5, color='lightgrey') rate_before = growth_rate[holiday_params[0] - 1] rate_return = np.argmax( growth_rate[(holiday_params[0] + holiday_params[1]):] >= rate_before) pts_to_days = simtools.PARAMS['time_points_up'] \ /simtools.PARAMS['time_range_up'][1] print(rate_before, rate_return, growth_rate[rate_return + holiday_params[0] + holiday_params[1]]) print(holiday_params[0] / pts_to_days, holiday_params[1] / pts_to_days, rate_return / pts_to_days) axs.axvline(time_axis[rate_return + holiday_params[0] + holiday_params[1]], linewidth=0.5, color='blue') axs.set_xlabel('Time') axs.set_xlabel('Growth rate') plt.tight_layout() plt.show() # small multiples version if len(indices) > 1: fig, axs = plt.subplots(nrows=len(indices)) fig.set_size_inches(4, 2 * len(indices)) for i, ix in enumerate(indices): time_axis = gp_input['time_axis'][ix, :] growth_rate = gp_input['growth_rate'][ix, :] holiday_params = gp_input['holiday_parameters'][ix, :] axs[i].plot(time_axis, growth_rate, color='k', linewidth='1', linestyle='-') # axs[i].axvline(time_axis[holiday_params[0]], # linewidth=0.5, color='lightgrey') # axs[i].axvline(time_axis[holiday_params[0] + holiday_params[1]], # linewidth=0.5, color='lightgrey') rate_before = growth_rate[holiday_params[0] - 1] rate_return = np.argmax( growth_rate[(holiday_params[0] + holiday_params[1]):] >= rate_before) pts_to_days = simtools.PARAMS['time_points_up'] \ /simtools.PARAMS['time_range_up'][1] print( rate_before, rate_return, growth_rate[rate_return + holiday_params[0] + holiday_params[1]]) print(holiday_params[0] / pts_to_days, holiday_params[1] / pts_to_days, rate_return / pts_to_days) # axs[i].axvline(time_axis[rate_return + holiday_params[0] + holiday_params[1]], # linewidth=0.5, color='blue') holiday_start = holiday_params[0] / pts_to_days holiday_end = (holiday_params[0] + holiday_params[1]) / pts_to_days effect_end = (rate_return + holiday_params[0] + holiday_params[1]) / pts_to_days wt_area = plt.Polygon([(holiday_start, axs[i].get_ylim()[0]), (holiday_end, axs[i].get_ylim()[0]), (holiday_end, axs[i].get_ylim()[1]), (holiday_start, axs[i].get_ylim()[1])], color='lightgrey', zorder=-3) axs[i].add_patch(wt_area) axs[i].text((holiday_start + holiday_end) / 2, axs[i].get_ylim()[1] * 1.1, 'Treatment holiday', color='grey', size=8, verticalalignment='center', horizontalalignment='center') axs[i].axvline(effect_end, linewidth=1.0, linestyle='--', color='k') axs[i].text(effect_end + axs[i].get_xlim()[1] * 0.01, axs[i].get_ylim()[0] + axs[i].get_ylim()[1] * 0.1, 'End of holiday\naftereffects', color='k', size=8, verticalalignment='center', horizontalalignment='left') axs[i].set_xlabel('Time') axs[i].set_ylabel('Growth rate') plt.tight_layout() plt.show()
def create_square(length): square = plt.Polygon([(1, 1), (length, 1), (length, length), (1, length)], closed=True, fc='gray') ax.add_patch(square)
(728, 511)) filenames = [f for f in glob.iglob("Node/*")] filenames.sort() for filename in filenames: img = cv2.imread(filename) print(filename) out.write(img) original.append(img) time.sleep(1) length = len(original) # print('Updated Images') # return original#, title, length goalNode = plt.scatter(goal[0], goal[1], s=10, color='g'), circle = plt.Circle((coord_circle[1]), coord_circle[0], fc=None) rectangle = plt.Polygon(coord_rectangle) rhombus = plt.Polygon(coord_rhombus) polygon = plt.Polygon(coord_polygon) ellipse = Ellipse((coord_ellipse[1]), coord_ellipse[0][0], coord_ellipse[0][1], 0) obstacles = [circle, rectangle, rhombus, polygon, ellipse] for obstacle in obstacles: plt.gca().add_patch(obstacle) count = 0 for expnode in range(1, len(ExploredNodeList)): try: parent_x = ExploredParentNodeList[expnode * 10][0] parent_y = ExploredParentNodeList[expnode * 10][1] node_x = ExploredNodeList[expnode * 10][0] node_y = ExploredNodeList[expnode * 10][1] plt.quiver(parent_x,