I have a raster data and i want to set the 0 value pixels to NoData using GDAL in python API.

I know that you can do this by inputting this code in the command prompt.

gdal_translate -of GTiff -a_nodata 0 input.tif output.tif

but can anyone translate this so that i can put it in a Python API?

  • 2
    A bit unclear what you mean, but you can gdal.Translate("output.tif", "input.tif", format="GTiff", noData=0) is equivalent to your command.
    – Jose
    Sep 10 at 11:04
  • Hello @Jose. Thanks for this, this is exactly what I needed. Sep 11 at 8:42

I would recommend to use gdal_edit.py script https://gdal.org/programs/gdal_edit.html or study the code and re-use in your own script.

-a_nodata <value>
Assign a specified nodata value to output bands.

Gdal_translate creates a new copy from your tif while gdal_edit updates just the GeoTIFF metadata in-place.

  • Hello. Thank you for this, this may be a better alternative to gdal.translate. May I ask how to do this code in a python API? Im sorry, im terrible in translating code from command line to python api. Thank you so much! Sep 11 at 10:29

You can do this with rasterio (GDAL python wrapper) using r+ mode:

import rasterio

with rasterio.open(file, 'r+') as rds:
    rds.nodata = 0
  • Hello! Thank you for this. Will try it out. Sep 11 at 10:29

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.