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

2024-06-26 13:40:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是rasterio示例模块,坐标列表只有3个随机点,但只有第2个在光栅边界内:

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

问题是-为了涵盖我需要在这个循环中写的所有可能性更多的条件,tere是让用户知道给定点超出光栅的更好方法吗


Tags: andofsample列表光栅elementcoordsout
2条回答

^{}提供一个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]

我能想到的最短的一段代码。这类似于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}")

相关问题 更多 >