【问题标题】:An error while writing matrix into a raster file with rasterio使用 rasterio 将矩阵写入光栅文件时出错
【发布时间】:2020-10-15 06:45:25
【问题描述】:

原始的两个数据集是两个 .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

它们都返回相同的错误:

'MaskedArray' object has no attribute 'xxx'(xxx represents all the attribute above: width, height, etc.)

似乎目标在数学后丢失了所有信息,我需要将这个新结果写入一个新的光栅文件,我应该怎么解决?

【问题讨论】:

    标签: python gis tiff rasterio


    【解决方案1】:

    当使用数据集的 read 方法时,它将返回一个 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

    【讨论】:

    • 谢谢回复,方法是正确的,但是还有一个问题是过程中存在数据类型问题(dtype),data1是float32目标是int64,有没有转移方式?
    • 您的个人资料应该与您的数据相符。您可以更新配置文件的 dtype 或转换 numpy 数组 dtype。请参阅上面的编辑。这是文档的第一个示例。花点时间阅读那里,你会很容易理解
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多