[gdal-dev] moving averaging filter in GDAL.

Even Rouault even.rouault at mines-paris.org
Thu Jul 2 14:20:09 EDT 2009


Belaid Moa,

Good point! Yes it should work as your code is directly derived from the VRT 
tutorial. I discovered that in fact support for SetMetadataItem( "source_0", 
szFilterSourceXML, "vrt_sources" ) was missing in the VRT driver. I've fixed 
that as ticket #3052.

In the meantime you've an easy workaround by using SetMetadata() instead of 
SetMetadataItem(). Here's the modified code snippet :

/**
* Apply an averaging filter to a GDALDataset
* sFileName: source file name
* dstFileName: destination file name
* size: size of the filter (kernal)
* coefficients: the coefficients of the filter.
**/
int average(char* sFileName, char* dstFileName, int size, const char* 
coefficients) {
  GDALDriver *poDriver = (GDALDriver *) GDALGetDriverByName( "VRT" );
  if (poDriver ==  NULL) {
      cout <<"VRT Driver not found!"<<endl;
      return -1;
  }
  GDALDataset *poVRTDS, *poSrcDS;
  poSrcDS = (GDALDataset *) GDALOpen( sFileName, GA_ReadOnly);
  poVRTDS = poDriver->CreateCopy( "", poSrcDS, FALSE, NULL, NULL, NULL );
  int   nBand;
  for( nBand = 1; nBand <= poVRTDS->GetRasterCount(); nBand++ ) {
      GDALRasterBand *poBand = poVRTDS->GetRasterBand( nBand );
      char szFilterSourceXML[10000];
/* note the addition of source_0= */
      sprintf( szFilterSourceXML,
        "source_0=<KernelFilteredSource>" 
        "  <SourceFilename>%s</SourceFilename><SourceBand>%d</SourceBand>"
        "  <Kernel>"
        "    <Size>%d</Size>"
        "    <Coefs>%s</Coefs>"
        "  </Kernel>"
        "</KernelFilteredSource>",
        sFileName,nBand,size,coefficients);
      cout << szFilterSourceXML <<endl;
      char* papszMetadata[2] = { (char*)szFilterSourceXML, NULL };
      poBand->SetMetadata( papszMetadata, "vrt_sources" );
      //poBand->FlushCache();
  }
  GDALDriver *poTIFFDriver = (GDALDriver *) GDALGetDriverByName( "GTiff" );
   if (poTIFFDriver ==  NULL) {
      cout <<"GTIFF Driver not found!"<<endl;
      return -1;
  }
  GDALDataset *poTiffDS;
  poTiffDS = poTIFFDriver->CreateCopy( dstFileName, poVRTDS, FALSE, NULL, 
NULL, NULL );
  poVRTDS->GetRasterBand( 1 )->FlushCache();

  GDALClose(poSrcDS);
  GDALClose(poTiffDS);
  GDALClose(poVRTDS);
  return 1;
}

Best regards,

Even


More information about the gdal-dev mailing list