def showAnns(self, anns):
"""
Display the specified annotations.
:param anns (array of object): annotations to display
:return: None
"""
if len(anns) == 0:
return 0
if self.dataset['type'] == 'instances':
ax = plt.gca()
polygons = []
color = []
for ann in anns:
c = np.random.random((1, 3)).tolist()[0]
if type(ann['segmentation']) == list:
# polygon
for seg in ann['segmentation']:
poly = np.array(seg).reshape((len(seg)/2, 2))
polygons.append(Polygon(poly, True,alpha=0.4))
color.append(c)
else:
# mask
mask = COCO.decodeMask(ann['segmentation'])
img = np.ones( (mask.shape[0], mask.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, mask*0.5) ))
p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
ax.add_collection(p)
if self.dataset['type'] == 'captions':
for ann in anns:
print ann['caption']
python类Polygon()的实例源码
def plotArc(start_angle, stop_angle, radius, width, **kwargs):
""" write a docstring for this function"""
numsegments = 100
theta = np.radians(np.linspace(start_angle+90, stop_angle+90, numsegments))
centerx = 0
centery = 0
x1 = -np.cos(theta) * (radius)
y1 = np.sin(theta) * (radius)
stack1 = np.column_stack([x1, y1])
x2 = -np.cos(theta) * (radius + width)
y2 = np.sin(theta) * (radius + width)
stack2 = np.column_stack([np.flip(x2, axis=0), np.flip(y2,axis=0)])
#add the first values from the first set to close the polygon
np.append(stack2, [[x1[0],y1[0]]], axis=0)
arcArray = np.concatenate((stack1,stack2), axis=0)
return patches.Polygon(arcArray, True, **kwargs), ((x1, y1), (x2, y2))
def display(self, output_filename):
fig, (ax) = plt.subplots(1, 1)
data = [d.values for d in self.datasets]
labels = [d.label for d in self.datasets]
bp = ax.boxplot(data, labels = labels, notch = 0, sym = '+', vert = '1', whis = 1.5)
plt.setp(bp['boxes'], color='black')
plt.setp(bp['whiskers'], color='black')
plt.setp(bp['fliers'], color='black', marker='+')
for i in range(len(self.datasets)):
box = bp['boxes'][i]
box_x = []
box_y = []
for j in range(5):
box_x.append(box.get_xdata()[j])
box_y.append(box.get_ydata()[j])
box_coords = list(zip(box_x, box_y))
box_polygon = Polygon(box_coords, facecolor = self.datasets[i].color)
ax.add_patch(box_polygon)
if self.title is not None:
ax.set_title(self.title)
x_min = np.amin([np.amin(d.values) for d in self.datasets])
x_max = np.amax([np.amax(d.values) for d in self.datasets])
ax.set_ylim(x_min - 0.05*(x_max - x_min), x_max + 0.05*(x_max - x_min))
fig.savefig(output_filename)
plt.close(fig)
def __update_artist(self):
# check if this is the first point of a branch
if self.artist is None:
self.artist = Circle([self.x[0], self.y[0]], radius=self.r[0], fill=False,
lw=2, color='red')
self.axes.add_artist(self.artist)
elif len(self.x) == 0:
self.artist.remove()
self.artist = None
elif len(self.x) == 1:
self.artist.remove()
self.artist = Circle([self.x[0], self.y[0]], radius=self.r[0], fill=False,
lw=2, color='red')
self.axes.add_artist(self.artist)
# change from circle to polygon if more than 1 points are available
elif len(self.x) == 2:
self.artist.remove()
branch = Branch(x=self.x, y=self.y, z=[0 for i in self.x], r=self.r)
self.artist = Polygon(branch.outline, fill=False, color='red', lw=2)
self.axes.add_artist(self.artist)
else:
assert (len(self.x) > 2)
branch = Branch(x=self.x, y=self.y, z=[0 for i in self.x], r=self.r)
self.artist.set_xy(branch.outline)
plot-train.py 文件源码
项目:kaggle-dstl-satellite-imagery-feature-detection
作者: alno
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def plot_overlay(image_id):
img = load_image(image_id)
fig, ax = plt.subplots()
xmax = grid_sizes.loc[image_id, 'xmax']
ymin = grid_sizes.loc[image_id, 'ymin']
ax.imshow(np.rollaxis(img, 0, 3))
# plotting, color by class type
for cls in xrange(10):
multi_poly = shapely.wkt.loads(train_wkt.loc[(train_wkt['cls'] == cls + 1) & (train_wkt['image_id'] == image_id), 'multi_poly_wkt'].values[0])
for poly in multi_poly:
coords = convert_geo_coords_to_raster(np.array(poly.exterior), img.shape[1:], (xmax, ymin))
ax.add_patch(Polygon(coords, color=cls_colors[cls], lw=1.0, alpha=cls_alphas[cls]))
plt.title(image_id)
plt.show()
def _plot_displacement(ms):
if not plot:
ms.down
return
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
fig = plt.figure()
ax = fig.gca()
ms.processSources()
ax.imshow(num.flipud(ms.down), aspect='equal',
extent=[0, ms.frame.E.max(), 0, ms.frame.N.max()])
for src in ms.sources:
for seg in src.segments:
p = Polygon(seg.outline(), alpha=.8, fill=False)
ax.add_artist(p)
if isinstance(src, OkadaPath):
nodes = num.array(src.nodes)
ax.scatter(nodes[:, 0], nodes[:, 1], color='r')
plt.show()
fig.clear()
def plot(self, mode='image', ax=None, **kwargs):
"""Visualize the box on a matplotlib plot.
:param mode: How should the box coordinates and angle be interpreted.
- mode `'image'` corresponds to the situation where x coordinate of the box
denotes the "row of an image" (ie. the Y coordinate of the plot, arranged downwards)
and y coordinate of the box corresponds to the "column of an image",
(ie X coordinate of the plot). In other words, box's x goes downwards and y - rightwards.
- mode `'math'` corresponds to the "mathematics" situation where box's x and y correspond to the X and Y axes of the plot.
:param ax: the matplotlib axis to draw on. If unspecified, the current axis is used.
:param kwargs: arguments passed to the matplotlib's `Polygon` patch object. By default, fill is set to False, color to red and lw to 2.
:return: The created Polygon object.
"""
ax = ax or plt.gca()
poly = self.as_poly()
if mode == 'image':
poly = poly[:,[1,0]]
kwargs.setdefault('fill', False)
kwargs.setdefault('color', 'r')
kwargs.setdefault('lw', 2)
p = patches.Polygon(poly, **kwargs)
ax.add_patch(p)
return p
def showAnns(self, anns):
"""
Display the specified annotations.
:param anns (array of object): annotations to display
:return: None
"""
if len(anns) == 0:
return 0
if self.dataset['type'] == 'instances':
ax = plt.gca()
polygons = []
color = []
for ann in anns:
c = np.random.random((1, 3)).tolist()[0]
if type(ann['segmentation']) == list:
# polygon
for seg in ann['segmentation']:
poly = np.array(seg).reshape((len(seg)/2, 2))
polygons.append(Polygon(poly, True,alpha=0.4))
color.append(c)
else:
# mask
mask = COCO.decodeMask(ann['segmentation'])
img = np.ones( (mask.shape[0], mask.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, mask*0.5) ))
p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
ax.add_collection(p)
if self.dataset['type'] == 'captions':
for ann in anns:
print ann['caption']
def plotTriangles(X, A, B, C):
plt.hold(True)
ax = plt.gca()
for i in range(len(A)):
poly = [X[A[i], :], X[B[i], :], X[C[i], :]]
ax.add_patch(Polygon(np.array(poly), linestyle='solid', color='#00FF00', alpha=0.05))
def plot_polygon(ax, polygon):
settings = dict(closed=True, facecolor="#eeeeee", linewidth=1.,
edgecolor="black")
polygon = np.array(polygon)
polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]])
patch = patches.Polygon(polygon, **settings)
patchm = patches.Polygon(polygon_m, **settings)
#patch.set_zorder(10)
#patchm.set_zorder(10)
ax.add_patch(patch)
ax.add_patch(patchm)
# will result in roughly nz * nr*(nr+1)/2 points
def __init__(self, domain, **params):
self.domain = domain
self.__dict__.update(domain_params)
self.__dict__.update(params)
if isinstance(domain, Polygon):
self.cyl = True
def polygon_patches(self, cyl=False):
poly_settings = dict(closed=True, facecolor="#eeeeee", linewidth=1.,
edgecolor="k")
ball_settings = dict(facecolor="#aaaaaa", linewidth=1., edgecolor="k",
alpha=0.5)
ball_bind_zone_settings = dict(facecolor="#ffaaaa", linewidth=0.,
alpha=0.5)
patches = []
for dom in self.domains:
domp = dom.domain
if isinstance(domp, Polygon):
polygon = domp.nodes
polygon = np.array(polygon)
patches.append(mpatches.Polygon(polygon, **poly_settings))
if not cyl:
polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]])
patches.append(mpatches.Polygon(polygon_m, **poly_settings))
elif isinstance(domp, Ball):
xy = domp.x0[0], domp.x0[2]
if dom.binding and dom.bind_type == "zone":
p1 = mpatches.Circle(xy, domp.r + dom.ra,
**ball_bind_zone_settings)
p1.set_zorder(-100)
patches.append(p1)
p = mpatches.Circle(xy, domp.r, **ball_settings)
p.set_zorder(200)
patches.append(p)
return patches
def getPolyIdxImg(corners,res,debug=False):
"""Returns all indices of image that lie within given polygon.
Args:
corners (list): List of (x,y)-coordinates of corners.
res (int): Resolution of image (e.g. 512).
Keyword Args:
debug (bool): Print debugging messages.
Returns:
tuple: Tuple containing:
* indX (list): List of indices inside polygon in x-direction.
* indY (list): List of indices inside polygon in y-direction.
"""
#Convert to np array if necessary
corners=np.asarray(corners)
#Define polygonial patch
poly = ptc.Polygon(corners,edgecolor='r',facecolor=(1,0,0,.2),)
#Create grid
x_int=np.arange(1,res+1,1)
y_int=np.arange(1,res+1,1)
g = np.meshgrid(x_int, y_int)
#Zip them into coordinate tuples
coords = list(zip(*(c.flat for c in g)))
#Check which point is inside
pts = np.vstack([p for p in coords if poly.contains_point(p, radius=0)])
indX,indY= pts[0,:],pts[1,:]
return indX,indY
def plot_elements(figname="elements.png",nodesfile="nodes.txt",elementsfile="elements.txt",dlm=","):
"""
Plot nodes and elements of mesh.
Parameters
----------
figname : str
Name of output picture
nodesfile : str
Path of node data file
elementsfile : str
Path of elements conectivity file
dlm : str
Delimiter (i.e. ",","\t")
"""
NC = np.loadtxt(nodesfile, delimiter=dlm)
EC = np.loadtxt(elementsfile, delimiter=dlm)
f = plt.figure()
ax = f.add_subplot(111)
plt.hold(True)
for element in EC:
XX = []
for node in element:
if str(node)!="nan":
XX.append([NC[node-1,0],NC[node-1,1]])
p = Polygon(XX, True, fc="#00DDDD", ec="#778877")
ax.add_patch(p)
plt.axis('equal')
plt.axis('off')
plt.savefig(figname)
def draw_map():
# colour all polygons for which we have data in evaluated.json
for shape, info in zip(basemap.berlin, basemap.berlin_info):
if info['ORT'] in json_data:
c_ort = json_data[info['ORT']]
colour = get_colour(c_ort[ARGV])
else:
colour = '#dddddd'
patches = [Polygon(numpy.array(shape), True)]
pc = PatchCollection(patches)
pc.set_facecolor(colour)
ax.add_collection(pc)
# draw map
plt.show()
def test_annotation2pltpatch():
assert list(ni.annotation2pltpatch(np.NaN)) == []
assert list(ni.annotation2pltpatch(())) == []
anno = ('point', ((1, 1), (1, 2)))
pltpatches = list(ni.annotation2pltpatch(anno))
assert len(pltpatches) == 2
assert isinstance(pltpatches[0], plp.CirclePolygon)
assert isinstance(pltpatches[1], plp.CirclePolygon)
anno = ('circle', ((2, 2, 2),))
pltpatches = list(ni.annotation2pltpatch(anno))
assert isinstance(pltpatches[0], plp.Circle)
anno = ('rect', ((1, 2, 2, 3),))
pltpatches = list(ni.annotation2pltpatch(anno))
assert isinstance(pltpatches[0], plp.Rectangle)
anno = ('polyline', (((1, 2), (3, 2), (3, 4), (1, 4), (1, 2)),))
pltpatches = list(ni.annotation2pltpatch(anno))
assert isinstance(pltpatches[0], plp.Polygon)
anno = ('polyline', (((0, 0), (2, 2), (2, 4)),))
pltpatches = list(ni.annotation2pltpatch(anno))
assert isinstance(pltpatches[0], plp.Polygon)
with pytest.raises(ValueError) as ex:
anno = ('invalid', ((1,),))
list(ni.annotation2pltpatch(anno))
assert str(ex.value).startswith('Invalid kind of annotation')
def annotation2pltpatch(annotation, **kwargs):
"""
Convert geometric annotation to matplotlib geometric objects (=patches)
For details regarding matplotlib patches see:
http://matplotlib.org/api/patches_api.html
For annotation formats see:
imageutil.annotation2coords
:param annotation annotation: Annotation of an image region such as
point, circle, rect or polyline
:return: matplotlib.patches
:rtype: generator over matplotlib patches
"""
if not annotation or isnan(annotation):
return
kind, geometries = annotation
for geo in geometries:
if kind == 'point':
pltpatch = plp.CirclePolygon((geo[0], geo[1]), 1, **kwargs)
elif kind == 'circle':
pltpatch = plp.Circle((geo[0], geo[1]), geo[2], **kwargs)
elif kind == 'rect':
x, y, w, h = geo
pltpatch = plp.Rectangle((x, y), w, h, **kwargs)
elif kind == 'polyline':
pltpatch = plp.Polygon(geo, closed=False, **kwargs)
else:
raise ValueError('Invalid kind of annotation: ' + kind)
yield pltpatch
def polygons(latitudes, longitudes, clusters, maptype=MAPTYPE):
"""Plot clusters of points on map, including them in a polygon defining their convex hull.
:param pandas.Series latitudes: series of sample latitudes
:param pandas.Series longitudes: series of sample longitudes
:param pandas.Series clusters: marker clusters, as integers
:param string maptype: type of maps, see GoogleStaticMapsAPI docs for more info
:return: None
"""
width = SCALE * MAX_SIZE
img, pixels = background_and_pixels(latitudes, longitudes, MAX_SIZE, maptype)
polygons = []
for c in clusters.unique():
in_polygon = clusters == c
if in_polygon.sum() < 3:
print '[WARN] Cannot draw polygon for cluster {} - only {} samples.'.format(c, in_polygon.sum())
continue
cluster_pixels = pixels.loc[clusters == c]
polygons.append(Polygon(cluster_pixels.iloc[ConvexHull(cluster_pixels).vertices], closed=True))
plt.figure(figsize=(10, 10))
ax = plt.subplot(111)
plt.imshow(np.array(img)) # Background map
p = PatchCollection(polygons, cmap='jet', alpha=0.15) # Collection of polygons
p.set_array(clusters.unique())
ax.add_collection(p)
plt.scatter( # Scatter plot
pixels['x_pixel'],
pixels['y_pixel'],
c=clusters,
s=width / 40,
linewidth=0,
alpha=0.25,
)
plt.gca().invert_yaxis() # Origin of map is upper left
plt.axis([0, width, width, 0]) # Remove margin
plt.axis('off')
plt.tight_layout()
plt.show()
def to_mpl_patch(self):
"""
This function ...
:return:
"""
points = []
for point in self.points: points.append([point.x, point.y])
points = np.array(points)
return mpl_Polygon(points, edgecolor='green', facecolor='none', lw=3, alpha=0.7)
# -----------------------------------------------------------------
def to_mpl_patch(self):
"""
This function ...
:return:
"""
points = []
for point in self.points: points.append([point.x, point.y])
points = np.array(points)
return mpl_Polygon(points, edgecolor='green', facecolor='none', lw=3, alpha=0.7)
# -----------------------------------------------------------------
def plotTriangles(X, A, B, C):
plt.hold(True)
ax = plt.gca()
for i in range(len(A)):
poly = [X[A[i], :], X[B[i], :], X[C[i], :]]
ax.add_patch(Polygon(np.array(poly), linestyle='solid', color='#00FF00', alpha=0.05))
def plot_mesh(self):
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
fig = plt.figure()
ax = fig.add_subplot(111)
_x,_y = [],[]
patches = []
for k,elm in enumerate(self.ec):
_x,_y,_ux,_uy = [],[],[],[]
for nd in elm:
_x.append(self.nc[nd,0])
_y.append(self.nc[nd,1])
polygon = Polygon(zip(_x,_y), True)
patches.append(polygon)
pc = PatchCollection(patches, color="#25CDCD", edgecolor="#435959", alpha=0.8, lw=0.5)
ax.add_collection(pc)
x0,x1,y0,y1 = self._rect_region()
ax.set_xlim(x0,x1)
ax.set_ylim(y0,y1)
#~ ax.set_title("Model %s"%(self.name))
ax.set_aspect("equal")
plt.show()
def plot_model(self):
"""
Plot the mesh model, including bcs
"""
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
fig = plt.figure()
ax = fig.add_subplot(111)
_x,_y = [],[]
patches = []
for k,elm in enumerate(self.get_elements()):
_x,_y,_ux,_uy = [],[],[],[]
for nd in elm.nodes:
if nd.fx != 0: self._draw_xforce(ax,nd.x,nd.y)
if nd.fy != 0: self._draw_yforce(ax,nd.x,nd.y)
if nd.ux == 0 and nd.uy == 0: self._draw_xyconstraint(ax,nd.x,nd.y)
_x.append(nd.x)
_y.append(nd.y)
polygon = Polygon(zip(_x,_y), True)
patches.append(polygon)
pc = PatchCollection(patches, color="#7CE7FF", edgecolor="k", alpha=0.4)
ax.add_collection(pc)
x0,x1,y0,y1 = self.rect_region()
ax.set_xlim(x0,x1)
ax.set_ylim(y0,y1)
ax.set_title("Model %s"%(self.name))
ax.set_aspect("equal")
def plot_esol(self,var="ux"):
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
fig = plt.figure()
ax = fig.add_subplot(111)
_x,_y = [],[]
patches = []
for k,elm in enumerate(self.get_elements()):
_x,_y,_ux,_uy = [],[],[],[]
for nd in elm.nodes:
_x.append(nd.x)
_y.append(nd.y)
polygon = Polygon(zip(_x,_y), True)
patches.append(polygon)
pc = PatchCollection(patches, cmap="jet", alpha=1)
solutions = {
"sxx": [e.sx for e in self.get_elements()],
"syy": [e.sy for e in self.get_elements()],
"sxy": [e.sxy for e in self.get_elements()],
"exx": [e.ex for e in self.get_elements()],
"eyy": [e.ey for e in self.get_elements()],
"exy": [e.exy for e in self.get_elements()]
}
fsol = np.array(solutions.get(var.lower()))
pc.set_array(fsol)
ax.add_collection(pc)
plt.colorbar(pc)
x0,x1,y0,y1 = self.rect_region()
ax.set_xlim(x0,x1)
ax.set_ylim(y0,y1)
ax.set_aspect("equal")
ax_title = "{0} (Max:{1}, Min:{2})".format(var,fsol.max(),fsol.min())
ax.set_title(ax_title)
def __init__(self,xcoord,ycoord,**kwargs):
collections.PatchCollection.__init__(self,[],**kwargs)
tol = 0.02
_xdata1 = np.array([xcoord-tol,xcoord,xcoord+tol])
_ydata1 = np.array([ycoord-tol,ycoord,ycoord-tol])
_xdata2 = np.array([xcoord-tol,xcoord,xcoord-tol])
_ydata2 = np.array([ycoord-tol,ycoord,ycoord+tol])
# Polygons
p1 = patches.Polygon(zip(_xdata1,_ydata1))
p1.set_color("r")
p2 = patches.Polygon(zip(_xdata2,_ydata2))
#print p1,p2
#p2.set_color("g")
# Set data
self.set_paths((p1,p2))
self.set_color("k")
#self.set_marker("-")
#self.set_mfc('r')
#self.set_ms(10)
def _config_axes(self, X, Y):
'''
Make an axes patch and outline.
'''
ax = self.ax
ax.set_frame_on(False)
ax.set_navigate(False)
xy = self._outline(X, Y)
ax.update_datalim(xy)
ax.set_xlim(*ax.dataLim.intervalx)
ax.set_ylim(*ax.dataLim.intervaly)
if self.outline is not None:
self.outline.remove()
self.outline = lines.Line2D(
xy[:, 0], xy[:, 1], color=mpl.rcParams['axes.edgecolor'],
linewidth=mpl.rcParams['axes.linewidth'])
ax.add_artist(self.outline)
self.outline.set_clip_box(None)
self.outline.set_clip_path(None)
c = mpl.rcParams['axes.facecolor']
if self.patch is not None:
self.patch.remove()
self.patch = mpatches.Polygon(xy, edgecolor=c,
facecolor=c,
linewidth=0.01,
zorder=-1)
ax.add_artist(self.patch)
self.update_ticks()
def tissot(self,lon_0,lat_0,radius_deg,npts,ax=None,**kwargs):
"""
Draw a polygon centered at ``lon_0,lat_0``. The polygon
approximates a circle on the surface of the earth with radius
``radius_deg`` degrees latitude along longitude ``lon_0``,
made up of ``npts`` vertices.
The polygon represents a Tissot's indicatrix
(http://en.wikipedia.org/wiki/Tissot's_Indicatrix),
which when drawn on a map shows the distortion
inherent in the map projection.
.. note::
Cannot handle situations in which the polygon intersects
the edge of the map projection domain, and then re-enters the domain.
Extra keyword ``ax`` can be used to override the default axis instance.
Other \**kwargs passed on to matplotlib.patches.Polygon.
returns a matplotlib.patches.Polygon object."""
ax = kwargs.pop('ax', None) or self._check_ax()
g = pyproj.Geod(a=self.rmajor,b=self.rminor)
az12,az21,dist = g.inv(lon_0,lat_0,lon_0,lat_0+radius_deg)
seg = [self(lon_0,lat_0+radius_deg)]
delaz = 360./npts
az = az12
for n in range(npts):
az = az+delaz
lon, lat, az21 = g.fwd(lon_0, lat_0, az, dist)
x,y = self(lon,lat)
# add segment if it is in the map projection region.
if x < 1.e20 and y < 1.e20:
seg.append((x,y))
poly = Polygon(seg,**kwargs)
ax.add_patch(poly)
# clip polygons for round polar plots.
if self.round: poly,c = self._clipcircle(ax,poly)
# set axes limits to fit map region.
self.set_axes_limits(ax=ax)
return poly
def _config_axes(self, X, Y):
'''
Make an axes patch and outline.
'''
ax = self.ax
ax.set_frame_on(False)
ax.set_navigate(False)
xy = self._outline(X, Y)
ax.update_datalim(xy)
ax.set_xlim(*ax.dataLim.intervalx)
ax.set_ylim(*ax.dataLim.intervaly)
if self.outline is not None:
self.outline.remove()
self.outline = mpatches.Polygon(
xy, edgecolor=mpl.rcParams['axes.edgecolor'],
facecolor='none',
linewidth=mpl.rcParams['axes.linewidth'],
closed=True,
zorder=2)
ax.add_artist(self.outline)
self.outline.set_clip_box(None)
self.outline.set_clip_path(None)
c = mpl.rcParams['axes.facecolor']
if self.patch is not None:
self.patch.remove()
self.patch = mpatches.Polygon(xy, edgecolor=c,
facecolor=c,
linewidth=0.01,
zorder=-1)
ax.add_artist(self.patch)
self.update_ticks()
def tissot(self,lon_0,lat_0,radius_deg,npts,ax=None,**kwargs):
"""
Draw a polygon centered at ``lon_0,lat_0``. The polygon
approximates a circle on the surface of the earth with radius
``radius_deg`` degrees latitude along longitude ``lon_0``,
made up of ``npts`` vertices.
The polygon represents a Tissot's indicatrix
(http://en.wikipedia.org/wiki/Tissot's_Indicatrix),
which when drawn on a map shows the distortion
inherent in the map projection.
.. note::
Cannot handle situations in which the polygon intersects
the edge of the map projection domain, and then re-enters the domain.
Extra keyword ``ax`` can be used to override the default axis instance.
Other \**kwargs passed on to matplotlib.patches.Polygon.
returns a matplotlib.patches.Polygon object."""
ax = kwargs.pop('ax', None) or self._check_ax()
g = pyproj.Geod(a=self.rmajor,b=self.rminor)
az12,az21,dist = g.inv(lon_0,lat_0,lon_0,lat_0+radius_deg)
seg = [self(lon_0,lat_0+radius_deg)]
delaz = 360./npts
az = az12
for n in range(npts):
az = az+delaz
lon, lat, az21 = g.fwd(lon_0, lat_0, az, dist)
x,y = self(lon,lat)
# add segment if it is in the map projection region.
if x < 1.e20 and y < 1.e20:
seg.append((x,y))
poly = Polygon(seg,**kwargs)
ax.add_patch(poly)
# clip polygons for round polar plots.
if self.round: poly,c = self._clipcircle(ax,poly)
# set axes limits to fit map region.
self.set_axes_limits(ax=ax)
return poly
def _post_to_mask(self, rois, id):
for r in rois:
if 'rec' in r:
x1,y1,x2,y2 = r['rec']
for x in range(self.mask.shape[0]):
for y in range(self.mask.shape[1]):
if (x >= x1 and x < x2) and (y >= y1 and y < y2):
self.mask[x,y] = id
if 'poly' in r:
import matplotlib.patches as patches
poly1 = patches.Polygon(r['poly'], closed=True)
for i in range(self.mask.shape[0]):
for j in range(self.mask.shape[1]):
if poly1.get_path().contains_point((i,j)) == True:
self.mask[i,j] = id