1

When I open a raster stack with GDAL and call it as a numpy array, lines with 'no data values' also appear. Since I do not want to include these 'no data values' (mine is 128) in the calculations I will make, I am looking for a way to prevent.

Is there a way to prevent 'no data values' from getting into numpy arrays when opening the raster stack? Or what would you recommend?

My codes are here:

outvrt = ('result/raster_stack_vrt.tif')
outtif = ('result/raster_stack.tif')
tifs = glob.glob('data/*.tif')
outds = gdal.BuildVRT(outvrt, tifs, separate = True)
outds = gdal.Translate(outtif, outds)
Lilium
1,0651 gold badge8 silver badges17 bronze badges
asked Mar 19, 2022 at 19:02

2 Answers 2

0
> import rasterio 
> import numpy as np

You can create a mask with numpy:

  1. Open the raster like a numpy array then run this code and plot the raster.

Blockquote

raster = rasterio.open(inputpath_raster)
raster = raster.read(1)
value = 0
raster = raster.astype('float32') # You can change the format
raster_copy = copy.copy(raster)
raster_copy[raster == value] = np.nan # Value equal 'nan value'
raster_copy[raster > value] = 1
raster_nan = raster_copy * raster

The process is something like this, I think you have to repeat the process por each band in your stack

enter image description here

answered Mar 19, 2022 at 23:12
1
  • No data value is 128 Commented Jun 4, 2023 at 11:12
0

The most efficient way to do this is with numpy and masked arrays:

import numpy as np
import rasterio as rio
src = rio.open(file.tif)
arr = src.read(1)
masked_arr = np.where(arr==128, np.nan, arr)

Then you can treat the array as you usually would when dealing with nan values. You can mask the array if you like:

https://numpy.org/devdocs/reference/maskedarray.generic.html

But if your calculations are simple you could use the numpy built in nan calculations:

numpy.nanmean(masked_arr)
answered Jun 4, 2023 at 11:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.