微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何引发坐标超出光栅范围的错误 (rasterio.sample)?

如何解决如何引发坐标超出光栅范围的错误 (rasterio.sample)?

我正在使用光栅示例模块,list_of_coords 只是 3 个随机点,但只有第 2 个在光栅边界内:

list_of_coords = [(754.2,4248548.6),(754222.6,(54.9,4248548.4)]
sample = np.array(list(Rasterio.sample.sample_gen(raster,list_of_coords))).flatten() 

输出

[  0 896   0]

效果很好,但正如您所看到的,如果坐标超出光栅图像,它的值为 0。有没有办法让用户知道他们放入列表中的坐标超出了光栅范围? 0 也可以是存在于栅格边界点内的值,如此简单的循环:

for idx,element in enumerate(sample):
    if element == 0:
        print(f"coords {a[idx]} out of raster")

不是一个好的解决方案。 这是我目前想到的:

了解有关地理坐标系和栅格边界的基本信息后,我们可以写下一些“规则”。使用 raster.bounds 我为我的光栅得到了 bBox 并且我写了一个更好的循环:

for idx,element in enumerate(a):
    if element[0] > 0 and band2.bounds.right > 0 and element[0] > band2.bounds.right\
       or element[0] > 0 and band2.bounds.left > 0 and element[0] < band2.bounds.left: #more conditions
       print(f"coords {a[idx]} out of raster")

输出(正确):

coords (754.6,4248548.6) out of raster
coords (54.6,4248548.6) out of raster

问题是 - 为了涵盖我需要以这种循环方式编写更多条件的所有可能性,是否有更好的方法用户知道给定点不在光栅范围内?

解决方法

rasterio.sample.sample_gen 提供一个 masked 参数。当 True 时,它根据栅格数据集的边界框产生 Masked arrays

>>> import rasterio
>>> ds = rasterio.open("raster.tif")
>>> ds.bounds
BoundingBox(left=-0.0001388888888888889,bottom=40.999861111111116,right=1.000138888888889,top=42.00013888888889)
>>> # Inside bbox
>>> next(rasterio.sample.sample_gen(ds,((0.5,41.5),),masked=True))
masked_array(data=[130],mask=False,# <= No mask (ndim=0)
       fill_value=999999,dtype=int16)
>>> # Outside bbox
>>> next(rasterio.sample.sample_gen(ds,((0,0),masked=True))
masked_array(data=[0],mask=[False],# <= Mask ndim=1
       fill_value=999999,dtype=int16)

当坐标超出光栅边界时,它们使用 None 转换为 python 列表:

>>> [None if x.mask.ndim == 1 and not x.mask[0] else x[0]
...  for x in rasterio.sample.sample_gen(ds,(0,0)),masked=True)]
[130,None]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。