Here is my question.
1. Introduction
- shapefile in the polygon represents the study area
http://i8.tietuku.com/08fdccbb7e11c0a9.png
- some point located in the entire map of the rectangle
http://i8.tietuku.com/877f87022bf817b8.png
I want to check if each point was inside / outside the polygon and performed some further operation (for example, sum the sum of the grid point within the study area)
2. My idea
I have two methods, thanks to stack overflow information.
2.1 Idea ARasterize the shapefile to a raster file, and then check.
I have not done this yet, but I asked one question here and got an answer.
2.2 Idea BI tried to use the poly.contain()scatter point to check the location, but the result was not true.
3. My code based on Idea B:
For example:
- The source data is pt (a pandas Dataframe), which contains 1000 X, Y grids.
- shapefile I already showed the area of study, I want to filter the source data, leaving only a point in this area.
3.1 Preparation
xc1,xc2,yc1,yc2 = 113.49805889531724,115.5030664238035,37.39995194888143,38.789235929357105
lon_grid = np.linspace(x_map1,x_map2,38)
lat_grid = np.linspace(y_map1,y_map2,32)
3.1 Preparation
xx = lon_grid[pt.X.iloc[:].as_matrix()]
yy = lat_grid[pt.Y.iloc[:].as_matrix()]
sh = (len(xx),2)
data = np.zeros(len(xx)*2).reshape(*sh)
for i in range(0,len(xx),1):
data[i] = np.array([xx[i],yy[i]])
map = Basemap(llcrnrlon=x_map1,llcrnrlat=y_map1,urcrnrlon=x_map2,\
urcrnrlat=y_map2)
map.readshapefile('/xx,'xx')
3.2 Testpatches=[]
for info, shape in zip(map.xxx_info, map.xxx):
x,y=zip(*shape)
patches.append(Polygon(np.array(shape), True) )
for poly in patches:
mask = np.array([poly.contains_point(xy) for xy in data])
- Then I have a numpy array with a value of 0.1 representing inside / outside.
- Combine the mask in pt ==> pt = pt [[pt.mask == 1]], I can filter the points
But the problem is the use poly,contains_point(xy), I could not get the results consistent with my attempt.
Example of my idea 2sum the value 0.1:
unique, counts = np.unique(mask, return_counts=True)
print np.asarray((unique, counts)).T
> [[0 7]
[1 3]]
http://i4.tietuku.com/7d156db62c564a30.png
3 , .
40
http://i4.tietuku.com/5fc12514265b5a50.png
4.
, .
, :
- polygon ( , , , ).
poly.contains_point(xy) .
2016-01-16
, , , .
., .
c = fiona.open("xxx.shp")
pol = c.next()
geom = shape(pol['geometry'])
poly_data = pol["geometry"]["coordinates"][0]
poly = Polygon(poly_data)
ax.add_patch(plt.Polygon(poly_data))
xx = lon_grid[pt_select.X.iloc[:].as_matrix()]
yy = lat_grid[pt_select.Y.iloc[:].as_matrix()]
sh = (len(xx),2)
points = np.zeros(len(xx)*2).reshape(*sh)
for i in range(0,len(xx),1):
points[i] = np.array([xx[i],yy[i]])
mask = np.array([poly.contains(Point(x, y)) for x, y in points])
ax.plot(points[:, 0], points[:, 1], "rx")
ax.plot(points[mask, 0], points[mask, 1], "ro")
http://i4.tietuku.com/8d895efd3d9d29ff.png