嗨,我正在尝试迭代栅格数据集(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行中的声明吗?
预先感谢
答案 0 :(得分:1)
GDALRasterIO返回什么?
根据documentation,它将返回int
值的CPLErr。您可以使用此值来检查您的读取是否成功:
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
的类型是不正确的,它不应该是矩阵。