[Python] gdal_array can't be imported in Python-GDAL

Discussão em 'Python' iniciado por Stack, Abril 27, 2025.

  1. Stack

    Stack Membro Participativo

    Ok, so, I'm trying to process some .bil files in Debian 12 I installed GDAL using:

    sudo apt install gdal-bin sudo apt-get install libgdal-dev

    And ogrinfo --version outputs:

    GDAL 3.6.2, released 2023/01/02

    Then I create a virtual environment (Python 3.11.2), activate it and install numpy, gdal. When I run this code:

    from osgeo import gdal
    import matplotlib.pyplot as plt
    import numpy as np

    # Register the EHdr driver (for handling header files)
    gdal.GetDriverByName('EHdr').Register()

    # Open the BIL file
    filename = 'my_file.bil'
    dataset = gdal.Open(filename)

    # Read the raster band (assuming single band)
    band = dataset.GetRasterBand(1)
    data = band.ReadAsArray()
    # Display the data
    plt.imshow(data, cmap='gray') # Adjust cmap as needed
    plt.colorbar()
    plt.show()


    This piece of code data = band.ReadAsArray() Raises the error (full trace):

    Traceback (most recent call last):
    File "/test.py", line 16, in <module>
    data = band.ReadAsArray()
    ^^^^^^^^^^^^^^^^^^
    File "/venv/lib/python3.11/site-packages/osgeo/gdal.py", line 4148, in ReadAsArray
    from osgeo import gdal_array
    File "/venv/lib/python3.11/site-packages/osgeo/gdal_array.py", line 13, in <module>
    from . import _gdal_array
    ImportError: cannot import name '_gdal_array' from 'osgeo' (venv/lib/python3.11/site-packages/osgeo/__init__.py)


    Things I've tried:

    • Conda: this was my first choice but I never managed to get it to work, that's why I'm trying venv / pip
    • Install numpy first and then gdal (pip install gdal==3.6.2)
    • Install using wheels

    Nothing seems to work, always the same error. Now comes the fun part: If I run the code with the default python (no virtual env) the code works!

    After checking, I have installed numpy==1.24.2 systemwide, so I uninstalled numpy (2.25) from my virtual environment and forced to install version 1.24.2 ... still doesn't work.

    Anyone has any ideas on something else to try? Python dependencies are so much fun...

    Continue reading...

Compartilhe esta Página