本文整理汇总了Python中matplotlib.path.Path类的典型用法代码示例。如果您正苦于以下问题:Python Path类的具体用法?Python Path怎么用?Python Path使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Path类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: selectArea
def selectArea(self, ptlist, latlon=False, reduced=None):
"""Select an area of the grid.
Parameters
----------
ptlist : list
latlon : bool
reduced : int
The amount by which the index array should be short (i.e., 1 for
basic difference, 2 for center difference).
"""
ptlist = np.asarray(ptlist)
if latlon:
ptlist[:,0], ptlist[:,1] = self.basemap(ptlist[:,0], ptlist[:,1])
# create the polygon
path = Path(ptlist)
if reduced is not None:
X, Y = np.meshgrid(self.x[:-reduced], self.y[:-reduced])
areaind = path.contains_points(zip(X.flatten(), Y.flatten()))
areaind = areaind.reshape((self.shape[0]-reduced,
self.shape[1]-reduced))
else:
X, Y = np.meshgrid(self.x, self.y)
areaind = path.contains_points(zip(X.flatten(), Y.flatten()))
areaind = areaind.reshape(self.shape)
# return array indices
return areaind
示例2: reverse_geocode
def reverse_geocode(tweet):
# print index
# latlong = json.load(tweets)[index]['coordinates']
latlong = tweet["coordinates"]
if latlong == [0.0, 0.0]:
return False
# latlong.reverse()
with open('world-countries.json.txt', 'r') as countries_json:
found_country = None
countries = json.load(countries_json)['features']
for country in countries:
country_name = country['properties']['name']
if country['geometry']['type'] == 'Polygon':
country_vertices = country['geometry']['coordinates'][0]
country_path = Path(country_vertices)
if country_path.contains_point(latlong):
found_country = country_name
break
if country['geometry']['type'] == 'MultiPolygon':
country_polygons = country['geometry']['coordinates']
for polygon in country_polygons:
country_vertices = polygon[0]
country_path = Path(country_vertices)
if country_path.contains_point(latlong):
found_country = country_name
break
if not found_country:
found_country = False
return found_country
# with open('Ferguson_tweets.txt', 'r') as tweets:
# print reverse_geocode(tweets, 0)
示例3: processPolygon
def processPolygon(polygon, rows, columns, mode):
"""
Finds the points within a particular polygon
"""
length = len(polygon)
polygon.append((0.0, 0.0))
codes = [Path.MOVETO]
for index in range(length - 1):
codes.append(Path.LINETO)
codes.append(Path.CLOSEPOLY)
path = Path(polygon, codes)
points = []
if mode == 'V':
for index in range(rows):
row = [(x, index) for x in range(columns)]
check = path.contains_points(row)
temp_points = ([row[i] for i, j in enumerate(check) if j == True and not contains(row[i], polygon)])
if (len(temp_points) > 0):
points.append(temp_points)
else:
for index in range(columns):
col = [(index, x) for x in range(rows)]
check = path.contains_points(col)
temp_points = ([col[i] for i, j in enumerate(check) if j == True and not contains(col[i], polygon)])
if (len(temp_points) > 0):
points.append(temp_points)
return points
示例4: pca_var
def pca_var(sub_dims):
data = np.array([df[d] for d in sub_dims]).T
try: pca = PCA(data, standardize=True)
except: return 0,1,0,1,None,None,None,sub_dims
classed_points = zip(classes, pca.Y)
pos = [(it[0], it[1]) for c, it in classed_points if c]
neg = [(it[0], it[1]) for c, it in classed_points if not c]
P_hull = [pos[i] for i in ConvexHull(pos).vertices]; P_hull.append(P_hull[0])
N_hull = [neg[i] for i in ConvexHull(neg).vertices]; N_hull.append(N_hull[0])
P_hull = np.array(P_hull)
N_hull = np.array(N_hull)
P_path = Path(P_hull)
N_path = Path(N_hull)
N_sep = 0
for it in neg:
if not P_path.contains_point(it):
N_sep += 1
P_sep = 0
for it in pos:
if not N_path.contains_point(it):
P_sep += 1
return N_sep, float(len(neg)), P_sep, float(len(pos)), P_hull, N_hull, pca, sub_dims
示例5: transform_path_non_affine
def transform_path_non_affine(self, path):
# Adaptive interpolation:
# we keep adding control points, till all control points
# have an error of less than 0.01 (about 1%)
# or if the number of control points is > 80.
ra0 = self.ra0
path = path.cleaned(curves=False)
v = path.vertices
diff = v[:, 0] - v[0, 0]
v00 = v[0][0] - ra0
while v00 > 180: v00 -= 360
while v00 < -180: v00 += 360
v00 += ra0
v[:, 0] = v00 + diff
nonstop = path.codes > 0
path = Path(v[nonstop], path.codes[nonstop])
isteps = path._interpolation_steps * 2
while True:
ipath = path.interpolated(isteps)
tiv = self.transform(ipath.vertices)
itv = Path(self.transform(path.vertices)).interpolated(isteps).vertices
if np.mean(np.abs(tiv - itv)) < 0.01:
break
if isteps > 20:
break
isteps = isteps * 2
return Path(tiv, ipath.codes)
示例6: contained_in
def contained_in(lat, lng, bound_coords):
"""
Returns true if (lat, lng) is contained within the polygon formed by the
points in bound_coords.
"""
bound_path = Path(np.array(bound_coords))
return bound_path.contains_point((lat, lng))
示例7: test_path_no_doubled_point_in_to_polygon
def test_path_no_doubled_point_in_to_polygon():
hand = np.array(
[[1.64516129, 1.16145833],
[1.64516129, 1.59375],
[1.35080645, 1.921875],
[1.375, 2.18229167],
[1.68548387, 1.9375],
[1.60887097, 2.55208333],
[1.68548387, 2.69791667],
[1.76209677, 2.56770833],
[1.83064516, 1.97395833],
[1.89516129, 2.75],
[1.9516129, 2.84895833],
[2.01209677, 2.76041667],
[1.99193548, 1.99479167],
[2.11290323, 2.63020833],
[2.2016129, 2.734375],
[2.25403226, 2.60416667],
[2.14919355, 1.953125],
[2.30645161, 2.36979167],
[2.39112903, 2.36979167],
[2.41532258, 2.1875],
[2.1733871, 1.703125],
[2.07782258, 1.16666667]])
(r0, c0, r1, c1) = (1.0, 1.5, 2.1, 2.5)
poly = Path(np.vstack((hand[:, 1], hand[:, 0])).T, closed=True)
clip_rect = transforms.Bbox([[r0, c0], [r1, c1]])
poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0]
assert np.all(poly_clipped[-2] != poly_clipped[-1])
assert np.all(poly_clipped[-1] == poly_clipped[0])
示例8: _gating
def _gating(self,DF_array_data,x_ax,y_ax,coords):
#np.ones(DF_array_data.shape[0],dtype=bool)
gate=Path(coords,closed=True)
projection=np.array(DF_array_data[[x_ax,y_ax]])
index=gate.contains_points(projection)
return index
示例9: paths_in_shape
def paths_in_shape(paths):
shape = shape_(shape_path)
minx, miny, maxx, maxy = shape.bounds
#print minx; print miny; print maxx; print maxy
#bounding_box = geometry.box(minx, miny, maxx, maxy)
#generate random points within bounding box!
sf = shapefile.Reader(shape_path)
shape = sf.shapes()[0]
#find polygon nodes lat lons
verticies = shape.points
#convert to a matplotlib path class!
polygon = Path(verticies)
points_in_shape = polygon.contains_points(paths)
points_in_shape = paths[points_in_shape == True]
return points_in_shape
示例10: __init__
def __init__(self, shape, scale=1):
"""
Initalize a Warper with a reference shape with coordinates in the
numpy array 'shape'
"""
xy = shape.copy() * scale
self.scale = scale
xy = self.shape_to_xy(xy)
xy = xy - np.min(xy,axis=0)
dt = scipy.spatial.Delaunay(xy)
# Define a grid
cols = int(np.ceil(np.max(xy[:,0])))
rows = int(np.ceil(np.max(xy[:,1])))
xx, yy = np.meshgrid(range(cols),range(rows))
xy_grid = np.vstack((xx.flatten(),yy.flatten())).T
# Define a mask
mask = Path(xy).contains_points(xy_grid)
self.mask = mask.reshape(xx.shape)
xy_grid = xy_grid[mask==True,:] # Remove pts not inside mask
# Calculate barycentric coordinates for all points inside mask
simplex_ids = dt.find_simplex(xy_grid)
bary_coords = points_to_bary(dt,simplex_ids,xy_grid)
self.tri = dt.simplices
self.warp_template = np.hstack((simplex_ids[:,np.newaxis],bary_coords))
示例11: _endGate
def _endGate(self, event):
#draw gate rectangle
start_x = self.start_x if self.start_x < event.xdata else event.xdata
start_y = self.start_y if self.start_y < event.ydata else event.ydata
width = np.absolute(event.xdata-self.start_x)
height = np.absolute(event.ydata-self.start_y)
rect = Rectangle((start_x, start_y), width, height,
fill=False, ec='black', alpha=1, lw=2)
self.ax.add_patch(rect)
self.canvas.draw()
#disable mouse events
self.canvas.mpl_disconnect(self.buttonPress)
self.canvas.mpl_disconnect(self.buttonRelease)
self.canvas.get_tk_widget().config(cursor='arrow')
#save cell gate
gate = Path([[start_x, start_y],
[start_x + width, start_y],
[start_x + width, start_y + height],
[start_x, start_y + height],
[start_x, start_y]])
gated_cells = self.scdata.tsne.index[gate.contains_points(self.scdata.tsne)]
self.gates[self.gateName.get()] = gated_cells
#replot tSNE w gate colored
self.fig.clf()
plt.scatter(self.scdata.tsne['x'], self.scdata.tsne['y'], s=10, edgecolors='none', color='lightgrey')
plt.scatter(self.scdata.tsne.ix[gated_cells, 'x'], self.scdata.tsne.ix[gated_cells, 'y'], s=10, edgecolors='none')
self.canvas.draw()
self.setGateButton.config(state='disabled')
self.visMenu.entryconfig(6, state='disabled')
示例12: distribute_pixels
def distribute_pixels(self, edges, length, width):
corners = self.get_corners()
reg_path = Path(corners)
# Get region boundaries.
bounds = reg_path.get_extents().get_points()
[[x_min_bound, y_min_bound], [x_max_bound, y_max_bound]] = bounds
# For cases when the boundary pixels are not integers:
x_min_bound = floor(x_min_bound)
y_min_bound = floor(y_min_bound)
x_max_bound = ceil(x_max_bound)
y_max_bound = ceil(y_max_bound)
pixels_in_bins = []
for x in range(max(0, x_min_bound), min(x_max_bound+1, width)):
for y in range(max(0, y_min_bound), min(y_max_bound+1, length)):
if reg_path.contains_point((x, y)):
x_nonrotated, y_nonrotated = rotate_point(self.x0, self.y0,
x - self.x0,
y - self.y0,
-self.angle)
dist_from_box_bottom = self.height/2. - \
(self.y0 - y_nonrotated)
for i, edge in enumerate(edges[1:]):
if edge > dist_from_box_bottom:
pixels_in_bins.append((y, x, i))
break
return pixels_in_bins
示例13: test_point_in_path_nan
def test_point_in_path_nan():
box = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
p = Path(box)
test = np.array([[np.nan, 0.5]])
contains = p.contains_points(test)
assert len(contains) == 1
assert not contains[0]
示例14: onselect
def onselect(self, verts):
path = Path(verts)
self.ind = np.nonzero([path.contains_point(xy) for xy in self.xys])[0]
self.fc[:, -1] = self.alpha_other
self.fc[self.ind, -1] = 1
self.collection.set_facecolors(self.fc)
self.canvas.draw_idle()
示例15: get_mask_img
def get_mask_img(transform, target_bin, camera_model):
"""
:param point: point that is going to be transformed
:type point: PointStamped
:param transform: camera_frame -> bbox_frame
:type transform: Transform
"""
# check frame_id of a point and transform just in case
assert camera_model.tf_frame == transform.header.frame_id
assert target_bin.bbox.header.frame_id == transform.child_frame_id
transformed_list = [
do_transform_point(corner, transform)
for corner in target_bin.corners]
projected_points = project_points(transformed_list, camera_model)
# generate an polygon that covers the region
path = Path(projected_points)
x, y = np.meshgrid(
np.arange(camera_model.width),
np.arange(camera_model.height))
x, y = x.flatten(), y.flatten()
points = np.vstack((x, y)).T
mask_img = path.contains_points(
points).reshape(
camera_model.height, camera_model.width
).astype('bool')
return mask_img