Search code examples
c++gisgdal

Read all point and insert into array


I came across this gdal code to read the elevation point for specific location. This code allow me to just read only one point. The elevation file information:

Upper Left X = 103.0000 Upper Left Y = 4.0000

Lower Right X = 104.0000 Lower Right Y = 3.0000

No. of columns = 3601, No. of rows = 3601

How can get read all the elevation point and store it in vector array?

   int _tmain(int argc, _TCHAR* argv[])
{
    const char* pszFilename = "C:\\Elevation.DT2";
    double adfGeoTransform[6];
    float buffEleveation[1];

    int row;
    int col;

    std::vector<float> elevationVecArr;

    GDALRasterBand *poBand;

    GDALDataset  *poDataset;
    GDALAllRegister();
    poDataset = (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly );

    printf( "Driver: %s/%s\n",
        poDataset->GetDriver()->GetDescription(),
        poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );
    printf( "Size is %dx%dx%d\n",
        poDataset->GetRasterXSize(),poDataset->GetRasterYSize(),
        poDataset->GetRasterCount() );
    if( poDataset->GetProjectionRef()  != NULL )
        printf( "Projection is `%s'\n", poDataset->GetProjectionRef() );
    if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None )
    {
        printf( "Origin = (%.6f,%.6f)\n",
                adfGeoTransform[0], adfGeoTransform[3] );
        printf( "Pixel Size = (%.6f,%.6f)\n",
                adfGeoTransform[1], adfGeoTransform[5] );
    }

    poDataset->GetGeoTransform(adfGeoTransform);
    poBand = poDataset->GetRasterBand(1); 
    float X = (103.0000);
    float Y = (4.000);
    
    row = (int)((adfGeoTransform[3] - Y) / -adfGeoTransform[5]); // ULY - xcoord / -N-S CellSize;
    col = (int)((X - adfGeoTransform[0]) / adfGeoTransform[1]);  // xcoord - ULX / E-W CellSize

    poBand->RasterIO(GF_Read, col, row, 1, 1, buffEleveation, 1, 1, GDT_Float32, 0, 0); // read the cell value

    float elevationValue = buffEleveation[0];           

    elevationVecArr.push_back(buffEleveation[0]);

    printf("Elevation = %.f", elevationValue);

    getchar();

    return 0;
    
    
}

Solution

  • According to the documentation at https://gdal.org/doxygen/classGDALRasterBand.html#a75d4af97b3436a4e79d9759eedf89af4 you can just specify the range you want to read.

    constexpr int rows=3601;
    constexpr int cols=3601;
    std::vector<float> buffEleveation(rows*cols);
    
    // Since we want to read all the data we set:
    // nXOff/nYOff to 0
    // nXSize/nYSize to 3601
    // nBufXSize/nBufXSize to 3601.
    poBand->RasterIO(GF_Read, 0, 0, rows, cols, buffEleveation.data(), rows, cols, GDT_Float32, 0, 0); // read all elevation values.