Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting raster cells equal to zero to no data in Rasterio

Given a random raster tif file, I want to set all cells which have a value of 0, to 'no data' using Python/rasterio. I just cant seem to find documentation about this simple operation.

import rasterio

src = rasterio.open('some_grid.tif')
...........

With R's raster package, with which I'm way more literate, I would perform this operation like this:

library(raster)

rast <- raster('some_grid.tif')
rast[rast == 0] <- NA
like image 267
mcdesign Avatar asked Jan 27 '23 05:01

mcdesign


1 Answers

Similar syntax in Python, first read in the tif file to a numpy array. array==0 produces a boolean array, which can then be used as an index mask for setting the desired values to NAN.

import rasterio
import numpy as np

with rasterio.open('some_grid.tif') as src:
    array = src.read(1)

array[array==0] = np.nan
like image 179
Christoph Rieke Avatar answered Feb 21 '23 05:02

Christoph Rieke