1

I'm trying to create a code that would allow me to stack the 10 bands of the same image for different images contained in different folders. I'm trying to create a code that would allow me to stack the 10 bands of the same image for different images contained in different folders. I found a piece of code on the forum from which I try to get inspiration but I can't apply it to my case... The code in question is as follows:

from osgeo import gdal, gdal_array
import numpy as np
b1 = gdal.Open("LT50250232011160PAC01_sr_band1.tif")
b2 = gdal.Open("LT50250232011160PAC01_sr_band2.tif")
array1 = b1.ReadAsArray()
array2 = b2.ReadAsArray()
stacked = np.array([array1,array2])
gdal_array.SaveArray(stacked.astype("int"), "b12_stacked.tif", "GTiff", gdal.Open("LT50250232011160PAC01_sr_band1.tif"))

My code is :

import os
from osgeo import gdal, gdal_array
import numpy as np

src_directory = "/d/afavro/Bureau/test_subset/stack_resample_subset/"
dossier = os.listdir (src_directory)
print(dossier)

for fichier in dossier:
    print (fichier)
    ssrc_directory = "/d/afavro/Bureau/test_subset/stack_resample_subset/" + fichier + "/"
    rasters = os.listdir (ssrc_directory) 
    print(rasters) 

    for img in rasters:
        print (img)

        INPUT_FOLDER = ssrc_directory
        print(INPUT_FOLDER)

        OUTPUT_FOLDER = "/d/afavro/Bureau/test_stack/" + fichier
        print(OUTPUT_FOLDER)
        if not os.path.exists(OUTPUT_FOLDER):
                    os.makedirs(OUTPUT_FOLDER)

        # Define output file name

        if img[-4:-3] == '.' :
            file_img = OUTPUT_FOLDER+'/'+os.path.basename(img[:-4])
        else:
            file_img = OUTPUT_FOLDER+'/'+os.path.basename(img)


        # Stack
       band = gdal.Open(img)
       array = band.ReadAsArray()
       stacked = np.array(array)

       gdal_array.SaveArray(stacked.astype("int"),"stack_" + fichier, "GTiff", prototype = None )

The problem is here, I have the error message :

band = gdal.Open(img)
^
IndentationError: unindent does not match any outer indentation level

I think we need to create an empty matrix or something like that, but I don't really see how, do you have any ideas ?

Axelle
  • 107
  • 1
  • 6
  • The error notification is clear, it's about your indentation for the last 4 lines of code. Add one more space to them if they are inside the `for img in rasters:` loop. – YusufUMS Apr 25 '19 at 08:38
  • Oh yes sorry ! I couldn't see, but there was a mistake... Now I have the following message : AttributeError: 'NoneType' object has no attribute 'ReadAsArray' – Axelle Apr 25 '19 at 08:44

0 Answers0