Search code examples
pythonarraysimagemultidimensional-arraygdal

How to read multiband image files with more than 4 bands in python?


I am using the following code to read geotiff images (~300). Each image file contains 15 bands.

code:

import gdal
inputPath="/content/drive/MyDrive/Notebook/test/tiled_stack"
images = []
# Load in the images
for filepath in os.listdir(inputPath):
    images.append(gdal.Open(inputPath+'/{0}'.format(filepath)))
    image = images.ReadAsArray()

print(type(images[1])) 

error:

AttributeError: 'list' object has no attribute 'ReadAsArray'

Another code from this link:

myImages= glob.glob(os.path.join(inputPath, '*.tif'))
for data_path in myImages:
  images=gdal.Open(data_path, gdal.GA_ReadOnly)

type(images)
osgeo.gdal.Dataset

How can I modify the code to resolve the error and have images in form of (width, height, number of bands)?


Solution

  • You may read the image using GDAL as described in the following post.

    Example:

    import gdal
    
    filepath = r'c:\Tmp\ds\images\remote_sensing\otherDatasets\sentinel_2\tif\Forest\Forest_1.tif'
    
    # https://stackoverflow.com/questions/43684072/how-to-import-multiple-bands-from-an-image-into-numpy
    # Load one GeoTIFF image using GDAL
    dataset = gdal.Open(filepath)
    image = dataset.ReadAsArray()
    
    print(type(image))  # <class 'numpy.ndarray'>
    print(image.shape)  # (13, 64, 64)
    print(image.dtype)  # uint16
    

    Installing GDAL in Windows is not so straight forward.

    I started working by the following instructions, but it's not up to date.

    I downloaded gdal-204-1911-x64-core.msi and GDAL-2.4.4.win-amd64-py3.6.msi (matches Python 3.6) from here.

    I updated the environment variables with C:\Program Files opposed to C:\Program Files (x86) (as described in the instructions).

    For some reason it's working only when I Run the Python script, but gives an error when I Debug the script.


    Update:

    images is a Python list.
    You can't use images.ReadAsArray(), because Python list has no method ReadAsArray().

    You may append an image to the list after executing image = dataset.ReadAsArray() - you have to call the method for every image, and can't apply it to the list.

    Example:

    import gdal
    
    inputPath="/content/drive/MyDrive/Notebook/test/tiled_stack"
    images = []
    
    # Load the images, and append them to a list.
    for filepath in os.listdir(inputPath):
        dataset = gdal.Open(inputPath+'/{0}'.format(filepath))
        image = dataset.ReadAsArray()  # Returned image is a NumPy array with shape (13, 64, 64) for example.
        images.append(image)  # Append the NumPy array to the list.
        
    print(type(images[1]))