[GIS] Exporting Raster Attribute Table using Open Source software

attribute-tablegdalopen-source-gisosgeo4wraster

I have 120 or so geotiff files that I'd like to build and export the raster attribute table to something a little more friendly (e.g. csv).

I'm curious if there is an open source way to do this. The files are rather large 36001 X 36001 pixels so brute force solutions may be out. Ideally, I'm looking to do this in gdal commandline/OSGEO4w or Qgis. Grass in a pinch.


Some additions in response to comments:

  • I am somewhat familiar with python. If anyone has a solution in that vein, I'd love to hear it. Same thing goes with R and windows command line.

-The table would look something like this:

Value | # of Cells
0 | 100000
1 | 3214
2 | 25125

98 | 2214213

Basically, I'm looking for a non-ArcGIS way to recreate the ArcGIS raster attribute table. The reason I want CSV is because I have some other mathematical operations I'd like to run, and a csv or some sort of text file works best for my workflow. Its a bit anti-dramatic, but all I really need at this stage is the number of cells for each value in the raster.

Best Answer

Ok, I'm still fuzzy on what exactly your export file is but I'll assume "#of cells" is simply the number of pixes for each raster and "Value" is some identifier for each raster (parse the file name??). In absence of how to get "Value", I just put an incremented variable. This script will require gdal.

import glob
from osgeo import gdal
import numpy as np

def get_raster_data(raster_file_name, band):
    r = gdal.Open(raster_file_name)
    return np.array(r.GetRasterBand(band).ReadAsArray())

fp = open('export.txt', 'w+')
fp.write('Value | # of Cells\n')

#what is Value?? I will just put an incremented number. 
#if Value is the raster number, parse yourself.
val = 1
for fname in glob.glob('*.tif'):
    arr = get_raster_data(fname, 1)
    num_cells = arr.shape[0] * arr.shape[1]
    fp.write('%i|%i\n' % (val, num_cells))
    val += 1
fp.close()