我正在使用栅格示例模块,list_of_coords 只是 3 个随机点,但只有第二个在栅格范围内:
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
问题是 - 为了涵盖我需要在此循环中编写更多条件的所有可能性,是否有更好的方法让用户知道给定点超出了栅格?
最佳答案
rasterio.sample.sample_gen
提供一个屏蔽
参数。当 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]
关于python - 如何引发坐标超出栅格范围(rasterio.sample)的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67893343/