首页 > 解决方案 > 如何引发坐标超出栅格边界(rasterio.sample)的错误?

问题描述

我正在使用 rasterio 示例模块,list_of_coords 只是 3 个随机点,但只有 2nd 在光栅范围内:

list_of_coords = [(754.2,4248548.6), (754222.6,4248548.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

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

标签: pythongeospatialspatialsentinelrasterio

解决方案


rasterio.sample.sample_gen提供masked论据。当True它根据栅格数据集的边界框产生掩码数组时。

>>> 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.5, 41.5), (0, 0)), masked=True)]
[130, None]

推荐阅读