GDAL获得像素颜色

时间:2016-09-15 11:07:58

标签: c++ image qt raster gdal

有问题。我有一个tiff图像(有4层)。 我的任务是对像素的颜色进行微小的改变,以使图像更好。 在这种情况下,我使用GDAL库。我的来源是:

GDALDataset  *poDataset;
GDALAllRegister();
poDataset = (GDALDataset *) GDALOpen(fileName.toStdString().c_str(), GA_ReadOnly);
if (poDataset == NULL) {
    QMessageBox::information(0, "error", "We have problems");
} else {
    QMessageBox::information(0, "Message", "All is ok");
}
int rasterCount = poDataset->GetRasterCount(); // Here is 4 raster images
GDALRasterBand *band = poDataset->GetRasterBand(1);
int width = band->GetXSize();
int height = band->GetYSize();


for (int i = 0; i < width; i++) {
    for (int j = 0; j < height; j++) {
        // cross all pixels 
        // How to get pixel color here?
    }
}

所以我不知道如何在循环中获得像素颜色。你能给我一些建议吗?

2 个答案:

答案 0 :(得分:0)

我没有GDAL API中的示例,但我已经在python库中完成了。你可以按照类似的逻辑做类似的事情,将图像值放到数组中并循环遍历它,同时对它应用一些条件更改。

import numpy as np
from osgeo import gdal
ds = gdal.Open("test.tif")
myarray = np.array(ds.GetRasterBand(1).ReadAsArray())
... 

答案 1 :(得分:0)

首先,您需要了解数据类型:

GDALDataType dataType=band->GetRasterDataType();

这将为您提供一个数字,定义为:

typedef enum {
    /*! Unknown or unspecified type */          GDT_Unknown = 0,
    /*! Eight bit unsigned integer */           GDT_Byte = 1,
    /*! Sixteen bit unsigned integer */         GDT_UInt16 = 2,
    /*! Sixteen bit signed integer */           GDT_Int16 = 3,
    /*! Thirty two bit unsigned integer */      GDT_UInt32 = 4,
    /*! Thirty two bit signed integer */        GDT_Int32 = 5,
    /*! Thirty two bit floating point */        GDT_Float32 = 6,
    /*! Sixty four bit floating point */        GDT_Float64 = 7,
    /*! Complex Int16 */                        GDT_CInt16 = 8,
    /*! Complex Int32 */                        GDT_CInt32 = 9,
    /*! Complex Float32 */                      GDT_CFloat32 = 10,
    /*! Complex Float64 */                      GDT_CFloat64 = 11,
    GDT_TypeCount = 12          /* maximum type # + 1 */
} GDALDataType;

因此,如果您的GDALDataType为6,则您的数据类型为浮点型,那么您可以像这样读取像素值:

float value=0;
band->RasterIO(GF_Read,i,j,1,1,&value,1,1,band->GetRasterDataType(),1,1,nullptr);
std::cout << "value = " << value << std::endl;