python 掩模mask制作以及绘图

依据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')

在这里插入图片描述

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值