Change the Nodata value in a file.

@cratcliff
 

Hi Everyone,

Using RasterIO, what is the correct way to change (or assign if it isn't already set) the no data value for a single or multi band TIF file?

For example using the test rgb.byte.tif file, how do I change the nodata value from 0 to 255?  So far I have tried:
with rasterio.open('RGB.byte.tif') as src:  
bands = src.read(masked=True)
bands.fill_value = 255
# or
# bands.set_fill_value(255)

kwargs = src.meta.copy()
kwargs.update({'nodata': 255})

with rasterio.open('copy.RGB.byte.tif', 'w', **kwargs) as dst:
dst.write(bands)
Currently this only changes tif header/metadata information and not the actual data.

Options I've seen to accomplish this include
# 1. masked arrays
bands = np.ma.masked_values(src.read(masked=True), 255)
dst.write(bands)

# 2. loop through bands and change value
for i in range(1, src.count + 1):
band = src.read(i)
band = np.where(band==0,255,band)
dst.write(bands,i)

# 3. numpy indexing
bands = src.read()
bands[bands==0] = 255
Or should I be using rasterIO's read_mask(), write_mask() or dataset_mask()?

What is the preferred method? I haven't been able to find this in any of the user documentation.

Thanks,

Join main@rasterio.groups.io to automatically receive all group messages.