Python – Subtracting Raster from Number Using Rasterio

pythonrasterio

How can I subtract a raster from a constant value using Rasterio?

I see many posts on how to subtract two rasters but not on subtracting a raster from a constant value.

What I have tried:

import rasterio as rio
with rio.open("final_elevation.tif", masked=True) as src:
   dem = src.read(1)
   # image_read_masked = np.ma.masked_array(dem, mask=(dem == -9999))
   depth = -dem + 100

The results will generate an incorrect output. For example, no data values are now 100 + 9999

An example raster is here

Best Answer

Just use the mask to reset the nodata. Don't forget to read the data as masked, not when you open the dataset.

import rasterio as rio

with rio.open("final_flood_elevation.tif") as src:
   dem = src.read(1, masked=True)
   profile = src.profile

depth = 100 - dem
depth[depth.mask] = profile["nodata"]

with rio.open("final_flood_elevation_calc.tif", 'w', **profile) as dst:
   dst.write(depth, 1,)
Related Question