#! /usr/bin/env python
#
# $Id$
#
# This is a simple script based on GDAL and used to retrieve value of single raster pixel.
# It is used in WKTRaster testing to compare raster samples.
#
# Copyright (C) 2009 Mateusz Loskot <mateusz@loskot.net>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
from osgeo import gdal
from osgeo import osr
import osgeo.gdalconst as gdalc
import struct
import sys

def pt2fmt(pt):
    fmttypes = {
        gdalc.GDT_Byte: 'B',
        gdalc.GDT_Int16: 'h',
        gdalc.GDT_UInt16: 'H',
        gdalc.GDT_Int32: 'i',
        gdalc.GDT_UInt32: 'I',
        gdalc.GDT_Float32: 'f',
        gdalc.GDT_Float64: 'f'
        }
    return fmttypes.get(pt, 'x')

if len(sys.argv) != 5:
    print "Usage: pixval.py <raster> <band> <x> <y>"
    print "\traster - GDAL supported dataset"
    print "\tband - 1-based number of band"
    print "\tx - Pixel column - 1..N where N is raster X dimension"
    print "\ty - Pixel row - 1..N where N is raster Y dimension"
    sys.exit(1)

infile = sys.argv[1]
nband = int(sys.argv[2])
x = int(sys.argv[3])
y = int(sys.argv[4])

print "File : %s" % infile
print "Band : %d" % nband
print "Pixel: %d x %d" % (x, y)

ds = gdal.Open(infile, gdalc.GA_ReadOnly);
if ds is None:
    sys.exit('Cannot open input file: ' + str(infile))

if x <= 0 or x > ds.RasterXSize or y <= 0 or y > ds.RasterYSize:
    print "Invalid pixel coordinates"
    print "Raster dimensions are %d x %d" % (ds.RasterXSize + 1, ds.RasterYSize + 1)
    sys.exit(1)

band = ds.GetRasterBand(nband)
if band is None:
    sys.exit('Cannot access band %d', nband)

# Pixel index is 0-based
pixel = band.ReadRaster(x - 1, y - 1, 1, 1, 1, 1)

fmt = pt2fmt(band.DataType)
pixval = struct.unpack(fmt, pixel)

print "Pixel value -> %s" % str(pixval[0])
