将栅格上的负值替换为NaN(不首先将其转换为数组)



我想将栅格(tiff)文件的所有负文件替换为无数据值(nan),并将其保存到新文件(也是tiff)中。我不想首先将其转换为numpy数组-我想直接替换光栅本身的像素,例如使用rasterio。

我试了如下:

#Open the file with rasterio
raster_file = rasterio.open(r"path_to_file.tif")
#Read as raster
raster = raster_file.read(1)
#Assign 999 to all negative values
raster[raster <= 0] = 999
#Create a boolean mask
mask_boolean = (raster !=999)
# Write the mask back to the dataset:
raster.write_mask(mask_boolean)
raster.close()

可以使用xarray:

import xarray
# Open the file with xarray
raster_file = xarray.open_dataarray(path, engine="rasterio")
print(raster_file.min().data)
# > - 1
# Assign NaN to negative values
raster_file = raster_file.where(raster_file > 0)
print(raster_file.min().data)
# > 0

你将得到一个用NaN填充的栅格的xarray表示。

然而,你不能改变像素值,你必须把栅格保存回磁盘。

最新更新