python - 如何引发坐标超出栅格边界(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
问题是 - 为了涵盖我需要以这种循环方式编写更多条件的所有可能性,是否有更好的方法让用户知道给定点超出了栅格?
解决方案
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]
推荐阅读
- python - 如何在 discord.py 中添加条件冷却?
- augmented-reality - 此应用程序需要在虚幻游戏中使用最新版本的arcore
- python - 尽管定义了变量,但出现名称未定义错误
- mysql - MySQL 中的递归查询(找到 Bob 的直接和间接主管)?
- html - SVG 动画圆圈垂直和水平居中
- python - 为什么使用 `as_index=False` 的 `groupby` 甚至比使用 `reset_index` 的 `groupby` 还要慢
- f# - 在 F# Akka.Net 中区分远程参与者之间的联合
- android - 如何使用NFC标签直接打开APP安卓
- scala - 有没有更好的方法来测试 Scala 中的泛型类型(没有类型参数)?
- docker - 在视频下载器中使用 ffmpeg 时出错:'ERR: spawn ./db/ffmpeg ENOENT'