当前位置: 首页>>代码示例>>Python>>正文


Python LineString.interpolate方法代码示例

本文整理汇总了Python中shapely.geometry.LineString.interpolate方法的典型用法代码示例。如果您正苦于以下问题:Python LineString.interpolate方法的具体用法?Python LineString.interpolate怎么用?Python LineString.interpolate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在shapely.geometry.LineString的用法示例。


在下文中一共展示了LineString.interpolate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: process_path_obstacle

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [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
开发者ID:GeoffGao,项目名称:apollo,代码行数:34,代码来源:obstacle_decider.py

示例2: evenly_spaced

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
def evenly_spaced(points, spacing):
    result = []
    line = LineString(points)
    length = line.length
    d = 0
    while d < length:
        point = line.interpolate(d)
        result.append((point.x, point.y))
        d += spacing
    point = line.interpolate(length)
    result.append((point.x, point.y))
    return result
开发者ID:RolandJuno,项目名称:xy,代码行数:14,代码来源:xkcd.py

示例3: getShortestDisLinePoint

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
def getShortestDisLinePoint(pointLon, pointLat, lineCoords, earthR):
	#get shortest distance between point and line
	line = LineString(lineCoords) 
	point = Point(pointLon, pointLat)
	closestCoord = line.interpolate(line.project(point))
	distance = haversine(pointLon, pointLat, closestCoord.x, closestCoord.y, earthR)
	return distance
开发者ID:sanchitaggarwal-innoplexus,项目名称:Next-Top-Analyst,代码行数:9,代码来源:Next+Top+Analyst.py

示例4: project

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
def project(p1, p2, p3):
    """Project a Point, p3 onto a line between Points p1 and p2.

    Uses Shapely and GEOS functions, which set distance to zero for all negative distances.

    Parameters:
        p1 (Point) : point at zero distance on line between p1 and p2.
        p2 (Point) : endpoint of line.
        p3 (Point) : the point to project.

    Returns:
        result (dict) : the projected Point, disctance along line, offset from line, and fractional distance along line.

    """
    line = LineString([(p1.x, p1.y),(p2.x, p2.y)])
    u = line.project(p3, normalized=True)
    d = line.project(p3, normalized=False)
    pt_xy = line.interpolate(d)
    pt = Point([pt_xy.x, pt_xy.y, p3.z])

    # calculate the offset distance of p3 from the line
    if (p1.y - p2.y) * (p3.x - p2.x) - (p1.x - p2.x) * (p3.y - p2.y) < 0:
        offset = -pt.distance(p3) # the point is offset left of the line
    else:
        offset = pt.distance(p3) # the point is offset right of the line

    result = {'pt':pt, 'd':d, 'o':offset, 'u':u}
    return result
开发者ID:mrahnis,项目名称:orangery,代码行数:30,代码来源:geometry.py

示例5: get_matched_trip_smooth

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
def get_matched_trip_smooth(data, matched_folder):
    xs, ys, mx0, mx1, my0, my1 = ([], [], [], [], [], [])
    for tid in data.tid.unique():
        matched_trip = pd.read_csv(matched_folder+'/matched_trip'+str(tid)+'.csv', sep=' ', names=['y','x','t','y0','x0','y1','x1'])
        matched_trip = matched_trip[matched_trip.t % 5 == 1]
        matched_trip = matched_trip.replace('unknown', 0)
        matched_trip.fillna(0)
        #print tid, len(trip), len(matched_trip), len(matched_trip[matched_trip.x0 == 'unknown'])
        for idx, row in matched_trip.iterrows():
            #print row
            if row.y0 == 0 or row.x0 == 0:
                xs.append(0)
                ys.append(0)
                mx0.append(0)
                my0.append(0)
                mx1.append(0)
                my1.append(0)
                '''
                xs.append(xs[-1])
                ys.append(ys[-1])
                mx0.append(mx0[-1])
                my0.append(my0[-1])
                mx1.append(mx1[-1])
                my1.append(my1[-1])
                '''
                continue
            line = LineString([(float(row.x0),float(row.y0)),(float(row.x1),float(row.y1))])
            mx0.append(float(row.x0))
            my0.append(float(row.y0))
            mx1.append(float(row.x1))
            my1.append(float(row.y1))
            p = Point(row.x, row.y)
            #print row.x, row.y, 
            #print list(line.interpolate(line.project(p)).coords)
            _x, _y = list(line.interpolate(line.project(p)).coords)[0]
            xs.append(_x)
            ys.append(_y)
    data['mLon'] = xs
    data['mLat'] = ys
    data['mx0'] = mx0
    data['my0'] = my0
    data['mx1'] = mx1
    data['my1'] = my1

    '''
    # naive fillna
    xs = []
    ys = []
    for idx, row in data.iterrows():
        if row.mLon == 0:
            xs.append(xs[-1])
            ys.append(ys[-1])
        else:
            xs.append(row.mLon)
            ys.append(row.mLat)
    data.mLon = xs
    data.mLat = ys
    '''

    return data
开发者ID:renj,项目名称:TrajMap,代码行数:62,代码来源:matcher.py

示例6: pymol_select_memb_old

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
def pymol_select_memb_old(pdb: MyPDB) -> set():
    """
    print a pymol selection line for all residues that are in the membrane
    !!! this assumes that cntr is at 0 0 0 and norm at 15 0 0 !!!
    """
    from shapely.geometry import LineString, Point
    # create Points from center & thickness
    cntr_pnt = Point(pdb.memb_res.cntr.x, pdb.memb_res.cntr.y, pdb.memb_res.cntr.z)
    thkn_m_pnt = Point(-pdb.memb_res.thkn.x, pdb.memb_res.thkn.y, pdb.memb_res.thkn.z)
    thkn_pnt = Point(pdb.memb_res.thkn.x, pdb.memb_res.thkn.y, pdb.memb_res.thkn.z)

    # define the line between center and thickness
    line = LineString([thkn_m_pnt, thkn_pnt])
    thickness = cntr_pnt.distance(thkn_pnt)

    result = set()
    # iterate over all CAs in the pdb
    for cid in sorted(pdb.chains.keys()):
        for rid in sorted(pdb[cid].residues.keys()):
            atom = pdb[cid][rid]['CA']

            # the atom as a Point
            p = Point(atom.xyz.x, atom.xyz.y, atom.xyz.z)

            # projection of the CA atom on the center-thickness line
            np = line.interpolate(line.project(p))

            # if the distance on the center-thickness line is smaller than 15, than this is in the membrane
            if cntr_pnt.distance(np) < thickness-0.1:
                result.add(atom.res_seq_num)

    return result
开发者ID:jonathaw,项目名称:general_scripts,代码行数:34,代码来源:pymol_select_RMP_memb.py

示例7: fitline_plot

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
def fitline_plot(df):
	## best fit straight line of points
	slope, intercept = hcf.fitline(df)

	## define Shapely linestring using westmost and eastmost endpoints
	point1 = Point(df['x_working'].min(), slope * df['x_working'].min() + intercept)
	point2 = Point(df['x_working'].max(), slope * df['x_working'].max() + intercept)
	ls = LineString([point1, point2])

	## iterate through dfframe, project each TS point on Shapely line.  Determine position on line and absolute x,y value
	for index, row in df.iterrows():
		pointN = Point(row['x_working'], row['y_working'])
		projectN = ls.project(pointN)
		df.set_value(index, 'position_on_line', projectN)
		globalN = ls.interpolate(projectN)
		df.set_value(index, 'x_project', globalN.x)
		df.set_value(index, 'y_project', globalN.y)
		offsetN = globalN.distance(pointN)
		df.set_value(index, 'offset_from_line', offsetN)

	df = df.sort_values(by='position_on_line', ascending='true')
	print df

	## plot points projected on best fit line
	plt.scatter(df['x_project'], df['y_project'], color='pink')

	## init Figure 2
	plt.figure(num=2, figsize=(13, 3), dpi=80)
	plt.grid(True)
	# plt.axes().set_aspect('equal', 'dflim')
	plt.axis([df['position_on_line'].min() - 20, df['position_on_line'].max() + 20, df['z_working'].min() - 4,
	          df['z_working'].max() + 4])
	plt.scatter(df['position_on_line'], df['z_working'], color='black')
	plt.plot(df['position_on_line'], df['z_working'], color='black')
开发者ID:jasondec,项目名称:HCF_python,代码行数:36,代码来源:TS_all_plot.py

示例8: acc2latlng

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
def acc2latlng(caseno):
    """Calculate the latitude/longitude and update into mongodb

    :param caseno: case number of the accident
    """
    # get the cnty_rte and mile post
    acc = acc_col.find_one({'caseno':caseno})

    # check exists
    if 'lat' in acc.keys() and 'lng' in acc.keys():
        return

    rte_nbr = acc['rte_nbr']
    cnty_rte = acc['cnty_rte']
    milepost = acc['milepost']
    if cnty_rte.index(rte_nbr) != 2:
        raise Exception("Unknown format")

    # get the road information
    rid = rte_nbr + cnty_rte[0:2]
    r_info = cnty_rte2linestring(rid)
    max_mp = r_info['rlist'][-1]['endmp']
    ls = LineString( r_info['plist'] )
    deg_mp = milepost / max_mp * ls.length # mile to degree
    acc_pos = ls.interpolate( deg_mp )
    lng = acc_pos.coords[0][0]
    lat = acc_pos.coords[0][1]
    #print ls
    #print acc_pos
    # TODO, update the lat lng information
    acc_col.update(
            {'caseno':caseno},
            {'$set':{'lat':lat, 'lng':lng}}
            )
开发者ID:ganyfml,项目名称:hcc_taaa,代码行数:36,代码来源:get_acc_latlng.py

示例9: getRel

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
def getRel(tri1, tri2):
	rels = set()
	## get triangle center
	center = triangle_center(*tri1)

	#print 'center:' , center
	for i in xrange(3):
		#print 'vertex: ', tri2[i]
		angle = __calAngle__(center, tri2[i])
		rels.add(__getRel__(angle))

	if len(rels) >= 2:
		scenter = Point(center) #point in shapely form
		edges = [[tri2[0], tri2[1]], [tri2[1], tri2[2]], [tri2[0],tri2[2]]]	
		for edge in edges:
			line = LineString(edge)			
			isectPnt = line.interpolate(line.project(scenter))
			angle = __calAngle__(center, (isectPnt.x, isectPnt.y))
			rels.add(__getRel__(angle))

	x_direction = set()
	y_direction = set()
	for rel in rels:
		if rel == WEST or rel == EAST:
			x_direction.add(rel)
		else:
			y_direction.add(rel)	


	return [x_direction, y_direction]
开发者ID:fantastdd,项目名称:physical-reasoning-2d,代码行数:32,代码来源:triangle_relation.py

示例10: positionInterpolator

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
def positionInterpolator(latlons, times):
	'''
	takes a list of lat/lons (that describe a contiguous line) and a tuple of times (where the times are strings)
	for the number of seconds between the two times, calculates interpolated lat/lons along the line for each second between the two times
	returns a dict of times as keys with lat/lons as values

	EXTERNAL LIB: uses Shapely for line interpolation
	'''
	#build dict
	interp_dict = {}

	#specify time format
	FMT = '%H:%M:%S'
	#convert times to datetime objects
	try:
		t1 = datetime.strptime(times[0], FMT)
	except ValueError:
		t1 = datetime.strptime(('00'+times[0][2:]), FMT)
	try:
		t2 = datetime.strptime(times[1], FMT)
	except ValueError: #trying to parse a time that is past midnight, stored like '24:00:00'
		t2 = datetime.strptime(('00'+times[1][2:]), FMT) #strip the '24' off and shove in a '00'

	#useful vars
	end_of_day = datetime.strptime('23:59:59', FMT)
	start_of_day = datetime.strptime('00:00:00', FMT)
	#difference between times, using timedelta objs
	#the 'midnight bug' - if times[1] is after midnight AND times[0] is before midnight (i.e. trip crosses midnight), then add the diff between times[0] and midnight (plus 1 to account for 23:59:59 being latest datetime will go) ((23:59:59 - times[0]) +1 ) to the diff between times[1] and midnight (times [1] - 00:00:00)
	if t2 < t1:
		diff = ((end_of_day - t1).total_seconds() + 1) + ((t2 - start_of_day).total_seconds())
	else:
		diff = (t2 - t1).total_seconds()

	#if there is only a second or less difference between the two times (happens at least once in the stop_times.txt file, bizarre)
	if diff <= 1:
		#then just return an empty interp_dict, as there are no in-between seconds to interpolate positions for
		return interp_dict
	else:
		#fraction to be plugged into shapely's interpolate (what % of 100 is diff?)
		fraction = (100 / diff) / 100

		#buiid Linestring
		linepoints = []
		for s,l in sorted(latlons.iteritems()):
			linepoints.append(l)
		line = LineString(linepoints)

		i = 1
		while i < diff:
			#t1 + seconds(i)
			coords = line.interpolate((fraction * i), normalized=True).coords[0]
			t = (t1 + timedelta(0,i)).strftime(FMT)
			interp_dict[t] = coords
			i += 1

		return interp_dict
开发者ID:iainkirkpatrick,项目名称:wellington-pt,代码行数:58,代码来源:SQLtoCSV.py

示例11: test_interpolate

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
 def test_interpolate(self):
     # successful interpolation
     test_line = LineString(((1,1),(1,2)))
     known_point = Point(1,1.5)
     interpolated_point = test_line.interpolate(.5, normalized=True)
     self.assertEqual(interpolated_point, known_point)
     
     # Issue #653; should raise ValueError on exception
     empty_line = loads('LINESTRING EMPTY')
     assert(empty_line.is_empty)
     with pytest.raises(ValueError):
         empty_line.interpolate(.5, normalized=True)
开发者ID:Toblerity,项目名称:Shapely,代码行数:14,代码来源:test_operations.py

示例12: computeClosestPoints

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
def computeClosestPoints(pbars, sqrtJ2s, pbars_hull, sqrtJ2s_hull):

  hull = list(zip(pbars_hull, sqrtJ2s_hull))
  polyline = LineString(hull)

  closest_polyline = []
  for pbar, sqrtJ2 in zip(pbars, sqrtJ2s):
    pt = Point(pbar, sqrtJ2)
    closest = polyline.interpolate(polyline.project(pt))
    closest_polyline.append((closest.x, closest.y))

  return np.array(closest_polyline)
开发者ID:bbanerjee,项目名称:ParSim,代码行数:14,代码来源:TabularCapYieldSurfaceUtils.py

示例13: path

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
class path():
    def __init__(self,pts,num_samples,stage_points):
        self.my_pts = pts
        self.num_points = num_samples 
        start = 0
        self.my_point_list = [] #interpolated around closed linestring
        for sp in stage_points:
            stop = sp+1
            self.my_linestring = LineString(pts[start:stop])

            for k in range(self.num_points):
                step_size = (float) (k / self.num_points)
                self.my_point_list.append(self.my_linestring.interpolate(step_size,normalized = True))
            start = sp
开发者ID:bless727,项目名称:Z,代码行数:16,代码来源:yr2_scen1_positions_v3.py

示例14: get_local_ref

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
 def get_local_ref(self, local_seg_x, local_seg_y):
     ref_x = []
     ref_y = []
     points = []
     for i in range(len(local_seg_x)):
         x = local_seg_x[i]
         y = local_seg_y[i]
         points.append((x, y))
     line = LineString(points)
     dist = line.project(Point((0, 0)))
     for i in range(int(line.length - dist) + 1):
         p = line.interpolate(i + dist)
         ref_x.append(p.x)
         ref_y.append(p.y)
     return ref_x, ref_y
开发者ID:GeoffGao,项目名称:apollo,代码行数:17,代码来源:provider_routing.py

示例15: translate_to_pose

# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import interpolate [as 别名]
    def translate_to_pose(self, point):
        """Move the robot's x,y positions towards a goal point.

        Parameters
        ----------
        point: [x, y] array_like

        """
        path = LineString((self.robot.pose2D.pose[0:2], point))
        next_point = path.interpolate(self.max_move_distance)
        self.robot.pose2D.pose[0:2] = (next_point.x, next_point.y)
        logging.debug("{} translated to {}"
                      .format(self.robot.name,
                              ["{:.2f}".format(a) for a
                               in self.robot.pose2D.pose]))
开发者ID:COHRINT,项目名称:cops_and_robots,代码行数:17,代码来源:planner.py


注:本文中的shapely.geometry.LineString.interpolate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。