基于GDAL和Opencv的Tiff数据重采样(目标:提高分辨率,实际地理范围不改变),以GByte格式为例
由于GDAL可以很好处理tiff等遥感数据,但重采样函数调用较为麻烦;Opencv在图像重采样等方面具有强大功能,但处理tiff数据流程较为麻烦。因此,本研究拟基于GDAL和Opencv对tiff数据进行重采样,经验证方法可行。
#include "gdal_priv.h"
#include "ogrsf_frmts.h"
#include<opencv2/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui.hpp>
using namespace cv;
using namespace std;
void resizeGByteTiff(nOriImgX, nOriImgY, std::string initialTiff, std::string newTiff)
{
GDALAllRegister();
CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");
const char * pszFile = initialTiff.c_str();
GDALDataset *poDataset = (GDALDataset*)GDALOpen(pszFile, GA_ReadOnly);
if (!poDataset)
{
printf("File: %s不能打开!\n", pszFile);
}
double padfTransform0[6];
if (poDataset->GetGeoTransform(padfTransform0) == CE_Failure)
{
printf("获取仿射变换参数失败");
}
int iImgSizeX0 = poDataset->GetRasterXSize();
int iImgSizeY0 = poDataset->GetRasterYSize();
int nCount = poDataset->GetRasterCount();
GDALDataType gdal_data_type = poDataset->GetRasterBand(1)->GetRasterDataType();
double dnodata = poDataset->GetRasterBand(1)->GetNoDataValue();
unsigned char *_pNewValue = new unsigned char[iImgSizeX0*iImgSizeY0];
poDataset->RasterIO(GF_Read, 0, 0, iImgSizeX0, iImgSizeY0, _pNewValue, iImgSizeX0, iImgSizeY0, gdal_data_type, 1, 0, 0, 0, 0);
cv::Mat _Mymat(iImgSizeY0, iImgSizeX0, CV_8UC1);
for (int i = 0; i < iImgSizeX0; i++)
{
for (int j = 0; j < iImgSizeY0; j++)
{
_Mymat.at<uchar>(j, i) = (uchar)_pNewValue[j * iImgSizeX0 + i];
}
}
Size dsize = Size(nOriImgX, nOriImgY);
Mat newMat = Mat(dsize, CV_32S);
resize(_Mymat, newMat, dsize);
int a = 0;
unsigned char* _pimageData = new unsigned char[nOriImgX*nOriImgY];
for (int i = 0; i < newMat.rows; i++)
{
for (int j = 0; j < newMat.cols; j++)
{
_pimageData[a] = newMat.at<uchar>(i, j);
a++;
}
}
double scale = (double)nOriImgX / iImgSizeX0;
padfTransform0[1] = padfTransform0[1] / scale;
scale = (double)nOriImgY / iImgSizeY0;;
padfTransform0[5] = padfTransform0[5] / scale;
int pBandMap[3] = { 1,2,3 };
const char* pszDstFilename = newTiff.c_str();
GDALDriver* poDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
GDALDataset* poDstDS = poDriver->Create(pszDstFilename, nOriImgX, nOriImgY, nCount, GDT_Byte, NULL);
poDstDS->SetProjection(poDataset->GetProjectionRef());
poDstDS->SetGeoTransform(padfTransform0);
poDstDS->GetRasterBand(1)->SetNoDataValue(dnodata);
poDstDS->RasterIO(GF_Write, 0, 0, nOriImgX, nOriImgY, _pimageData, nOriImgX, nOriImgY, GDT_Byte, nCount, pBandMap, 0, 0, 0);
poDstDS->GetRasterBand(1)->RasterIO(GF_Write, 0, 0, nOriImgX, nOriImgY, _pimageData, nOriImgX, nOriImgY, GDT_Byte, 0, 0);
GDALClose(poDstDS);
GDALClose(poDataset);
delete[]_pNewValue;
delete[]_pimageData;
}
|