gdal icon indicating copy to clipboard operation
gdal copied to clipboard

GDALRasterBand: define +, -, *, /, AsType(), gdal::min()/max() to perform band lazy-evaluated arithmetics from C++, C and SWIG (Python)

Open rouault opened this issue 6 months ago • 3 comments

Documentation in https://gdal--12507.org.readthedocs.build/en/12507/user/band_algebra.html

Uses VRTDerivedRasterBand and pixel functions underneath.

Demo program converting a RGB image to grey level:

  • Python:
from osgeo import gdal
gdal.UseExceptions()
   
with gdal.Open("rgbsmall.tif") as ds:
   R = ds.GetRasterBand(1)
   G = ds.GetRasterBand(2)
   B = ds.GetRasterBand(3)
   greylevel = (0.299 * R + 0.587 * G + 0.114 * B).astype(gdal.GDT_Byte)
   gdal.GetDriverByName("GTiff").CreateCopy("greylevel.tif", greylevel)
  • C++:
#include <gdal_priv.h>

int main()
{
    GDALAllRegister();

    auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open("rgbsmall.tif"));
    auto& R = *(poDS->GetRasterBand(1));
    auto& G = *(poDS->GetRasterBand(2));
    auto& B = *(poDS->GetRasterBand(3));
    auto greylevel = (0.299 * R + 0.587 * G + 0.114 * B).AsType(GDT_Byte);

    auto poGTiffDrv = GetGDALDriverManager()->GetDriverByName("GTiff");
    std::unique_ptr<GDALDataset>(
        poGTiffDrv->CreateCopy("greylevel.tif", greylevel.GetDataset(), false, nullptr, nullptr, nullptr)).reset();

    return 0;
}

CC @dbaston I've experimented with the above as a potentially alternative/complement to gdal raster calc for C++ & Python users. Thoughts?

rouault avatar Jun 02 '25 10:06 rouault

Python support now added !

rouault avatar Jun 02 '25 20:06 rouault

Ready for review

rouault avatar Jun 15 '25 15:06 rouault

Documentation in https://gdal--12507.org.readthedocs.build/en/12507/user/band_algebra.html

rouault avatar Jun 15 '25 19:06 rouault