项目需要解析etop数据,都是grd格式文件,可以用surfer软件打开,但是并不适合开发,以及对数据的解析
这里基于gdal库提供的接口对grd文件进行读取和解析,代码如下
#include <iostream>
#include <gdal_priv.h>
#include <string>
using namespace std;
void fileRead(const char* pszFile);
int main(int argc, char *argv[])
{
fileRead("/home/leo/example.grd");
return 0;
}
void fileRead(const char* pszFile)
{
GDALAllRegister();
GDALDataset *poDataset;
//使用只读方式打开图像
poDataset = (GDALDataset*)GDALOpen(pszFile, GA_ReadOnly);
if (poDataset == NULL) {
printf("File: %s不能打开!\n", pszFile);
return;
}
printf("Driver:%s/%s\n",
poDataset->GetDriver()->GetDescription(),
poDataset->GetDriver()->GetMetadataItem(GDAL_DMD_LONGNAME));
//输出图像的大小和波段个数
printf("Size is %d x %d x %d\n",
poDataset->GetRasterXSize(),
poDataset->GetRasterYSize(),
poDataset->GetRasterCount());
//输出图像的投影信息
if (poDataset->GetProjectionRef() != NULL)
printf("Projection is %s\n", poDataset->GetProjectionRef());
//输出图像的坐标和分辨率信息
double adfGeoTransform[6];
if (poDataset->GetGeoTransform(adfGeoTransform) == CE_None) {
printf("Origin =(%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3]);
printf("PixelSize = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5]);
}
//读取第一个波段
GDALRasterBand *poBand = poDataset->GetRasterBand(1);
//获取该波段的最大值最小值,如果获取失败,则进行统计
int bGotMin, bGotMax;
double adfMinMax[2];
adfMinMax[0] = poBand->GetMinimum(&bGotMin);
adfMinMax[1] = poBand->GetMaximum(&bGotMax);
if (!(bGotMin&& bGotMax))
GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
printf("Min=%.3fd,Max=%.3f\n", adfMinMax[0], adfMinMax[1]);
int nXSize = poBand->GetXSize();
int nYSize = poBand->GetYSize();
float *pafScanline = new float[nXSize];
//读取图像数据
for (int i = 0; i < 10/*nYSize*/; i++) {
poBand->RasterIO(GF_Read, 0, i, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0);
//poBand->RasterIO(GF_Read, 0, i, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0);
string LineDataInfo = "";
for (int j = 0; j < 10/*nXSize*/; j++) {
if (j == 0) {
LineDataInfo = to_string(pafScanline[j]);
}
else {
LineDataInfo = LineDataInfo + ", " + to_string(pafScanline[j]);
}
}
cout << LineDataInfo << endl;
}
delete[]pafScanline;
//关闭文件
GDALClose((GDALDatasetH)poDataset);
}