GDAL对影像进行划分网格,并通过像素坐标转换为地理坐标
#include "gdal_priv.h"
#include<iostream>
#include<fstream>
using namespace std;
typedef struct imgpoint {
int id;
int leftPointX;
int leftPointY;
double w;
double h;
};
void ImageProcess(const char* pszSrcFile, const char* pszFormat)
{
FILE *fp;
fp = fopen("D:/dcj/test.txt", "r+");
GDALAllRegister();
GDALDataset *poSrcDS = (GDALDataset*)GDALOpen(pszSrcFile, GA_ReadOnly);
GDALRasterBand *poBand;
int bandcount;
bandcount = poSrcDS->GetRasterCount();
cout << "波段数:" << bandcount << endl;
double adfGeotransform[6] = { 0 };
poSrcDS->GetGeoTransform(adfGeotransform);
const char* pszProj = poSrcDS->GetProjectionRef();
GDALRasterBand *poBand = poSrcDS->GetRasterBand(1);
if (poBand == NULL)
{
GDALClose((GDALDatasetH)poSrcDS);
}
int nBlockSize = 256;
int nBands = poSrcDS->GetRasterCount();
unsigned char *pSrcData = new unsigned char[nBlockSize*nBlockSize*nBands];
int *pBandMaps = new int[nBands];
for (int b = 0; b < nBands; b++)
pBandMaps[b] = b + 1;
vector<imgpoint> block;
imgpoint sig;
int nYSize = poSrcDS->GetRasterYSize();
int id = 0;
for (int i = 0; i < nYSize; i += nBlockSize)
{
int Yid = 0;
int nXSize = poSrcDS->GetRasterXSize();
for (int j = 0; j <nXSize; j += nBlockSize)
{
int xid = 0;
int nXBK = nBlockSize;
int nYBK = nBlockSize;
if (i + nBlockSize > nYSize)
nYBK = nYSize - i;
if (j + nBlockSize > nXSize)
nXBK = nXSize - j;
poSrcDS->RasterIO(GF_Read, j, i, nXBK, nYBK, pSrcData, nXBK, nYBK, GDT_Byte, nBands, pBandMaps, 0, 0, 0, NULL);
sig.id = id;
sig.leftPointX = i;
sig.leftPointY = j;
sig.w = nBlockSize;
sig.h = nBlockSize;
block.push_back(sig);
imgpoint sigs = block[id];
double Xgeo, Ygeo;
Xgeo = adfGeotransform[0] + sig.leftPointX * adfGeotransform[1] + sig.leftPointY * adfGeotransform[2];
Ygeo = adfGeotransform[3] + sig.leftPointX * adfGeotransform[4] + sig.leftPointY * adfGeotransform[5];
fprintf(fp, "%d\t",id);
fprintf(fp, "%d\t", sig.leftPointX);
fprintf(fp, "%d\t", sig.leftPointY);
fprintf(fp, "%lf\t", Xgeo);
fprintf(fp, "%lf\n", Ygeo);
cout << id << ":" << sig.leftPointX << "," << sig.leftPointY << "," << Xgeo << "," << Ygeo << endl;
id++;
;
}
}
delete[]pSrcData;
delete[]pBandMaps;
GDALClose((GDALDatasetH)poSrcDS);
}
int main()
{
const char* pszFile;
const char* outFile;
GDALAllRegister();
pszFile = "G:/3Datas/wgs841_10w/H49D001004.tif";
GDALDataset *poDataset = (GDALDataset*)GDALOpen(pszFile, GA_ReadOnly);
GDALRasterBand *poBand = poDataset->GetRasterBand(1);
int xsize = poBand->GetXSize();
int ysize = poBand->GetYSize();
cout << xsize << endl;
cout << ysize << endl;
const char *pszFormat = "Tif";
ImageProcess(pszFile,pszFormat);
return 0;
}