5

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
2

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).

  • Could you set the scale using a GDAL Virtual Format and then open that in python? – Matthew Snape Mar 17 '11 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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