def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False, \ head_width=None, head_length=None, shape='full', overhang=0, \ head_starts_at_zero=False,**kwargs): """Returns a new Arrow. length_includes_head: True if head is counted in calculating the length. shape: ['full', 'left', 'right'] overhang: distance that the arrow is swept back (0 overhang means triangular shape). head_starts_at_zero: if True, the head starts being drawn at coordinate 0 instead of ending at coordinate 0. """ if head_width is None: head_width = 3 * width if head_length is None: head_length = 1.5 * head_width distance = sqrt(dx**2 + dy**2) if length_includes_head: length=distance else: length=distance+head_length if not length: verts = [] #display nothing if empty else: #start by drawing horizontal arrow, point at (0,0) hw, hl, hs, lw = head_width, head_length, overhang, width left_half_arrow = array([ [0.0,0.0], #tip [-hl, -hw/2.0], #leftmost [-hl*(1-hs), -lw/2.0], #meets stem [-length, -lw/2.0], #bottom left [-length, 0], ]) #if we're not including the head, shift up by head length if not length_includes_head: left_half_arrow += [head_length, 0] #if the head starts at 0, shift up by another head length if head_starts_at_zero: left_half_arrow += [head_length/2.0, 0] #figure out the shape, and complete accordingly if shape == 'left': coords = left_half_arrow else: right_half_arrow = left_half_arrow*[1,-1] if shape == 'right': coords = right_half_arrow elif shape == 'full': coords=concatenate([left_half_arrow,right_half_arrow[::-1]]) else: raise ValueError, "Got unknown shape: %s" % shape cx = float(dx)/distance sx = float(dy)/distance M = array([[cx, sx],[-sx,cx]]) verts = dot(coords, M) + (x+dx, y+dy) Polygon.__init__(self, map(tuple, verts), **kwargs)
def __init__(self, xyz, **kargs): self._gl_3dpath = kargs.pop('gl_3dpath', None) self._gl_lighting = kargs.pop('gl_lighting', True) xy = xyz[:,0:2] Polygon.__init__(self, xy, **kargs) self.do_stencil_test = True self.set_3d_properties(zs = xyz[:,2])
def write_body(self): try: from matplotlib.path import Path except ImportError: Path = None from matplotlib.patches import Circle, Polygon else: from matplotlib.patches import Circle, PathPatch indices = self.X[:, 2].argsort() for a in indices: xy = self.X[a, :2] if a < self.natoms: r = self.d[a] / 2 if ((xy[1] + r > 0) and (xy[1] - r < self.h) and (xy[0] + r > 0) and (xy[0] - r < self.w)): circle = Circle(xy, r, facecolor=self.colors[a]) circle.draw(self.renderer) else: a -= self.natoms c = self.T[a] if c != -1: hxy = self.D[c] if Path is None: line = Polygon((xy + hxy, xy - hxy)) else: line = PathPatch(Path((xy + hxy, xy - hxy))) line.draw(self.renderer)
def __init__(self, xy, closed=True, plotview=None, **opts): shape = Polygon(xy, closed, **opts) if 'linewidth' not in opts: shape.set_linewidth(1.0) if 'facecolor' not in opts: shape.set_facecolor('r') super(NXpolygon, self).__init__(shape, resize=False, plotview=plotview) self.shape.set_label('Polygon') self.polygon = self.shape
def getGuards(polygon_no): positions = [] data = triangulate(polygons[str(polygon_no)]) vertices = data['tri']['vertices'] colours = get_colour(data) min_c = get_min_colour(colours) stars = get_stars(data) star_polygons = star_poly_array(stars, vertices) # print(stars) # print(star_polygons) # print(vertices) # print(min_c) adj = adj_matrix(data) # print(adj[24]) # print(adj[33]) # print(adj[60]) # pdb.set_trace() def compare(plt, A, B): ax1 = plt.subplot(121, aspect='equal') triangle.plot.plot(ax1, **A) ax2 = plt.subplot(122, sharex=ax1, sharey=ax1) triangle.plot.plot(ax2, **B) return (ax1, ax2) ax1, ax2 = compare(plt, data['original'], data['tri']) # Colour polygons patches = [] for polygon in star_polygons: p = Polygon(polygon, True) patches.append(p) p = PatchCollection(patches, cmap=matplotlib.cm.jet) plt.gca().add_collection(p) # Label vertex indices for i, v in enumerate(vertices): ax1.text(v[0], v[1], str(i)) for c, v in zip(colours, vertices): if c == min_c: positions.append(v.tolist()) plt.annotate(c, xy=tuple(v), color='darkblue') # positions = starise.kernels(stars, vertices) # Plot kernel points ax1.plot(*zip(*positions), marker='^', color='g', ls='') # Set colours and config for plot colors = range(0,1000, int(1000/len(patches))) p.set_array(np.array(colors)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) plt.show() # pdb.set_trace() return positions
def plotReachSet_norm1(self, NUM, figname): fig = p.figure() for j in range(n): ax = fig.add_subplot(2,2,j+1 , aspect='equal') ax.set_xlim(0, 4) ax.set_ylim(0, 1) ax.set_xlabel('$x_'+str(j+1)+'$') ax.set_ylabel('$y_'+str(j+1)+'$') for trace in self: for i in [int(floor(k*len(trace.T)/NUM)) for k in range(NUM)]: verts = [(trace.x[i][j] + 1/trace.d_norm1[i][2*j], trace.y[i][j] ), (trace.x[i][j] , trace.y[i][j] - 1/trace.d_norm1[i][2*j+1]), (trace.x[i][j] - 1/trace.d_norm1[i][2*j], trace.y[i][j] ), (trace.x[i][j] , trace.y[i][j] + 1/trace.d_norm1[i][2*j+1])] # poly = Ellipse((trace.x[i][j],trace.y[i][j]), width=trace.d1[i], height=trace.d2[i], angle=trace.theta[i]) poly = Polygon(verts, facecolor='0.8', edgecolor='k') ax.add_artist(poly) poly.set_clip_box(ax.bbox) poly.set_alpha(1) if i==0: poly.set_facecolor('r') else: poly.set_facecolor(p.rand(3)) #for trace in self: #e = Ellipse((trace.x[0][j],trace.y[0][j]), width=trace.d1[0], height=trace.d2[0], angle=trace.theta[0]) #ax.add_artist(e) #e.set_clip_box(ax.bbox) #e.set_alpha(1) #e.set_facecolor('r') #e.set_edgecolor('r') p.savefig(figname)
def add_to_axes(self, ax=None, **kwargs): polys = [(c, self.fields[c]) for c in self.fclasses if self.fields[c]['poly']] if ax is None: fig, ax = plt.subplots(1) pgns = [] for c, f in polys: label = f['names'] pg = Polygon(f['poly'], closed=True, **kwargs) pgns.append(pg) x, y = pg.get_xy().T ax.annotate(c, xy=(np.nanmean(x), np.nanmean(y))) ax.add_patch(pg)
def get_features_from_shape(basemap, path = 'data/shape/contour_bv_MRCC/Bassins_MRCC_utm18.shp', linewidth = 2, edgecolor = 'k', face_color = "none", id_list = None, zorder = 0, alpha = 1): driver = ogr.GetDriverByName("ESRI Shapefile") dataStore = driver.Open(path, 0) layer = dataStore.GetLayer(0) latlong = osr.SpatialReference() latlong.ImportFromProj4("+proj=latlong") result = [] id_list_lower = [] if id_list is not None: id_list_lower = map(lambda x: x.lower(), id_list) feature = layer.GetNextFeature() while feature: geom = feature.GetGeometryRef() geom.TransformTo(latlong) #get fields of the feature # for i in xrange(feature.GetFieldCount()): # print feature.GetField(i) # print geom.ExportToWkt() polygon = loads(geom.ExportToWkt()) boundary = polygon.exterior coords = np.zeros(( len(boundary.coords), 2)) currentId = None for i, the_coord in enumerate(boundary.coords): # if feature.GetFieldAsString('abr').lower() == 'rdo': # print the_coord[0], the_coord[1] if basemap is not None: coords[i, 0], coords[i, 1] = basemap( the_coord[0], the_coord[1] ) currentId = feature.GetFieldAsString("abr").lower() to_add = True if id_list is not None: to_add = currentId in id_list_lower if to_add: p = Polygon(coords,linewidth = linewidth, edgecolor = edgecolor, facecolor=face_color, zorder = zorder, alpha = alpha) p.basin_id = currentId result.append(p) feature = layer.GetNextFeature() dataStore.Destroy() return result
def __init__(self, ax, poly_xy=None, max_ds=10, line_width=2, line_color=(0, 0, 1), face_color=(1, .5, 0)): self.showverts = True self.max_ds = max_ds if poly_xy is None: poly_xy = default_vertices(ax) self.poly = Polygon(poly_xy, animated=True, fc=face_color, ec='none', alpha=0.4) ax.add_patch(self.poly) ax.set_clip_on(False) ax.set_title("Click and drag a point to move it; " "'i' to insert; 'd' to delete.\n" "Close figure when done.") self.ax = ax x, y = zip(*self.poly.xy) #line_color = 'none' color = np.array(line_color) * .6 marker_face_color = line_color line_kwargs = {'lw': line_width, 'color': color, 'mfc': marker_face_color} self.line = plt.Line2D(x, y, marker='o', alpha=0.8, animated=True, **line_kwargs) self._update_line() self.ax.add_line(self.line) self.poly.add_callback(self.poly_changed) self._ind = None # the active vert canvas = self.poly.figure.canvas canvas.mpl_connect('draw_event', self.draw_callback) canvas.mpl_connect('button_press_event', self.button_press_callback) canvas.mpl_connect('button_release_event', self.button_release_callback) canvas.mpl_connect('key_press_event', self.key_press_callback) canvas.mpl_connect('motion_notify_event', self.motion_notify_callback) self.canvas = canvas
def __init__(self, ax, poly_xy=None, max_ds=10): self.showverts = True self.max_ds = max_ds if poly_xy is None: poly_xy = default_vertices(ax) self.poly = Polygon(poly_xy, animated=True, fc='y', ec='none', alpha=0.4) ax.add_patch(self.poly) ax.set_clip_on(False) ax.set_title("Click and drag a point to move it; " "'i' to insert; 'd' to delete.\n" "Close figure when done.") self.ax = ax x, y = zip(*self.poly.xy) self.line = plt.Line2D(x, y, color='none', marker='o', mfc='r', alpha=0.2, animated=True) self._update_line() self.ax.add_line(self.line) self.poly.add_callback(self.poly_changed) self._ind = None # the active vert canvas = self.poly.figure.canvas canvas.mpl_connect('draw_event', self.draw_callback) canvas.mpl_connect('button_press_event', self.button_press_callback) canvas.mpl_connect('button_release_event', self.button_release_callback) canvas.mpl_connect('key_press_event', self.key_press_callback) canvas.mpl_connect('motion_notify_event', self.motion_notify_callback) self.canvas = canvas
def _setup_patch(self): self._patch = Polygon(np.array(list(zip([0, 1], [0, 1])))) self._patch.set_zorder(100) self._patch.set(**self.plot_opts) self._axes.add_patch(self._patch) self._patch.set_visible(False) self._sync_patch()
def __init__(self, ax, Inpimg, Mask, max_ds=10,PolyAtStart = [(50,50),(100,50),(100,100),(50,100)]): self.showverts = True self.max_ds = max_ds self.Mask = Mask self.img = Inpimg self.maskinvert = False # imshow the image self.imgplot = ax.imshow(np.ma.filled(np.ma.array(self.img,mask=self.Mask,fill_value=np.nan)), cmap=cm.gray) self.poly = Polygon(PolyAtStart, animated=True, fc='y', ec='none', alpha=0.5) ax.add_patch(self.poly) ax.set_clip_on(False) ax.set_title("Click and drag a point to move it; " "'i' to insert; 'd' to delete.\n" "'n' to invert the region for masking, 'c' to confirm & apply the mask.") self.ax = ax x, y = zip(*self.poly.xy) self.line = Line2D(x, y, color='none', marker='o', mfc='r', alpha=0.7, animated=True) # self._update_line() self.ax.add_line(self.line) self.poly.add_callback(self.poly_changed) self._ind = None # the active vert canvas = self.poly.figure.canvas canvas.mpl_connect('draw_event', self.draw_callback) canvas.mpl_connect('button_press_event', self.button_press_callback) canvas.mpl_connect('button_release_event', self.button_release_callback) canvas.mpl_connect('key_press_event', self.key_press_callback) canvas.mpl_connect('motion_notify_event', self.motion_notify_callback) self.canvas = canvas
def _setEdge(self, **kwargs): self._dec_range = np.linspace(-90, 90, self._resolution) self._ra_range = np.linspace(-180, 180, self._resolution) + self.proj.ra_0 # styling: frame needs to be on top of everything, must be transparent facecolor = 'None' zorder = 1000 lw = kwargs.pop('lw', 0.7) edgecolor = kwargs.pop('edgecolor', 'k') # if there is facecolor: clone the polygon and put it in as bottom layer facecolor_ = kwargs.pop('facecolor', '#dddddd') # polygon of the map edge: top, left, bottom, right # don't draw poles if that's a single point lines = [self._getMeridian(self.proj.ra_0 + 180, reverse=True), self._getMeridian(self.proj.ra_0 - 180)] if not self.proj.poleIsPoint[-90]: lines.insert(1, self._getParallel(-90, reverse=True)) if not self.proj.poleIsPoint[90]: lines.insert(0, self._getParallel(90)) xy = np.concatenate(lines, axis=1).T self._edge = Polygon(xy, closed=True, edgecolor=edgecolor, facecolor=facecolor, lw=lw, zorder=zorder,gid="edge", **kwargs) self.ax.add_patch(self._edge) if facecolor_ is not None: zorder = -1000 edgecolor = 'None' poly = Polygon(xy, closed=True, edgecolor=edgecolor, facecolor=facecolor_, zorder=zorder, gid="edge-background") self.ax.add_patch(poly)
def __init__(self, axtmp, pntxy): QtCore.QObject.__init__(self) self.ax = axtmp self.poly = Polygon([(1, 1)], animated=True) self.ax.add_patch(self.poly) self.canvas = self.poly.figure.canvas self.poly.set_alpha(0.5) self.pntxy = pntxy self.ishist = True self.background = self.canvas.copy_from_bbox(self.ax.bbox) xtmp, ytmp = list(zip(*self.poly.xy)) self.line = Line2D(xtmp, ytmp, marker='o', markerfacecolor='r', color='y', animated=True) self.ax.add_line(self.line) self.poly.add_callback(self.poly_changed) self._ind = None # the active vert self.canvas.mpl_connect('button_press_event', self.button_press_callback) self.canvas.mpl_connect('button_release_event', self.button_release_callback) self.canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
def getCatalog(size=10000, surveyname=None): # dummy catalog: uniform on sphere # Marsaglia (1972) xyz = np.random.normal(size=(size, 3)) r = np.sqrt((xyz**2).sum(axis=1)) dec = np.arccos(xyz[:,2]/r) / skm.DEG2RAD - 90 ra = - np.arctan2(xyz[:,0], xyz[:,1]) / skm.DEG2RAD if surveyname is not None: from matplotlib.patches import Polygon # construct survey polygon ra_fp, dec_fp = skm.survey_register[surveyname].getFootprint() poly = Polygon(np.dstack((ra_fp,dec_fp))[0], closed=True) inside = [poly.get_path().contains_point(Point(ra_,dec_)) for (ra_,dec_) in zip(ra,dec)] ra = ra[inside] dec = dec[inside] return ra, dec
def pressContour(self, event): if event.inaxes==None: return if event.button != 1: return # new contour if self.poly is None: self.poly = Polygon( [(event.xdata , event.ydata)] , animated=False , alpha = .3 , color = 'g') self.ax.add_patch(self.poly) self.line, = self.ax.plot([event.xdata] , [event.ydata] , color = 'g', linewidth = 2 , marker = 'o' , markerfacecolor='g', animated=False) #~ self.canvas.draw() self.redraw() return # event near a point xy = asarray(self.poly.xy) xyt = self.poly.get_transform().transform(xy) xt, yt = xyt[:, 0], xyt[:, 1] print '#######' d = sqrt((xt-event.x)**2 + (yt-event.y)**2) indseq = nonzero(equal(d, amin(d)))[0] self._ind = indseq[0] if d[self._ind]>=self.epsilon: self._ind = None self.a=list(numpy.copy(self.poly.xy)) for i,j in enumerate(self.a): self.a[i]=tuple(j) # new point if self._ind is None: b=float(event.xdata) c=float(event.ydata) d=(b,c) e=[d] #self.a=numpy.append(self.a,e) self.a.extend(e) self.line.set_xdata( list(self.line.get_xdata()) + [ event.xdata] ) self.line.set_ydata( list(self.line.get_ydata()) + [ event.ydata] ) #~ self.canvas.draw() self.redraw() #self.poly.xy=a print self.a, type(self.a) if self.a != None: test=Path(self.a) self.actualSelection, = where(test.contains_points(dot( self.data, self.projection ))) self.emit(SIGNAL('selectionChanged'))
def __init__(self, axes, roi=None): super(MplPolygonalROI, self).__init__(axes, roi=roi) self.plot_opts = {'edgecolor': PATCH_COLOR, 'facecolor': PATCH_COLOR, 'alpha': 0.3} self._patch = Polygon(np.array(list(zip([0, 1], [0, 1]))), zorder=100) self._patch.set_visible(False) self._axes.add_patch(self._patch)
def __init__(self, ax): """ :param ax: A matplotlib Axes object to attach the graphical ROI to """ AbstractMplRoi.__init__(self, ax) self.plot_opts = {'edgecolor': PATCH_COLOR, 'facecolor': PATCH_COLOR, 'alpha': 0.3} self._patch = Polygon(np.array(zip([0, 1], [0, 1]))) self._patch.set_zorder(100) self._patch.set(**self.plot_opts) self._setup_patch()
def draw_new_poly(self): coords = default_vertices(self.ax) Poly = Polygon(coords, animated=True, fc="white", ec='none', alpha=0.2, picker=True) self.polyList.append(Poly) self.ax.add_patch(Poly) x, y = zip(*Poly.xy) #line_color = 'none' color = np.array((1,1,1)) marker_face_color = (1,1,1) line_width = 4; line_kwargs = {'lw': line_width, 'color': color, 'mfc': marker_face_color} self.line.append(plt.Line2D(x, y, marker='o', alpha=1, animated=True, **line_kwargs)) self._update_line() self.ax.add_line(self.line[-1]) Poly.add_callback(self.poly_changed) Poly.num = self.poly_count self._ind = None # the active vert self.poly_count+=1;
def __init__(self, filename, **kwargs): """ Create a new coastline polygon. Parameters ---------- color : color, optional, default 'gray' Line color of the coastline. land : color, optional, default 'seashell' Fill color of the land polygons. Other parameters ---------------- kwargs : polygon properties Other parameters passed on to :class:`~matplotlib.patches.Polygon`, e.g. zorder=N to control drawing the land polygons above/below other data. """ color = kwargs.pop('color', 'gray') land = kwargs.pop('land', 'seashell') self.data = [] self.extents = None if not color: color = 'none' if not land: land = 'none' xy = [[None, None], [None, None]] Polygon.__init__(self, xy, edgecolor=color, facecolor=land, **kwargs) datapath = os.path.join(os.path.dirname(__file__), 'data') coastfile = _find(filename, datapath) if coastfile: file = shapefile.Reader(coastfile) for shape in file.shapes(): for points in _split(shape.points, shape.parts): self.data += [Path(points)] else: raise Warning('coastline "%s" not found in directory "%s"' % (filename, datapath))
def fill_between(x, y1, y2, ax=P.gca(), alpha=0.5, **kwargs): """Plot distribution to a head surface, derived from some sensor locations. The sensor locations are first projected onto the best fitting sphere and finally projected onto a circle (by simply ignoring the z-axis). :Parameters: x: ,y1,y2 ax: mpl axes axes to plot to. Standard is pylab. view: one of 'top' and 'rear' Defines from where the head is viewed. **kwargs: All additional arguments will be passed to `pylab.imshow()`. :Returns: (map, head, sensors) The corresponding matplotlib objects are returned if plotted, ie. if plothead is set to `False`, `head` will be `None`. map The colormap that makes the actual plot, a matplotlib.image.AxesImage instance. head What is returned by `plot_head_outline()`. sensors The dots marking the electrodes, a matplotlib.lines.Line2d instance. """ # add x,y2 in reverse order for proper polygon filling verts = zip(x,y1) + [(x[i], y2[i]) for i in range(len(x)-1,-1,-1)] poly = Polygon(verts, **kwargs) poly.set_alpha(alpha) ax.add_patch(poly) ax.autoscale_view() return poly
def draw(self, renderer): if isSupportedRenderer(renderer): renderer.use_gl = True glcanvas = get_glcanvas() if self.axes is not None: tag = self.axes trans = self.axes.transAxes elif self.figure is not None: tag = self.figure trans = self.figure.transFigure gc = renderer.new_gc() rgbFace = self._facecolor gc.set_foreground(self._edgecolor, isRGBA=True) glcanvas.frame_request(self, trans) # if not glcanvas.has_vbo_data(self): glcanvas.start_draw_request(self) if self._invalidz: if glcanvas.has_vbo_data(self): d = glcanvas.get_vbo_data(self) d[0]['v'].need_update = True self._invalidz = False renderer.gl_draw_path(gc, self._verts3d, trans, rgbFace = rgbFace, stencil_test = self.do_stencil_test) # glcanvas.update_gc(self, gc) glcanvas.end_draw_request() # else: # glcanvas.update_gc(self, gc) gc.restore() renderer.use_gl = False finish_gl_drawing(glcanvas, renderer, tag, trans) else: Polygon.draw(self, renderer)
def plot_category_chart(ax, res, show_legend=True): """Plot stacked bar chart of remapping response categories Arguments: ax -- axis to plot into res -- trends results dictionary Keyword arguments: show_legend -- whether to draw legend """ from matplotlib.patches import Polygon labels = res['mismatch_labels'] N = res['N_mismatch'] x = np.arange(1, N+1) stacked = np.empty((len(CL_LABELS)+1, N), 'd') stacked[0] = 0.0 stacked[-1] = 1.0 cats = res['categories'] for i in xrange(1,len(CL_LABELS)): stacked[i] = stacked[i-1] + cats[CL_LABELS[i-1]] poly_kwargs = dict(aa=True, lw=1.5, alpha=0.85) xloop = np.concatenate((x, x[::-1])) for i in xrange(len(CL_LABELS)): yloop = np.concatenate((stacked[i], stacked[i+1,::-1])) p = Polygon(np.c_[xloop, yloop], fc=CL_COLORS[i], ec=CL_COLORS[i], label=CL_LABELS[i], **poly_kwargs) ax.add_artist(p) p.set_clip_box(ax.bbox) ax.axis([1, N, 0, 1]) ax.set_xticks(x) ax.set_xticklabels(labels) ax.set_xlabel('Mismatch') ax.set_ylabel('Response Fraction') if show_legend: ax.legend(loc='upper left', bbox_to_anchor=(1.01, 1.0)) return ax
def overlapping_bricks(self, candidates, map_petals=False): """Convert a list of potentially overlapping bricks into actual overlaps. Parameters ---------- candidates : :class:`list` A list of candidate bricks. map_petals : bool, optional If ``True`` a map of petal number to a list of overlapping bricks is returned. Returns ------- :class:`list` A list of Polygon objects. """ petals = self.petals() petal2brick = dict() bricks = list() for b in candidates: b_ra1, b_ra2 = self.brick_offset(b) brick_corners = np.array([[b_ra1, b.dec1], [b_ra2, b.dec1], [b_ra2, b.dec2], [b_ra1, b.dec2]]) brick = Polygon(brick_corners, closed=True, facecolor='r') for i, p in enumerate(petals): if brick.get_path().intersects_path(p.get_path()): brick.set_facecolor('g') if i in petal2brick: petal2brick[i].append(b.id) else: petal2brick[i] = [b.id] bricks.append(brick) if map_petals: return petal2brick return bricks
def on_press(self, event): #Comprobamos si hemos pulsado en un punto antiguo para moverlo for circle in self.list_circles: contains, attr = circle.contains(event) if contains: self.touched_circle = circle self.exists_touched_circle = True self.pressed_event = event self.touched_x0, self.touched_y0 = circle.center return #Limpiamos los ejes y pintamos todos los puntos plt.cla() if self.cont==2: self.list_circles.remove(self.list_circles[0]) c = Circle((event.xdata,event.ydata),0.02) ax.add_patch(Circle((0,0),1,color='blue', fill = False)) self.list_circles.append(c) for circle in self.list_circles : self.ax.add_patch(circle) #Guardamos el nuevo punto (borrando el primero si ya habia dos) new_point = [event.xdata,event.ydata] if not(self.polygon_exist) : self.polygon.append(new_point) self.P = Polygon(self.polygon, closed = False,color = 'red', fill = False) self.polygon_exist = True else : if self.cont==2: self.polygon.remove(self.polygon[0]) self.polygon.append(new_point) self.P.set_xy(self.polygon) self.ax.add_patch(self.P) self.fig.canvas.draw() #Si a1 y a2 se encuentran dentro del disco unidad: if self.cont<2: self.cont=self.cont+1 if self.cont==2: a1 = self.polygon[0] a2 = self.polygon[1] if np.linalg.norm(a1)<=1 and np.linalg.norm(a2)<=1: self.calculate_Blaschke3(a1,a2)
def _createWidgets(self): # Create the mpl Figure and FigCanvas objects. # 5x4 inches, 100 dots-per-inch # self.dpi = 100 self.fig = Figure((1.0, 1.0), dpi=self.dpi) self.fig.autolayout = True self.canvas = FigCanvas(self, -1, self.fig) self.axes = self.fig.add_axes([0.0, 0.0, 1, 1]) pol = Polygon(list(zip([0], [0])), animated=True) self.axes.add_patch(pol) self.polygon_drawer = PolygonDrawer(self.axes, pol=pol, empty_pol=True) self.zoom_wheel_coords = None self.zoom_rect_coords = None self.zoom_rect = Polygon(list(zip([0], [0])), facecolor='none') self.zoom_rect.set_visible(False) self.axes.add_patch(self.zoom_rect)
def pressContour(self, event): if event.inaxes==None: return if event.button != 1: return # new contour if self.poly is None: self.poly = Polygon( [[event.xdata , event.ydata]] , animated=False , alpha = .3 , color = 'g') self.ax.add_patch(self.poly) self.line, = self.ax.plot([event.xdata] , [event.ydata] , color = 'g', linewidth = 2 , marker = 'o' , markerfacecolor='g', animated=False) self.redraw() return # event near a point xy = np.asarray(self.poly.xy) xyt = self.poly.get_transform().transform(xy) xt, yt = xyt[:, 0], xyt[:, 1] d = np.sqrt((xt-event.x)**2 + (yt-event.y)**2) indseq = np.nonzero(np.equal(d, np.amin(d)))[0] self._ind = indseq[0] if d[self._ind]>=self.epsilon: self._ind = None # new point if self._ind is None: self.poly.xy = np.array( list(self.poly.xy) + [[event.xdata , event.ydata]]) self.line.set_xdata( np.array(list(self.line.get_xdata()) + [ event.xdata]) ) self.line.set_ydata( np.array(list(self.line.get_ydata()) + [ event.ydata]) ) self.redraw() self.actualSelection = points_inside_poly(np.dot( self.data, self.projection ), self.poly.xy) self.selection_changed.emit()
def _init_boundary_interactor(self): """Send polyclick thread to boundary interactor""" # Get rid old mpl connections. self._ax.figure.canvas.mpl_disconnect(self._key_id) self._ax.figure.canvas.mpl_disconnect(self._click_id) # Shade the selected region in a polygon self._poly = Polygon(self.verts, alpha=0.2, fc='k', animated=True) self._ax.add_patch(self._poly) # modify the line properties self._line.set_markerfacecolor('k') # get the canvas and connect the callback events cid = self._poly.add_callback(self._poly_changed) self._ind = None # the active vert self._canvas.mpl_connect('draw_event', self._draw_callback) self._canvas.mpl_connect('button_press_event', self._button_press_callback) self._canvas.mpl_connect('key_press_event', self._key_press_callback) self._canvas.mpl_connect('button_release_event', self._button_release_callback) self._canvas.mpl_connect('motion_notify_event', self._motion_notify_callback)
def update(self): # print "updating" if len(self.vertices) >= 3: xy = numpy.array([v.circle.center for v in self.vertices]) # bug in matplotlib? patch is not closed without this xy = numpy.concatenate([xy, [xy[0]]]) if self.poly is None: self.poly = Polygon(xy, closed=True, alpha=0.5, facecolor="pink") self.ax.add_patch(self.poly) else: self.poly.set_xy(xy) if self.background is not None: self.canvas.restore_region(self.background) if self.poly is not None: self.ax.draw_artist(self.poly) for vertex in self.vertices: self.ax.draw_artist(vertex.circle) # print ">>>", self.ax.bbox self.canvas.blit(self.ax.bbox)
def _init_boundary_interactor(self): """Send polyclick thread to boundary interactor""" # Get rid old mpl connections. self._ax.figure.canvas.mpl_disconnect(self._key_id) self._ax.figure.canvas.mpl_disconnect(self._click_id) # Shade the selected region in a polygon self._poly = Polygon(self.verts, alpha=0.1, fc='k', animated=True) self._ax.add_patch(self._poly) # change line to animated # self._line.set_animated(True) # self._line.set_markerfacecolor('k') self._line.set_marker('None') # Link in the two lines that will show the beta values # pline for positive turns, mline for negative (minus) turns. self._pline = Line2D([], [], marker='^', ms=12, mfc='g', animated=True, lw=0) self._mline = Line2D([], [], marker='v', ms=12, mfc='r', animated=True, lw=0) self._zline = Line2D([], [], marker='o', mfc='k', animated=True, lw=0) self._sline = Line2D([], [], marker='s', mfc='k', animated=True, lw=0) self._update_beta_lines() self._ax.add_artist(self._pline) self._ax.add_artist(self._mline) self._ax.add_artist(self._zline) self._ax.add_artist(self._sline) # get the canvas and connect the callback events cid = self._poly.add_callback(self._poly_changed) self._ind = None # the active vert self._canvas.mpl_connect('draw_event', self._draw_callback) self._canvas.mpl_connect('button_press_event', self._button_press_callback) self._canvas.mpl_connect('key_press_event', self._key_press_callback) self._canvas.mpl_connect('button_release_event', self._button_release_callback) self._canvas.mpl_connect('motion_notify_event', self._motion_notify_callback)
def create_figure(): f = plt.figure(frameon=False) f.set_size_inches(1, 1) ax = plt.Axes(f, [0.0, 0.0, 1.0, 1.0]) #ax.set_axis_off() f.add_axes(ax) ax.set_xlim([0, 50]) ax.set_ylim([0, 50]) # # Circe of random size # f.patch.set_facecolor("black") ax.patch.set_facecolor("black") n = np.random.randint(0, 20) for i in range(n): r = np.random.uniform(5, 10) x, y = np.random.uniform(0, 100, size=2) circle = plt.Circle((x, y), r, color="white") ax.add_artist(circle) # # Random triangle # n = np.random.randint(0, 20) for i in range(n): r = np.random.uniform(2, 10) x, y = np.random.uniform(0, 100, size=2) v0 = np.array([x, y]) v1 = v0 + np.array([r, 0]) v2 = np.array([x + 0.5 * r, y + r * np.sin(60.0 / 180.0 * np.pi)]) points = np.stack([v0, v1, v2]) midpoint = (v0 + v1 + v2) / 3.0 polygon = Polygon(points, color="white") theta = np.random.uniform(0, 360) r = Affine2D().rotate_around(midpoint[0], midpoint[1], theta) tra = r + ax.transData polygon.set_transform(tra) ax.add_artist(polygon) # # Random line # n = np.random.randint(0, 20) for i in range(n): l = 2 * np.random.normal() + 10 x, y = np.random.uniform(0, 100, size=2) theta = np.random.uniform(0, 360) v0 = np.array([x, y]) v1 = v0 + np.array([np.cos(theta)]) v0 = np.array([x, y]) theta = np.random.uniform(0, 2 * np.pi) v1 = v0 + np.array([l * np.cos(theta), l * np.sin(theta)]) ax.plot([v0[0], v1[0]], [v0[1], v1[1]], c="white", lw=3) return f
map = Basemap(projection='merc',llcrnrlat=50,urcrnrlat=55,\ llcrnrlon=-7,urcrnrlon=2,lat_ts=52,resolution='c') map.drawmapboundary(fill_color='#99ccff') map.readshapefile('countries/countries', 'countries', drawbounds=False) patches = [] for info, shape in zip(map.countries_info, map.countries): if info['NAME'] in [ 'United Kingdom', 'Ireland', 'France', 'Belgium', 'Luxembourg', 'Netherlands', 'Norway' ]: patches.append( Polygon(np.array(shape), True, facecolor='#ccffcc', edgecolor='none')) ax.add_collection(PatchCollection(patches, zorder=2, match_original=True)) map.plot(t['longitude'], t['latitude'], 'k.', latlon=True, ax=ax, alpha=0.1, markersize=1) map.plot(-1.5788031, 53.8164596, 'ro', latlon=True, markersize=5, alpha=0.5) fig.savefig('uk_map.png', bbox_inches='tight', dpi=150)
def display_instances(image, boxes, masks, class_ids, class_names,poses, scores=None, title="",title1='', figsize=(16, 16), axs=None): """ boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. poses: [num_instance, (tetax,tetay,tetaz,x,y,z)] in radians and cm. masks: [height, width, num_instances] class_ids: [NUM_FEATURES,num_instances] ids/feature class_names: [NUM_FEATURES], list of class names of the dataset/feature scores: [NUM_FEATURES,num_instances],(optional) confidence scores for each box/feature figsize: (optional) the size of the image. """ # Number of instances N = boxes.shape[0] if not N: print("\n*** No instances to display *** \n") return 0 else: assert boxes.shape[0] == masks.shape[-1] == class_ids[0].shape[0]==class_ids[1].shape[0]==class_ids[2].shape[0]==\ class_ids[3].shape[0]==class_ids[4].shape[0]==class_ids[5].shape[0]==scores[0].shape[0]==scores[1].shape[0]==scores[2].shape[0]==\ scores[3].shape[0]==scores[4].shape[0]==scores[5].shape[0]==poses.shape[0] if not np.any(axs): _, axs = plt.subplots(1,2, figsize=figsize) ax=axs[0] ax1=axs[1] # Generate random colors colors = random_colors(N) titles=[title,title1] # Show area outside image boundaries. height, width = image.shape[:2] for i in range(axs.size): axs[i].set_ylim(height + 10, -10) axs[i].set_xlim(-10, width + 10) axs[i].axis('off') axs[i].set_title(titles[i]) masked_image = image.astype(np.uint32).copy() back_img=image.astype(np.uint32).copy()*0+255 x3=10 y3=10 #class_ids[len(class_ids)-1]=class_ids[len(class_ids)-1]+1 #best_relations=np.argmax(scores[len(class_ids)-1],axis=1) #best_relations=utils.relation_graph(boxes) for i in range(N): color = colors[i] # Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=0.7, linestyle="dashed", edgecolor=color, facecolor='none') ax.add_patch(p) # Label caption=str(i)+'. ' if scores!=None and False: for j in range(len(class_ids)-1): caption=caption+class_names[j][class_ids[j][i]]+' '+str(scores[j][i])+'\n' else: for j in range(len(class_ids)-1): caption=caption+class_names[j][class_ids[j][i]]+'\n' caption=caption+'Orientation: ('+str(poses[i][0])+','+str(poses[i][1])+','+str(poses[i][2])+')\n' caption=caption+'Position: ('+str(poses[i][3])+','+str(poses[i][4])+','+str(poses[i][5])+')' x = random.randint(x1, (x1 + x2) // 2) ax.text(x1, y1 + 8, caption, color='black', size=7, backgroundcolor="none") #object relationship for k in range(N): #k=best_relations[i] if(class_ids[len(class_ids)-1][i][k]!=0 and i!=k): caption=str(i)+'.'+class_names[0][class_ids[0][i]]+' is '+class_names[5][class_ids[len(class_ids)-1][i][k]]+' '+str(k)+\ '.'+class_names[0][class_ids[0][k]]+': '+str((scores[len(class_ids)-1][i][k]))+'.' print('RELATION:'+caption) ax1.text(x3, y3, caption,color='black', size=8, backgroundcolor="none") y3+=30 # Mask mask = masks[:, :, i] masked_image = apply_mask(masked_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros( (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) ax.add_patch(p) ax.imshow(masked_image.astype(np.uint8)) ax1.imshow(back_img) plt.show()
def plot(): from matplotlib.patches import Circle, Ellipse, Polygon, Rectangle, Wedge from matplotlib.collections import PatchCollection from matplotlib import pyplot as plt import numpy as np import matplotlib as mpl np.random.seed(123) fig = plt.figure() ax = fig.add_subplot(111) N = 3 x = np.random.rand(N) y = np.random.rand(N) radii = 0.1 * np.random.rand(N) patches = [] for x1, y1, r in zip(x, y, radii): circle = Circle((x1, y1), r) patches.append(circle) rect = Rectangle(xy=[0.0, 0.25], width=1.0, height=0.5, angle=-45.0) patches.append(rect) x = np.random.rand(N) y = np.random.rand(N) radii = 0.1 * np.random.rand(N) theta1 = 360.0 * np.random.rand(N) theta2 = 360.0 * np.random.rand(N) for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2): wedge = Wedge((x1, y1), r, t1, t2) patches.append(wedge) # Some limiting conditions on Wedge patches += [ Wedge((0.3, 0.7), 0.1, 0, 360), # Full circle Wedge((0.7, 0.8), 0.2, 0, 360, width=0.05), # Full ring Wedge((0.8, 0.3), 0.2, 0, 45), # Full sector Wedge((0.8, 0.3), 0.2, 45, 90, width=0.10), # Ring sector ] for _ in range(N): polygon = Polygon(np.random.rand(N, 2), True) patches.append(polygon) colors = 100 * np.random.rand(len(patches)) p = PatchCollection(patches, cmap=mpl.cm.jet, alpha=0.4) p.set_array(np.array(colors)) ax.add_collection(p) ellipse = Ellipse(xy=[1.0, 0.5], width=1.0, height=0.5, angle=45.0, alpha=0.4) ax.add_patch(ellipse) circle = Circle(xy=[0.0, 1.0], radius=0.5, color="r", alpha=0.4) ax.add_patch(circle) plt.colorbar(p) return fig
def fisher_jenks_map(coords, y, k, title='Fisher-Jenks', sampled=False): """ coords: Map_Projection instance y: array variable to map k: int number of classes title: string map title sampled: binary if True classification bins obtained on a sample of y and then applied. Useful for large n arrays """ if sampled: classification = ps.esda.mapclassify.Fisher_Jenks_Sampled(y,k) else: classification = ps.Fisher_Jenks(y,k) fig = plt.figure() ax = fig.add_subplot(111) patches = [] colors = [] i = 0 shape_colors = y #classification.bins[classification.yb] for shp in coords.projected: for ring in shp: x,y = ring x = x / coords.bounding_box[2] y = y / coords.bounding_box[3] n = len(x) x.shape = (n,1) y.shape = (n,1) xy = np.hstack((x,y)) polygon = Polygon(xy, True) patches.append(polygon) colors.append(shape_colors[i]) i += 1 cmap = cm.get_cmap('hot_r', k+1) boundaries = classification.bins[:] #print boundaries #print min(shape_colors) > 0.0 if min(shape_colors) > 0.0: boundaries.insert(0,0) else: boundaries.insert(0, boundaries[0] - boundaries[1]) #print boundaries norm = clrs.BoundaryNorm(boundaries, cmap.N) p = PatchCollection(patches, cmap=cmap, alpha=0.4, norm=norm) colors = np.array(colors) p.set_array(colors) ax.add_collection(p) ax.set_frame_on(False) ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False) ax.set_title(title) plt.colorbar(p, cmap=cmap, norm = norm, boundaries = boundaries, ticks= boundaries) plt.show() return classification
ea_file = 'EA_prj.shp' land_cover = fiona.open(shapefile_dir + land_cover_file) vjr = fiona.open(shapefile_dir + vjr_file) ea = fiona.open(shapefile_dir + ea_file) patches = [] colours = ['#30A000', '#85EE58', '#E756A8', '0.75'] for poly in land_cover: color_iter = colours[poly['properties']['HCS_CLass'] - 1] if poly['geometry']['type'] == 'MultiPolygon': Npoly = len(poly['geometry']['coordinates'][1]) for nn in range(0, Npoly): polygon = Polygon(poly['geometry']['coordinates'][1][nn], True, ec='None', fc=color_iter) patches.append(polygon) else: polygon = Polygon(poly['geometry']['coordinates'][0], True, ec='None', fc=color_iter) patches.append(polygon) VJR_poly = vjr[0] polygon = Polygon(VJR_poly['geometry']['coordinates'][0], True, ec='#1A2CCE', fc='None') patches.append(polygon)
def display_instances(image, boxes, masks, class_ids, class_names, scores=None, title="", figsize=(16, 16), ax=None): """ boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. masks: [height, width, num_instances] class_ids: [num_instances] class_names: list of class names of the dataset scores: (optional) confidence scores for each box figsize: (optional) the size of the image. """ # Number of instances N = boxes.shape[0] if not N: print("\n*** No instances to display *** \n") else: assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0] if not ax: _, ax = plt.subplots(1, figsize=figsize) # Generate random colors colors = random_colors(N) # Show area outside image boundaries. height, width = image.shape[:2] ax.set_ylim(height + 10, -10) ax.set_xlim(-10, width + 10) ax.axis('off') ax.set_title(title) masked_image = image.astype(np.uint32).copy() contourlist = [] for i in range(N): color = colors[i] # Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=0.7, linestyle="dashed", edgecolor=color, facecolor='none') # ax.add_patch(p) # Label class_id = class_ids[i] score = scores[i] if scores is not None else None label = class_names[class_id] x = random.randint(x1, (x1 + x2) // 2) caption = "{} {:.3f}".format(label, score) if score else label # ax.text(x1, y1 + 8, caption,color='w', size=11, backgroundcolor="none") # Mask mask = masks[:, :, i] masked_image = apply_mask(masked_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) # contourlist.append(contours) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) contourlist.append(p.get_xy()) ax.add_patch(p) break image1 = cv2.imread( '/home/sumedh/Machine Learning/Mask_RCNN/images/cool.jpg', -1) resultant = image1.copy() image = Image.open( '/home/sumedh/Machine Learning/Mask_RCNN/images/cool.jpg') blurred_image = image.filter(ImageFilter.GaussianBlur(radius=3)) blurred_image.show() # blur = cv2.GaussianBlur(resultant, (39, 39), 0) # blur = cv2.blur(resultant, (5, 5)) # mask defaulting to black for 3-channel and transparent for 4-channel # (of course replace corners with yours) a = np.array(contourlist) mask4 = np.zeros(image1.shape, dtype=np.uint8) roi_corners = np.array(contourlist, dtype=np.int32) # fill the ROI so it doesn't get wiped out when the mask is applied channel_count = image1.shape[2] # i.e. 3 or 4 depending on your image ignore_mask_color = (255, ) * channel_count cv2.fillPoly(mask4, roi_corners, ignore_mask_color) # from Masterfool: use cv2.fillConvexPoly if you know it's convex # resultant[mask4] = mask4 # apply the mask mask_to_pil = Image.fromarray(np.uint8(255 * mask4)) background = cv2.bitwise_not(mask4) fore_ground_image = cv2.bitwise_and(image1, mask4) background_image = cv2.bitwise_and(image1, background) blur = cv2.GaussianBlur(background_image, (49, 49), 0) blur_original = cv2.GaussianBlur(image1, (49, 49), 0) cv2.imwrite("background.png", blur) cv2.imwrite("foreground.png", fore_ground_image) bck = Image.open("background.png") fgk = Image.open("foreground.png") blended = Image.blend(bck, fgk, alpha=15.0) blended.save("resultant.png") cv2.imwrite("mask.png", mask4) cv2.imwrite("blur_original.png", blur_original) callling() #cv2.imwrite("final_image.png",vis) # save the result # cv2.imwrite('image_masked.png', background) # m_image = Image.open('image_masked.png') # blurred_image.paste(m_image, box=None, mask=mask_to_pil) # blurred_image.show() # store_cropped_image(masked_image,contourlist) ax.imshow(masked_image.astype(np.uint8)) plt.show()
def compare_mesh_topo (): # File paths # I know the copy-paste of 6 meshes is terrible programing practice. # But I am in a hurry. mesh_path_A = '../FESOM_mesh/low_res_fixsmooth/output/' mesh_path_B = '../FESOM_mesh/high_res_fixsmooth/output/' mesh_path_C = '../FESOM_mesh/extra_high_res_less_amery/output/' mesh_path_D = '../FESOM_mesh/extra_high_res_less_amery_more_acc/output/' mesh_path_E = '../FESOM_mesh/extra_high_res/output/' mesh_path_F = '../FESOM_mesh/extra_high_res_more_acc/output/' rtopo_data_file = '../FESOM_mesh/RTopo105/RTopo105_data.nc' rtopo_aux_file = '../FESOM_mesh/RTopo105/RTopo105_aux.nc' # Maximum j-index to read from RTopo (can skip most of the world) rtopo_max_j = 2000 # Degrees to radians conversion factor deg2rad = pi/180.0 # Name of each region region_names = ['Filchner-Ronne Ice Shelf', 'Eastern Weddell Region', 'Amery Ice Shelf', 'Australian Sector', 'Ross Sea', 'Amundsen Sea', 'Bellingshausen Sea', 'Larsen Ice Shelves'] num_regions = len(region_names) # Beginning of filenames for figures fig_heads = ['filchner_ronne', 'eweddell', 'amery', 'australian', 'ross', 'amundsen', 'bellingshausen', 'larsen'] # Bounds for each region (using polar coordinate transformation as below) x_min = [-14, -8, 15.25, 12, -9.5, -15.5, -20.25, -22.5] x_max = [-4.5, 13, 20.5, 25.5, 4, -10.5, -15.5, -14.5] y_min = [1, 12, 4.75, -20, -13, -11.25, -4.5, 8.3] y_max = [10, 21, 8, 4, -4.75, -2.25, 7.6, 13] # Size of each plot in the y direction ysize = [12, 9, 10, 13, 10, 13, 15, 10] # Grey colourmap for RTopo land mask grey_cmap = ListedColormap([(0.6, 0.6, 0.6)]) print 'Reading mesh A' # Build mesh elements_A = fesom_grid(mesh_path_A, circumpolar=True, cross_180=True) # Build patches for ocean, open ocean, and ice shelves patches_A = [] shelf_patches_A = [] ocean_patches_A = [] for elm in elements_A: coord = transpose(vstack((elm.x, elm.y))) if elm.cavity: shelf_patches_A.append(Polygon(coord, True, linewidth=0.)) else: ocean_patches_A.append(Polygon(coord, True, linewidth=0.)) patches_A.append(Polygon(coord, True, linewidth=0.)) # Calculate bathy, draft, wct at each element bathy_A = [] draft_A = [] wct_A = [] for elm in elements_A: # Bathymetry is depth of bottom layer, averaged over 3 Nodes bathy_A.append(mean([elm.nodes[0].find_bottom().depth, elm.nodes[1].find_bottom().depth, elm.nodes[2].find_bottom().depth])) if elm.cavity: # Ice shelf draft is depth of surface layer draft_A.append(mean([elm.nodes[0].depth, elm.nodes[1].depth, elm.nodes[2].depth])) # Water column thickness is depth of bottom layer minus depth of # surface layer wct_A.append(mean([elm.nodes[0].find_bottom().depth - elm.nodes[0].depth, elm.nodes[1].find_bottom().depth - elm.nodes[1].depth, elm.nodes[2].find_bottom().depth - elm.nodes[2].depth])) print 'Reading mesh B' elements_B = fesom_grid(mesh_path_B, circumpolar=True, cross_180=True) patches_B = [] shelf_patches_B = [] ocean_patches_B = [] for elm in elements_B: coord = transpose(vstack((elm.x, elm.y))) if elm.cavity: shelf_patches_B.append(Polygon(coord, True, linewidth=0.)) else: ocean_patches_B.append(Polygon(coord, True, linewidth=0.)) patches_B.append(Polygon(coord, True, linewidth=0.)) bathy_B = [] draft_B = [] wct_B = [] for elm in elements_B: bathy_B.append(mean([elm.nodes[0].find_bottom().depth, elm.nodes[1].find_bottom().depth, elm.nodes[2].find_bottom().depth])) if elm.cavity: draft_B.append(mean([elm.nodes[0].depth, elm.nodes[1].depth, elm.nodes[2].depth])) wct_B.append(mean([elm.nodes[0].find_bottom().depth - elm.nodes[0].depth, elm.nodes[1].find_bottom().depth - elm.nodes[1].depth, elm.nodes[2].find_bottom().depth - elm.nodes[2].depth])) print 'Reading mesh C' elements_C = fesom_grid(mesh_path_C, circumpolar=True, cross_180=True) patches_C = [] shelf_patches_C = [] ocean_patches_C = [] for elm in elements_C: coord = transpose(vstack((elm.x, elm.y))) if elm.cavity: shelf_patches_C.append(Polygon(coord, True, linewidth=0.)) else: ocean_patches_C.append(Polygon(coord, True, linewidth=0.)) patches_C.append(Polygon(coord, True, linewidth=0.)) bathy_C = [] draft_C = [] wct_C = [] for elm in elements_C: bathy_C.append(mean([elm.nodes[0].find_bottom().depth, elm.nodes[1].find_bottom().depth, elm.nodes[2].find_bottom().depth])) if elm.cavity: draft_C.append(mean([elm.nodes[0].depth, elm.nodes[1].depth, elm.nodes[2].depth])) wct_C.append(mean([elm.nodes[0].find_bottom().depth - elm.nodes[0].depth, elm.nodes[1].find_bottom().depth - elm.nodes[1].depth, elm.nodes[2].find_bottom().depth - elm.nodes[2].depth])) print 'Reading mesh D' elements_D = fesom_grid(mesh_path_D, circumpolar=True, cross_180=True) patches_D = [] shelf_patches_D = [] ocean_patches_D = [] for elm in elements_D: coord = transpose(vstack((elm.x, elm.y))) if elm.cavity: shelf_patches_D.append(Polygon(coord, True, linewidth=0.)) else: ocean_patches_D.append(Polygon(coord, True, linewidth=0.)) patches_D.append(Polygon(coord, True, linewidth=0.)) bathy_D = [] draft_D = [] wct_D = [] for elm in elements_D: bathy_D.append(mean([elm.nodes[0].find_bottom().depth, elm.nodes[1].find_bottom().depth, elm.nodes[2].find_bottom().depth])) if elm.cavity: draft_D.append(mean([elm.nodes[0].depth, elm.nodes[1].depth, elm.nodes[2].depth])) wct_D.append(mean([elm.nodes[0].find_bottom().depth - elm.nodes[0].depth, elm.nodes[1].find_bottom().depth - elm.nodes[1].depth, elm.nodes[2].find_bottom().depth - elm.nodes[2].depth])) print 'Reading mesh E' elements_E = fesom_grid(mesh_path_E, circumpolar=True, cross_180=True) patches_E = [] shelf_patches_E = [] ocean_patches_E = [] for elm in elements_E: coord = transpose(vstack((elm.x, elm.y))) if elm.cavity: shelf_patches_E.append(Polygon(coord, True, linewidth=0.)) else: ocean_patches_E.append(Polygon(coord, True, linewidth=0.)) patches_E.append(Polygon(coord, True, linewidth=0.)) bathy_E = [] draft_E = [] wct_E = [] for elm in elements_E: bathy_E.append(mean([elm.nodes[0].find_bottom().depth, elm.nodes[1].find_bottom().depth, elm.nodes[2].find_bottom().depth])) if elm.cavity: draft_E.append(mean([elm.nodes[0].depth, elm.nodes[1].depth, elm.nodes[2].depth])) wct_E.append(mean([elm.nodes[0].find_bottom().depth - elm.nodes[0].depth, elm.nodes[1].find_bottom().depth - elm.nodes[1].depth, elm.nodes[2].find_bottom().depth - elm.nodes[2].depth])) print 'Reading mesh F' elements_F = fesom_grid(mesh_path_F, circumpolar=True, cross_180=True) patches_F = [] shelf_patches_F = [] ocean_patches_F = [] for elm in elements_F: coord = transpose(vstack((elm.x, elm.y))) if elm.cavity: shelf_patches_F.append(Polygon(coord, True, linewidth=0.)) else: ocean_patches_F.append(Polygon(coord, True, linewidth=0.)) patches_F.append(Polygon(coord, True, linewidth=0.)) bathy_F = [] draft_F = [] wct_F = [] for elm in elements_F: bathy_F.append(mean([elm.nodes[0].find_bottom().depth, elm.nodes[1].find_bottom().depth, elm.nodes[2].find_bottom().depth])) if elm.cavity: draft_F.append(mean([elm.nodes[0].depth, elm.nodes[1].depth, elm.nodes[2].depth])) wct_F.append(mean([elm.nodes[0].find_bottom().depth - elm.nodes[0].depth, elm.nodes[1].find_bottom().depth - elm.nodes[1].depth, elm.nodes[2].find_bottom().depth - elm.nodes[2].depth])) print 'Reading RTopo' # Read grid, bathy, draft id = Dataset(rtopo_data_file, 'r') rtopo_lon = id.variables['lon'][:] rtopo_lat = id.variables['lat'][:rtopo_max_j] rtopo_bathy = -1*id.variables['bathy'][:rtopo_max_j,:] rtopo_draft = -1*id.variables['draft'][:rtopo_max_j,:] id.close() # Calculate wct rtopo_wct = rtopo_bathy - rtopo_draft # Read composite mask id = Dataset(rtopo_aux_file, 'r') rtopo_amask = id.variables['amask'][:rtopo_max_j,:] id.close() # Create ocean and ice shelf masks rtopo_omask = zeros(shape(rtopo_amask)) rtopo_imask = zeros(shape(rtopo_amask)) index = rtopo_amask == 0 rtopo_omask[index] = 1 index = rtopo_amask == 2 rtopo_omask[index] = 1 rtopo_imask[index] = 1 # Create land mask for plotting in grey rtopo_land = ma.masked_where(rtopo_amask==0, rtopo_amask) # Apply masks to each variable rtopo_bathy = ma.masked_where(rtopo_omask==0, rtopo_bathy) rtopo_draft = ma.masked_where(rtopo_imask==0, rtopo_draft) rtopo_wct = ma.masked_where(rtopo_imask==0, rtopo_wct) # Calculate polar coordinate transformation rtopo_lon2d, rtopo_lat2d = meshgrid(rtopo_lon, rtopo_lat) rtopo_x = -(rtopo_lat2d+90)*cos(rtopo_lon2d*deg2rad+pi/2) rtopo_y = (rtopo_lat2d+90)*sin(rtopo_lon2d*deg2rad+pi/2) # Loop over regions for index in range(num_regions): print 'Processing ' + region_names[index] # Set up a grey square to fill the background with land x_reg, y_reg = meshgrid(linspace(x_min[index], x_max[index], num=100), linspace(y_min[index], y_max[index], num=100)) land_square = zeros(shape(x_reg)) # Find bounds on variables in this region # Start with RTopo loc = (rtopo_x >= x_min[index])*(rtopo_x <= x_max[index])*(rtopo_y >= y_min[index])*(rtopo_y <= y_max[index]) bathy_min = amin(rtopo_bathy[loc]) bathy_max = amax(rtopo_bathy[loc]) draft_min = amin(rtopo_draft[loc]) draft_max = amax(rtopo_draft[loc]) wct_min = amin(rtopo_wct[loc]) wct_max = amax(rtopo_wct[loc]) # Modify with each mesh i = 0 j = 0 for elm in elements_A: if any(elm.x >= x_min[index]) and any(elm.x <= x_max[index]) and any(elm.y >= y_min[index]) and any(elm.y <= y_max[index]): if bathy_A[i] < bathy_min: bathy_min = bathy_A[i] if bathy_A[i] > bathy_max: bathy_max = bathy_A[i] if elm.cavity: if draft_A[j] < draft_min: draft_min = draft_A[j] if draft_A[j] > draft_max: draft_max = draft_A[j] if wct_A[j] < wct_min: wct_min = wct_A[j] if wct_A[j] > wct_max: wct_max = wct_A[j] i += 1 if elm.cavity: j += 1 i = 0 j = 0 for elm in elements_B: if any(elm.x >= x_min[index]) and any(elm.x <= x_max[index]) and any(elm.y >= y_min[index]) and any(elm.y <= y_max[index]): if bathy_B[i] < bathy_min: bathy_min = bathy_B[i] if bathy_B[i] > bathy_max: bathy_max = bathy_B[i] if elm.cavity: if draft_B[j] < draft_min: draft_min = draft_B[j] if draft_B[j] > draft_max: draft_max = draft_B[j] if wct_B[j] < wct_min: wct_min = wct_B[j] if wct_B[j] > wct_max: wct_max = wct_B[j] i += 1 if elm.cavity: j += 1 i = 0 j = 0 for elm in elements_C: if any(elm.x >= x_min[index]) and any(elm.x <= x_max[index]) and any(elm.y >= y_min[index]) and any(elm.y <= y_max[index]): if bathy_C[i] < bathy_min: bathy_min = bathy_C[i] if bathy_C[i] > bathy_max: bathy_max = bathy_C[i] if elm.cavity: if draft_C[j] < draft_min: draft_min = draft_C[j] if draft_C[j] > draft_max: draft_max = draft_C[j] if wct_C[j] < wct_min: wct_min = wct_C[j] if wct_C[j] > wct_max: wct_max = wct_C[j] i += 1 if elm.cavity: j += 1 i = 0 j = 0 for elm in elements_D: if any(elm.x >= x_min[index]) and any(elm.x <= x_max[index]) and any(elm.y >= y_min[index]) and any(elm.y <= y_max[index]): if bathy_D[i] < bathy_min: bathy_min = bathy_D[i] if bathy_D[i] > bathy_max: bathy_max = bathy_D[i] if elm.cavity: if draft_D[j] < draft_min: draft_min = draft_D[j] if draft_D[j] > draft_max: draft_max = draft_D[j] if wct_D[j] < wct_min: wct_min = wct_D[j] if wct_D[j] > wct_max: wct_max = wct_D[j] i += 1 if elm.cavity: j += 1 i = 0 j = 0 for elm in elements_E: if any(elm.x >= x_min[index]) and any(elm.x <= x_max[index]) and any(elm.y >= y_min[index]) and any(elm.y <= y_max[index]): if bathy_E[i] < bathy_min: bathy_min = bathy_E[i] if bathy_E[i] > bathy_max: bathy_max = bathy_E[i] if elm.cavity: if draft_E[j] < draft_min: draft_min = draft_E[j] if draft_E[j] > draft_max: draft_max = draft_E[j] if wct_E[j] < wct_min: wct_min = wct_E[j] if wct_E[j] > wct_max: wct_max = wct_E[j] i += 1 if elm.cavity: j += 1 i = 0 j = 0 for elm in elements_F: if any(elm.x >= x_min[index]) and any(elm.x <= x_max[index]) and any(elm.y >= y_min[index]) and any(elm.y <= y_max[index]): if bathy_F[i] < bathy_min: bathy_min = bathy_F[i] if bathy_F[i] > bathy_max: bathy_max = bathy_F[i] if elm.cavity: if draft_F[j] < draft_min: draft_min = draft_F[j] if draft_F[j] > draft_max: draft_max = draft_F[j] if wct_F[j] < wct_min: wct_min = wct_F[j] if wct_F[j] > wct_max: wct_max = wct_F[j] i += 1 if elm.cavity: j += 1 # Plot fig = figure(figsize=(20, ysize[index])) fig.patch.set_facecolor('white') gs = GridSpec([3,7]) gs.update(left=0.05, right=0.9, bottom=0.05, top=0.9, wspace=0.05, hspace=0.1) # RTopo # Bathymetry ax = subplot(gs[0,0], aspect='equal') # First plot land in grey pcolor(rtopo_x, rtopo_y, rtopo_land, cmap=grey_cmap) # Now plot bathymetry pcolor(rtopo_x, rtopo_y, rtopo_bathy, vmin=bathy_min, vmax=bathy_max) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Ice shelf draft ax = subplot(gs[1,0], aspect='equal') pcolor(rtopo_x, rtopo_y, rtopo_land, cmap=grey_cmap) pcolor(rtopo_x, rtopo_y, rtopo_draft, vmin=draft_min, vmax=draft_max) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Water column thickness ax = subplot(gs[2,0], aspect='equal') pcolor(rtopo_x, rtopo_y, rtopo_land, cmap=grey_cmap) pcolor(rtopo_x, rtopo_y, rtopo_wct, vmin=wct_min, vmax=wct_max) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Add RTopo label on bottom xlabel('RTopo') # Mesh A # Bathymetry ax = subplot(gs[0,1], aspect='equal') # Start with land background contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) # Add bathymetry data img = PatchCollection(patches_A, cmap='jet') img.set_array(array(bathy_A)) img.set_edgecolor('face') img.set_clim(vmin=bathy_min, vmax=bathy_max) ax.add_collection(img) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Ice shelf draft ax = subplot(gs[1,1], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_A, cmap='jet') img.set_array(array(draft_A)) img.set_edgecolor('face') img.set_clim(vmin=draft_min, vmax=draft_max) ax.add_collection(img) # Mask out the open ocean in white overlay = PatchCollection(ocean_patches_A, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Water column thickness in cavity ax = subplot(gs[2,1], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_A, cmap='jet') img.set_array(array(wct_A)) img.set_edgecolor('face') img.set_clim(vmin=wct_min, vmax=wct_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_A, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Mesh title xlabel('Mesh A') # Mesh B # Bathymetry ax = subplot(gs[0,2], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(patches_B, cmap='jet') img.set_array(array(bathy_B)) img.set_edgecolor('face') img.set_clim(vmin=bathy_min, vmax=bathy_max) ax.add_collection(img) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Ice shelf draft ax = subplot(gs[1,2], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_B, cmap='jet') img.set_array(array(draft_B)) img.set_edgecolor('face') img.set_clim(vmin=draft_min, vmax=draft_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_B, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Water column thickness in cavity ax = subplot(gs[2,2], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_B, cmap='jet') img.set_array(array(wct_B)) img.set_edgecolor('face') img.set_clim(vmin=wct_min, vmax=wct_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_B, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) xlabel('Mesh B') # Mesh C # Bathymetry ax = subplot(gs[0,3], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(patches_C, cmap='jet') img.set_array(array(bathy_C)) img.set_edgecolor('face') img.set_clim(vmin=bathy_min, vmax=bathy_max) ax.add_collection(img) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Variable title title('Bathymetry (m)') # Ice shelf draft ax = subplot(gs[1,3], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_C, cmap='jet') img.set_array(array(draft_C)) img.set_edgecolor('face') img.set_clim(vmin=draft_min, vmax=draft_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_C, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) title('Ice shelf draft (m)') # Water column thickness in cavity ax = subplot(gs[2,3], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_C, cmap='jet') img.set_array(array(wct_C)) img.set_edgecolor('face') img.set_clim(vmin=wct_min, vmax=wct_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_C, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) title('Water column thickness (m)') xlabel('Mesh C') # Mesh D # Bathymetry ax = subplot(gs[0,4], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(patches_D, cmap='jet') img.set_array(array(bathy_D)) img.set_edgecolor('face') img.set_clim(vmin=bathy_min, vmax=bathy_max) ax.add_collection(img) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Ice shelf draft ax = subplot(gs[1,4], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_D, cmap='jet') img.set_array(array(draft_D)) img.set_edgecolor('face') img.set_clim(vmin=draft_min, vmax=draft_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_D, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Water column thickness in cavity ax = subplot(gs[2,4], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_D, cmap='jet') img.set_array(array(wct_D)) img.set_edgecolor('face') img.set_clim(vmin=wct_min, vmax=wct_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_D, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) xlabel('Mesh D') # Mesh E # Bathymetry ax = subplot(gs[0,5], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(patches_E, cmap='jet') img.set_array(array(bathy_E)) img.set_edgecolor('face') img.set_clim(vmin=bathy_min, vmax=bathy_max) ax.add_collection(img) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Ice shelf draft ax = subplot(gs[1,5], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_E, cmap='jet') img.set_array(array(draft_E)) img.set_edgecolor('face') img.set_clim(vmin=draft_min, vmax=draft_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_E, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Water column thickness in cavity ax = subplot(gs[2,5], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_E, cmap='jet') img.set_array(array(wct_E)) img.set_edgecolor('face') img.set_clim(vmin=wct_min, vmax=wct_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_E, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) xlabel('Mesh E') # Mesh F # Bathymetry ax = subplot(gs[0,6], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(patches_F, cmap='jet') img.set_array(array(bathy_F)) img.set_edgecolor('face') img.set_clim(vmin=bathy_min, vmax=bathy_max) ax.add_collection(img) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) # Colourbar on right cbaxes = fig.add_axes([0.92, 0.7, 0.01, 0.15]) cbar = colorbar(img, cax=cbaxes) # Ice shelf draft ax = subplot(gs[1,6], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_F, cmap='jet') img.set_array(array(draft_F)) img.set_edgecolor('face') img.set_clim(vmin=draft_min, vmax=draft_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_F, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) cbaxes = fig.add_axes([0.92, 0.4, 0.01, 0.15]) cbar = colorbar(img, cax=cbaxes) # Water column thickness in cavity ax = subplot(gs[2,6], aspect='equal') contourf(x_reg, y_reg, land_square, 1, colors=(('0.6', '0.6', '0.6'))) img = PatchCollection(shelf_patches_F, cmap='jet') img.set_array(array(wct_F)) img.set_edgecolor('face') img.set_clim(vmin=wct_min, vmax=wct_max) ax.add_collection(img) overlay = PatchCollection(ocean_patches_F, facecolor=(1,1,1)) overlay.set_edgecolor('face') ax.add_collection(overlay) xlim([x_min[index], x_max[index]]) ylim([y_min[index], y_max[index]]) ax.set_xticks([]) ax.set_yticks([]) xlabel('Mesh F') cbaxes = fig.add_axes([0.92, 0.1, 0.01, 0.15]) cbar = colorbar(img, cax=cbaxes) # Main title suptitle(region_names[index]) fig.show()
def showAnns(self, anns, draw_bbox=False): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) == 0: return 0 if 'segmentation' in anns[0] or 'keypoints' in anns[0]: datasetType = 'instances' elif 'caption' in anns[0]: datasetType = 'captions' else: raise Exception('datasetType not supported') if datasetType == 'instances': ax = plt.gca() ax.set_autoscale_on(False) polygons = [] color = [] for ann in anns: c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0] if 'segmentation' in ann: if type(ann['segmentation']) == list: # polygon for seg in ann['segmentation']: poly = np.array(seg).reshape( (int(len(seg) / 2), 2)) polygons.append(Polygon(poly)) color.append(c) else: # mask t = self.imgs[ann['image_id']] if type(ann['segmentation']['counts']) == list: rle = maskUtils.frPyObjects([ann['segmentation']], t['height'], t['width']) else: rle = [ann['segmentation']] m = maskUtils.decode(rle) img = np.ones((m.shape[0], m.shape[1], 3)) if ann['iscrowd'] == 1: color_mask = np.array([2.0, 166.0, 101.0]) / 255 if ann['iscrowd'] == 0: color_mask = np.random.random((1, 3)).tolist()[0] for i in range(3): img[:, :, i] = color_mask[i] ax.imshow(np.dstack((img, m * 0.5))) if 'keypoints' in ann and type(ann['keypoints']) == list: # turn skeleton into zero-based index sks = np.array( self.loadCats(ann['category_id'])[0]['skeleton']) - 1 kp = np.array(ann['keypoints']) x = kp[0::3] y = kp[1::3] v = kp[2::3] for sk in sks: if np.all(v[sk] > 0): plt.plot(x[sk], y[sk], linewidth=3, color=c) plt.plot(x[v > 0], y[v > 0], 'o', markersize=8, markerfacecolor=c, markeredgecolor='k', markeredgewidth=2) plt.plot(x[v > 1], y[v > 1], 'o', markersize=8, markerfacecolor=c, markeredgecolor=c, markeredgewidth=2) if draw_bbox: [bbox_x, bbox_y, bbox_w, bbox_h] = ann['bbox'] poly = [[bbox_x, bbox_y], [bbox_x, bbox_y + bbox_h], [bbox_x + bbox_w, bbox_y + bbox_h], [bbox_x + bbox_w, bbox_y]] np_poly = np.array(poly).reshape((4, 2)) polygons.append(Polygon(np_poly)) color.append(c) p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4) ax.add_collection(p) p = PatchCollection(polygons, facecolor='none', edgecolors=color, linewidths=2) ax.add_collection(p) elif datasetType == 'captions': for ann in anns: print(ann['caption'])
'perim', drawbounds=False) # fire August 6th, 2016 patches = [] for info, shape in zip(m.perim_info, m.perim): #if info['FIRENAME'] == 'PIONEER' and info['SHAPENUM']==1772: if info['FIRENAME'] == 'PIONEER' and info['PERDATTIME'] == [ 2016, 8, 6 ] and np.shape(shape)[0] > 6000 and info['SHAPENUM'] == 1914: x, y = zip(*shape) print info['FIRENAME'], info['SHAPENUM'], info['PERDATTIME'], info[ 'DATECRNT'] print 'GIS Acres', info['GISACRES'] #m.plot(x, y, marker=None,color=colors[colorI],linewidth=lw) patches.append(Polygon(np.array(shape), True)) print "" ax.add_collection( PatchCollection(patches, facecolor='indianred', alpha=.75, edgecolor='k', linewidths=1.5, zorder=1)) # fire August 4th 2016 patches2 = [] for info, shape in zip(m.perim_info, m.perim): #if info['FIRENAME'] == 'PIONEER' and info['SHAPENUM']==1772: if info['FIRENAME'] == 'PIONEER' and info['PERDATTIME'] == [ 2016, 8, 4
def display_instances(image, boxes, masks, class_ids, class_names, scores=None, title="", figsize=(16, 16), ax=None, show_mask=True, show_bbox=True, colors=None, captions=None): """ boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. masks: [height, width, num_instances] class_ids: [num_instances] class_names: list of class names of the dataset scores: (optional) confidence scores for each box title: (optional) Figure title show_mask, show_bbox: To show masks and bounding boxes or not figsize: (optional) the size of the image colors: (optional) An array or colors to use with each object captions: (optional) A list of strings to use as captions for each object """ # Number of instances N = boxes.shape[0] if not N: print("\n*** No instances to display *** \n") else: assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0] # If no axis is passed, create one and automatically call show() auto_show = False if not ax: _, ax = plt.subplots(1, figsize=figsize) auto_show = True # Generate random colors colors = colors or random_colors(N) # Show area outside image boundaries. height, width = image.shape[:2] ax.set_ylim(height + 10, -10) ax.set_xlim(-10, width + 10) ax.axis('off') ax.set_title(title) masked_image = image.astype(np.uint32).copy() for i in range(N): color = colors[i] # Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] if show_bbox: p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=0.7, linestyle="dashed", edgecolor=color, facecolor='none') ax.add_patch(p) # Label if not captions: class_id = class_ids[i] score = scores[i] if scores is not None else None label = class_names[class_id] x = random.randint(x1, (x1 + x2) // 2) caption = "{} {:.3f}".format(label, score) if score else label else: caption = captions[i] ax.text(x1, y1 + 8, caption, color='w', size=11, backgroundcolor="none") # Mask mask = masks[:, :, i] if show_mask: masked_image = apply_mask(masked_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) ax.add_patch(p) ax.imshow(masked_image.astype(np.uint8)) if auto_show: plt.show()
def draw_boxes(image, boxes=None, refined_boxes=None, masks=None, captions=None, visibilities=None, title="", ax=None): """Draw bounding boxes and segmentation masks with different customizations. boxes: [N, (y1, x1, y2, x2, class_id)] in image coordinates. refined_boxes: Like boxes, but draw with solid lines to show that they're the result of refining 'boxes'. masks: [N, height, width] captions: List of N titles to display on each box visibilities: (optional) List of values of 0, 1, or 2. Determine how prominent each bounding box should be. title: An optional title to show over the image ax: (optional) Matplotlib axis to draw on. """ # Number of boxes assert boxes is not None or refined_boxes is not None N = boxes.shape[0] if boxes is not None else refined_boxes.shape[0] # Matplotlib Axis if not ax: _, ax = plt.subplots(1, figsize=(12, 12)) # Generate random colors colors = random_colors(N) # Show area outside image boundaries. margin = image.shape[0] // 10 ax.set_ylim(image.shape[0] + margin, -margin) ax.set_xlim(-margin, image.shape[1] + margin) ax.axis('off') ax.set_title(title) masked_image = image.astype(np.uint32).copy() for i in range(N): # Box visibility visibility = visibilities[i] if visibilities is not None else 1 if visibility == 0: color = "gray" style = "dotted" alpha = 0.5 elif visibility == 1: color = colors[i] style = "dotted" alpha = 1 elif visibility == 2: color = colors[i] style = "solid" alpha = 1 # Boxes if boxes is not None: if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in cropping. continue y1, x1, y2, x2 = boxes[i] p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=alpha, linestyle=style, edgecolor=color, facecolor='none') ax.add_patch(p) # Refined boxes if refined_boxes is not None and visibility > 0: ry1, rx1, ry2, rx2 = refined_boxes[i].astype(np.int32) p = patches.Rectangle((rx1, ry1), rx2 - rx1, ry2 - ry1, linewidth=2, edgecolor=color, facecolor='none') ax.add_patch(p) # Connect the top-left corners of the anchor and proposal if boxes is not None: ax.add_line(lines.Line2D([x1, rx1], [y1, ry1], color=color)) # Captions if captions is not None: caption = captions[i] # If there are refined boxes, display captions on them if refined_boxes is not None: y1, x1, y2, x2 = ry1, rx1, ry2, rx2 x = random.randint(x1, (x1 + x2) // 2) ax.text(x1, y1, caption, size=11, verticalalignment='top', color='w', backgroundcolor="none", bbox={ 'facecolor': color, 'alpha': 0.5, 'pad': 2, 'edgecolor': 'none' }) # Masks if masks is not None: mask = masks[:, :, i] masked_image = apply_mask(masked_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) ax.add_patch(p) ax.imshow(masked_image.astype(np.uint8))
# bmap = Basemap(llcrnrlon=80.33, # llcrnrlat=3.01, # urcrnrlon=138.16, # urcrnrlat=56.123, # resolution='h', projection='cass', lat_0 = 42.5,lon_0=120) # shp_info = bmap.readshapefile("D:\\GoogleDownload\\CHN_adm_shp\\CHN_adm1", 'states', drawbounds=False) for info, shp in zip(bmap.states_info, bmap.states): proid = info['NAME_1'] if proid == 'Guangdong': poly = Polygon(shp, facecolor='g', edgecolor='b', lw=0.8) ax1.add_patch(poly) bmap.drawcoastlines() #bmap.drawcountries() bmap.drawparallels(np.arange(3, 55, 10), labels=[1, 0, 0, 0]) bmap.drawmeridians(np.arange(80, 140, 10), labels=[0, 0, 0, 1]) plt.title('Province') plt.show() plt.savefig('d:\\fig_province.png', dpi=100, bbox_inches='tight') plt.clf() plt.close() end = time.clock() print(end - start)
def plotproj(plotdef, data, outdir): ''' Plot map. ''' axes = plt.axes() bounds = (plotdef['lonmin'], plotdef['latmin'], plotdef['lonmax'], plotdef['latmax']) for geom in data.filter(bbox=bounds): temp_pol = shape(geom['geometry']) box = Polygon([ (plotdef['lonmin'], plotdef['latmin']), (plotdef['lonmin'], plotdef['latmax']), (plotdef['lonmax'], plotdef['latmax']), (plotdef['lonmax'], plotdef['latmin']), ]) try: temp_pol = temp_pol.intersection(box) except Exception as e: continue if plotdef['type'] == 'poly': if isinstance(temp_pol, MultiPolygon): polys = [resample_polygon(polygon) for polygon in temp_pol] pol = MultiPolygon(polys) else: pol = resample_polygon(temp_pol) else: pol = temp_pol trans = functools.partial(project_xy, proj_string=plotdef['projstring']) proj_geom = transform(trans, pol) if plotdef['type'] == 'poly': patch = PolygonPatch(proj_geom, fc=COLOR_LAND, zorder=0) axes.add_patch(patch) else: x, y = proj_geom.xy axes.plot(x, y, color=COLOR_COAST, linewidth=0.5) # Plot frame frame = [ parallel(plotdef['latmin'], plotdef['lonmin'], plotdef['lonmax']), parallel(plotdef['latmax'], plotdef['lonmin'], plotdef['lonmax']), ] for line in frame: line = project(line, plotdef['projstring']) x = line[:, 0] y = line[:, 1] axes.plot(x, y, '-k') graticule = build_graticule( plotdef['lonmin'], plotdef['lonmax'], plotdef['latmin'], plotdef['latmax'], ) # Plot graticule for feature in graticule: feature = project(feature, plotdef['projstring']) x = feature[:, 0] y = feature[:, 1] axes.plot(x, y, color=COLOR_GRAT, linewidth=0.4) # Switch off the axis lines... plt.axis('off') # ... and additionally switch off the visibility of the axis lines and # labels so they can be removed by "bbox_inches='tight'" when saving axes.get_xaxis().set_visible(False) axes.get_yaxis().set_visible(False) font = {'family': 'serif', 'color': 'black', 'style': 'italic', 'size': 12} # Make sure the plot is not stretched axes.set_aspect('equal') if not os.path.exists(outdir): os.makedirs(outdir) plt.savefig(outdir + '/' + plotdef['filename'], dpi=400, bbox_inches='tight') # Clean up axes = None del axes plt.close()
zorder=7, ls="solid", lw=LW, color="black", alpha=1.0, ) ################################################################################ # Draw triangles between bottom and top layer # dark colored isosceles triangles triangles = [] for i, j1, j2 in lines_bottom_to_top: p0 = points_bottom[i] p1 = points_top[j1] p2 = points_top[j2] triangles.append(Polygon([p0, p1, p2], closed=True)) collection = PatchCollection( triangles, zorder=3, facecolors=FACECOLOR, linewidths=0.0, alpha=0.65, ) ax.add_collection(collection) # Draw triangles on the top layer # light colored equilateral triangles trios = [ [0, 2, 3], [1, 3, 4], [2, 5, 6],
drawbounds=True) # collect the state names from the shapefile attributes so we can look up the shape obect for a state by it's name names = [] colors = {} i = 0 for shape_dict in m.states_info: names.append(shape_dict['HASC_1']) if shape_dict['HASC_1'] in corSTs.keys(): colors[ shape_dict['HASC_1']] = corSTs[shape_dict['HASC_1']] / 2 + 0.5 else: colors[shape_dict['HASC_1']] = 0.5 ax = plt.gca() # get current axes instance for nshape, seg in enumerate(m.states): poly = Polygon(seg, facecolor=cm.BrBG(colors[names[nshape]]), edgecolor='k') ax.add_patch(poly) ARshp = m.readshapefile( '/Volumes/Data_Archive/Data/adminBoundaries/GADM/ARG_adm_shp/ARG_adm1', name='states', drawbounds=True) # collect the state names from the shapefile attributes so we can look up the shape obect for a state by it's name names = [] colors = {} i = 0 for shape_dict in m.states_info: names.append(shape_dict['HASC_1']) if shape_dict['HASC_1'] in corSTs.keys(): colors[ shape_dict['HASC_1']] = corSTs[shape_dict['HASC_1']] / 2 + 0.5
0, 2.5, 5, 7.5, 10, 12.5, 15, 17.5, 20, 22.5, 25, 27.5, 30, 32.5, 35 ]) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) cbr = plt.colorbar(im, cax=cax) cbr.set_label('Sidescan Intensity [dBW]') m.readshapefile( r"C:\workspace\Reach_4a\Multibeam\mb_sed_class\output\shapefiles\visual_seg_2_geo", "layer", drawbounds=False) #sand, sand/gravel, gravel, sand/rock, rock s_patch, g_patch, r_patch, = [], [], [] for info, shape in zip(m.layer_info, m.layer): if info['substrate'] == 'sand': s_patch.append(Polygon(np.asarray(shape), True)) if info['substrate'] == 'gravel': g_patch.append(Polygon(np.asarray(shape), True)) if info['substrate'] == 'boulders': r_patch.append(Polygon(np.asarray(shape), True)) ax.add_collection( PatchCollection(s_patch, facecolor=colors[4], alpha=a_val, edgecolor='none', zorder=10)) ax.add_collection( PatchCollection(g_patch, facecolor=colors[2],
def _drawPolygonEvent(self, points): polygon = Polygon(np.array(points), color=np.random.rand(3, )) self._addPatch(polygon)
forward = False poly, text = None, None while True: forward = not forward if text is None: text = plt.figtext(0.05, 0.25, "") # initialize text section for i in range(b_min * 10, b_max * 10): b = i / 10 if forward else (b_min + b_max) - i / 10 # Make the shaded region ix = np.linspace(a, b) iy = func(ix) verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)] if poly is not None: poly.remove() poly = Polygon(verts, facecolor='0.9', edgecolor='0.5') ax.add_patch(poly) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') fig.texts.remove(text) text = plt.figtext(.3, 0.5, s=r"$\int_a^b f(x)\mathrm{d}x=$ " + r"$\int_{" + str(round(a, 2)) + "}^{" + str(round(b, 2)) + r"} f(x)\mathrm{d}x$", horizontalalignment='center', fontsize=15) ax.set_xticks((a, b)) ax.set_xticklabels(('$a$', '$b$'))
meridians = np.arange(-180.,180.,20.) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=8) ny = 180; nx = 360 lons, lats = m.makegrid(nx, ny) #get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) from matplotlib.patches import Polygon m.readshapefile("/Users/zhengkai/slm5/RasterT_Int_slm9_SplitLine3",'states',drawbounds=False) # m.readshapefile("./slm/land_sea",'states',drawbounds=False) # m.readshapefile("./CHN_adm/CHN_adm1",'states',drawbounds=False) for info, shp in zip(m.states_info, m.states): # proid = info['NAME_0'] # if proid == 'China': poly = Polygon(shp,facecolor='w',fill=False,edgecolor='k', lw=1.0) ax.add_patch(poly) #compute map proj coordinates. #draw filled contours. # clevs = [-2,-1,0,1,2.5,5,7.5,10,15,20,30,40,50,70,100,150,200,250,300,400,500,600,750] #clevs = [-1,-0.75,-0.5,-0.25,0,0.25,0.5,0.75,1] # clevs = [0,1,5,10,20,30,45,50,70,85,100,130,150,170,190,210,230] #cs = m.contourf(x,y,prcpvar[0,:,:],clevs,linewidths=0.5,colors='k',animated=True) clevs = np.arange(1032,1043,1) #clevs = [-1,0,0.5,0.75,1,15,20,30,40,70] lonnumber=360# data.shape[2]; latnumber=180 prcpvar1=np.zeros(shape=(latnumber,lonnumber)) for i in range(int(lonnumber/2),int(lonnumber)): prcpvar1[:,i]= prcpvar[0,:,i-int(lonnumber/2)]
from matplotlib.backends.backend_agg import ( FigureCanvasAgg as FigureCanvas) from mpl_toolkits.basemap import Basemap from matplotlib.patches import Polygon fig = figure.Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(1,1,1) m = Basemap(projection='cyl', lat_0 = 50, lon_0 = -100, ax=ax, resolution = 'l', area_thresh = 1000, llcrnrlat=-90,urcrnrlat=90, llcrnrlon=-180,urcrnrlon=180) border_color = '0.8' m.drawcoastlines(color=border_color) m.drawcountries(color=border_color) m.drawmapboundary(color=border_color) shp_info = m.readshapefile('st99_d00', 'states', drawbounds=True) ax = fig.gca() # get current axes instance non_states = ['District of Columbia','Puerto Rico'] statenames = [sp['NAME'] for sp in m.states_info if sp['NAME'] not in non_states] cls = ['r','g','b','y'] for nshape,seg in enumerate(m.states): poly = Polygon(seg, ec='k', fc=cls[nshape%4]) ax.add_patch(poly) canvas.print_figure('../figures/mapshape.png', facecolor='lightgray')
def plot(): """ info: plots the results and saves them input: - output: - """ # info: Fig1 - plot degree over N ax1.plot(Ns, np.divide(degMaxsPre, Ns)) ax1.plot(Ns, np.divide(degMaxsPost, Ns)) ax1.set_xscale('log') ax1.set_xlabel('sample size $N$') ax1.set_ylabel('maximum degree $d_{max}$') if withTitle > 0: ax1.set_title('degMaxsPre') alphaVal = 0.5 # info: Fig. 2 - plot clustersize of N ax2.plot(Ns, np.divide(clustersizesMaxPre, Ns), color='blue', zorder=0) ax2.plot(Ns, np.divide(clustersizesMaxPost, Ns), color='orange', zorder=0) #Nperfect = np.linspace(0.5, 10**5, num = 1000) ax2.legend(['fit', 'Pre selection', 'Post selection'], frameon=False) ax2.set_xlim(min(Ns), max(Ns)) ax2.set_ylim(-1.0, 1.0) ax2.set_xscale('log') ax2.set_xlabel('cluster size') ax2.set_ylabel('frequency') ax2.set_title('clustersizes') xText = 0.7 yText = 0.7 dxText = 0.2 dyText = 0.2 ax2.add_patch( Polygon( [[xText, yText], [xText + dxText, yText], [xText + dxText, yText + dyText], [xText, yText + dyText]], closed=False, fill=True, color='white', alpha=0.9, transform=ax2.transAxes, zorder=2)) # info: digits - number of digits for the parameters of the fit digits = 2 content = "a = " + digNum(popt1[0], digits)+ "(" + digNum(pcov1[0][0], digits), \ + ")" + "\n b = " + digNum(popt1[1], digits) + "(", \ + digNum(pcov1[1][1], digits) + ")" content = "a = " + sci(popt1[0], digits) + "\n b = " + sci( popt1[1], digits) if withParams > 0: ax2.text(xText, yText, content, transform=ax2.transAxes, zorder=3) # info: Fig. 6 - probability, that everything is connected ax6.plot(Ns, isConnectedsPre, color='blue', zorder=0) ax6.plot(Ns, isConnectedsPost, color='orange', zorder=0) ax6.set_xlim(min(Ns), max(Ns)) ax6.set_ylim(0.0, 1.0) ax6.set_xlabel('sample size $N$') ax6.set_ylabel('probability $p$') # info: save fig1.savefig('degreeNum.png', dpi=300, bbox_inches="tight") fig2.savefig('clusterProb.png', dpi=300, bbox_inches="tight") fig3.savefig('diameters.png', dpi=300, bbox_inches="tight") fig6.savefig('connectedProb.png', dpi=300, bbox_inches="tight") plt.show()
def display_instances(n, image, boxes, masks, class_ids, class_names, scores=None, title="", figsize=(16, 16), ax=None): """ boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. masks: [num_instances, height, width] class_ids: [num_instances] class_names: list of class names of the dataset scores: (optional) confidence scores for each box figsize: (optional) the size of the image. """ N = 3 if not N: print("\n*** No instances to display *** \n") else: assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0] if not ax: _, ax = plt.subplots(1, figsize=figsize) # Generate random colors if n == 1: colors = random_colors(N) elif n == 2: colors = random_colors(1) # Show area outside image boundaries. height, width = image.shape[:2] ax.set_ylim(height + 10, -10) ax.set_xlim(-10, width + 10) ax.axis('off') ax.set_title(title) ax.imshow(image.astype(np.uint8)) plt.savefig("D:\FYP\myfyp\static\img\original.png") masked_image = image.astype(np.uint32).copy() list_num = 0 label_list = ['a', 'b', 'c'] for i in range(N): if n == 1: color = colors[i] elif n == 2: color = colors[0] # Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=0.7, linestyle="dashed", edgecolor=color, facecolor='none') ax.add_patch(p) # Label class_id = class_ids[i] # print("------------------------------------") # print(class_id) # print("------------------------------------") score = scores[i] if scores is not None else None label = class_names[class_id] label_list[list_num] = label list_num = list_num + 1 # x = random.randint(x1, (x1 + x2) // 2) # caption = "{} {:.3f}".format(label, score) if score else label # ax.text(x1, y1 + 8, caption, # color='w', size=11, backgroundcolor="none") # Mask mask = masks[:, :, i] masked_image = apply_mask(masked_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) ax.add_patch(p) ax.imshow(masked_image.astype(np.uint8)) # plt.show() plt.savefig("D:\FYP\myfyp\static\img\mask.png") plt.close() return label_list
stepCount = 12 # Aufteilung der Bewegung in 12 Abschnitte / Frames step = 2 * np.pi / 32 / stepCount # Schrittweite Drehung des großen Zahnrades fig = plt.figure(figsize=(3, 2)) ax = fig.add_axes([-.05, -.05, 1.1, 1.1]) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.set_aspect("equal") plt.margins(0, 0) plt.xlim(-9.5, 17.6) plt.ylim(-9.5, 9.5) ims = [] for i in range(stepCount): g1 *= np.exp(1j * step) g2 *= np.exp(-2j * step) ims.append([ ax.add_patch( Polygon(g1.view(float).reshape(g1.size, 2), color=(.1, 0, 1, .5))), ax.add_patch( Polygon(g2.view(float).reshape(g2.size, 2) + [d2, 0], color=(1, 0, .1, .5))) ]) ani = animation.ArtistAnimation(fig, ims, interval=1000. * 2 / 3 / stepCount) plt.show()
self.ax.draw_artist(self.poly) self.ax.draw_artist(self.line) self.canvas.blit(self.ax.bbox) if __name__ == '__main__': import matplotlib.pyplot as plt from matplotlib.patches import Polygon fig = plt.figure() theta = np.arange(0, 2 * np.pi, 0.1) r = 1.5 xs = r * np.cos(theta) ys = r * np.sin(theta) poly = Polygon(zip( xs, ys, ), animated=True) ax = plt.subplot(111) ax.add_patch(poly) p = PolygonInteractor(ax, poly) #ax.add_line(p.line) ax.set_title('Click and drag a point to move it') ax.set_xlim((-2, 2)) ax.set_ylim((-2, 2)) plt.show()
def save_image_keypoint_and_mask(image, boxes, keypoints, masks, class_ids, class_names, filename=None, skeleton=[], scores=None, title="", figsize=(16, 9), ax=None, save_picture=False): """ boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. keypoints: [num_instance, num_keypoints] Every value is a int label which indicates the position ([0,56*56)) of the joint masks: [height, width, num_instances] class_ids: [num_instances] class_names: list of class names of the dataset """ # Plot keypoints first. # Number of persons N = boxes.shape[0] keypoints = np.array(keypoints).astype(int) print("keypoint_shape:", np.shape(keypoints)) if not N: print("\n*** No persons to display *** \n") else: assert boxes.shape[0] == keypoints.shape[0] == class_ids.shape[0] if not ax: fig, ax = plt.subplots(1, figsize=figsize) fig.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0) # Generate random colors colors = random_colors(N) # Show area outside image boundaries. height, width = image.shape[:2] ax.set_ylim(height + 10, -10) ax.set_xlim(-10, width + 10) ax.axis('off') ax.set_title(title) final_image = image.astype(np.float32).copy() for i in range(N): color = colors[i] # Bounding box if not np.any(boxes[i]): # Skip this instance. Has no bbox. Likely lost in image cropping. continue y1, x1, y2, x2 = boxes[i] p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=0.7, linestyle="dashed", edgecolor=color, facecolor='none') ax.add_patch(p) # Label class_id = class_ids[i] score = scores[i] if scores is not None else None label = class_names[class_id] # x = random.randint(x1, (x1 + x2) // 2) caption = "{} {:.3f}".format(label, score) if score else label ax.text(x1, y1 + 8, caption, color='w', size=11, backgroundcolor="none") # # Keypoints: num_person, num_keypoint, 3 # for Joint in keypoints[i]: # if(Joint[2]!=0): # circle = patches.Circle((Joint[0],Joint[1]),radius=1,edgecolor=color,facecolor='none') # ax.add_patch(circle) # # # Skeleton: 11*2 # limb_colors = [[0, 0, 255], [0, 170, 255], [0, 255, 170], [0, 255, 0], [170, 255, 0], # [255, 170, 0], [255, 0, 0], [255, 0, 170], [170, 0, 255], [170,170,0],[170,0,170]] # if(len(skeleton)): # skeleton = np.reshape(skeleton,(-1,2)) # neck = np.array((keypoints[i, 5, :] + keypoints[i,6,:])/2).astype(int) # if(keypoints[i, 5, 2] == 0 or keypoints[i,6,2] == 0): # neck = [0,0,0] # limb_index = -1 # for limb in skeleton: # limb_index += 1 # start_index, end_index = limb # connection joint index from 0 to 16 # if(start_index == -1): # Joint_start = neck # else: # Joint_start = keypoints[i][start_index] # if(end_index == -1): # Joint_end = neck # else: # Joint_end = keypoints[i][end_index] # # both are Annotated # # Joint:(x,y,v) # if ((Joint_start[2] != 0) & (Joint_end[2] != 0)): # # print(color) # cv2.line(final_image, tuple(Joint_start[:2]), tuple(Joint_end[:2]), limb_colors[limb_index],5) # Mask mask = masks[:, :, i] final_image = apply_mask(final_image, mask, color) # Mask Polygon # Pad to ensure proper polygons for masks that touch image edges. padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8) padded_mask[1:-1, 1:-1] = mask contours = find_contours(padded_mask, 0.5) for verts in contours: # Subtract the padding and flip (y, x) to (x, y) verts = np.fliplr(verts) - 1 p = Polygon(verts, facecolor="none", edgecolor=color) ax.add_patch(p) ax.imshow(final_image.astype(np.uint8)) # plt.show() if save_picture: plt.savefig(filename) plt.close(fig)
def visualize_tone(args): with open('output/tone_analyzer.json') as data_file: outputs = json.load(data_file) emotions = [ e['tone_name'] for e in outputs[0]['tone']['tone_categories'][0]['tones'] ] nostalgic_emotion = np.array([0.0] * len(emotions)) nostalgic_emotion_lst = [] nostalgic_count = 0 ordinary_emotion = np.array([0.0] * len(emotions)) ordinary_emotion_lst = [] ordinary_count = 0 for idx, t in enumerate(outputs): score = [s['score'] for s in t['tone']['tone_categories'][0]['tones']] if t['tag'] == 'nostalgic': nostalgic_emotion += np.array(score) nostalgic_emotion_lst.append(score) nostalgic_count += 1 elif t['tag'] == 'ordinary': ordinary_emotion += np.array(score) ordinary_emotion_lst.append(score) ordinary_count += 1 print(emotions) print(nostalgic_emotion, nostalgic_count) print(ordinary_emotion, ordinary_count) ind = np.arange(len(emotions)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(ind, nostalgic_emotion / nostalgic_count, width, color='darkkhaki') rects2 = ax.bar(ind + width, ordinary_emotion / ordinary_count, width, color='royalblue') # add some text for labels, title and axes ticks ax.set_ylabel('Average Tone Score') ax.set_title('Emotion Score from Tone Analyzer') ax.set_xticks(ind + width / 2) ax.set_xticklabels(emotions) ax.legend((rects1[0], rects2[0]), ('Nostalgic', 'Ordinary')) if args.save_fig: plt.savefig('output/tone_analyzer_emotion_comparison.pdf', bbox_inches='tight') else: plt.show() plt.close() # create box plot nostalgic_emotion_lst = np.array(nostalgic_emotion_lst) ordinary_emotion_lst = np.array(ordinary_emotion_lst) data_for_box_plot = [] for i in range(len(emotions)): data_for_box_plot.append(nostalgic_emotion_lst[:, i]) data_for_box_plot.append(ordinary_emotion_lst[:, i]) fig, ax1 = plt.subplots(figsize=(10, 6)) plt.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25) bp = plt.boxplot(data_for_box_plot, notch=0, sym='+', vert=1, whis=1.5, showmeans=True) plt.setp(bp['boxes'], color='black') plt.setp(bp['whiskers'], color='black') plt.setp(bp['fliers'], color='red', marker='+') # Add a horizontal grid to the plot, but make it very light in color # so we can use it for reading data values but not be distracting ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5) # Hide these grid behind plot objects ax1.set_axisbelow(True) ax1.set_title('Comparison of Emotion Tones') ax1.set_xlabel('Emotions') ax1.set_ylabel('Scores') # Now fill the boxes with desired colors boxColors = ['darkkhaki', 'royalblue'] numBoxes = len(emotions) * 2 medians = list(range(numBoxes)) for i in range(numBoxes): box = bp['boxes'][i] boxX = [] boxY = [] for j in range(5): boxX.append(box.get_xdata()[j]) boxY.append(box.get_ydata()[j]) boxCoords = list(zip(boxX, boxY)) # Alternate between Dark Khaki and Royal Blue k = i % 2 boxPolygon = Polygon(boxCoords, facecolor=boxColors[k]) ax1.add_patch(boxPolygon) # Set the axes ranges and axes labels ax1.set_xlim(0.5, numBoxes + 0.5) top = 1.2 bottom = -0.2 ax1.set_ylim(bottom, top) xtickNames = plt.setp(ax1, xticklabels=np.repeat(emotions, 2)) plt.setp(xtickNames, rotation=45, fontsize=10) # Finally, add a basic legend plt.figtext(0.15, 0.8, 'Nostalgic', backgroundcolor=boxColors[0], color='black', weight='roman', size='small') plt.figtext(0.15, 0.75, 'Ordinary', backgroundcolor=boxColors[1], color='white', weight='roman', size='small') if args.save_fig: plt.savefig('output/tone_analyzer_emotion_boxplot.pdf', bbox_inches='tight') else: plt.show() plt.close() plt.show()
def vis_one_image(im, im_name, output_dir, boxes, segms=None, keypoints=None, thresh=0.9, kp_thresh=2, dpi=200, box_alpha=0.0, dataset=None, show_class=False, ext='pdf', thresh_lo=None, range_thresh=False, scale=None, classes=None): """Visual debugging of detections. :param range_thresh: :param thresh_lo: """ output_name = os.path.basename(im_name) + '.' + ext fig_path = os.path.join(output_dir, '{}'.format(output_name)) if os.path.isfile(fig_path): return if not os.path.exists(output_dir): try: os.makedirs(output_dir) except: pass if isinstance(boxes, list): boxes, segms, keypoints, classes = convert_from_cls_format( boxes, segms, keypoints) if range_thresh: if boxes is None or boxes.shape[0] == 0 or ( max(boxes[:, 4]) <= thresh_lo and min(boxes[:, 4]) > thresh): return elif boxes is None or boxes.shape[0] == 0 or max(boxes[:, 4]) < thresh: return dataset_keypoints, _ = keypoint_utils.get_keypoints() if segms is not None: masks = mask_util.decode(segms) if scale: im_size_max = max(masks.shape) if np.round(scale * im_size_max) > cfg.TRAIN.MAX_SIZE: scale = float(cfg.TRAIN.MAX_SIZE) / float(im_size_max) masks = cv2.resize(masks, None, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR) if len(masks.shape) == 2: masks = np.expand_dims(masks, -1) boxes = boxes * scale color_list = colormap(rgb=True) / 255 kp_lines = kp_connections(dataset_keypoints) cmap = plt.get_cmap('rainbow') colors = [cmap(i) for i in np.linspace(0, 1, len(kp_lines) + 2)] fig = plt.figure(frameon=False) fig.set_size_inches(im.shape[1] / dpi, im.shape[0] / dpi) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.axis('off') fig.add_axes(ax) ax.imshow(im) # Display in largest to smallest order to reduce occlusion areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) sorted_inds = np.argsort(-areas) mask_color_id = 0 for i in sorted_inds: bbox = boxes[i, :4] score = boxes[i, -1] if range_thresh: if not (thresh_lo < score <= thresh): continue elif score < thresh: continue # show box (off by default) ax.add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='b', linewidth=0.2, alpha=0.3)) if show_class: ax.text(bbox[0], bbox[1] - 2, get_class_string(classes[i], score, dataset), fontsize=2, family='serif', bbox=dict(facecolor='g', alpha=0.2, pad=0, edgecolor='none'), color='white') # show mask if segms is not None and len(segms) > i: img = np.ones(im.shape) color_mask = color_list[mask_color_id % len(color_list), 0:3] mask_color_id += 1 w_ratio = .1 for c in range(3): color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio for c in range(3): img[:, :, c] = color_mask[c] e = masks[:, :, i] _, contour, hier = cv2.findContours(e.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) for c in contour: polygon = Polygon(c.reshape((-1, 2)), fill=True, facecolor=color_mask, edgecolor='b', linewidth=0.2, alpha=0.2) ax.add_patch(polygon) # show keypoints if keypoints is not None and len(keypoints) > i: kps = keypoints[i] plt.autoscale(False) for l in range(len(kp_lines)): i1 = kp_lines[l][0] i2 = kp_lines[l][1] if kps[2, i1] > kp_thresh and kps[2, i2] > kp_thresh: x = [kps[0, i1], kps[0, i2]] y = [kps[1, i1], kps[1, i2]] line = plt.plot(x, y) plt.setp(line, color=colors[l], linewidth=1.0, alpha=0.7) if kps[2, i1] > kp_thresh: plt.plot(kps[0, i1], kps[1, i1], '.', color=colors[l], markersize=3.0, alpha=0.7) if kps[2, i2] > kp_thresh: plt.plot(kps[0, i2], kps[1, i2], '.', color=colors[l], markersize=3.0, alpha=0.7) # add mid shoulder / mid hip for better visualization mid_shoulder = ( kps[:2, dataset_keypoints.index('right_shoulder')] + kps[:2, dataset_keypoints.index('left_shoulder')]) / 2.0 sc_mid_shoulder = np.minimum( kps[2, dataset_keypoints.index('right_shoulder')], kps[2, dataset_keypoints.index('left_shoulder')]) mid_hip = (kps[:2, dataset_keypoints.index('right_hip')] + kps[:2, dataset_keypoints.index('left_hip')]) / 2.0 sc_mid_hip = np.minimum( kps[2, dataset_keypoints.index('right_hip')], kps[2, dataset_keypoints.index('left_hip')]) if (sc_mid_shoulder > kp_thresh and kps[2, dataset_keypoints.index('nose')] > kp_thresh): x = [mid_shoulder[0], kps[0, dataset_keypoints.index('nose')]] y = [mid_shoulder[1], kps[1, dataset_keypoints.index('nose')]] line = plt.plot(x, y) plt.setp(line, color=colors[len(kp_lines)], linewidth=1.0, alpha=0.7) if sc_mid_shoulder > kp_thresh and sc_mid_hip > kp_thresh: x = [mid_shoulder[0], mid_hip[0]] y = [mid_shoulder[1], mid_hip[1]] line = plt.plot(x, y) plt.setp(line, color=colors[len(kp_lines) + 1], linewidth=1.0, alpha=0.7) fig.savefig(fig_path, dpi=dpi) plt.close('all')
import sim import cache deg = np.pi / 180.0 path = "./results/efficiency" if len(sys.argv) > 1: path = sys.argv[1] files = glob.glob(path + "/*.root") files.sort() # Load famous model famousModel = sim.FamousModel(files[0]) pixels = famousModel.pixels_to_cart(polygons=False) pixel_centers = famousModel.pixel_centers_to_cart() pixels = [Polygon(p) for p in pixels] def find(point, pixels): for i, p in enumerate(pixels): if p.contains_point(point): return i return None def read(filename): # Open root file and retreive tree file = TFile(filename) hits = file.Get("wicoBackHits") n = hits.GetEntriesFast() pos = np.zeros((n, 3)) for i in xrange(n): hits.GetEntry(i)
this_point[2] / this_point[3], this_point[3] / this_point[3] ]) triangle_arr.append(perspective_point) #append the color as well triangle_arr.append(triangle[3]) model.append(triangle_arr) # next need to use the painters algoritm (z sorting) model.sort(key=sort_avgz, reverse=True) # now we plot points that are only within the z range of 0 to 1 fig, ax = plt.subplots() patches = [] for triangle in model: if (triangle[0][2] >= 0 and triangle[1][2] >= 0 and triangle[2][2] >= 0) or (triangle[0][2] <= 1 and triangle[1][2] <= 1 and triangle[2][2] <= 1): #if meets above condition of being between 0 and 1 we plot the triangle with its corresponding color polygon_triangle = Polygon(array([[triangle[0][0], triangle[0][1]], [triangle[1][0], triangle[1][1]], [triangle[2][0], triangle[2][1]]]), True, color=rgb_color(triangle[3])) patches.append(polygon_triangle) p = PatchCollection(patches, match_original=True) # colors = array([100,100,100]) # p.set_array(colors) ax.add_collection(p) plt.show()