英文:
Update raster values using Python
问题
我试图读取一个栅格文件。这是一个32位浮点栅格,其中的值要么是1,要么是无数据。我想将值为1的更新为10,然后再次写出它(可能作为UNIT8数据类型)。以下是我的尝试:
import rioxarray
import numpy
my_rast = rioxarray.open_rasterio("my_file.tif", masked=True, cache=False)
my_rast[numpy.where(my_rast == 1)] = 10
my_rast.rio.set_nodata(255)
my_rast.rio.to_raster("output.tif", compress='lzw', num_threads='all_cpus', tiled=True,
dtype='uint8', driver="GTiff", predictor=2, windowed=True)
然而,第四行似乎永远无法完成(可能是因为它是一个相当大的栅格?)。我不确定我做错了什么。
这是print(my_rast)
的结果:
<xarray.DataArray (band: 1, y: 1140, x: 1053)>
[1200420 values with dtype=float64]
Coordinates:
* band (band) int64 1
* x (x) float64 9.412 9.412 9.412 9.413 ... 9.703 9.704 9.704 9.704
* y (y) float64 47.32 47.32 47.32 47.32 ... 47.0 47.0 47.0 47.0
spatial_ref int64 0
Attributes:
AREA_OR_POINT: Area
scale_factor: 1.0
add_offset: 0.0
英文:
I'm trying to read in a raster file. It's a 32-bit float raster, with either values 1 or no data. I want to update the values of 1 to 10, and write it out again (probably as a UNIT8 data type?). Here is my attempt:
import rioxarray
import numpy
my_rast = rioxarray.open_rasterio("my_file.tif", masked=True, cache=False)
my_rast[numpy.where(my_rast == 1)] = 10
my_rast.rio.set_nodata(255)
my_rast.rio.to_raster("output.tif", compress='lzw', num_threads='all_cpus', tiled=True,
dtype='uint8', driver="GTiff", predictor=2, windowed=True)
However the fourth line never seems to finish (maybe as it's a fairly large raster?). I'm not sure what I'm doing wrong.
Here is the result of print(my_rast)
:
<xarray.DataArray (band: 1, y: 1140, x: 1053)>
[1200420 values with dtype=float64]
Coordinates:
* band (band) int64 1
* x (x) float64 9.412 9.412 9.412 9.413 ... 9.703 9.704 9.704 9.704
* y (y) float64 47.32 47.32 47.32 47.32 ... 47.0 47.0 47.0 47.0
spatial_ref int64 0
Attributes:
AREA_OR_POINT: Area
scale_factor: 1.0
add_offset: 0.0
答案1
得分: 1
无法像这样使用3D位置索引:
my_rast[numpy.where(my_rast == 1)] = 10
而应该使用 xarray.DataArray.where
:
my_rast = my_rast.where(my_rast != 1, 10)
在xarray中,当提供类似数组的对象作为索引时,索引的工作方式与numpy略有不同 - 值得阅读关于向量化索引和更高级的索引的文档。
英文:
You can’t use a 3D positional index like this:
my_rast[numpy.where(my_rast == 1)] = 10
Instead, use xarray.DataArray.where
:
my_rast = my_rast.where(my_rast != 1, 10)
Indexing in xarray works slightly differently from numpy when providing array-like objects as indices - it’s worth giving the docs on Vectorized Indexing and More Advanced Indexing a read.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论