比较来自rasterio的两个数组中的值并执行操作

2024-05-16 16:30:48 发布

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

我有一个GeoTIFF,它有两个波段,一个是“precip反射率”(强度)和“precip类型”(雪/雨/等)。我想调整雪的精度值,这样我就可以在最终的地图上对它们进行不同的着色。以下是我目前正在做的和我正在尝试做的。我正在使用的tif可用here

我正在使用光栅加载两个波段,如下所示:

import rasterio


src = rasterio.open("stack.tif")
ref=src.read(1) # This is the precip reflectivity
ptype=src.read(2) # This is the precip type

目前,ref和ptype是两个数组,如下所示(-999是nodata值):

[[-999. -999. -999. ... -999. -999. -999.]
 [-999. -999. -999. ... -999. -999. -999.]
 [-999. -999. -999. ... -999. -999. -999.]
 ...
 [-999. -999. -999. ... -999. -999. -999.]
 [-999. -999. -999. ... -999. -999. -999.]
 [-999. -999. -999. ... -999. -999. -999.]]

我想最终用颜色贴图正确地着色。对于“雪”值(或为ptype键入3),我想在值中添加200以表示雪,对于所有其他值,我想保持值不变

这就引出了我的问题,有没有比较这些值或任何示例的最佳方法


Tags: thesrcrefreadis波段thisgeotiff
1条回答
网友
1楼 · 发布于 2024-05-16 16:30:48

docs中所述,使用光栅读取数据集将返回numpy.ndarray

因此,您可以利用布尔比较来执行以下操作:

import numpy as np
import rasterio

fill_val = -999.0
snow_val = 3

# open original dataset
with rasterio.open("stack.tif") as src:
    ref = src.read(1) # This is the precip reflectivity
    ptype = src.read(2) # This is the precip type
    kwargs = src.meta.copy()

# modify valid `ref` data based on values in the `ptype` layer
ref[np.logical_and(ptype == snow_val, ref != fill_val)] += 200

# write the result to a new raster dataset with same structure
with rasterio.open("stack_modified.tif", "w", **kwargs) as dst:
    dst.write(ref, 1)
    dst.write(ptype, 2)

请注意,不要修改nodata(fill)值很重要,因为这会错误地将它们识别为有效数据

相关问题 更多 >