3

The following code reads in several .tif files from an input folder, converts them to numpy arrays and adds them together. All input files are binary:

inputFolder = "/home/usr/Desktop/BufferFolder/"
outputFolder = "/home/usr/Desktop//BufferFolder/Addition"
template = gdal.Open("/home/usr/Desktop//BufferFolder/Template.tif")
rows = template.RasterYSize 
cols = template.RasterXSize
if template is None: 
print 'Unable to open template file' 
    sys.exit(1) 
templateArray = np.array(template.GetRasterBand(1).ReadAsArray())  
mainArray = 0 * templateArray

os.chdir(inputFolder)

def findRasters(path, filter):
    for root, dirs, files in os.walk(path, filter):
        for file in fnmatch.filter(files, filter):
            yield os.path.join(root, file)

count = 0 
for raster in findRasters(inputFolder, '*.tif'):
    (infilepath, infilename) = os.path.split(raster)
    openraster = gdal.Open(infilename)
    rasterToArray = np.array(openraster.GetRasterBand(1).ReadAsArray())
    mainArray = mainArray + rasterToArray 
    count = count + 1 

I am interested in the 0 values from mainArray. How can I output these values into a separate raster in the outputFolder?

1

1 Answer 1

3

Below should work. The key part is the assignment d[(mainArray == 0)] = 0 setting all the items to zero in a new array where mainArray is zero. Sounds like your rasters might be spatial so the projection setting stuff is important too.

#
# ----- create output raster
#
outfilename = outputFolder + '/zeros.tif'
driver = gdal.GetDriverByName("GTiff")
output = driver.Create(outfilename, cols, rows, 1, gdal.GDT_Byte)
if output is None:
    sys.exit("Unable to create raster " + outfilename)

#
# ----- set output projection to the same as the template
#
output.SetGeoTransform(template.GetGeoTransform())
output.SetProjection(template.GetProjection())

#
# ----- create output array of all ones to match the template
#
d = np.ones((rows, cols), np.uint8)

#
# ----- change 1 to 0 in output array where mainArray is 0
#
d[(mainArray == 0)] = 0

print "Number of zeros in mainArray = %d" % (mainArray == 0).sum()
print "Number of zeros in output array = %d" % (d == 0).sum()

#
# ----- write and close output file
#
output.GetRasterBand(1).WriteArray(d)
output = None
1
  • 1
    Thanks for your answer. I used your code with the following modification" d[(mainArray != 0)] = 0 and I got what I wanted
    – ELD
    Feb 12, 2016 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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