Check if GeoTIFF Spatial Reference is Geodetic with GDAL

Answered using GPT-4o by GPT4oMini.app

Question:

In python, how to check whether the spatial reference of a geotiff is geodetic or not? Please use gdal only, not rasterio or pyproj

Answer:

To check whether the spatial reference of a GeoTIFF is geodetic using GDAL in Python, you can follow these steps:

  1. Open the GeoTIFF file using GDAL.
  2. Retrieve the spatial reference information.
  3. Check if the spatial reference is geodetic.

Here's a sample code to achieve this:

from osgeo import gdal, osr

def is_geodetic(filepath):
    # Open the GeoTIFF file
    dataset = gdal.Open(filepath)
    if not dataset:
        raise FileNotFoundError(f"Unable to open file: {filepath}")

    # Get the spatial reference
    projection = dataset.GetProjection()
    if not projection:
        raise ValueError("No projection information found in the file.")

    srs = osr.SpatialReference()
    srs.ImportFromWkt(projection)

    # Check if the spatial reference is geodetic
    return srs.IsGeographic()

# Example usage
filepath = 'path/to/your/geotiff.tif'
if is_geodetic(filepath):
    print("The spatial reference is geodetic.")
else:
    print("The spatial reference is not geodetic.")

Explanation:

  1. Open the GeoTIFF file: The gdal.Open(filepath) function is used to open the GeoTIFF file.
  2. Retrieve the spatial reference: The GetProjection() method retrieves the projection information in WKT (Well-Known Text) format.
  3. Check if the spatial reference is geodetic: The osr.SpatialReference class is used to parse the WKT projection. The IsGeographic() method returns True if the spatial reference system is geographic (geodetic), and False otherwise.

Make sure you have the GDAL library installed in your Python environment. You can install it using pip if you haven't already:

pip install gdal

This code will help you determine whether the spatial reference of a given GeoTIFF file is geodetic or not.