Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Set any pixels adjacent to a nodata pixel to nodata
#!/usr/bin/env python
import numpy
import sys
import gdal
def cleanup_edges(source, nodata_value, mask_filename="mask.tiff"):
band_data = source.GetRasterBand(1).ReadAsArray()
y_size, x_size = band_data.shape
print y_size, x_size
mask = numpy.zeros(shape=(y_size, x_size), dtype=bool)
for y in range(0, y_size):
print y
for x in range(0, x_size):
adjacent_nodata_count = 0
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if x + dx < 0 or x + dx >= x_size - 1 or y + dy < 0 or y + dy >= y_size - 1:
continue
if band_data[y + dy, x + dx] == nodata_value:
adjacent_nodata_count += 1
if adjacent_nodata_count > 0:
mask[y, x] = True
if mask_filename:
driver = gdal.GetDriverByName('GTIFF')
driver.Register()
output = driver.CreateCopy(mask_filename, source, 0)
outBand = output.GetRasterBand(1)
output.GetRasterBand(1).SetNoDataValue(0)
outBand.WriteArray(mask, 0, 0)
output.FlushCache()
result = numpy.ma.fix_invalid(band_data, mask=mask, copy=True, fill_value=nodata_value).filled(fill_value=nodata_value)
return result
def _main():
in_file = sys.argv[1]
out_file = sys.argv[2]
source = gdal.Open(in_file)
cleaned = cleanup_edges(source, source.GetRasterBand(1).GetNoDataValue())
# Register driver
driver = gdal.GetDriverByName('GTIFF')
driver.Register()
# Get source metadata
gt = source.GetGeoTransform()
proj = source.GetProjection()
cols = source.RasterXSize
rows = source.RasterYSize
bands = source.RasterCount
band = source.GetRasterBand(1)
datatype = band.DataType
# Create output image
output = driver.Create(out_file, cols, rows, bands, datatype)
output.SetGeoTransform(gt)
output.SetProjection(proj)
# Get band from newly created image
outBand = output.GetRasterBand(1)
outBand.SetNoDataValue(source.GetRasterBand(1).GetNoDataValue())
# Write to file
outBand.WriteArray(cleaned, 0, 0)
if __name__ == "__main__":
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment