def draw_triangle(fig, ax, x1, y1, x2, y2, x3, y3, fillcolor, bordercolor):
xy = [
(x1, y1),
(x2, y2),
(x3, y3),
]
polygon = patches.Polygon(
xy=xy,
ls='solid',
lw=1.0,
ec=bordercolor,
closed=True,
color=fillcolor)
ax.add_patch(polygon)
python类Polygon()的实例源码
def _getPatches(self):
return [Polygon(self._getPolygonPoints(node.size), True) for node in tree.allNodes]
def look_for_ice(planes, icebergs, k):
"""Retrieve, for each plane, the visible ice."""
for p in planes:
if p.active(k):
fov = Polygon(p.fov)
p.findings = [i for i in range(icebergs.positions.shape[1])
if fov.contains(Point(icebergs.positions[0, i], icebergs.positions[1, i]))]
p.scan = lmb.Scan(
lmb.sensors.SquareSensor(p.fov, p.p_detect, p.lambdaB),
[lmb.GaussianReport(np.random.multivariate_normal(
icebergs.positions[:, i], Pz_true), p.Pz, i)
for i in p.findings])
plot-submission.py 文件源码
项目:kaggle-dstl-satellite-imagery-feature-detection
作者: alno
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def plot_prediction_overlay(subm_name, image_id, save_file=None):
subm = pd.read_csv('subm/%s.csv.gz' % subm_name)
img = load_image(image_id)
if save_file:
fig, ax = plt.subplots(figsize=(30, 30))
else:
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(subm.loc[(subm['ClassType'] == cls + 1) & (subm['ImageId'] == image_id), 'MultipolygonWKT'].values[0])
#if cls == 3:
#multi_poly = multi_poly.buffer(2e-5).buffer(-2e-5)
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(subm_name)
if save_file:
plt.savefig(save_file)
plt.close()
else:
plt.show()
def visualize_jackal(figure, pose, img):
pyplot.cla()
fig = figure
ax = fig.add_subplot(111)
ax.imshow(img, cmap=cm.Greys_r)
ax.axis('image')
if pose:
meter_to_pixel = 10.6
xl = pose[0]*meter_to_pixel
yl = pose[1]*meter_to_pixel
dl = pose[2]
ax.plot(xl, yl, 'ro', markersize=10)
L1 = 0.8*meter_to_pixel
L2 = 1.6*meter_to_pixel
car=[(xl-L1,yl-L1), (xl-L1,yl+ L1), (xl, yl+L2), (xl+L1, yl+L1), (xl+L1,yl-L1)]
polygon2 = Polygon(transform(car, [xl,yl],dl+3.14), fill = True, facecolor='blue', edgecolor='blue', lw=4, zorder=2)
ax.add_patch(polygon2)
ax.grid()
#fig.subplots_adjust(0.003,0.062,0.97,0.94)
#pyplot.show()
pyplot.pause(0.01)
return fig
#==============================
#==============================
def visualize_jackal(figure, pose):
pyplot.cla()
fig = figure
ax = fig.add_subplot(111)
if pose:
xl = pose[0]
yl = pose[1]
dl = pose[2]
ax.plot(xl, yl, 'ro', markersize=8)
L1 = 0.4
L2 = 0.8
car=[(xl-L1,yl-L1), (xl-L1,yl+ L1), (xl, yl+L2), (xl+L1, yl+L1), (xl+L1,yl-L1)]
Ecolor = 'Grey'
polygon2 = Polygon(transform(car, [xl,yl], dl), fill = True, facecolor=Ecolor, edgecolor='black', lw=4, zorder=2)
ax.add_patch(polygon2)
ax.grid()
ax.set_xlabel('x(m)')
ax.set_ylabel('y(m)')
ax.set_aspect('equal')
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
#fig.subplots_adjust(0.003,0.062,0.97,0.94)
#pyplot.show()
pyplot.pause(0.01)
return fig
#==============================
#==============================
def draw_triangle(fig, ax, x1, y1, x2, y2, x3, y3, fillcolor):
xy = [
(x1, y1),
(x2, y2),
(x3, y3),
]
polygon = patches.Polygon(
xy=xy,
closed=True,
color=fillcolor)
ax.add_patch(polygon)
def on_pick(self, event):
# Filter any non-Polygons (axvspan:s) or non-visible
artist = event.artist
if not isinstance(artist, Polygon) or not artist.get_visible():
return
item = self.span2item.get(artist, None)
if not item:
logging.error('item for artist unexpectedly not found')
return
marking = self.span2marking[artist]
self.sig_span_picked.emit(item, marking, event)
def map(dataframe, title = "Map", colorbarName = None):
fig, ax = plt.subplots(figsize=(80,40))
m = Basemap(resolution='l', # c, l, i, h, f or None
projection='robin',
lon_0=0)
m.drawmapboundary(fill_color='#46bcec')
m.fillcontinents(color='#f2f2f2',lake_color='#46bcec')
# m.drawcoastlines()
plt.title(title, fontsize=50, y=1.08)
m.readshapefile('visualization/World/World', 'world',drawbounds=False)
df_plot = pd.DataFrame({
'shapes': [Polygon(np.array(shape), True) for shape in m.world],
'country': [country['ISO3'] for country in m.world_info]
})
df_plot = df_plot.merge(dataframe, on='country', how='left')
df_plot = df_plot.dropna()
cmap = plt.get_cmap('RdYlGn')
pc = PatchCollection(df_plot.shapes, zorder=2)
norm = Normalize()
pc.set_facecolor(cmap(norm(df_plot['value'].values)))
ax.add_collection(pc)
mapper = matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap)
mapper.set_array(df_plot['value'])
cbar = plt.colorbar(mapper, shrink=0.7, label = colorbarName)
fig = plt.gcf()
fig.savefig("Map.jpg")
plt.show()
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 'segmentation' in anns[0]:
datasetType = 'instances'
elif 'caption' in anns[0]:
datasetType = 'captions'
if datasetType == '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
t = self.imgs[ann['image_id']]
if type(ann['segmentation']['counts']) == list:
rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
else:
rle = [ann['segmentation']]
m = mask.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) ))
p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
ax.add_collection(p)
elif datasetType == 'captions':
for ann in anns:
print ann['caption']
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 'segmentation' in anns[0]:
datasetType = 'instances'
elif 'caption' in anns[0]:
datasetType = 'captions'
if datasetType == '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
t = self.imgs[ann['image_id']]
if type(ann['segmentation']['counts']) == list:
rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
else:
rle = [ann['segmentation']]
m = mask.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) ))
p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
ax.add_collection(p)
elif datasetType == 'captions':
for ann in anns:
print ann['caption']
def plot_synteny(seq1, ind1, seq2, ind2, y1, y2,
featType, matrix, cm, seqname):
"""This function plots all the lines for each"""
myPatches = []
colormap = {"COX1": '#c0d9ef',
"L": '#e8f1df',
"I": '#f7dedc',
"16S": '#ff2e00',
"12S": '#ffc239',
"cal": '#ffff54',
"COX2": "#7fce66",
"ND2": "#00ae60",
"COX3": "#00aeec",
"ND1": "#006fbb",
"*": "#ffffff",
"(": "#ded9c5",
"Q": "#ffc294",
"?": "#b5a2c4",
"ND4": "#968b5a",
"ND3": "#00fc65",
"ND4L": "#00dcf0",
"ND6": "#ff994e",
"ND5": "#dc31e6",
"X": "#d8d8d8",
"G": "#abdce7",
"CYTB": "#ff0059"}
for i in range(len(seq1)):
feat1 = seq1[i]
feat2 = seq2[i]
if feat1 != '-' and feat2 != '-':
xs = []
ys = []
xs.append(ind1[i]) # top left
ys.append(y1)
xs.append(ind1[i] + 1) # top right
ys.append(y1)
xs.append(ind2[i] + 1) # bottom right
ys.append(y2)
xs.append(ind2[i]) #bottom left
ys.append(y2)
xs.append(ind1[i]) #top left
ys.append(y1)
alpha = 0.5
if featType in ['CDS', 'gene']:
try:
val = matrix[(feat1, feat2)]
except:
val = matrix[(feat2, feat1)]
color = cm[val]
alpha = color[-1]
elif featType == 'rRNA':
if feat1 != feat2:
alpha=0
color = colormap[seqname]
stack1 = np.column_stack([xs, ys])
myPatches.append(patches.Polygon(stack1, closed=True,
color = color,
alpha = alpha,
lw=0))
return myPatches
def porestreamlines(polygon=None, rx=10., ry=10., Nx=100, Ny=100,
maxvalue=None, **fields):
"streamlines plot of vector field around nanopore"
# interpolate on regular mesh symmetric w.r.t. center axis
mesh2D = nanopores.RectangleMesh([-rx-0.1,-ry-0.1], [rx+0.1,ry+0.1], Nx, Ny)
fields2 = nanopores.convert2D(mesh2D, *(fields.values()))
# prepare polygon and copy to left half
settings = dict(closed=True, facecolor="#eeeeee", linewidth=3.,
edgecolor="black")
if polygon is not None:
polygon = np.array(polygon)
polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]])
# prepare plots
Ny += 1
Nx += 1
Y, X = np.mgrid[-ry:ry:Ny*1j, -rx:rx:Nx*1j]
U = np.zeros((Ny,Nx))
V = np.zeros((Ny,Nx))
formt = matplotlib.ticker.FuncFormatter(fmt)
ticks = [0] + [10**n for n in range(-16, -9)]
# determine uniform color range from fields (maybe round to nearest 10-power)
if maxvalue is None:
maxvalue = max(dolfin.norm(F.vector(), "linf") for F in fields2)
#maxvalue = 10**int(np.log10(maxvalue))
for i, F in enumerate(fields2):
Fstr = fields.keys()[i]
fig, ax = plt.subplots(figsize=(5, 4.5), num=Fstr)
# fill array with function values
for y in range(Ny):
for x in range(Nx):
f = F(X[y][x], Y[y][x])
U[y][x] = f[0]
V[y][x] = f[1]
# streamplot with logarithmic scale
strength = np.sqrt(U*U+V*V)
norm = matplotlib.colors.SymLogNorm(linthresh=ticks[1], linscale=1.0,
vmin=0., vmax=maxvalue)
strm = plt.streamplot(X, Y, U, V, arrowsize=1.5, linewidth=1.5, density=1.5,
cmap=cm.viridis, color=strength, norm=norm)
plt.colorbar(strm.lines, ticks=ticks, format=formt)
plt.xlabel('x [nm]') #, fontsize=20)
plt.ylabel('z [nm]') #, fontsize=20)
# plot pore polygon on top
if polygon is not None:
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)
def porestreamlines(polygon=None, rx=10., ry=10., Nx=100, Ny=100,
maxvalue=None, **fields):
"streamlines plot of vector field around nanopore"
# interpolate on regular mesh symmetric w.r.t. center axis
#mesh2D = nanopores.RectangleMesh([-rx-0.1,-ry-0.1], [rx+0.1,ry+0.1], Nx, Ny)
#fields2 = nanopores.convert2D(mesh2D, *(fields.values()))
# prepare polygon and copy to left half
settings = dict(closed=True, facecolor="#eeeeee", linewidth=3.,
edgecolor="black")
if polygon is not None:
polygon = np.array(polygon)
polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]])
# prepare plots
Ny += 1
Nx += 1
Y, X = np.mgrid[-ry:ry:Ny*1j, -rx:rx:Nx*1j]
U = np.zeros((Ny,Nx))
V = np.zeros((Ny,Nx))
formt = matplotlib.ticker.FuncFormatter(fmt)
ticks = [0] + [10**n for n in range(-16, -9)]
# determine uniform color range from fields (maybe round to nearest 10-power)
if maxvalue is None:
maxvalue = max(dolfin.norm(F.vector(), "linf") for F in fields.values())
#maxvalue = 10**int(np.log10(maxvalue))
for i, F in enumerate(fields.values()):
Fstr = fields.keys()[i]
fig, ax = plt.subplots(figsize=(rx+1., ry), num=Fstr)
# fill array with function values
for y in range(Ny):
for x in range(Nx):
f = F(X[y][x], Y[y][x])
U[y][x] = f[0]
V[y][x] = f[1]
# streamplot with logarithmic scale
strength = np.sqrt(U*U+V*V)
norm = matplotlib.colors.SymLogNorm(linthresh=ticks[1], linscale=1.0,
vmin=0., vmax=maxvalue)
strm = plt.streamplot(X, Y, U, V, arrowsize=1., linewidth=1., density=3.,
cmap=cm.viridis, color=strength, norm=norm)
plt.colorbar(strm.lines, ticks=ticks, format=formt)
plt.xlabel('x [nm]') #, fontsize=20)
plt.ylabel('z [nm]') #, fontsize=20)
# plot pore polygon on top
if polygon is not None:
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)
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 'segmentation' in anns[0]:
datasetType = 'instances'
elif 'caption' in anns[0]:
datasetType = 'captions'
if datasetType == '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
t = self.imgs[ann['image_id']]
if type(ann['segmentation']['counts']) == list:
rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
else:
rle = [ann['segmentation']]
m = mask.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) ))
p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
ax.add_collection(p)
elif datasetType == 'captions':
for ann in anns:
print ann['caption']
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 'segmentation' in anns[0]:
datasetType = 'instances'
elif 'caption' in anns[0]:
datasetType = 'captions'
if datasetType == '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
t = self.imgs[ann['image_id']]
if type(ann['segmentation']['counts']) == list:
rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
else:
rle = [ann['segmentation']]
m = mask.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) ))
p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
ax.add_collection(p)
elif datasetType == 'captions':
for ann in anns:
print(ann['caption'])
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 'segmentation' in anns[0]:
datasetType = 'instances'
elif 'caption' in anns[0]:
datasetType = 'captions'
if datasetType == '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
t = self.imgs[ann['image_id']]
if type(ann['segmentation']['counts']) == list:
rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
else:
rle = [ann['segmentation']]
m = mask.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) ))
p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
ax.add_collection(p)
elif datasetType == 'captions':
for ann in anns:
print ann['caption']
coco.py 文件源码
项目:visually-informed-embedding-of-word-VIEW-
作者: oswaldoludwig
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
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 'segmentation' in anns[0]:
datasetType = 'instances'
elif 'caption' in anns[0]:
datasetType = 'captions'
if datasetType == '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
t = self.imgs[ann['image_id']]
if type(ann['segmentation']['counts']) == list:
rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
else:
rle = [ann['segmentation']]
m = mask.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) ))
p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
ax.add_collection(p)
elif datasetType == 'captions':
n=0
cap= [None] * 5
for ann in anns:
#print ann['caption']
if n<5:
cap[n]=ann['caption']
#print cap[n]
n = n + 1
print n
print cap
return cap
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 'segmentation' in anns[0]:
datasetType = 'instances'
elif 'caption' in anns[0]:
datasetType = 'captions'
if datasetType == '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
t = self.imgs[ann['image_id']]
if type(ann['segmentation']['counts']) == list:
rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
else:
rle = [ann['segmentation']]
m = mask.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) ))
p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
ax.add_collection(p)
elif datasetType == 'captions':
for ann in anns:
print ann['caption']
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 'segmentation' in anns[0]:
datasetType = 'instances'
elif 'caption' in anns[0]:
datasetType = 'captions'
if datasetType == '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
t = self.imgs[ann['image_id']]
if type(ann['segmentation']['counts']) == list:
rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
else:
rle = [ann['segmentation']]
m = mask.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) ))
p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
ax.add_collection(p)
elif datasetType == 'captions':
for ann in anns:
print ann['caption']