[Gdal-dev] Conversion to Grayscale

Norman Vine nhv at cape.com
Fri Dec 3 14:20:16 EST 2004


Frank Warmerdam writes:
> 
> Chris Hodgson writes:
> >
> > Do any of the existing gdal tools support converting a color (RGB or
> > paletted) image to a grayscale image? 
..
> > I'm guessing it would be relatively easy to
> > write a python script to do this - however I know nothing of Python, let
> > alone the gdal interface. Has anyone done this already?
> 
> Chris, 
> 
> Do you want a "proper" RGB to greyscale conversion or is
> it sufficient to just take any one of the bands and use it as
> greyscale?  I believe a "proper" conversion would involve
> a colorspace transformation on the RGB image into IHS or
> something like that, and then taking the intensity.  This is
> not conveniently available in GDAL but could be implemented
> in Python. 
> 
> However, if the file is really just a greyscale image represented
> in RGB then you could use the -b switch to pick out one band
> from the source image to use as the output greyscale image. 
> 
> eg. 
> 
> gdal_translate -b 1 in.tif out.tif

Here is a quick and dirty to get a NumPy greyscale representation
requires the PIL and the GDAL extensions

Python Imaging extensions <PIL>
http://www.pythonware.com/products/pil/

Norman



from PIL import Image,ImageOps
from gdalnumeric import *

def ImageToArray(i):
    a=fromstring(i.tostring(),'b')
    a.shape=i.im.size[1], i.im.size[0]
    return a

myImage = Image.open(filename)

greyImage = ImageOps.greyscale(myImage)

greyScaleNumericArray = ImageToArray(greyImage) 





More information about the Gdal-dev mailing list