本文整理汇总了Python中shapely.geometry.LineString.parallel_offset方法的典型用法代码示例。如果您正苦于以下问题:Python LineString.parallel_offset方法的具体用法?Python LineString.parallel_offset怎么用?Python LineString.parallel_offset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shapely.geometry.LineString
的用法示例。
在下文中一共展示了LineString.parallel_offset方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: offset
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import parallel_offset [as 别名]
def offset(self, distance):
self.points.append(self.points[0])
line = LineString(self.getSequence())
offset = line.parallel_offset(distance, 'right', join_style=1)
# return list(offset.coords)
self.setSequence(list(offset.coords))
return self
示例2: _cont_to_polys
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import parallel_offset [as 别名]
def _cont_to_polys(self, cont_lats, cont_lons):
polys = []
start_idx = 0
splits = []
while True:
try:
split_idx = cont_lats[start_idx:].index(99.99)
splits.append(start_idx + split_idx)
start_idx += split_idx + 1
except ValueError:
break
splits = [ -1 ] + splits + [ len(cont_lats) + 1 ]
poly_lats = [ cont_lats[splits[i] + 1:splits[i + 1]] for i in xrange(len(splits) - 1) ]
poly_lons = [ cont_lons[splits[i] + 1:splits[i + 1]] for i in xrange(len(splits) - 1) ]
# Intersect with the US boundary shape file.
for plat, plon in zip(poly_lats, poly_lons):
cont = LineString(zip(plon, plat))
if plat[0] != plat[-1] or plon[0] != plon[-1]:
# If the line is not a closed contour, then it intersects with the edge of the US. Extend
# the ends a little bit to make sure it's outside the edge.
dln = np.diff(plon)
dlt = np.diff(plat)
pre = [ (plon[0] - 0.5 * dln[0], plat[0] - 0.5 * dlt[0]) ]
post = [ (plon[-1] + 0.5 * dln[-1], plat[-1] + 0.5 * dlt[-1]) ]
cont.coords = pre + list(cont.coords) + post
# polygonize() will split the country into two parts: one inside the outlook and one outside.
# Construct test_ln that is to the right of (inside) the contour and keep only the polygon
# that contains the line
test_ln = cont.parallel_offset(0.05, 'right')
for poly in polygonize(self._conus.boundary.union(cont)):
if (poly.crosses(test_ln) or poly.contains(test_ln)) and self._conus.contains(poly.buffer(-0.01)):
polys.append(poly)
# Sort the polygons by area so we intersect the big ones with the big ones first.
polys.sort(key=lambda p: p.area, reverse=True)
# If any polygons intersect, replace them with their intersection.
intsct_polys = []
while len(polys) > 0:
intsct_poly = polys.pop(0)
pops = []
for idx, poly in enumerate(polys):
if intsct_poly.intersects(poly):
intsct_poly = intsct_poly.intersection(poly)
pops.append(idx)
for pop_idx in pops[::-1]:
polys.pop(pop_idx)
intsct_polys.append(intsct_poly)
return intsct_polys
示例3: _cont_to_polys
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import parallel_offset [as 别名]
def _cont_to_polys(self, cont_lats, cont_lons, cont_val):
"""
Take the lat/lon contours, split them into their different segments, and create polygons out of them. Contours
that stretch from border to border will end up covering large sections of the country. That's okay; we'll take
care of that later.
"""
polys = {}
start_idx = 0
splits = []
while True:
try:
split_idx = cont_lats[start_idx:].index(99.99)
splits.append(start_idx + split_idx)
start_idx += split_idx + 1
except ValueError:
break
splits = [ -1 ] + splits + [ len(cont_lats) + 1 ]
poly_lats = [ cont_lats[splits[i] + 1:splits[i + 1]] for i in xrange(len(splits) - 1) ]
poly_lons = [ cont_lons[splits[i] + 1:splits[i + 1]] for i in xrange(len(splits) - 1) ]
# Intersect with the US boundary shape file.
for plat, plon in zip(poly_lats, poly_lons):
cont = LineString(zip(plon, plat))
if plat[0] != plat[-1] or plon[0] != plon[-1]:
# If the line is not a closed contour, then it intersects with the edge of the US. Extend
# the ends a little bit to make sure it's outside the edge.
dln = np.diff(plon)
dlt = np.diff(plat)
pre = [ (plon[0] - 0.03 * dln[0], plat[0] - 0.03 * dlt[0]) ]
post = [ (plon[-1] + 0.03 * dln[-1], plat[-1] + 0.03 * dlt[-1]) ]
cont.coords = pre + list(cont.coords) + post
# polygonize() will split the country into two parts: one inside the outlook and one outside.
# Construct test_ln that is to the right of (inside) the contour and keep only the polygon
# that contains the line
test_ln = cont.parallel_offset(0.05, 'right')
polys[cont] = []
for poly in polygonize(self._conus.boundary.union(cont)):
if (poly.crosses(test_ln) or poly.contains(test_ln)) and self._conus.contains(poly.buffer(-0.01)):
polys[cont].append(poly)
return polys
示例4: test_parallel_offset_linestring
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import parallel_offset [as 别名]
def test_parallel_offset_linestring(self):
line1 = LineString([(0, 0), (10, 0)])
left = line1.parallel_offset(5, 'left')
self.assertEqual(left, LineString([(0, 5), (10, 5)]))
right = line1.parallel_offset(5, 'right')
self.assertEqual(right, LineString([(10, -5), (0, -5)]))
right = line1.parallel_offset(-5, 'left')
self.assertEqual(right, LineString([(10, -5), (0, -5)]))
left = line1.parallel_offset(-5, 'right')
self.assertEqual(left, LineString([(0, 5), (10, 5)]))
# by default, parallel_offset is right-handed
self.assertEqual(line1.parallel_offset(5), right)
line2 = LineString([(0, 0), (5, 0), (5, -5)])
self.assertEqual(line2.parallel_offset(2, 'left', resolution=1),
LineString([(0, 2), (5, 2), (7, 0), (7, -5)]))
self.assertEqual(line2.parallel_offset(2, 'left', join_style=2,
resolution=1),
LineString([(0, 2), (7, 2), (7, -5)]))
示例5: generate_intersections
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import parallel_offset [as 别名]
def generate_intersections(poly, width):
"Subdivide a filed into coverage lines."
starting_breakdown = poly.bounds[0:2]
line = LineString([starting_breakdown, (starting_breakdown[0],
starting_breakdown[1] +
poly.bounds[3] - poly.bounds[1])])
try:
bounded_line = poly.intersection(line)
except TopologicalError as e:
error("Problem looking for intersection.", exc_info=1)
return
lines = [bounded_line]
iterations = int(math.ceil((poly.bounds[2] - poly.bounds[0]) / width)) + 1
for x in range(1, iterations):
bounded_line = line.parallel_offset(x * width, 'right')
if poly.intersects(bounded_line):
try:
bounded_line = poly.intersection(bounded_line)
except TopologicalError as e:
error("Problem looking for intersection.", exc_info=1)
continue
lines.append(bounded_line)
return lines
示例6: LineString
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import parallel_offset [as 别名]
ax.set_aspect(1)
line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
line_bounds = line.bounds
ax_range = [int(line_bounds[0] - 1.0), int(line_bounds[2] + 1.0)]
ay_range = [int(line_bounds[1] - 1.0), int(line_bounds[3] + 1.0)]
fig = pyplot.figure(1, figsize=(SIZE[0], 2 * SIZE[1]), dpi=90)
# 1
ax = fig.add_subplot(221)
plot_line(ax, line)
x, y = list(line.coords)[0]
plot_coords(ax, x, y)
offset = line.parallel_offset(0.5, 'left', join_style=1)
plot_line(ax, offset, color=BLUE)
ax.set_title('a) left, round')
set_limits(ax, ax_range, ay_range)
#2
ax = fig.add_subplot(222)
plot_line(ax, line)
x, y = list(line.coords)[0]
plot_coords(ax, x, y)
offset = line.parallel_offset(0.5, 'left', join_style=2)
plot_line(ax, offset, color=BLUE)
示例7: draw_text_on_line
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import parallel_offset [as 别名]
def draw_text_on_line(
self,
coords,
text,
color=(0, 0, 0),
font_size=10,
font_family='Tahoma',
font_style=cairo.FONT_SLANT_NORMAL,
font_weight=cairo.FONT_WEIGHT_NORMAL,
text_halo_width=1,
text_halo_color=(1, 1, 1),
text_halo_line_cap=cairo.LINE_CAP_ROUND,
text_halo_line_join=cairo.LINE_JOIN_ROUND,
text_halo_line_dash=None,
text_transform=None,
):
'''
Draws text on a line. Tries to find a position with the least change
in gradient and which is closest to the middle of the line.
:param coords: iterable containing all coordinates as ``(lon, lat)``
:param text: text to be drawn
:param color: ``(r, g, b[, a])``
:param font_size: font-size in unit (pixel/point)
:param font_family: font name
:param font_style: ``cairo.FONT_SLANT_NORMAL``,
``cairo.FONT_SLANT_ITALIC`` or ``cairo.FONT_SLANT_OBLIQUE``
:param font_weight: ``cairo.FONT_WEIGHT_NORMAL`` or
``cairo.FONT_WEIGHT_BOLD``
:param text_halo_width: border-width in unit (pixel/point)
:param text_halo_color: ``(r, g, b[, a])``
:param text_halo_line_cap: one of :const:`cairo.LINE_CAP_*`
:param text_halo_line_join: one of :const:`cairo.LINE_JOIN_*`
:param text_halo_line_dash: list/tuple used by
:meth:`cairo.Context.set_dash`
:param text_transform: one of ``'lowercase'``, ``'uppercase'`` or
``'capitalize'``
'''
text = text.strip()
if not text:
return
coords = map(lambda c: self.transform_coords(*c), coords)
self.context.select_font_face(font_family, font_style, font_weight)
self.context.set_font_size(font_size)
text = utils.text_transform(text, text_transform)
width, height = self.context.text_extents(text)[2:4]
font_ascent, font_descent = self.context.font_extents()[0:2]
self.context.new_path()
#: make sure line does not intersect other conflict objects
line = LineString(coords)
line = self.map_area.intersection(line)
line = line.difference(self.map_area.exterior.buffer(height))
line = line.difference(self.conflict_area)
#: check whether line is empty or is split into several different parts
if line.geom_type == 'GeometryCollection':
return
elif line.geom_type == 'MultiLineString':
longest = None
min_len = width * 1.2
for seg in line.geoms:
seg_len = seg.length
if seg_len > min_len:
longest = seg
min_len = seg_len
if longest is None:
return
line = longest
coords = tuple(line.coords)
seg = utils.linestring_text_optimal_segment(coords, width)
# line has either to much change in gradients or is too short
if seg is None:
return
#: crop optimal segment of linestring
start, end = seg
coords = coords[start:end+1]
#: make sure text is rendered from left to right
if coords[-1][0] < coords[0][0]:
coords = tuple(reversed(coords))
# translate linestring so text is rendered vertically in the middle
line = LineString(tuple(coords))
offset = font_ascent / 2. - font_descent
line = line.parallel_offset(offset, 'left', resolution=3)
# make sure text is rendered centered on line
start_len = (line.length - width) / 2.
char_coords = None
chars = utils.generate_char_geoms(self.context, text)
#: draw all character paths
for char in utils.iter_chars_on_line(chars, line, start_len):
for geom in char.geoms:
char_coords = iter(geom.exterior.coords)
self.context.move_to(*char_coords.next())
for lon, lat in char_coords:
self.context.line_to(lon, lat)
self.context.close_path()
#: only add line to reserved area if text was drawn
if char_coords is not None:
covered = line.buffer(height)
self.conflict_union(covered)
#.........这里部分代码省略.........
示例8: zip
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import parallel_offset [as 别名]
xPoints, yPoints = zip(*PolylineCodec().
decode(str(polylines[i][POLYLINE].values()[0])))
abcisses += xPoints
images += yPoints
resultPoints = list(imap(list, izip(abcisses, images)))
reducedList = []
#Reduce the number of points to optimize further computation.
for i in range (0, len(resultPoints), 100):
reducedList.append(resultPoints[i])
#Convert the line into a LineString to use the parallel_offset function.
line = LineString(reducedList)
#Build the left Buffer.
leftBuffer = line.parallel_offset(BUFFER_OFFSET,'left')
xLeft, yLeft = leftBuffer.xy
xLeftPoints = xLeft.tolist()
yLeftPoints = yLeft.tolist()
bufferLeftPoints = list(imap(list, izip(xLeftPoints, yLeftPoints)))
#Build the right Buffer.
rightBuffer = line.parallel_offset(BUFFER_OFFSET,'right')
xRight, yRight = rightBuffer.xy
xRightPoints = xRight.tolist()
yRightPoints = yRight.tolist()
bufferRightPoints = list(imap(list, izip(xRightPoints, yRightPoints)))
#Create a map.
map = folium.Map()
示例9: LineString
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import parallel_offset [as 别名]
ax.set_aspect(1)
line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
line_bounds = line.bounds
ax_range = [int(line_bounds[0] - 1.0), int(line_bounds[2] + 1.0)]
ay_range = [int(line_bounds[1] - 1.0), int(line_bounds[3] + 1.0)]
fig = pyplot.figure(1, figsize=(SIZE[0], 2 * SIZE[1]), dpi=90)
# 1
ax = fig.add_subplot(221)
plot_line(ax, line)
x, y = list(line.coords)[0]
plot_coords(ax, x, y)
offset = line.parallel_offset(0.5, 'left', join_style=2, mitre_limit=0.1)
plot_line(ax, offset, color=BLUE)
ax.set_title('a) left, limit=0.1')
set_limits(ax, ax_range, ay_range)
#2
ax = fig.add_subplot(222)
plot_line(ax, line)
x, y = list(line.coords)[0]
plot_coords(ax, x, y)
offset = line.parallel_offset(0.5, 'left', join_style=2, mitre_limit=10.0)
plot_line(ax, offset, color=BLUE)
示例10: run
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import parallel_offset [as 别名]
def run(self):
# show the dialog
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result == 1:
layers = iface.legendInterface().layers()
if len(layers) != 0:
#Check that there is a selected layer
layer = iface.mapCanvas().currentLayer()
if layer.type() == 0:
#check selected layer is a vector layer
if layer.geometryType() == 1:
#check to see if selected layer is a linestring geometry
if len(layer.selectedFeatures()) != 0:
#Dir = float(self.dlg.ui.radLeft.isChecked()
layers = iface.legendInterface().layers()
Lexists = "false"
#check to see if the virtual layer already exists
for layer in layers:
if layer.name() == "Parallel_Offset":
Lexists = "true"
vl = layer
#if it doesn't exist create it
if Lexists == "false":
vl = QgsVectorLayer("Linestring?field=offset:integer&field=direction:string(10)&field=method:string(10)","Parallel_Offset","memory")
#vl = QgsVectorLayer("Linestring", "Parallel_Offset", "memory")
pr = vl.dataProvider()
vl.startEditing()
#pr.addAttributes( [ QgsField("offset", Double), QgsField("direction", String), QgsField("method", String) ] )
else:
pr = vl.dataProvider()
vl.startEditing()
#get the direction
Dir = 'right'
if self.dlg.ui.radLeft.isChecked():
Dir = 'left'
#get the method
if self.dlg.ui.radRound.isChecked():
js = 1
if self.dlg.ui.radMitre.isChecked():
js = 2
if self.dlg.ui.radBevel.isChecked():
js = 3
#get the offset
loffset = float(self.dlg.ui.txtDistance.text())
#create the new feature from the selection
for feature in layer.selectedFeatures():
geom = feature.geometry()
h = geom.asPolyline()
line = LineString(h)
nline = line.parallel_offset(loffset, Dir,resolution=16,join_style=js,mitre_limit=10.0)
#turn nline back into a polyline and add it to the map as a new layer.
fet = QgsFeature()
fet.setGeometry(QgsGeometry.fromWkt(str(nline)))
fet.setAttributes( [loffset,Dir ,js] )
pr.addFeatures( [ fet ] )
vl.commitChanges()
QgsMapLayerRegistry.instance().addMapLayer(vl)
mc=self.iface.mapCanvas()
mc.refresh()