項目需要解析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/tcy/etop/ETOPO1_Bed_c_gmt4.grd");
//fileRead("/home/taochengye/etop/ETOPO1_Bed_g_gdal.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);
}