本文整理汇总了Python中shapely.geometry.LineString.distance方法的典型用法代码示例。如果您正苦于以下问题:Python LineString.distance方法的具体用法?Python LineString.distance怎么用?Python LineString.distance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shapely.geometry.LineString
的用法示例。
在下文中一共展示了LineString.distance方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: collide
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
def collide(self, other_ball):
# Present and future positions of both balls
p1 = (self.coord[0], self.coord[2])
q1 = (self.coord[0] + COF*self.vel[0], self.coord[2] + COF*self.vel[2])
p2 = (other_ball.coord[0], other_ball.coord[2])
q2 = (other_ball.coord[0] + COF*other_ball.vel[0], other_ball.coord[2] + COF*other_ball.vel[2])
# Both balls are moving
if self.isMoving() and other_ball.isMoving():
segment1 = LineString([p1,q1])
segment2 = LineString([p2,q2])
return segment1.distance(segment2) <= self.radius+other_ball.radius
# Only this ball is moving
elif self.isMoving():
segment1 = LineString([p1,q1])
return segment1.distance(Point(p2)) <= self.radius+other_ball.radius
#Only the other ball is moving
elif other_ball.isMoving():
segment2 = LineString([p2,q2])
return segment2.distance(Point(p1)) <= self.radius+other_ball.radius
return False
示例2: process_path_obstacle
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
def process_path_obstacle(self, fpath):
if self.path_obstacle_processed:
return
path_x, path_y = fpath.get_xy()
self.obstacle_lat_dist = {}
path = []
self.mobileye.process_obstacles()
for i in range(len(path_x)):
path.append((path_x[i], path_y[i]))
line = LineString(path)
for obs_id, obstacle in self.mobileye.obstacles.items():
point = Point(obstacle.x, obstacle.y)
dist = line.distance(point)
if dist < self.LAT_DIST + obstacle.width + self.left_edge_to_center:
proj_len = line.project(point)
if proj_len == 0 or proj_len >= line.length:
continue
p1 = line.interpolate(proj_len)
if (proj_len + 1) > line.length:
p2 = line.interpolate(line.length)
else:
p2 = line.interpolate(proj_len + 1)
d = (point.x - p1.x) * (p2.y - p1.y) - (point.y - p1.y) * (
p2.x - p1.x)
if d > 0:
dist *= -1
self.obstacle_lat_dist[obstacle.obstacle_id] = dist
self.path_obstacle_processed = True
示例3: identify_first_point_in_polygon
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
def identify_first_point_in_polygon(points, ddd=0.5):
"""
Identify the cycle beginning for the last point
:param points: array of objects of PointX
:param ddd: distance to the fist point ddd>0.
:return -1 if do not close, or i if close in point i.
"""
if len(points) < 3:
return -1
# last point
lp = Point(points[-1])
first_point = len(points) - 2
# Distance between last point and a line segment
distance_point_line = 2 * ddd
# Distance is not less than ddd or less than 3 points.
while not (distance_point_line < ddd and polyline_length(points[first_point:]) > 2):
# next segment
first_point -= 1
if first_point == -1:
break
pt1 = points[first_point + 1]
pt2 = points[first_point]
# Distance to the first point to the line segment
line_segment = LineString([pt1, pt2])
distance_point_line = line_segment.distance(lp)
return first_point
示例4: find_corners
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
def find_corners(self, bounding_polygon, tol=1.0e-08, print_flag=False):
"""Find the corners of a layer cut by a bounding polygon.
Saves: self.corners
"""
list_of_corners = []
bounding_line = LineString(bounding_polygon.exterior)
for coord in self.polygon.exterior.coords[:-1]:
pt = Point(coord[0],coord[1])
# determine if this point is on the bounding_polygon
if bounding_line.distance(pt) < tol:
list_of_corners.append(pt)
if print_flag:
print pt
self.corners = list_of_corners
示例5: closest_side_alignment_norm
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
def closest_side_alignment_norm(sample0,sample1):
polygons=mp.map_layoutsamples_to_geometricobjects([sample0,sample1],shape_name="shape")
min_dist=float("inf")
min_l0=None
min_l1=None
for p00,p01 in ut.pairwise(polygons[0].exterior.coords):
for p10,p11 in ut.pairwise(polygons[1].exterior.coords):
l0=LineString([p00,p01])
l1=LineString([p10,p11])
dist=l1.distance(l0)
if dist<min_dist:
min_dist=dist
min_l0=l0.coords
min_l1=l1.coords
#the constraint of alignement between 2 closest sides of 2 polygons as defined in a paper
#the difference is defined over 90 degrees
angle0=_angle(min_l0)
angle1=_angle(min_l1)
return (1+np.cos(4*(angle0-angle1)))/2
示例6: _sanitize_edges
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
def _sanitize_edges(self, edges):
"""
Checks if there are points that lay on the edges.
"""
new_edges = set()
for edge in edges:
found_point_between = False
segment = LineString([(edge[0].x, edge[0].y), (edge[1].x, edge[1].y)])
for point in self.points:
if point is not edge[0] and point is not edge[1]:
if segment.distance(ShapelyPoint(point.x, point.y)) < 1e-8:
if (edge[0], point) not in self.edges and (point, edge[0]) not in self.edges:
new_edges.add((edge[0], point))
if (edge[1], point) not in self.edges and (point, edge[1]) not in self.edges:
new_edges.add((point, edge[1]))
found_point_between = True
break
if not found_point_between:
new_edges.add(edge)
if set(edges) == new_edges:
return list(edges)
else:
return self._sanitize_edges(list(new_edges))
示例7: ADPolyline
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
#.........这里部分代码省略.........
if type(intersects) is ADPoint:
# single intersection
return intersects
elif type(intersects) is None:
raise UnknownIntersection('BFE doesn\'t intersect with contour')
elif type(intersects) is not list:
raise UnknownIntersection('Unknown return type from intersection: '+str(type(intersects)))
# Assume intersects is a list of ADPoints
# Sort by distance along self, relative to test_point
test_dist = self.project(test_point)
for point in intersects:
point.station = abs(self.project(point)-test_dist)
intersects.sort(key=lambda x: x.station)
# Return closest point
return intersects[0]
def num_intersects(self, line):
"""
Intersects self with line. returns the number of point intersections
:param line: ADPolyline
:return: int
"""
intersect = self.intersection(line)
if intersect is None:
return 0
elif type(intersect) is ADPoint:
return 1
elif type(intersect) is list:
return len(intersect)
else:
# Returned polyline or something weird. Maybe raise an exception here?
return 0
def point_at_distance(self, distance, normalize=False):
new_pt = self.shapely_geo.interpolate(distance, normalized=normalize)
return ADPoint(shapely_geo=new_pt)
def distance_to(self, gis_thing):
#print type(gis_thing)
return self.shapely_geo.distance(gis_thing.shapely_geo)
def interpolate(self, distance, normalized=False):
""" Returns ADPoint at distance along polyline """
geo = self.shapely_geo.interpolate(distance, normalized)
return ADPoint(shapely_geo=geo)
def project(self, gis_thing):
"""Returns the distance along this geometric object to a point nearest the other object."""
return self.shapely_geo.project(gis_thing.shapely_geo)
def plot(self, *args, **kwargs):
pyplot.plot(self.shapely_geo.xy[0], self.shapely_geo.xy[1], *args, **kwargs)
def label(self, text='insert text here', reverse=False, *args, **kwargs):
if reverse:
X = self.last_point.X
Y = self.last_point.Y
else:
X = self.first_point.X
Y = self.first_point.Y
pyplot.annotate(str(text), xy=(X, Y), *args, **kwargs)
def clip(self, point1, point2):
"""
Returns ADPolyline of the current polyline clipped between point1 and point2
Searches for loop (closed) contours and returns the shortest portion of the contour
示例8: line_dist
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
def line_dist(boundary1, boundary2):
line1 = LineString([boundary1[0], boundary1[1]])
line2 = LineString([boundary2[0], boundary2[1]])
l_dist = line1.distance(line2)
return l_dist
示例9: pdfer
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
#.........这里部分代码省略.........
try:
one,two,three,four = grid[k]['bbox']
polys.append(box(two, one, four, three))
except TypeError:
pass
mpoly = MultiPolygon(polys)
bb_poly = box(*mpoly.bounds)
min_key = keys[0]
max_key = keys[-2]
bminx, bminy = grid[min_key]['bbox'][0], grid[min_key]['bbox'][1]
bmaxx, bmaxy = grid[max_key]['bbox'][2], grid[max_key]['bbox'][3]
bmin_mx, bmin_my = mercator.LatLonToMeters(bminx, bminy)
bmax_mx, bmax_my = mercator.LatLonToMeters(bmaxx, bmaxy)
bmin_px, bmin_py = mercator.MetersToPixels(bmin_mx,bmin_my,float(grid['zoom']))
bmax_px, bmax_py = mercator.MetersToPixels(bmax_mx,bmax_my,float(grid['zoom']))
bmin_rx, bmin_ry = mercator.PixelsToRaster(bmin_px,bmin_py,int(grid['zoom']))
if shape_overlays:
all_polys = []
for shape_overlay in shape_overlays:
if shape_overlay:
shape_overlay = json.loads(shape_overlay)
if shape_overlay.get('geometry'):
shape_overlay = shape_overlay['geometry']
coords = shape_overlay['coordinates'][0]
all_polys.append(Polygon(coords))
mpoly = MultiPolygon(all_polys)
one, two, three, four, five = list(box(*mpoly.bounds).exterior.coords)
left, right = LineString([one, two]), LineString([three, four])
top, bottom = LineString([two, three]), LineString([four, five])
left_to_right = left.distance(right)
top_to_bottom = top.distance(bottom)
if left_to_right > top_to_bottom:
page_height, page_width, _, _ = page_size
else:
page_width, page_height, _, _ = page_size
center_lon, center_lat = list(mpoly.centroid.coords)[0]
if point_overlays:
all_points = []
for point_overlay in point_overlays:
point_overlay = json.loads(point_overlay)
for p in point_overlay['points']:
if p[0] and p[1]:
all_points.append(p)
mpoint = MultiPoint(all_points)
center_lon, center_lat = list(mpoint.centroid.coords)[0]
one, two, three, four, five = list(box(*mpoint.bounds).exterior.coords)
left, right = LineString([one, two]), LineString([three, four])
top, bottom = LineString([two, three]), LineString([four, five])
left_to_right = left.distance(right)
top_to_bottom = top.distance(bottom)
if left_to_right > top_to_bottom:
page_height, page_width, _, _ = page_size
示例10: __init__
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
class RoutingProvider:
def __init__(self):
self.routing_str = None
self.routing_points = []
self.routing = None
self.routing_lock = threading.Lock()
self.SMOOTH_FORWARD_DIST = 150
self.SMOOTH_BACKWARD_DIST = 150
self.human = False
def update_navigation(self, navigation_info_pb):
self.routing_str = navigation_info_pb
self.human = True
routing_points = []
for navi_path in navigation_info_pb.navigation_path:
for path_point in navi_path.path.path_point:
routing_points.append([path_point.x, path_point.y])
self.routing_lock.acquire()
self.routing_points = routing_points
self.routing_lock.release()
self.routing = LineString(self.routing_points)
def update(self, routing_str):
self.routing_str = routing_str
routing_json = json.loads(routing_str.data)
routing_points = []
self.human = False
for step in routing_json:
if step.get('human'):
self.human = True
points = step['polyline']['points']
for point in points:
routing_points.append(point)
self.routing_lock.acquire()
self.routing_points = routing_points
self.routing_lock.release()
self.routing = LineString(self.routing_points)
def get_segment(self, utm_x, utm_y):
if self.routing_str is None:
return None
point = Point(utm_x, utm_y)
if self.routing.distance(point) > 10:
return []
if self.routing.length < 10:
return []
vehicle_distance = self.routing.project(point)
points = []
total_length = self.routing.length
for i in range(self.SMOOTH_BACKWARD_DIST):
backward_dist = vehicle_distance - self.SMOOTH_BACKWARD_DIST + i
if backward_dist < 0:
continue
p = self.routing.interpolate(backward_dist)
points.append(p.coords[0])
for i in range(self.SMOOTH_FORWARD_DIST):
forward_dist = vehicle_distance + i
if forward_dist >= total_length:
break
p = self.routing.interpolate(forward_dist)
points.append(p.coords[0])
return points
def get_local_segment(self, utm_x, utm_y, heading):
points = self.get_segment(utm_x, utm_y)
if points is None or len(points) < 30:
return [], []
points_x = []
points_y = []
for point in points:
points_x.append(point[0])
points_y.append(point[1])
path_x = [x - utm_x for x in points_x]
path_y = [y - utm_y for y in points_y]
npath_x = []
npath_y = []
for i in range(len(path_x)):
x = path_x[i]
y = path_y[i]
newx = x * math.cos(-heading) - y * math.sin(-heading)
newy = y * math.cos(-heading) + x * math.sin(-heading)
npath_x.append(newx)
npath_y.append(newy)
return npath_x, npath_y
def to_monotonic_segment(self, seg_x, seg_y):
left_cut_idx = 0
right_cut_idx = len(seg_x)
for i in range(len(seg_x) - 1):
if seg_x[i + 1] < seg_x[i]:
if seg_x[i] >= 0:
right_cut_idx = i + 1
break
else:
left_cut_idx = i + 1
#.........这里部分代码省略.........
示例11: Points
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
#Create a map.
map = folium.Map()
#Draw the main path.
map.line(reducedList, line_color = 'Red', line_weight = 2)
#Draw the buffers.
map.line(bufferLeftPoints, line_color = 'Blue', line_weight = 2)
map.line(bufferRightPoints, line_color = 'Blue', line_weight = 2)
#Draw markers randomly and create Points (Shapely) to be able to use
#the distance() function. Counts the number of markers in between
#the buffers.
markerCount = 0;
for i in range(len(reducedList)):
yValue = random.uniform(reducedList[i][1] - OFFSET, reducedList[i][1] + OFFSET)
map.polygon_marker(location=[reducedList[i][0], yValue], radius = 2,
line_color = 'Black', fill_opacity = 1)
point = Point(reducedList[i][0], yValue)
if (line.distance(point) < 0.125):
markerCount += 1
#Sums up the number of panels seen.
print 'Approximately %d panels seen' % markerCount
#Creates map.
map.create_map(path='map.html')
示例12: merge_parallel_street_segments
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
def merge_parallel_street_segments(self, parallel_pairs):
"""
Note: Maybe I don't even have to merge any path (which breaks the original street network data structure.
Instead, I can mark ways that have parallel neighbors not make sidewalks on both sides...
:param parallel_pairs: pairs of street_ids.
Todo: This method needs to be optimized using some spatial data structure (e.g., r*-tree) and other metadata..
# Expand streets into rectangles, then find intersections between them.
# http://gis.stackexchange.com/questions/90055/how-to-find-if-two-polygons-intersect-in-python
"""
# Merge parallel pairs
for pair in parallel_pairs:
streets_to_remove = []
street_pair = (self.ways.get(pair[0]), self.ways.get(pair[1]))
# First find parts of the street pairs that you want to merge (you don't want to merge entire streets
# because, for example, one could be much longer than the other and it doesn't make sense to merge
subset_nids, street1_segment, street2_segment = self.segment_parallel_streets((street_pair[0], street_pair[1]))
if not subset_nids:
continue
# Get two parallel segments and the distance between them
try:
street1_node = self.nodes.get(street1_segment[1][0])
street2_node = self.nodes.get(street2_segment[1][0])
except IndexError:
log.debug("Warning! Segment to merge was empty for one or both streets, so skipping this merge...")
continue
street1_end_node = self.nodes.get(street1_segment[1][-1])
street2_end_node = self.nodes.get(street2_segment[1][-1])
LS_street1 = LineString((street1_node.location(), street1_end_node.location()))
LS_street2 = LineString((street2_node.location(), street2_end_node.location()))
distance = LS_street1.distance(LS_street2) / 2
# Merge streets
node_to = {}
new_street_nids = []
street1_idx = 0
street2_idx = 0
street1_nid = street1_segment[1][0]
street2_nid = street2_segment[1][0]
for nid in subset_nids:
try:
if nid == street1_nid:
street1_idx += 1
street1_nid = street1_segment[1][street1_idx]
node = self.nodes.get(nid)
opposite_node_1 = self.nodes.get(street2_nid)
opposite_node_2_nid = street2_segment[1][street2_idx + 1]
opposite_node_2 = self.nodes.get(opposite_node_2_nid)
else:
street2_idx += 1
street2_nid = self.ways.get(pair[1]).nids[street2_idx]
node = self.nodes.get(nid)
opposite_node_1 = self.nodes.get(street1_nid)
opposite_node_2_nid = street1_segment[1][street1_idx + 1]
opposite_node_2 = self.nodes.get(opposite_node_2_nid)
v = opposite_node_1.vector_to(opposite_node_2, normalize=True)
v2 = opposite_node_1.vector_to(node, normalize=True)
if np.cross(v, v2) > 0:
normal = np.array([v[1], v[0]])
else:
normal = np.array([- v[1], v[0]])
new_position = node.location() + normal * distance
new_node = Node(None, new_position[0], new_position[1])
self.add_node(new_node)
new_street_nids.append(new_node.id)
except IndexError:
# Take care of the last node.
# Use the previous perpendicular vector but reverse the direction
node = self.nodes.get(nid)
new_position = node.location() - normal * distance
new_node = Node(None, new_position[0], new_position[1])
self.add_node(new_node)
new_street_nids.append(new_node.id)
log.debug(pair)
node_to[subset_nids[0]] = new_street_nids[0]
node_to[subset_nids[-1]] = new_street_nids[-1]
merged_street = Street(None, new_street_nids)
merged_street.distance_to_sidewalk *= 2
streets_to_remove.append(street_pair[0].id)
streets_to_remove.append(street_pair[1].id)
# Create streets from the unmerged nodes.
# Todo: I think this part of the code can be prettier
if street1_segment[0] or street2_segment[0]:
if street1_segment[0] and street2_segment[0]:
if street1_segment[0][0] == street2_segment[0][0]:
# The two segments street1 and street2 share a common node. Just connect one of them to the
# new merged street.
if subset_nids[0] in street1_segment[1]:
#.........这里部分代码省略.........
示例13: track_to_segment_projction
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
def track_to_segment_projction(track,
road_segments,
angle_threshold = np.pi/4.0):
""" Project tracks to road segments
Args:
- track: a GPS track
- road_segments: a list of RoadSegment
- dist_threshold: in meters
Return:
- related_segments: an index list
"""
road_segment_linestrings = []
for r_seg in road_segments:
r_start = r_seg.center - r_seg.half_length*r_seg.direction
r_end = r_seg.center + r_seg.half_length*r_seg.direction
r_linestring = LineString([r_start, r_end])
road_segment_linestrings.append(r_linestring)
related_segments = []
line = LineString([(pt[0], pt[1]) for pt in track.utm])
simplified_line = line.simplify(10.0)
coords = simplified_line.coords
for pt_idx in range(1, len(coords)):
track_segment_dir = np.array(coords[pt_idx]) - np.array(coords[pt_idx-1])
track_segment_dir_norm = np.linalg.norm(track_segment_dir)
if track_segment_dir_norm < 1.0:
continue
track_segment_dir /= np.linalg.norm(track_segment_dir)
track_segment = LineString([coords[pt_idx-1], coords[pt_idx]])
for r_seg_idx in np.arange(len(road_segments)):
r_segment = road_segments[r_seg_idx]
if np.dot(track_segment_dir, r_segment.direction) >= np.cos(angle_threshold):
dist = track_segment.distance(road_segment_linestrings[r_seg_idx])
if dist <= r_segment.half_width:
related_segments.append(r_seg_idx)
nearby_segments = list(set(related_segments))
if len(nearby_segments) <= 1:
return nearby_segments
# Select through nearby segments to get the cover of the trajctory
m = len(track.utm)
n = len(nearby_segments)
A = np.zeros((m,n))
for pt_idx in np.arange(len(track.utm)):
point = Point(track.utm[pt_idx][0], track.utm[pt_idx][1])
for nb_seg_idx in np.arange(len(nearby_segments)):
seg_idx = nearby_segments[nb_seg_idx]
if point.distance(road_segment_linestrings[seg_idx]) <= road_segments[seg_idx].half_width:
A[pt_idx, nb_seg_idx] = 1.0
alpha = 0.5
x = Variable(n)
delta = Variable(m)
objective = Minimize(sum(alpha*x)+sum(delta))
constraints = [0 <= x,
x <= 1,
0 <= delta,
delta <= 1,
A*x >= 1 - delta]
prob = Problem(objective, constraints)
prob.solve()
selected_segments = []
order = []
for i in np.arange(len(x.value)):
if x.value[i] > 0.5:
selected_segments.append(nearby_segments[i])
order_of_this_segment = np.average(np.where(A[:, i])[0])
order.append(order_of_this_segment)
order = np.array(order)
sorted_idxs = np.argsort(order)
sorted_segments = []
for idx in sorted_idxs:
sorted_segments.append(selected_segments[idx])
return sorted_segments
示例14: err
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import distance [as 别名]
def err(p,coor,pts,pt):
line=LineString([coor[0]+p[0]*(coor[1]-coor[0]),pt])
distance=[line.distance(pt) for pt in pts]
return distance