【问题标题】:How to raise an error that coordinates are out of raster bounds (rasterio.sample)?如何引发坐标超出栅格边界(rasterio.sample)的错误?
【发布时间】:2026-02-14 14:55:01
【问题描述】:

我正在使用 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

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

【问题讨论】:

  • 你想让事情停下来吗?你可以说raise ValueError(f"coords {a[idx]} out of raster")
  • @TimRoberts 不,我正在处理空间数据,我想知道是否有一种有效的方法(比我的解决方案更好)向用户提供列表中给出的坐标超出栅格的信息界限。因此,例如,我的栅格边界是 (x1 = 2, x2=6, y1 = 3, y2 = 7),用户给出点 (100,100) 的坐标。那一点不在光栅范围内,我正在尝试找到一种方法来通知用户。在这种情况下,光栅示例模块返回值 0,但这不好(因为如果光栅图像的值是 0-255)0 在那个范围内。

标签: python geospatial spatial sentinel rasterio


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我能想到的最短的代码。类似于sample 函数检查屏蔽https://github.com/mapbox/rasterio/blob/master/rasterio/sample.py#L46

    def sample_or_error(raster_file, x, y):
        with rasterio.open(raster_file) as src:
            row, col = src.index(x, y)
            if any([row < 0, col < 0, row >= src.height, col >= src.width]):
                raise ValueError(f"({lon}, {lat}) is out of bounds from {src.bounds}")
    

    【讨论】:

      最近更新 更多