本文整理汇总了Python中shapely.geometry.Polygon.contains方法的典型用法代码示例。如果您正苦于以下问题:Python Polygon.contains方法的具体用法?Python Polygon.contains怎么用?Python Polygon.contains使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shapely.geometry.Polygon
的用法示例。
在下文中一共展示了Polygon.contains方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: triangulate_area_in_closed_curve
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def triangulate_area_in_closed_curve(bndry_pts,xmax,xmin,ymax,ymin,N,vector_map):
polygon = Polygon(bndry_pts)
interior_pts = []
dx = (xmax-xmin)/float(N+1)
dy = (ymax-ymin)/float(N+1)
x0 = xmin+dx
y0 = ymin+dy
for i in range(N):
x = x0+float(i)*dx+random.uniform(-0.1,0.1)
for j in range(N):
y = y0+float(j)*dy+random.uniform(-0.1,0.1)
pt = Point(x,y)
if polygon.contains(pt):
interior_pts.append((x,y))
surface_pts = bndry_pts+interior_pts
simplices = core.Triangulation(surface_pts)
triangles = simplices.get_elements()
pts = simplices.get_set()
(u1,u2,u3) = vector_map(pts)
indices = simplices.get_elements_indices()
reduced_indices = []
for index in indices:
x1 = numpy.array(pts[index[0]])
x2 = numpy.array(pts[index[1]])
x3 = numpy.array(pts[index[2]])
xcg = (x1+x2+x3)/3.0
x1 = xcg+0.999*(x1-xcg)
x2 = xcg+0.999*(x2-xcg)
x3 = xcg+0.999*(x3-xcg)
tmp = Polygon((x1,x2,x3))
if polygon.contains(tmp):
reduced_indices.append(index)
return(triangular_mesh(u1,u2,u3,reduced_indices,line_width=0.25,tube_radius=0.005,representation='fancymesh'))
示例2: pg_pix2latlon_strdf
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def pg_pix2latlon_strdf(im_name):
# load the polygon data for each region
poly_path = './shpres/%s.json'%(im_name)
if not os.path.isfile(poly_path):
#print 'no shape files', im_name
exit()
#print 'shift', shift_dict[im_name]
rs, cs = shift_dict[im_name]
pg = simplejson.load(open(poly_path))
#print pg
exter = np.array(pg['ext'])
exter[:,0] += cs
exter[:,1] += rs
ex_lonlat = pix2ll(exter,t)
inters = pg['intlist']
inter_list = []
for inter in inters:
np_inter = np.array(inter)
np_inter[:,0] += cs
np_inter[:,1] += rs
np_inter = pix2ll(np_inter,t)
inter_list.append(np_inter)
pg_obj = Polygon(ex_lonlat, inter_list)
print pg_obj.contains( Point(69.178746, 35.813774) )
示例3: get_busses_in_box
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def get_busses_in_box(self, key, lat1, lng1, lat2, lng2):
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
coord1 = (float(lat1), float(lng1))
coord2 = (float(lat1), float(lng2))
coord3 = (float(lat2), float(lng2))
coord4 = (float(lat2), float(lng1))
rect = Polygon([coord1,coord2,coord3,coord4])
ourRoutes = []
city_data = []
with open(os.path.join(PATH, 'stops.pickle'), 'rb') as f:
stops = pickle.load(f)
for stopid, stop in stops.items():
point = Point(float(stop.lat), float(stop.lng))
if rect.contains(point):
ourRoutes.extend(stop.routes)
ten = []
while (len(ourRoutes) > 10):
ten.append(ourRoutes.pop())
print ten
if (len(ten) == 10):
url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[0]+"&rt="+",".join(ten)+"&format=json&diagnostics=true&callback="
r = requests.get(url)
i = 1
while (r.text.find("exceeded") != -1):
url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[i]+"&rt="+",".join(ten)+"&format=json&diagnostics=true&callback="
r = requests.get(url)
i = i+1
ten = []
j = r.json()
for bus in j['bustime-response'][0]['vehicle']:
city_data.append(bus)
url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[0]+"&rt="+",".join(ourRoutes)+"&format=json&diagnostics=true&callback="
r = requests.get(url)
i = 0
while (r.text.find("exceeded") != -1):
url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[i]+"&rt="+",".join(ourRoutes)+"&format=json&diagnostics=true&callback="
r = requests.get(url)
i = i+1
j = r.json()
for bus in j['bustime-response'][0]['vehicle']:
city_data.append(bus)
ret_busses = []
for bus in city_data:
point = Point(float(bus['lat']), float(bus['lon']))
if rect.contains(point):
ret_busses.append(bus)
return json.dumps(ret_busses)
示例4: pointinside
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def pointinside(lat, lon, shapefile):
# Verifica todos os pontos que estão dentro do polígono
# http://streamhacker.com/2010/03/23/python-point-in-polygon-shapely/
# '/home/rodrigues/AmbientePython27/lib/python2.7/site-packages/PyFuncemeClimateTools/shp/pontos_ce.txt'
# Ler os pontos do vértice e tranformar em um poligno
poly = Polygon(shapefile)
nlons = len(lon)
nlats = len(lat)
points_grid = []
lonlat_grid = []
array_bool = np.ones((nlats, nlons), dtype="bool")
for xlon in range(0, nlons):
for ylat in range(0, nlats):
point = Point((lon[xlon], lat[ylat]))
a = poly.contains(point)
if a == True:
array_bool[ylat, xlon] = False
points_grid.append((ylat, xlon))
lonlat_grid.append((lat[ylat], lon[xlon]))
return points_grid, lonlat_grid, array_bool
示例5: return_points_in_polygon
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def return_points_in_polygon(coordinates, polygon_boundaries):
"""
Receives a list of tuples of coordinates and returns those
tuples that are contained within the boundaries of the polygon
specified in polygon_boundaries
:param coordinates
:param polygon_boundaries
:return contained_points
"""
#Verify that the inputs of the function are correct.
if not (isinstance(coordinates,list) and isinstance(polygon_boundaries,list)):
raise TypeError('List of tuples of coordinates is expected for coordinates and polygon_boundaries')
for point in coordinates:
if not (isinstance(point,list) or isinstance(point,tuple)):
raise TypeError('Values in coordinates should be lists or tuples of coordinates')
if len(point) != 2:
raise ValueError('Each coordinate should be represented as a list or tuple of two values, lat and lon')
for boundary_point in polygon_boundaries:
if not (isinstance(boundary_point,list) or isinstance(boundary_point,tuple)):
raise TypeError('Values in coordinates should be lists or tuples of coordinates')
if len(boundary_point) != 2:
raise ValueError('Each coordinate should be represented as a list or tuple of two values, lat and lon')
polygon = Polygon(polygon_boundaries)
contained_points = list()
for point in coordinates:
if polygon.contains(Point(point)):
contained_points.append(point)
return contained_points
示例6: return_sample_list
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def return_sample_list(num, regions, dist, scale):
"""
Return a list containing the position (x,y) of the samples.
Output is a list of lists: the ith list contains samples for
the ith region.
"""
sample_list = []
for index, region in enumerate(regions):
min_x = min([region[i][0] for i in xrange(len(region))])
max_x = max([region[i][0] for i in xrange(len(region))])
min_y = min([region[i][1] for i in xrange(len(region))])
max_y = max([region[i][1] for i in xrange(len(region))])
poly = Polygon(region)
region_samples = []
while len(region_samples) != num:
if dist == "normal":
candidate = (np.random.normal(loc = (min_x + max_x)/2, scale = scale), \
np.random.normal(loc = (min_y + max_y)/2, scale = scale))
if dist == "uniform":
candidate = (np.random.uniform(min_x, max_x),np.random.uniform(min_y, max_y))
if poly.contains(Point(candidate)):
region_samples.append(candidate)
sample_list.append(region_samples)
print "-done sampling-"
return sample_list
示例7: setStInShape
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def setStInShape(self,shpfile):
"""
Функция возвращает список станций попадающий в полигон(ы) из шэйпфайла файла
"""
import shapefile as shp
import geocalc
from shapely.geometry import Polygon,Point
res=[]
sf = shp.Reader(shpfile)
for sp in sf.shapes():
res_tmp=[]
lonmin,latmin,lonmax,latmax=sp.bbox
lonmin,lonmax=geocalc.cLon(lonmin),geocalc.cLon(lonmax)
if lonmin<0 or lonmax<0:
polygonPoints=[[geocalc.cLon(cors[0]),cors[1]] for cors in sp.points]
else:
polygonPoints=sp.points
poly=Polygon(polygonPoints)
indsInBox=[ind for ind in self.stInds if lonmin<=geocalc.cLon(self.stMeta[ind]['lon'])<=lonmax and latmin<=self.stMeta[ind]['lat']<=latmax]
for ind in indsInBox:
lat,lon=self.stMeta[ind]['lat'], geocalc.cLon(self.stMeta[ind]['lon'])
pnt=Point(lon,lat)
if poly.contains(pnt): res_tmp.append(ind)
res=res+res_tmp
return list(set(res))
示例8: generate_zones
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def generate_zones(poly_points, lon_unit, lat_unit, lons, lats):
poly = Polygon(poly_points)
zones = {}
geo_json = {"type": "FeatureCollection", "features": []}
for i, lon in enumerate(lons):
for j, lat in enumerate(lats):
leftBottom, rightBottom = (lon, lat), (lon + lon_unit, lat)
rightTop, leftTop = (lon + lon_unit, lat + lat_unit), (lon, lat + lat_unit)
polyPoints_gps = [leftBottom, rightBottom, rightTop, leftTop, leftBottom]
cCoor_gps = (lon + lon_unit / 2.0, lat + lat_unit / 2.0)
zone_poly = Polygon(polyPoints_gps)
if poly.contains(zone_poly):
boundary_relation = zone.IN
elif poly.intersects(zone_poly):
boundary_relation = zone.INTERSECT
else:
boundary_relation = zone.OUT
zones[(i, j)] = zone(boundary_relation, i, j, cCoor_gps, polyPoints_gps)
feature = {"type":"Feature",
"id": '%d#%d' % (i,j),
"properties": {"cCoor_gps": cCoor_gps},
"geometry":
{"type": "Polygon",
"coordinates": [[leftBottom,
rightBottom,
rightTop,
leftTop,
leftBottom
]]
}
}
geo_json["features"].append(feature)
return zones, geo_json
示例9: __init__
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
class Block:
def __init__( self, shp ):
"""
Build one Block object from the shapefile._Shape object
"""
self.bbox = box(*shp.bbox)
self.polygon = Polygon(shp.points)
self.count = {'total': 0} # type: value
def containPoint( self, p ):
"""
return true if the point p happened within current Block
"""
if self.bbox.contains(p):
if self.polygon.contains(p):
return True
return False
@classmethod
def createAllCAObjects( cls ):
cls.casf = shapefile.Reader('data/ChiCA_gps/ChiCaGPS')
cls.cas = {}
shps = cls.casf.shapes()
for idx, shp in enumerate(shps):
tid = cls.casf.record(idx)[4]
trt = Block(shp)
cls.cas[int(tid)] = trt
return cls.cas
示例10: latlon2countycode
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def latlon2countycode(lat,lon):
hits = []
try:
# Return a list of all counties that match lon OR lat
hits = list(idx.intersection((lon,lat,lon,lat)))
if len(hits) == 1: # Exact match
recno = hits[0]
elif len(hits) > 1: # Multiple candidate counties
#
# For example, 42.66326054 -87.80922716 [3180, 3193] - either kenosha or racine county.
for hitIdx in hits: # Search all counties in list
county = shapes[hitIdx]
poly = Polygon(county.points)
if poly.contains(Point(lon,lat)):
recno = hitIdx
break
else:
continue
else:
# if DEBUG:
# sys.stderr.write("Error: Latlon2countycode unexpected error. -1\n")
recno = -1
except:
# Lat/Lon don't match US county shapefiles
recno = 0
return recno
示例11: intersectNodes
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [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
示例12: __create_grid
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def __create_grid(self):
"""
Create uniform grid over region.
"""
polygon_coords = self.__resample_polygon()
# define polygon from polygon coords
polygon = Polygon(polygon_coords)
# get bounding box coordinates
bounding_box = polygon.bounds
min_lon = bounding_box[0]
max_lon = bounding_box[2]
min_lat = bounding_box[1]
max_lat = bounding_box[3]
# compute number of nodes along lat and lon
n_lat = int(round((max_lat - min_lat) / self.grid_spacing)) + 1
n_lon = int(round((max_lon - min_lon) / self.grid_spacing)) + 1
# create grid of points inside polygon
grid = []
for i in range(n_lat):
for j in range(n_lon):
lat = min_lat + i * self.grid_spacing
lon = min_lon + j * self.grid_spacing
p = shapelyPoint(lon,lat)
if polygon.contains(p) or polygon.touches(p):
grid.append((lon,lat))
return grid
示例13: goal
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def goal(p):
near_area = Polygon([
(p.ha - HA_STEP/2, p.de - DE_STEP/2),
(p.ha - HA_STEP/2, p.de + DE_STEP/2),
(p.ha + HA_STEP/2, p.de + DE_STEP/2),
(p.ha + HA_STEP/2, p.de - DE_STEP/2),
])
return near_area.contains(p_1.point()) or near_area.touches(p_1.point()) # touches if point exactly on the grid
示例14: get_shp_index
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def get_shp_index(im_name,debug=False,folder='./rawdata'):
shp_path = './shp/%s.shp'%(im_name)
im_path = '%s/%s'%(folder,im_name)
# get the pos for the good_label
fg_mask = get_fg_mask(im_path)
if debug:
plt.imshow(fg_mask)
plt.show()
sr = shapefile.Reader(shp_path)
shapes = sr.shapes()
pg_list = []
max_score = -1
for i,shape in enumerate(shapes):
tmp_pts = np.array(shape.points)
old_ci,c_i,first_poly = -1,0, True
exter = None
inter = []
for j in range(tmp_pts.shape[0]):
if j == c_i:
continue
v = tmp_pts[j,:] - tmp_pts[c_i,:]
d = np.sqrt(np.dot(v,v))
if d <= 0.5:
old_ci = c_i
c_i = j+1
plt.plot(tmp_pts[old_ci:c_i,0], tmp_pts[old_ci:c_i,1])
if first_poly:
exter = tmp_pts[old_ci:c_i,:]
first_poly = False
else:
# TODO, if area less than 4*4, then remove
tmp_pg = Polygon( tmp_pts[old_ci:c_i,:] )
if tmp_pg.area > 4*4:
inter.append( tmp_pts[old_ci:c_i,:] )
pg = Polygon( exter, inter)
if pg.area < 16:
pg_list.append(None)
continue
pg_list.append(pg)
score = 0
print fg_mask.shape[0], fg_mask.shape[1]
for ii in range(fg_mask.shape[0]):
for jj in range(fg_mask.shape[1]):
# NOTE, the Point with first dimension as col, second dimension as row
try:
if fg_mask[ii,jj] and pg.contains( Point(jj,ii)):
score += 1
except Exception as e:
print e
print i, score, pg.area
if score > max_score:
max_score = score
mi = i
print 'max score',max_score, mi
return mi, pg_list
示例15: test
# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import contains [as 别名]
def test():
point = Point(0.5,0.5)
r2 = LinearRing([
(1.1),
(0, 0),
(1, 0),
(0, 1)])
polygon2 = Polygon(r2)
boolean = polygon2.contains(point)
print (boolean)