0

I have a folder with 4 .tiff (GeoTiff) files. Each of these contains two layers (the spectral band and a mask). I'm able to create a list containig each image using xarray.open_rasterio.

Now I need to stack the bands of the list into a single DataArray. How can I do this?

# Path of the folder containing the .tiff files
IMG_PATH = 'D:/test_xarray/data/'

import rasterio as rio
import xarray as xr
import numpy as np
from glob import glob

# List of .tiff files
sentinel_bands = glob(f"{IMG_PATH}*B?*.tiff")
sentinel_bands.sort() # sorted list
        
ls_bands = [] # list filled with the first layer of each file
for band in sentinel_bands:
    with xr.open_rasterio(band) as b:
        ls_bands.append(b[0,]) # index 0 corresponds to the first band of each file

# Stack bands into a single DataArray

Data available here https://github.com/syamkakarla98/Satellite_Imagery_Analysis/tree/main/Data/sundarbans_raw_data

2
  • you need a shape of (num_of_images, width, height) right? Commented May 10, 2022 at 14:11
  • using xarray.concat
    – Val
    Commented Nov 9, 2022 at 9:16

2 Answers 2

1

To stack the array into shape (n_image, width, height), you need np.vstack. Check out https://numpy.org/doc/stable/reference/generated/numpy.vstack.html

For 3 bands image e.g RGB you get shape (3,width,height).

Note: width and height must be equal in all arrays.

0

You can try

xr.open_mfdataset('my/files/*.nc', parallel=True)
1
  • Welcome GIS SE. There is an accepted answer, for this question. You can add alternate solutions, but you have to be precise in how your solution can give better outputs. You can get details from here for writing good answers.
    – Padmanabha
    Commented Aug 8, 2023 at 15:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.