1

I'm working with GDAL using C++.

I've got a code to create a black-and-white image:

GDALAllRegister();
GDALDriver *pDriverTiff = GetGDALDriverManager()->GetDriverByName("GTiff");
GDALDataset *pNewDS;
pNewDS = pDriverTiff->Create(output, nCols, nRows, 1, GDT_UInt16, NULL);
double *transform = geotiff->get_transform();
pNewDS->SetProjection(geotiff->get_proj().c_str());
pNewDS->SetGeoTransform(geotiff->get_transform());
float *newRow = (float *) CPLMalloc(sizeof(float)*nCols);
for (int i = 0; i < nRows; i++){
    for (int j = 0; j < nCols; j++){
        newRow[j] = matrix[i * nCols + j];
    }
    pNewDS->GetRasterBand(1)->RasterIO(GF_Write, 0, i, nCols, 1, newRow, nCols, 1, GDT_Float32, 0, 0);
}
GDALClose(pNewDS);
GDALDestroyDriverManager();

And it works flawlessly.

But now I want to create a colored RGB image. I'm trying to do it this way:

GDALAllRegister();
GDALDriver *pDriverTiff = GetGDALDriverManager()->GetDriverByName("GTiff");
GDALDataset *pNewDS;
char* options[] = {"PHOTOMETRIC=RGB", "PROFILE=GeoTIFF"};
pNewDS = pDriverTiff->Create(output, nCols, nRows, 3, GDT_UInt16, options);
double *transform = geotiff->get_transform();
pNewDS->SetProjection(geotiff->get_proj().c_str());
pNewDS->SetGeoTransform(geotiff->get_transform());
float *newRow = (float *) CPLMalloc(sizeof(float)*nCols);
for (int i = 0; i < nRows; i++){
    for (int j = 0; j < nCols; j++){
        newRow[j] = matrix[i * nCols + j];
    }
    pNewDS->GetRasterBand(1)->RasterIO(GF_Write, 0, i, nCols, 1, newRow, nCols, 1, GDT_Float32, 0, 0);
}
for (int i = 0; i < nRows; i++){
    for (int j = 0; j < nCols; j++){
        newRow[j] = matrix[i * nCols + j];
    }
    pNewDS->GetRasterBand(2)->RasterIO(GF_Write, 0, i, nCols, 1, newRow, nCols, 1, GDT_Float32, 0, 0);
}
for (int i = 0; i < nRows; i++){
    for (int j = 0; j < nCols; j++){
        newRow[j] = matrix[i * nCols + j];
    }
    pNewDS->GetRasterBand(3)->RasterIO(GF_Write, 0, i, nCols, 1, newRow, nCols, 1, GDT_Float32, 0, 0);
}
pNewDS->GetRasterBand(1)->SetColorInterpretation(GCI_RedBand);
pNewDS->GetRasterBand(2)->SetColorInterpretation(GCI_GreenBand);
pNewDS->GetRasterBand(3)->SetColorInterpretation(GCI_BlueBand);
GDALClose(pNewDS);
GDALDestroyDriverManager();

But the image is still black-and-white. How to make it colored?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.