使用Python更新栅格数值

huangapple go评论63阅读模式
英文:

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(&quot;my_file.tif&quot;, masked=True, cache=False)
my_rast[numpy.where(my_rast == 1)] = 10
my_rast.rio.set_nodata(255)
my_rast.rio.to_raster(&quot;output.tif&quot;, compress=&#39;lzw&#39;, num_threads=&#39;all_cpus&#39;, tiled=True, 
dtype=&#39;uint8&#39;, driver=&quot;GTiff&quot;, 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):

&lt;xarray.DataArray (band: 1, y: 1140, x: 1053)&gt;
[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.

huangapple
  • 本文由 发表于 2023年2月24日 07:00:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定