Big Face
Big Face

Reputation: 53

An error while writing matrix into a raster file with rasterio

The original two datasets are two .tiff image file with same coordinate, height, width and transform information (let's say data1 and data2). I need to perform a simple math on them, but they both have null values, so I first use masked=True:

new1 = data1.read(1,masked=True)
new2 = data2.read(1,masked=True)

Then do the math:

target = new1 - new2

When I get the target, I try codes as below:

target.width
target.height
target.transform
target.crs

They all return the same error:

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

It seems the target loses all the information after math, I need to write this new result into a new raster file, what should I do to solve it?

Upvotes: 1

Views: 1667

Answers (1)

dzang
dzang

Reputation: 2260

When using the read method of a dataset, it will return a numpy array (masked in your case). The numpy array is not a rasterio dataset, so it doesn't have those attributes.

To write it to disk you need to create a new profie (or copy the source dataset one) and use rasterio.open to create a new raster file:

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)

See the docs for a more detailed example

Upvotes: 2

Related Questions