[Gdal-dev] How to efficiently read in a GDAL image into a matrix

Frank Warmerdam warmerdam at pobox.com
Wed Nov 7 15:14:40 EST 2007


Ryan Lewis wrote:
> Hi,
> 
> I would like to read in an entire ENVI image into a GDAL Dataset, and 
> then, create a matrix the size of which is pixels X number of raster bands
> So each column of the matrix is a raster band of the image, and each row 
> is a pixel of the image.  so the idea is I would linearize the 2d raster 
> band with something like the pixel at (x,y) in a particular rasterband 
> would be at the position
> x*width + y in the column.

Ryan,

I don't understand how you would use x*width+y to get to a particular pixel.
Perhaps you mean y*width + x?

If you have an image that is 200 width, 300 height and 3 bands you could
read it into a single "band sequential" array like this:

   GByte data[200*300*3];

   ...

   GDALDatasetRasterIO( hDS, GF_Read, 0, 0, 200, 300,
                        data, 200, 300, GDT_Byte,
                        3, NULL, 1, 200, 200*300 );

If you want to have an array of 2D arrays, one for each band, you might do:

   GByte *bands[3];
   GByte band1[200*300];
   GByte band2[200*300];
   GByte band3[200*300];
   GByte *bands[3] = {band1,band2,band3};

   for( int band = 1; band <= 3; band++ )
     GDALRasterIO( GDALGetRasterBand(hDS,band), GF_Read,
                   0, 0, 200, 300,
                   bands[band-1], 200, 300, GDT_Byte, 0, 0 );

Key things to keep in mind.

  o If you want to read more than one band at a time, you need to use
    GDALDatasetRasterIO() (or the RasterIO() method on GDALDataset).
  o The final 2/3 values in the RasterIO() call control the packing
    of the buffer.  Values of 0,0,0 are default packing, otherwise it
    is "pixel step", "line step" and "band step".

I'm open to contributed improvements to the GDAL raster api tutorial,
and the appropriate method docs to make this stuff clearer.

Best regards,
-- 
---------------------------------------+--------------------------------------
I set the clouds in motion - turn up   | Frank Warmerdam, warmerdam at pobox.com
light and sound - activate the windows | http://pobox.com/~warmerdam
and watch the world go round - Rush    | President OSGeo, http://osgeo.org




More information about the gdal-dev mailing list