本文整理汇总了Python中shapely.geometry.Polygon.buffer方法的典型用法代码示例。如果您正苦于以下问题:Python Polygon.buffer方法的具体用法?Python Polygon.buffer怎么用?Python Polygon.buffer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shapely.geometry.Polygon
的用法示例。
在下文中一共展示了Polygon.buffer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _center_pts
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def _center_pts(pts):
'''Fancy label position generator, using erosion to get label coordinate'''
min = pts.min(0)
pts -= min
max = pts.max(0)
pts /= max
#probably don't need more than 20 points, reduce detail of the polys
if len(pts) > 20:
pts = pts[::len(pts)//20]
try:
poly = Polygon([tuple(p) for p in pts])
for i in np.linspace(0,1,100):
if poly.buffer(-i).is_empty:
return list(poly.buffer(-last_i).centroid.coords)[0] * max + min
last_i = i
print("unable to find zero centroid...")
return list(poly.buffer(-100).centroid.coords)[0] * max + min
except:
# This may not be worth being so verbose about... I think this is only for label positions.
import warnings
warnings.warn("Shapely error - computing mean of points instead of geometric center")
return np.nanmean(pts, 0)
示例2: gerber2shapely
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def gerber2shapely(self):
for gbr in self.gerber.figures:
if(gbr.active < 1):
continue
if(gbr.type > 4):
continue
if(gbr.type == 0): #Path or Polygon
if gbr.fig_type == 0: #Circle
cap_s=1
elif gbr.fig_type == 1: #Rectangle
cap_s=3
else:
cap_s=1
if gbr.polygon:
tmp_polygon = Polygon(gbr.points)
self.tmp_figs.add(self.Figs(tmp_polygon.buffer(float(gbr.w)/2.0+self.tool_r, cap_style=cap_s)))
raw_polygon = tmp_polygon.buffer(float(gbr.w)/2.0, cap_style=cap_s)
self.raw_figs.add(self.Figs(raw_polygon))
if raw_polygon.interiors:
for interior in raw_polygon.interiors:
self.raw_figs.add(self.Figs(Polygon(interior)))
else:
if self.zone_segment:
if LineString(gbr.points).is_simple:
self.lines.append(self.Line(gbr.points,fig_type = cap_s,r = float(gbr.w)/2.0+self.tool_r))
else:
self.tmp_figs.add(self.Figs(Polygon(gbr.points).buffer(float(gbr.w)/2.0+self.tool_r, cap_style=cap_s)))
else:
self.tmp_figs.add(self.Figs(LineString(gbr.points).buffer(float(gbr.w)/2.0+self.tool_r, cap_style=cap_s)))
#
self.raw_figs.add(self.Figs(LineString(gbr.points).buffer(float(gbr.w)/2.0, cap_style=cap_s)))
elif(gbr.type == 1):
#Circle
self.tmp_figs.add(self.Figs(Point(gbr.cx,gbr.cy).buffer(float(gbr.r)+self.tool_r,resolution=self.circle_ang)))
self.raw_figs.add(self.Figs(Point(gbr.cx,gbr.cy).buffer(float(gbr.r),resolution=self.circle_ang)))
elif(gbr.type == 2):
#Rectangle
points = [(gbr.x1-self.tool_r,gbr.y1-self.tool_r),(gbr.x1-self.tool_r,gbr.y2+self.tool_r),
(gbr.x2+self.tool_r,gbr.y2+self.tool_r),(gbr.x2+self.tool_r,gbr.y1-self.tool_r),
(gbr.x1-self.tool_r,gbr.y1-self.tool_r)]
self.tmp_figs.add(self.Figs(Polygon(points)))
points = [(gbr.x1,gbr.y1),(gbr.x1,gbr.y2),(gbr.x2,gbr.y2),(gbr.x2,gbr.y1),(gbr.x1,gbr.y1)]
self.raw_figs.add(self.Figs(Polygon(points)))
elif(gbr.type == 3):
#Oval
if gbr.h <= gbr.w:
tmp_r = gbr.h/2.0+self.tool_r
shift_x = (gbr.w-gbr.h)/2.0
self.tmp_figs.add(self.Figs(LineString([(gbr.cx-shift_x,gbr.cy),(gbr.cx+shift_x,gbr.cy)]).buffer(tmp_r)))
self.raw_figs.add(self.Figs(LineString([(gbr.cx-shift_x,gbr.cy),(gbr.cx+shift_x,gbr.cy)]).buffer(gbr.h/2.0)))
else:
tmp_r = gbr.w/2.0+self.tool_r
shift_y = (gbr.h-gbr.w)/2.0
self.tmp_figs.add(self.Figs(LineString([(gbr.cx,gbr.cy-shift_y),(gbr.cx,gbr.cy+shift_y)]).buffer(tmp_r)))
self.raw_figs.add(self.Figs(LineString([(gbr.cx,gbr.cy-shift_y),(gbr.cx,gbr.cy+shift_y)]).buffer(gbr.w/2.0)))
elif(gbr.type == 4):
#Polygon
self.tmp_figs.add(self.Figs(Point(gbr.cx,gbr.cy).buffer(float(gbr.r)+self.tool_r,resolution=gbr.sides)))
self.raw_figs.add(self.Figs(Point(gbr.cx,gbr.cy).buffer(float(gbr.r),resolution=gbr.sides)))
示例3: _center_pts
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def _center_pts(pts):
'''Fancy label position generator, using erosion to get label coordinate'''
min = pts.min(0)
pts -= min
max = pts.max(0)
pts /= max
poly = Polygon([tuple(p) for p in pts])
for i in np.linspace(0,1,100):
if poly.buffer(-i).is_empty:
return list(poly.buffer(-last_i).centroid.coords)[0] * max + min
last_i = i
print("unable to find zero centroid...")
return list(poly.buffer(-100).centroid.coords)[0] * max + min
示例4: test_polygon_topojson
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def test_polygon_topojson(self):
'''
Create a polygon to cover the world and make sure it is "similar" (clip on)
'''
self.defineGeometry('POLYGON')
geom = Polygon( [(-180, -85.0511),
( 180, -85.0511),
( 180, 85.0511),
(-180, 85.0511),
(-180, -85.0511)])
self.insertTestRow(geom.wkt)
tile_mimetype, tile_content = utils.request(self.config_file_content, "vectile_test", "topojson", 0, 0, 0)
self.assertTrue(tile_mimetype.endswith('/json'))
topojson_result = json.loads(tile_content)
topojson_xform = get_topo_transform(topojson_result)
parts = [topojson_result['arcs'][arc[0]] for arc in topojson_result['objects']['vectile']['geometries'][0]['arcs']]
parts = [map(topojson_xform, topojson_dediff(part)) for part in parts]
result_geom = Polygon(*parts)
expected_geom = Polygon( [(-180, -85.0511), (180, -85.0511), (180, 85.0511), (-180, 85.0511), (-180, -85.0511)])
# What is going on here is a bit unorthodox, but let me explain. The clipping
# code inside TileStache relies on GEOS Intersection alongside some TileStache code
# that creates a clipping geometry based on the tile perimeter. The tile perimeter
# is made out of 17 (x,y) coordinates and not a box. Hence, the GEOS::Intersection
# os that perimeter with the geometry of the vector we get back from the data provider
# can end with extra vertices. Although it is the right shape, we cannot do a straight
# comparisson because the expected geometry and the returned geometry *may* have extra
# vertices. Simplify() will not do much because the distance of the vertices can clearly
# be bigger than the tolerance.
#
# To add to this, because of double precision, the vertices may not be exact.
# An optional way to find out if two shapes are close enough, is to buffer the two features
# by just a little bit and then subtract each other like so:
#
# geometry1.difference(geometry2) == empty set?
# geometry2.difference(geometry1) == empty set?
#
# If both geometries are empty, then they are similar. Hence what you see below
# Close enough?
self.assertTrue(result_geom.difference(expected_geom.buffer(1)).is_empty)
self.assertTrue(expected_geom.difference(result_geom.buffer(1)).is_empty)
示例5: PaintConnectTest3
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
class PaintConnectTest3(PaintTestCase):
"""
Tests with linerings among elements.
"""
def setUp(self):
self.boundary = Polygon([[0, 0], [0, 5], [5, 5], [5, 0]])
print "TEST w/ LinearRings"
def test_jump2(self):
print "Test: WALK Expected"
paths = [
LineString([[0.5, 2], [2, 4.5]]),
LineString([[2, 0.5], [4.5, 2]]),
self.boundary.buffer(-0.5).exterior
]
for p in paths:
print p
tooldia = 1.0
print "--"
result = Geometry.paint_connect(mkstorage(deepcopy(paths)), self.boundary, tooldia)
result = list(result.get_objects())
for r in result:
print r
self.assertEqual(len(result), 1)
示例6: intersectNodes
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def intersectNodes(path, srs, projName, projSRS, isGridProject, gridResolution):
j = []
isGridLine = False
sf = shapefile.Reader(path)
nodes = list(getShapelyNodes(projName))
for shape in sf.shapes():
shType = shape.shapeType
# http://en.wikipedia.org/wiki/Shapefile#Shapefile_shape_format_.28.shp.29
if shType == 5: # Polygon
sh = Polygon(shape.points)
elif shType == 3: # Line
if isGridProject:
sh = LineString(shape.points)
isGridLine = True
else:
pass
else:
consoleAppend('Unknown shape type %s. Continue without access' %shType)
if srs != projSRS:
sh = shapelyReproject(sh, srs, projSRS)
if isGridLine:
sh = sh.buffer(gridResolution)
for node in nodes:
if sh.contains(node[1]): # node.geom
j.append(node[0]) # node.node_id
return j if j else None
示例7: fix_geometry
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def fix_geometry(geometry):
"""Attempts to fix an invalid geometry (from https://goo.gl/nfivMh)"""
try:
return geometry.buffer(0)
except ValueError:
pass
polygons = geom_as_list(geometry)
fixed_polygons = list()
for i, polygon in enumerate(polygons):
if not linear_ring_is_valid(polygon.exterior):
continue
interiors = []
for ring in polygon.interiors:
if linear_ring_is_valid(ring):
interiors.append(ring)
fixed_polygon = Polygon(polygon.exterior, interiors)
try:
fixed_polygon = fixed_polygon.buffer(0)
except ValueError:
continue
fixed_polygons.extend(geom_as_list(fixed_polygon))
if len(fixed_polygons) > 0:
return MultiPolygon(fixed_polygons)
else:
return None
示例8: Perimeter
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
class Perimeter(object):
def __init__(self, perimeter_points, buffer_size=10):
self.outer_polygon = Polygon(perimeter_points)
self.buffer_size = buffer_size
self.inner_polygon = self.outer_polygon.buffer(-1 * buffer_size)
def get_bounds(self):
return self.outer_polygon.bounds
def get_repulsive_vel(self, xy):
point = Point(xy)
containment_field = self.inner_polygon
if containment_field.contains(point):
return NULL_VECTOR
vector_from_center = np.asarray([point.x - containment_field.centroid.x, point.y - containment_field.centroid.y])
vector_to_center = -1 * vector_from_center
line_to_center = LineString(((containment_field.centroid.x, containment_field.centroid.y), (point.x, point.y)))
line_center_field = containment_field.intersection(line_to_center)
distance_to_field = line_to_center.length - line_center_field.length
repulsion_scale = distance_to_field / self.buffer_size
return _normalized(vector_to_center) * repulsion_scale
def get_perimeter_coordinates(self):
return self.outer_polygon.exterior.coords
def get_field_coordinates(self):
return self.inner_polygon.exterior.coords
示例9: test_attribute_chains
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def test_attribute_chains(self):
# Attribute Chaining
# See also ticket #151.
p = Polygon(((0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)))
self.assertEqual(
list(p.boundary.coords),
[(0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0), (0.0, 0.0)])
ec = list(Point(0.0, 0.0).buffer(1.0, 1).exterior.coords)
self.assertIsInstance(ec, list) # TODO: this is a poor test
# Test chained access to interiors
p = Polygon(
((0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)),
[((-0.25, 0.25), (-0.25, 0.75), (-0.75, 0.75), (-0.75, 0.25))]
)
self.assertEqual(p.area, 0.75)
"""Not so much testing the exact values here, which are the
responsibility of the geometry engine (GEOS), but that we can get
chain functions and properties using anonymous references.
"""
self.assertEqual(
list(p.interiors[0].coords),
[(-0.25, 0.25), (-0.25, 0.75), (-0.75, 0.75), (-0.75, 0.25),
(-0.25, 0.25)])
xy = list(p.interiors[0].buffer(1).exterior.coords)[0]
self.assertEqual(len(xy), 2)
# Test multiple operators, boundary of a buffer
ec = list(p.buffer(1).boundary.coords)
self.assertIsInstance(ec, list) # TODO: this is a poor test
示例10: build_polygon
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def build_polygon(refs):
coords = []
for ref in refs:
coord = coordsDB.get(str(ref))
if coord:
coord = map(float, coord.split(','))
coords.append(coord)
else:
# for some reason coordinates are missing
# this is usually because an extract cuts coordinates out
return False
if len(coords) > 2:
# 3 point minimum for polygon
# avoids common osm problems
polygon = Polygon(coords)
if polygon.is_valid:
return polygon
else:
# 0.0 buffer cleans invalid polygons
# they're invalid for many reasons, people prone problems
return polygon.buffer(0.0)
else:
return False
示例11: polybuff
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def polybuff(tum,minus=False):
if minus==True:
offs=-offset
else:
offs=offset
tum=Polygon(tum)
tum=tum.buffer(offs)
return np.array(tum.exterior.coords)
示例12: shape_to_polygons
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def shape_to_polygons(shape):
def inside(pt):
return hypot(*pt) <= R
def adjust(pt):
x, y = pt
a = atan2(y, x)
x = cos(a) * R
y = sin(a) * R
return (x, y)
result = []
parts = list(shape.parts) + [len(shape.points)]
for i1, i2 in zip(parts, parts[1:]):
points = map(tuple, shape.points[i1:i2])
points = map(laea, points)
points = filter(None, points)
p = Polygon(points)
p = p.buffer(-0.01)
p = p.buffer(0.01)
p = p.simplify()
if p.is_empty:
continue
if isinstance(p, Polygon):
ps = [p]
else:
ps = p.geoms
for p in ps:
points = list(p.exterior.coords)
print points
for a, b in zip(points, points[1:]):
# if not a[-1] and not b[-1]:
# continue
a = a[:2]
b = b[:2]
in1 = inside(a)
in2 = inside(b)
if not in1 and not in2:
continue
if in1 and not in2:
b = adjust(b)
if in2 and not in1:
a = adjust(a)
result.append(LineString([a, b]))
return result
示例13: _center_pts
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def _center_pts(pts):
'''Fancy label position generator, using erosion to get label coordinate'''
min = pts.min(0)
pts -= min
max = pts.max(0)
pts /= max
#probably don't need more than 20 points, reduce detail of the polys
if len(pts) > 20:
pts = pts[::len(pts)/20]
poly = Polygon([tuple(p) for p in pts])
for i in np.linspace(0,1,100):
if poly.buffer(-i).is_empty:
return list(poly.buffer(-last_i).centroid.coords)[0] * max + min
last_i = i
print("unable to find zero centroid...")
return list(poly.buffer(-100).centroid.coords)[0] * max + min
示例14: _crosses_antimeridian
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def _crosses_antimeridian(region: Polygon) -> bool:
"""
Determine if the given region crosses the Antimeridian line, by converting
the given Polygon from -180;180 to 0;360 and checking if the antimeridian
line crosses it.
This only works with Polygons without holes
:param region: Polygon to test
"""
# Convert region to only have positive longitudes.
# This way we can perform a simple antimeridian check
old_exterior = region.exterior.coords
new_exterior = []
for point in old_exterior:
lon, lat = point[0], point[1]
if -180. <= lon < 0.:
lon += 360.
new_exterior.append((lon, lat))
converted_region = Polygon(new_exterior)
# There's a problem at this point. Any polygon crossed by the zero-th
# meridian can in principle convert to an inverted polygon that is crossed
# by the antimeridian.
if not converted_region.is_valid:
# The polygon 'became' invalid upon conversion => probably the original
# polygon is what we want
# noinspection PyBroadException
try:
# First try cleaning up geometry that is invalid
converted_region = converted_region.buffer(0)
except BaseException:
pass
if not converted_region.is_valid:
return False
test_line = LineString([(180, -90), (180, 90)])
if test_line.crosses(converted_region):
# The converted polygon seems to be valid and crossed by the
# antimeridian. At this point there's no 'perfect' way how to tell if
# we wanted the converted polygon or the original one.
# A simple heuristic is to check for size. The smaller one is quite
# likely the desired one
if converted_region.area < region.area:
return True
else:
return False
else:
return False
示例15: cluster_to_venues
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import buffer [as 别名]
def cluster_to_venues(indices, vloc, kdtree, n_steps=5):
# Given a cluster (ie a set of venues indices), it should return
# neighborhoods (ie compact/complete sets of venues indices) that will be
# evaluated by EMD.
# Given how DBSCAN works, most of these clusters look rather convex, so
# convex hull could be a good option. Otherwise, I could use CGAL binding
# to get alpha shapes. Then I can consider bounding box (called envelope
# by Shapely) or circle. Finally, some dilation and erosion of the
# previous shapes.
# I can also add or remove individual points (but it's unclear which one,
# see notebook) while maintaining more or less neighborhood property.
# Get initial polygon
points = vloc[indices, :]
try:
hull = points[ConvexHull(points).vertices, :]
except (KeyboardInterrupt, SystemExit):
raise
except:
print(indices)
return []
poly = Polygon(hull)
center = np.array(poly.centroid.coords)
# Query neighboring venues
radius = np.max(cdist(np.array(poly.exterior.coords), center))
cd_idx = kdtree.query_ball_point(center, 2.0*radius)[0]
# Build increasing regions
inc = 1.0*radius/n_steps
extensions = [poly]
extensions += [poly.buffer(i*inc,
resolution=2).convex_hull.simplify(30, False)
for i in range(1, n_steps+1)]
# Get venues inside them
remaining = set(cd_idx)
inside = set([])
res_cluster = []
for region in extensions:
if region.exterior is None:
continue
cpoly = np.array(region.exterior.coords)
inside_this = set([idx for idx in remaining
if point_inside_poly(cpoly, vloc[idx, :])])
remaining.difference_update(inside_this)
inside.update(inside_this)
res_cluster.append(list(inside))
return res_cluster