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类PatchCollection()的实例源码
def draw_group(data, panel_params, coord, ax, **params):
data = coord.transform(data, panel_params)
fill = to_rgba(data['fill'], data['alpha'])
color = to_rgba(data['color'], data['alpha'])
ranges = coord.range(panel_params)
# For perfect circles the width/height of the circle(ellipse)
# should factor in the dimensions of axes
bbox = ax.get_window_extent().transformed(
ax.figure.dpi_scale_trans.inverted())
ax_width, ax_height = bbox.width, bbox.height
factor = ((ax_width/ax_height) *
np.ptp(ranges.y)/np.ptp(ranges.x))
size = data.loc[0, 'binwidth'] * params['dotsize']
offsets = data['stackpos'] * params['stackratio']
if params['binaxis'] == 'x':
width, height = size, size*factor
xpos, ypos = data['x'], data['y'] + height*offsets
elif params['binaxis'] == 'y':
width, height = size/factor, size
xpos, ypos = data['x'] + width*offsets, data['y']
circles = []
for xy in zip(xpos, ypos):
patch = mpatches.Ellipse(xy, width=width, height=height)
circles.append(patch)
coll = mcoll.PatchCollection(circles,
edgecolors=color,
facecolors=fill)
ax.add_collection(coll)
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 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 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 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 _createFigure(self):
fig, ax = self._plotter.subplots()
pObj = PatchCollection(self._patches, cmap=matplotlib.cm.jet, alpha=0.4)
pObj.set_array(np.array(self._colors))
ax.add_collection(pObj)
def chloropleth(self, query, color = "Blues"):
"""shows a chloropleth map of crimes
Args:
query: name of sql
"""
self.load()
data = pd.read_sql_query(con=self.con, sql=query)
points = self.gen_points(data, self.data_map)
self.data_map['count'] = self.data_map['poly'].map(lambda x: len(list(filter(prep(x).contains, points))))
self.data_map['density_m'] = self.data_map['count'] / self.data_map['area_m']
self.data_map['density_km'] = self.data_map['count'] / self.data_map['area_km']
self.data_map.replace(to_replace={'density_m': {0: np.nan}, 'density_km': {0: np.nan}}, inplace=True)
breaks = nb(
self.data_map[self.data_map['density_km'].notnull()].density_km.values,
initial=300,
k=5)
jb = pd.DataFrame({'jenks_bins': breaks.yb}, index=self.data_map[self.data_map['density_km'].notnull()].index)
self.data_map = self.data_map.join(jb)
self.data_map.jenks_bins.fillna(-1, inplace=True)
jenks_labels = ["<= %0.1f/km$^2$(%s communities)" % (b, c) for b, c in zip(
breaks.bins, breaks.counts)]
jenks_labels.insert(0, 'None (%s communities)' % len(self.data_map[self.data_map['density_km'].isnull()]))
cmap = plt.get_cmap(color)
self.data_map['patches'] = self.data_map['poly'].map(lambda x: PolygonPatch(x, ec='#555555', lw=.2, alpha=1., zorder=4))
pc = PatchCollection(self.data_map['patches'], match_original=True)
norm = Normalize()
pc.set_facecolor(cmap(norm(self.data_map['jenks_bins'].values)))
self.ax.add_collection(pc)
cb = self.gen_colorbar(colors=len(jenks_labels), color_map=cmap, shrink=0.5, labels=jenks_labels)
cb.ax.tick_params(labelsize=6)
plt.tight_layout()
plt.show()
def add_sub_collection(ax, df, df_filter, cmap_values):
sub_df = df[df_filter]
pc = PatchCollection(sub_df['patches'], match_original=True)
pc.set_facecolor(cmap_values[df_filter.values, :])
ax.add_collection(pc)
def build_map_nmf(df_map, m, coords, info, title, CrimePatterns):
# plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='w', frame_on=True)
# draw wards with grey outlines
norm = Normalize()
for i in xrange(5):
color = colormaps[i]
cmap = plt.get_cmap(color)
pc = PatchCollection(df_map[df_map['class'] == i+1]['patches'], match_original=True, alpha=0.8)
pc.set_facecolor(cmap(norm(df_map.loc[(df_map['class'] == i+1), i].values)))
ax.add_collection(pc)
pc = PatchCollection(df_map[df_map['class'] == 0]['patches'], match_original=True, alpha=0.2)
pc.set_facecolor('grey')
ax.add_collection(pc)
x, y = m(coords[0] + 0.02, coords[1] + 1.0)
details = plt.annotate(info, xy=(x, y), size=24, color='#555555')
# Draw a map scale
m.drawmapscale(
coords[0] + 0.2, coords[1] + 0.95,
coords[0], coords[1],
20., fontsize=8,
barstyle='fancy', labelstyle='simple',
fillcolor1='w', fillcolor2='#555555',
fontcolor='#555555', units='mi',
zorder=5)
legend_patches = []
for i in range(6):
legend_patches.append(mpatches.Patch(color=colors[i],
label=CrimePatterns[i]))
plt.legend(handles=legend_patches, loc='lower right')
x1, y1 = m(coords[0] + 0.05, 33.62)
colorinfo = 'Color represent each cluster of community;\nBrightness represent the severities of crime in each community'
plt.annotate(colorinfo, xy=(x1, y1), size=16, color='#555555')
plt.tight_layout()
fig.set_size_inches(12, 13)
plt.savefig(title, dpi=300, alpha=True)
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'):
# https://matplotlib.org/examples/color/colormaps_reference.html
patches = []
for pos in var:
if shape == 'c':
patches.append(mpatches.Circle(pos, r))
elif shape == 'r':
patches.append(mpatches.RegularPolygon(pos, 4, r))
elif shape == 's':
patches.append(mpatches.RegularPolygon(pos, 6, r))
colors = np.linspace(start_color, .9, len(patches))
collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.)
collection.set_array(np.array(colors))
collection.set_clim(0, 1)
return collection
def conductor_collection(self):
# TODO: Once dielectrics register with solver add in loop to append them to dielectric array
if not self.plot_axes:
self.create_axes()
if len(self.voltages) > 0:
self.set_collection_colors(self.conductor_patch_colors, self.voltages, self.map)
# Assign patches for conductors to the plot axes
self.conductor_patches = PatchCollection(self.conductors)
self.conductor_patches.set_color(self.conductor_patch_colors)
self.plot_axes.add_collection(self.conductor_patches)
if len(self.permittivities) > 0:
self.set_collection_colors(self.dielectric_patch_colors, self.permittivities, plt.cm.viridis)
# Assign patches for dielectrics to the plot axes
self.dielectric_patches = PatchCollection(self.dielectrics)
self.dielectric_patches.set_color(self.dielectric_patch_colors)
self.dielectric_patches.set_hatch('//')
self.plot_axes.add_collection(self.dielectric_patches)
# Setup the legend and set data for legend axes
self.create_legend()
if len(self.voltages) > 0:
cond_legend = self.legend_axes.legend(handles=self.conductor_legend_handles,
bbox_to_anchor=self.legend_anchor,
borderaxespad=0.,
fontsize=self.legend_fontsize,
title='Voltage (V)')
self.legend_axes.add_artist(cond_legend)
if len(self.permittivities) > 0:
diel_legend = self.legend_axes.legend(handles=self.dielectric_legend_handles,
bbox_to_anchor=(self.legend_anchor[0] + 0.05, self.legend_anchor[1] - 0.2),
borderaxespad=0.,
fontsize=self.legend_fontsize,
title=' Relative\nPermittivity')
self.legend_axes.add_artist(diel_legend)
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 draw_small_clustering(clustering, axs=None, params=None):
""" given a mem_dict and an axis object, draw the clustering """
# processing the parameters.
if params is None:
params = {}
w_padding = params.get('w_padding', 0.05)
fontsize = params.get('fontsize', 10)
cmap = params.get('cmap', 'jet')
alpha = params.get('alpha', 0.3)
xlim = params.get('xlim', (-0.07, 1))
ylim = params.get('xlim', (-0.1, 0.1))
boxstyle = params.get('boxstyle', mpatches.BoxStyle("Round", pad=0.02))
xmin = 0.0 + w_padding
xmax = 1.0 - w_padding
xspacing = (xmax - xmin)/float(clustering.number_of_elements())
# create ax object if there is none provided.
if axs is None:
_, axs = plt.subplots(1, 1, figsize=(10, 1))
axs = blank_axis(axs)
axs.set_xlim(*xlim)
axs.set_ylim(*ylim)
patches = []
for _, elms in sorted(iteritems(clustering.clu_dict),
key=lambda x: int(x[0].strip('.'))):
cstart = xmin + min(elms) * xspacing #- 0.95 * w_padding
clength = (max(elms) - min(elms)) * xspacing
fancybox = mpatches.FancyBboxPatch([cstart, -0.05],
clength,
0.1,
boxstyle=boxstyle)
patches.append(fancybox)
colors = np.linspace(0, 1, len(patches))
collection = PatchCollection(patches, cmap=cmap, alpha=alpha)
collection.set_array(np.array(colors))
axs.add_collection(collection)
for elm_idx, elm in enumerate(sorted(clustering.elements)):
axs.text(xmin + elm_idx * xspacing,
0.0, str(elm), ha='center', va='center', fontsize=fontsize)
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
项目源码
文件源码
阅读 21
收藏 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']
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']
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'])