用C++代码和gdal库实现tif影像的匀光匀色程序
时间: 2024-05-13 12:17:13 浏览: 102
gdal裁剪tif_tif遥感图像_GDAL裁剪_遥感影像_GDAL_gdal批量裁剪_
5星 · 资源好评率100%
以下是一个简单的使用gdal库实现tif影像匀光匀色的C++代码示例。该程序读取输入tif影像文件,对其进行直方图均衡化处理,并输出匀光匀色后的tif影像文件。
```c++
#include "gdal_priv.h"
#include "cpl_conv.h" // for CPLMalloc()
int main(int argc, char* argv[])
{
// Register all known GDAL drivers.
GDALAllRegister();
// Open input tif file.
GDALDataset *poDataset;
poDataset = (GDALDataset *) GDALOpen(argv[1], GA_ReadOnly );
if( poDataset == NULL )
{
printf("Open failed.\n");
exit(1);
}
// Get image width and height.
int nXSize = poDataset->GetRasterXSize();
int nYSize = poDataset->GetRasterYSize();
// Get band count.
int nBands = poDataset->GetRasterCount();
// Allocate memory for input data.
float *pData = (float *) CPLMalloc(sizeof(float) * nXSize * nYSize * nBands);
// Read input data.
poDataset->RasterIO(GF_Read, 0, 0, nXSize, nYSize, pData, nXSize, nYSize, GDT_Float32, nBands, NULL, 0, 0, 0);
// Histogram equalization for each band.
for(int i=0; i<nBands; i++)
{
GDALRasterBand *poBand = poDataset->GetRasterBand(i+1);
// Get histogram.
double adfHist[256];
poBand->GetHistogram(0, 255, 256, adfHist, FALSE, FALSE, NULL, NULL);
// Get cumulative histogram.
double adfCumulativeHist[256];
adfCumulativeHist[0] = adfHist[0];
for(int j=1; j<256; j++)
{
adfCumulativeHist[j] = adfCumulativeHist[j-1] + adfHist[j];
}
// Normalize cumulative histogram.
for(int j=0; j<256; j++)
{
adfCumulativeHist[j] = adfCumulativeHist[j] / (nXSize * nYSize);
}
// Equalize image.
float fMin, fMax;
poBand->ComputeRasterMinMax(TRUE, &fMin, &fMax);
float fRange = fMax - fMin;
for(int j=0; j<nXSize*nYSize; j++)
{
int nValue = (int) ((pData[j*nBands+i] - fMin) / fRange * 255);
pData[j*nBands+i] = (float) adfCumulativeHist[nValue];
}
}
// Create output tif file.
GDALDriver *poDriver;
poDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
if( poDriver == NULL )
{
printf("Create driver failed.\n");
exit(1);
}
GDALDataset *poOutputDataset;
poOutputDataset = poDriver->Create(argv[2], nXSize, nYSize, nBands, GDT_Float32, NULL);
if( poOutputDataset == NULL )
{
printf("Create output dataset failed.\n");
exit(1);
}
// Write output data.
poOutputDataset->RasterIO(GF_Write, 0, 0, nXSize, nYSize, pData, nXSize, nYSize, GDT_Float32, nBands, NULL, 0, 0, 0);
// Close datasets.
GDALClose((GDALDatasetH) poDataset);
GDALClose((GDALDatasetH) poOutputDataset);
// Free memory.
CPLFree(pData);
return 0;
}
```
需要注意的是,该程序只支持单波段tif影像文件,如果需要处理多波段tif影像文件,需要对代码进行修改。
阅读全文