依据shp文件生成范围内特定精度的mask
import shapefile
import shapely.geometry as sgeom
import numpy as np
import numpy.ma as npm
filepath = './地理数据/guangdong.shp'
file = shapefile.Reader(filepath)#读取
#获取地理坐标范围 左下 经纬度 右上经纬度
file.bbox
此处为地理坐标 若是投影坐标 可以线删除投影
#生成经纬度范围内的 精度为0.25°的网格 (可适当扩大)
x = np.arange(file.bbox[0],file.bbox[2],0.25)
y = np.arange(file.bbox[1],file.bbox[3],0.25)
x, y = np.meshgrid(x, y)
#生成False矩阵
mask = np.zeros(x.shape, dtype=bool)
# 判断每个点是否落入polygon, 不包含边界.
filepath = './地理文件/guangdong.shp'
with shapefile.Reader(filepath) as reader:
guangdong = sgeom.shape(reader.shape(0))
for index in np.ndindex(x.shape):
#在每个网格上生成一个点
point = sgeom.Point(x[index], y[index])
#如果网格上的点包含在shp范围内,则保持原值,否则赋值为True
if guangdong.contains(point):
mask[index] = False
else :
mask[index] = True
#由于plt.imshow 默认origin 为 'upper' 改为lower 即y轴从下往上画
plt.imshow(mask,origin='lower')
data_m = np.ones(mask.shape)
#mask False的地方为掩模内部 True为掩模外部
arr = npm.array(data_m, mask=mask)
plt.imshow(arr,origin='lower')