I am attempting to contour a DEM raster using gdal.ContourGenerate().

This is my code:

in_data_set = gdal.Open(TEMP_CROP_DEM_PATH, gdal.GA_ReadOnly)
in1 = in_data_set.GetRasterBand(1)

ogr_ds = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(TEMP_CONTOURS_PATH)
contour_shp = ogr_ds.CreateLayer('contour', dest_srs)

field_defn = ogr.FieldDefn("ID", ogr.OFTInteger)
field_defn = ogr.FieldDefn("elev", ogr.OFTReal)

gdal.ContourGenerate(in1, contour_offset, 0, [], 0, 0, contour_shp, 0, 1)

This code has worked for me on several tests, however it does not work when there is an area of no data in the DEM. When contouring a DEM with no data areas, QGIS freezes on the last line (ContourGenerate) and crashes.

I have looked through the GDAL API and made sure all my arguments are correct. I have tried changing the 5th argument useNoData to 1 and saw no change.

Running in1.GetNoDataValue() also causes QGIS to crash.

I am running out of ideas of where to look to solve my problem. Has anyone come across something similar? Are there other ways to achieve my goal, create vector contours from a DEM in Python?

1 Answer 1


I was able to solve my problem by setting the no data value. I used QgsRasterLayer class to grab the no_data_value. I then changed my arguments on the gdal.ContourGenerate to set useNoData to 1 and set noDataValue to the no_data_value.

The docstring for gdal.ContourGenerate is:

"""ContourGenerate(Band srcBand, double contourInterval, double contourBase,
int fixedLevelCount, int useNoData, double noDataValue, Layer dstLayer,
int idField, int elevField, GDALProgressFunc callback=0,
void * callback_data=None) -> int"""

my final code additions:

layer = QgsRasterLayer(TEMP_CROP_DEM_PATH, 'terrain_temp')
block = layer.dataProvider().block(
no_data_value = block.noDataValue()


gdal.ContourGenerate(in1, contour_offset, 0, [], 1, no_data_value, contour_shp, 0, 1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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