Arcpy Python – How to Change No-Value Data from 0 to Another Value in Raster

arcpynodatapythonraster

I am using satellite data and by default it has a nodata value of 0 for each band.

This is fine except for when I'm making NDVIs where 0 is a real value we need to include and I don't want it to be classified as nodata.

I want to make sure all the bands/tifs I am working with have the same nodata value. So how do I convert a nodata value of 0 to something else, like -10000.

I was thinking of using arcpy's reclassify tool on my bands changing 0 to -10000 (before I make NDVIs) and then copying the raster with the copyraster tool using the setting for nodata as -10000.

This seems inefficient. Is there a tool that does this better? I'm open to open source libraries or arcpy

Best Answer

You can use gdal and numpy for this. Here is an example that will change all the 0's to -10000's for all the bands in a given set of TIFF files (tha are in the same directory):

import glob
import os

from osgeo import gdal
import numpy as np

os.chdir(r'C:\path\to\raster\files')           # change to directory with the tiff files

filenames = glob.glob('*.tif')

for fn in filenames:
    ds = gdal.Open(fn, 1)                      # pass 1 to modify the raster
    n = ds.RasterCount                         # get number of bands
    for i in range(1, n+1):
        band = ds.GetRasterBand(i)
        arr = band.ReadAsArray()               # read band as numpy array
        arr = np.where(arr == 0, -10000, arr)  # change 0 to -10000
        band.WriteArray(arr)                   # write the new array
        band.SetNoDataValue(-10000)            # set the NoData value
        band.FlushCache()                      # save changes
    del ds

Note that the data type of your TIFF files has to support negative values in order for this to work. Otherwise, the raster won't recognize the -10000 value.

Related Question