嗨,我正在尝试遍历栅格数据集(band1)的值。我可以使用以下代码段在python中完成此操作(抱歉,我无法提供原始栅格)

import numpy as np
import gdal

path = "data/Isle_wight.tif"

ds = gdal.Open(path)
myarray = np.array(ds.GetRasterBand(1).ReadAsArray())
print(myarray.shape[0])
#print(columns)
for j in range(myarray.shape[0]-1):
    for i in range(myarray.shape[1]-1):
        print( myarray[j][i])


我的目标是在C-GDAL中进行模拟

这是我的代码段(不起作用)

#include "gdal/gdal.h"
#include "gdal/cpl_conv.h"
int main()
{

    GDALDatasetH raster;
    GDALAllRegister();
    raster = GDALOpen( "/home/roger/Documents/98_GDAL_C++_snippets/data/Isle_wight.tif", GA_ReadOnly);
    if(raster==NULL)
    {
    printf("Invalid Raster Dataset");
    }
    else
    {
    GDALRasterBandH raster_band;
    int XSize, YSize;

    raster_band = GDALGetRasterBand( raster, 1);
    GDALGetBlockSize( raster_band, &XSize, &YSize);
    float *pafScanline;
    int nXSize = GDALGetRasterBandXSize (raster_band);
    int nYSize = GDALGetRasterBandYSize (raster_band);
    pafScanline = (float*) CPLMalloc(sizeof(float)*nXSize);
    int address_of_pafScanline = *pafScanline;
    int band1[nXSize][nYSize];
    int band1 = GDALRasterIO(raster_band, 0, 0,GF_Read, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0);
    for(int i = 0; i <= nXSize; i++) {
        for(int j = 0; j < nYSize; j++ ) {
            printf("%d", band1[i][j]);
        }
    }
}

}


问题:GDALRasterIO返回什么?我在第25行编写时做了一个数组声明:

int band1[nXSize][nYSize],


然后,我读取栅格数据并将其分配给下一行(26)中的上一个band1数组:

int band1 = GDALRasterIO(raster_band, 0, 0,GF_Read, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0);


通过编译时

cc open_array.c -o open_array -lgdal


我收到以下错误:

open_array.c: In function ‘main’:
open_array.c:26:9: error: conflicting types for ‘band1’
     int band1 = GDALRasterIO(raster_band, 0, 0,GF_Read, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0);
         ^~~~~
open_array.c:25:9: note: previous declaration of ‘band1’ was here
     int band1[nXSize][nYSize];
         ^~~~~
open_array.c:29:31: error: subscripted value is neither array nor pointer nor vector
             printf("%d", band1[i][j]);


为什么会这样呢?
我应该删除第25行中的声明吗?

提前致谢

最佳答案

GDALRasterIO返回什么?


按照documentation,它返回一个CPLErr,它是一个int值。您可以使用此值来检查您的读取是否成功:

CPLErr readResult = GDALRasterIO(raster_band, 0, 0,GF_Read, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0);
if (readResult != CE_None) {
  // error reading the file
}
// else continue processing


您的代码中的错误与您试图两次重新声明相同的变量(band1)有关。这就是编译器所抱怨的。
首先,您必须先int band1[nXSize][nYSize]->声明变量,然后再进行int band1 = GDALRasterIO(...声明。由于再次使用类型(int),因此需要重新声明变量。如果您不想重新声明,则只应在第二行:band1 = GDALRasterIO(...中进行分配。无论如何,band1的类型都不正确,它不应该是矩阵。

08-19 18:42