使用 rasterio 将矩阵写入光栅文件时出错
An error while writing matrix into a raster file with rasterio
原来的两个数据集是两个.tiff 图像文件,具有相同的坐标、高度、宽度和变换信息(假设为data1 和data2)。我需要对它们进行简单的数学计算,但它们都有空值,所以我首先使用 masked=True:
new1 = data1.read(1,masked=True)
new2 = data2.read(1,masked=True)
然后算一下:
target = new1 - new2
当我得到目标时,我尝试如下代码:
target.width
target.height
target.transform
target.crs
他们都return同样的错误:
'MaskedArray' object has no attribute 'xxx'(xxx represents all the attribute above: width, height, etc.)
似乎目标在数学运算后丢失了所有信息,我需要将这个新结果写入一个新的光栅文件,我应该怎么做才能解决?
当使用数据集的 read
方法时,它将 return 一个 numpy 数组(在你的情况下被屏蔽)。
numpy 数组不是栅格数据集,因此它没有这些属性。
要将其写入磁盘,您需要创建一个新的配置文件(或复制源数据集)并使用 rasterio.open
创建一个新的光栅文件:
profile = data1.profile
band_number = 1
# to update the dtype
profile.update(dtype=target.dtype)
with rasterio.open('raster.tif', 'w', **profile) as dst:
dst.write(target, band_number)
有关更详细的示例,请参阅 docs
原来的两个数据集是两个.tiff 图像文件,具有相同的坐标、高度、宽度和变换信息(假设为data1 和data2)。我需要对它们进行简单的数学计算,但它们都有空值,所以我首先使用 masked=True:
new1 = data1.read(1,masked=True)
new2 = data2.read(1,masked=True)
然后算一下:
target = new1 - new2
当我得到目标时,我尝试如下代码:
target.width
target.height
target.transform
target.crs
他们都return同样的错误:
'MaskedArray' object has no attribute 'xxx'(xxx represents all the attribute above: width, height, etc.)
似乎目标在数学运算后丢失了所有信息,我需要将这个新结果写入一个新的光栅文件,我应该怎么做才能解决?
当使用数据集的 read
方法时,它将 return 一个 numpy 数组(在你的情况下被屏蔽)。
numpy 数组不是栅格数据集,因此它没有这些属性。
要将其写入磁盘,您需要创建一个新的配置文件(或复制源数据集)并使用 rasterio.open
创建一个新的光栅文件:
profile = data1.profile
band_number = 1
# to update the dtype
profile.update(dtype=target.dtype)
with rasterio.open('raster.tif', 'w', **profile) as dst:
dst.write(target, band_number)
有关更详细的示例,请参阅 docs