Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I am trying to figure out how to rescale a raster band's pixel value using the GDAL python bindings. I am looking to emulate the -scale switch in gdal_translate.exe; rescaling the pixel values in my raster to 0-255.

EDIT: Some goofing around today has produced this, seems to work thus far.

from osgeo import gdal
import numpy
import math

def singleBandToRGB(source,output):
    src_ds = gdal.Open(source)
    band = src_ds.GetRasterBand(1)
    min = band.GetMinimum()
    max = band.GetMaximum()
    data = src_ds.ReadAsArray(0,0,src_ds.RasterXSize,src_ds.RasterYSize)
    data = ((255-0)*((data-min)/(max-min)))+0
    data = data.astype(numpy.uint8)
    driver = gdal.GetDriverByName("GTiff")
    dst_ds = driver.Create(output,src_ds.RasterXSize,src_ds.RasterYSize,3,gdal.GDT_Byte)
    for i in range(1,4):
        dst_ds.GetRasterBand(i).WriteArray(data)
        dst_ds.GetRasterBand(i).ComputeStatistics(False)
    dst_ds.SetProjection(src_ds.GetProjection())
    dst_ds.SetGeoTransform(src_ds.GetGeoTransform())

    # housekeeping
    driver = None
    dst_ds = None
    src_ds = None
share|improve this question
add comment

1 Answer 1

Not entirely sure there's a ready-made function/class in GDAL python bindings, but if you're brave, you can look at the source of gdal_translate and find out how its done. From my quick skim, I think that scale ratio is set on VRTComplexSource (dfScaleRatio property).

share|improve this answer
    
Could you set the scale using a GDAL Virtual Format and then open that in python? –  Matthew Snape Mar 17 '11 at 14:08
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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