# coding=utf-8
'''
本程序实现shp文件范围内的格点选取
'''
import numpy as np
import shapefile
import shapely.geometry as geometry
from shapely.geometry import Polygon
from shapely.ops import cascaded_union
import matplotlib.pyplot as plt
shp = shapefile.Reader(r'DTool\dishi.shp')
rec = shp.shapeRecords()
polygon = []
for r in rec:
polygon.append(Polygon(r.shape.points)) # 获取各个地市点边界
poly = cascaded_union(polygon) # 并集
ext = list(poly.exterior.coords) # 外部点,即最外面轮廓(省界)
x = [i[0] for i in ext]
y = [i[1] for i in ext]
plt.plot(x, y, 'r')
lon = np.linspace(72.25, 135.75, 128)
lat = np.linspace(18.25, 53.75, 72)
grid_lon, grid_lat = np.meshgrid(lon, lat)
flat_lon = grid_lon.flatten() # 将坐标展成一维
flat_lat = grid_lat.flatten() # 将坐标展成一维
plt.scatter(flat_lon, flat_lat)
flat_points = np.column_stack((flat_lon, flat_lat)) # 拼接成二维点
in_shape_points = []
for pt in flat_points:
if geometry.Point(pt).within(geometry.shape(poly)): # 判断点是否在多边形内
in_shape_points.append(pt)
sel_lon = [elem[0] for elem in in_shape_points]
sel_lat = [elem[1] for elem in in_shape_points]
plt.scatter(np.array(sel_lon), np.array(sel_lat), c='g')
plt.show()
或用函数表示
import numpy as np
import shapefile
import shapely.geometry as geometry
from shapely.geometry import Polygon
from shapely.ops import cascaded_union
import matplotlib.pyplot as plt
# 用函数表示
def mask_grid(shp, ilon, ilat): # 本函数实现shp文件范围内的格点选取
shp = shapefile.Reader(shp)
rec = shp.shapeRecords()
polygon = []
for r in rec:
polygon.append(Polygon(r.shape.points)) # 获取各个地市点边界
poly = cascaded_union(polygon) # 并集
# ext = list(poly.exterior.coords) # 外部点,即最外面轮廓(省界)
# x = [i[0] for i in ext]
# y = [i[1] for i in ext]
# plt.plot(x, y, 'r')
# 提取边界内格点
grid_lon, grid_lat = np.meshgrid(ilon, ilat)
flat_lon = grid_lon.flatten() # 将坐标展成一维
flat_lat = grid_lat.flatten() # 将坐标展成一维
plt.scatter(flat_lon, flat_lat)
flat_points = np.column_stack((flat_lon, flat_lat)) # 拼接成二维点
in_shape_points = []
for pt in flat_points:
if geometry.Point(pt).within(geometry.shape(poly)): # 判断点是否在多边形内
in_shape_points.append(pt)
sel_lon = [elem[0] for elem in in_shape_points]
sel_lat = [elem[1] for elem in in_shape_points]
plt.scatter(np.array(sel_lon), np.array(sel_lat), c='g')
plt.show()
return sel_lon, sel_lat
# -*- coding: utf-8 -*-
'''
本程序实现按shp文件掩膜提取
'''
import shapefile
import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import matplotlib.pyplot as plt
from shapely.geometry import Polygon
from shapely.ops import cascaded_union
shp = shapefile.Reader('dishi.shp')
rec = shp.shapeRecords()
polygon = []
for r in rec:
polygon.append(Polygon(r.shape.points))
poly = cascaded_union(polygon) # 并集
ext = list(poly.exterior.coords) # 外部点
codes = [Path.MOVETO] + [Path.LINETO] * (len(ext) - 1)
codes += [Path.CLOSEPOLY]
ext.append(ext[0])
path = Path(np.array(ext), codes)
patch = PathPatch(path, facecolor='None')
fig, ax = plt.subplots()
ax.add_patch(patch)
sample_data = np.random.rand(100, 100)
x = np.linspace(112.8, 119, 100)
y = np.linspace(24, 30.5, 100)
qs = plt.contourf(x, y, sample_data)
for col in qs.collections:
col.set_clip_path(patch)
plt.show()
def inpolygon(path_shp, pre_arge):
'''
:param path_shp: shp file
:param pre_arge: 全国站点降水数据
:return: shp内的站点经纬度和降水量
'''
lon, lat = pre_arge[2, 3::], pre_arge[1, 3::]
points = np.vstack([lon, lat]).T
shp_df = geopandas.GeoDataFrame.from_file(path_shp)
in_shape_points = []
in_shape_data = np.zeros([np.size(pre_arge, 0), np.size(pre_arge, 1)])
for index, pt in enumerate(points):
pnts = Point(pt)
for i in range(len(shp_df)):
if pnts.within(shp_df.iloc[i]['geometry']):
in_shape_points.append(pt)
in_shape_data[:, index] = pre_arge[:, index + 3] # 数据前三列为年月日,因此后退3列
in_shape_points = np.array(in_shape_points)
idx = np.argwhere(np.all(in_shape_data[:, :] == 0, axis=0))
in_shape_data = np.delete(in_shape_data, idx, axis=1)
in_shape_data = np.hstack([pre_arge[:, 0:3], in_shape_data])
return in_shape_points, in_shape_data