Exemplo n.º 1
0
QgsAlignRaster::RasterInfo::RasterInfo( const QString& layerpath )
{
  mDataset = GDALOpen( layerpath.toLocal8Bit().constData(), GA_ReadOnly );
  if ( !mDataset )
    return;

  mXSize = GDALGetRasterXSize( mDataset );
  mYSize = GDALGetRasterYSize( mDataset );

  GDALGetGeoTransform( mDataset, mGeoTransform );

  // TODO: may be null or empty string
  mCrsWkt = QString::fromAscii( GDALGetProjectionRef( mDataset ) );

  mBandCnt = GDALGetBandNumber( mDataset );
}
Exemplo n.º 2
0
void MDAL::GdalDataset::parseParameters()
{
  mNBands = static_cast<unsigned int>( GDALGetRasterCount( mHDataset ) );
  if ( mNBands == 0 ) throw MDAL_Status::Err_InvalidData;

  GDALGetGeoTransform( mHDataset, mGT ); // in case of error it returns Identid

  mXSize = static_cast<unsigned int>( GDALGetRasterXSize( mHDataset ) ); //raster width in pixels
  if ( mXSize == 0 ) throw MDAL_Status::Err_InvalidData;

  mYSize = static_cast<unsigned int>( GDALGetRasterYSize( mHDataset ) ); //raster height in pixels
  if ( mYSize == 0 ) throw MDAL_Status::Err_InvalidData;

  mNPoints = mXSize * mYSize;
  mNVolumes = ( mXSize - 1 ) * ( mYSize - 1 );
}
Exemplo n.º 3
0
static void WorkerFunc( void * )

{
    GDALDatasetH hDS;
    int iIter, iOpenIter;

    for( iOpenIter = 0; iOpenIter < nOpenIterations; iOpenIter++ )
    {
        if( bLockOnOpen )
            CPLAcquireMutex( pGlobalMutex, 100.0 );

        hDS = GDALOpen( pszFilename, GA_ReadOnly );

        if( bLockOnOpen )
            CPLReleaseMutex( pGlobalMutex );

        for( iIter = 0; iIter < nIterations && hDS != NULL; iIter++ )
        {
            int nMyChecksum;
        
            nMyChecksum = GDALChecksumImage( GDALGetRasterBand( hDS, 1 ), 
                                             0, 0, 
                                             GDALGetRasterXSize( hDS ), 
                                             GDALGetRasterYSize( hDS ) );

            if( nMyChecksum != nChecksum )
            {
                printf( "Checksum ERROR in worker thread!\n" );
                break;
            }
        }

        if( hDS )
        {
            if( bLockOnOpen )
                CPLAcquireMutex( pGlobalMutex, 100.0 );
            GDALClose( hDS );
            if( bLockOnOpen )
                CPLReleaseMutex( pGlobalMutex );
        }
    }

    CPLAcquireMutex( pGlobalMutex, 100.0 );
    nPendingThreads--;
    CPLReleaseMutex( pGlobalMutex );
}
Exemplo n.º 4
0
//duplicated from QgsNineCellFilter. Todo: make common base class
GDALDatasetH QgsRelief::openInputFile( int &nCellsX, int &nCellsY )
{
  GDALDatasetH inputDataset = GDALOpen( mInputFile.toUtf8().constData(), GA_ReadOnly );
  if ( inputDataset )
  {
    nCellsX = GDALGetRasterXSize( inputDataset );
    nCellsY = GDALGetRasterYSize( inputDataset );

    //we need at least one band
    if ( GDALGetRasterCount( inputDataset ) < 1 )
    {
      GDALClose( inputDataset );
      return nullptr;
    }
  }
  return inputDataset;
}
Exemplo n.º 5
0
GDALDatasetH QgsNineCellFilter::openInputFile( int& nCellsX, int& nCellsY )
{
  GDALDatasetH inputDataset = GDALOpen( mInputFile.toLocal8Bit().data(), GA_ReadOnly );
  if ( inputDataset != NULL )
  {
    nCellsX = GDALGetRasterXSize( inputDataset );
    nCellsY = GDALGetRasterYSize( inputDataset );

    //we need at least one band
    if ( GDALGetRasterCount( inputDataset ) < 1 )
    {
      GDALClose( inputDataset );
      return NULL;
    }
  }
  return inputDataset;
}
Exemplo n.º 6
0
//duplicated from QgsNineCellFilter. Todo: make common base class
GDALDatasetH QgsRelief::openInputFile( int& nCellsX, int& nCellsY )
{
  GDALDatasetH inputDataset = GDALOpen( TO8F( mInputFile ), GA_ReadOnly );
  if ( inputDataset != NULL )
  {
    nCellsX = GDALGetRasterXSize( inputDataset );
    nCellsY = GDALGetRasterYSize( inputDataset );

    //we need at least one band
    if ( GDALGetRasterCount( inputDataset ) < 1 )
    {
      GDALClose( inputDataset );
      return NULL;
    }
  }
  return inputDataset;
}
Exemplo n.º 7
0
void TestQgsGdalUtils::testCreateSingleBandMemoryDataset()
{
  gdal::dataset_unique_ptr ds1 = QgsGdalUtils::createSingleBandMemoryDataset( GDT_Float32, QgsRectangle( 1, 1, 21, 11 ), 40, 20, QgsCoordinateReferenceSystem( "EPSG:4326" ) );
  QVERIFY( ds1 );

  QCOMPARE( GDALGetRasterCount( ds1.get() ), 1 );
  QCOMPARE( GDALGetRasterXSize( ds1.get() ), 40 );
  QCOMPARE( GDALGetRasterYSize( ds1.get() ), 20 );

  QCOMPARE( GDALGetProjectionRef( ds1.get() ), EPSG_4326_WKT );
  double geoTransform[6];
  double geoTransformExpected[] = { 1, 0.5, 0, 11, 0, -0.5 };
  QCOMPARE( GDALGetGeoTransform( ds1.get(), geoTransform ), CE_None );
  QVERIFY( memcmp( geoTransform, geoTransformExpected, sizeof( double ) * 6 ) == 0 );

  QCOMPARE( GDALGetRasterDataType( GDALGetRasterBand( ds1.get(), 1 ) ), GDT_Float32 );
}
/* Makes a copy of a dataset, and opens it for writing.. */
GDALDatasetH make_me_a_sandwitch(GDALDatasetH *in_dataset, char *filename)
{
    char **papszOptions = NULL;
    const char *pszFormat = "GTiff";
    GDALDriverH hDriver;
    GDALDatasetH out_gdalfile;
    hDriver = GDALGetDriverByName( pszFormat );
    papszOptions = CSLSetNameValue( papszOptions, "TILED", "YES" );
    papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "DEFLATE" );
    
    /*Create copy..*/
    /*return GDALCreateCopy( hDriver, filename, *in_dataset, FALSE, papszOptions, NULL, NULL );*/
    return GDALCreate(hDriver, filename,
        GDALGetRasterXSize( *in_dataset ),
        GDALGetRasterYSize( *in_dataset ),
        1,
        GDT_Byte, papszOptions );
}
Exemplo n.º 9
0
GDALDatasetH QgsNineCellFilter::openOutputFile( GDALDatasetH inputDataset, GDALDriverH outputDriver )
{
  if ( inputDataset == NULL )
  {
    return NULL;
  }

  int xSize = GDALGetRasterXSize( inputDataset );
  int ySize = GDALGetRasterYSize( inputDataset );;

  //open output file
  char **papszOptions = NULL;
  GDALDatasetH outputDataset = GDALCreate( outputDriver, mOutputFile.toLocal8Bit().data(), xSize, ySize, 1, GDT_Float32, papszOptions );
  if ( outputDataset == NULL )
  {
    return outputDataset;
  }

  //get geotransform from inputDataset
  double geotransform[6];
  if ( GDALGetGeoTransform( inputDataset, geotransform ) != CE_None )
  {
    GDALClose( outputDataset );
    return NULL;
  }
  GDALSetGeoTransform( outputDataset, geotransform );

  //make sure mCellSizeX and mCellSizeY are always > 0
  mCellSizeX = geotransform[1];
  if ( mCellSizeX < 0 )
  {
    mCellSizeX = -mCellSizeX;
  }
  mCellSizeY = geotransform[5];
  if ( mCellSizeY < 0 )
  {
    mCellSizeY = -mCellSizeY;
  }

  const char* projection = GDALGetProjectionRef( inputDataset );
  GDALSetProjection( outputDataset, projection );

  return outputDataset;
}
Exemplo n.º 10
0
static dErr JakoFileDataView(GDALDatasetH filedata,const char *name,PetscViewer viewer)
{
  dErr err;
  CPLErr cplerr;
  double geo[6],data[8*12];
  int nx=8,ny=12,snx,sny;
  GDALRasterBandH band;

  dFunctionBegin;
  cplerr = GDALGetGeoTransform(filedata,geo);
  err = dRealTableView(2,3,geo,PETSC_VIEWER_STDOUT_WORLD,"%s:geo",name);dCHK(err);
  snx = GDALGetRasterXSize(filedata);
  sny = GDALGetRasterYSize(filedata);
  err = PetscViewerASCIIPrintf(viewer,"%s: nx=%d ny=%d\n",name,snx,sny);dCHK(err);
  band = GDALGetRasterBand(filedata,1);
  cplerr = GDALRasterIO(band,GF_Read,snx/2,sny/2,nx,ny,data,nx,ny,GDT_Float64,0,0);dCPLCHK(cplerr);
  err = dRealTableView(ny,nx,data,PETSC_VIEWER_STDOUT_WORLD,name);dCHK(err);
  dFunctionReturn(0);
}
Exemplo n.º 11
0
static dErr JakoGDALMemAddBand(GDALDatasetH dset,GDALDataType dtype,void *memory)
{
  char buf[256] = {0},**bandoptions = NULL;
  int bytes,nx,ny;
  CPLErr cplerr;
  dErr err;

  dFunctionBegin;
  bytes = GDALGetDataTypeSize(dtype);
  nx = GDALGetRasterXSize(dset);
  ny = GDALGetRasterYSize(dset);
  err = dMalloc(nx*ny*bytes,(void**)memory);dCHK(err);

  // This is where the API moves from merely cumbersome to outright demeaning, like some twisted hazing ritual.
  CPLPrintPointer(buf,*(void**)memory,sizeof(buf));
  bandoptions = CSLSetNameValue(bandoptions,"DATAPOINTER",buf);
  cplerr = GDALAddBand(dset,dtype,bandoptions);dCPLCHK(cplerr);
  CSLDestroy(bandoptions);
  dFunctionReturn(0);
}
Exemplo n.º 12
0
void generic_read(struct FI *f, char *filename)
{
	if (filename_corresponds_to_tiffo(filename)) {
#ifdef FANCY_TIFF
		f->tiffo = true;
		tiff_octaves_init0(f->t, filename, f->megabytes,f->max_octaves);
		if (f->option_write) f->t->option_write = true;
		f->w = f->t->i->w;
		f->h = f->t->i->h;
		f->pd = f->t->i->spp;
		f->no = f->t->noctaves;
#else
		assert(false);
#endif
	} else if (!f->option_write && FORCE_GDAL()) {
#ifdef FANCY_GDAL
		f->gdal = true;
		GDALAllRegister();
		char buf[2*FILENAME_MAX];
		snprintf(buf, 2*FILENAME_MAX, has_prefix(filename, "http://") ||
				has_prefix(filename, "https://") ?
				"/vsicurl/%s" : "%s", filename);
		f->gdal_img = GDALOpen(buf, GA_ReadOnly);
		fprintf(stderr, "gdal_dataset = %p\n", f->gdal_img);
		f->pd = GDALGetRasterCount(f->gdal_img);
		f->w = GDALGetRasterXSize(f->gdal_img);
		f->h = GDALGetRasterYSize(f->gdal_img);
		f->no = 1;
		for (int i = 0; i < f->pd; i++)
			f->gdal_band[i] = GDALGetRasterBand(f->gdal_img, i+1);
#else
		assert(false);
#endif
	} else {
		f->x = iio_read_image_float_vec(filename, &f->w, &f->h, &f->pd);
		f->no = build_pyramid(f, f->max_octaves);
		snprintf(f->x_filename, FILENAME_MAX, "%s", filename);
		f->x_changed = false;
	}
}
Exemplo n.º 13
0
// Determines the pixel/line position given an x/y.
// No reprojection is done at this time.
bool Colorization::getPixelAndLinePosition(double x,
        double y,
        boost::array<double, 6> const& inverse,
        boost::int32_t& pixel,
        boost::int32_t& line,
        void* ds)
{
#ifdef PDAL_HAVE_GDAL
    pixel = (boost::int32_t) std::floor(
                inverse[0]
                + inverse[1] * x
                + inverse[2] * y);
    line = (boost::int32_t) std::floor(
               inverse[3]
               + inverse[4] * x
               + inverse[5] * y);
    
    int xs = GDALGetRasterXSize(ds);
    int ys = GDALGetRasterYSize(ds);
    
    if (!xs || !ys)
    {
        throw pdal_error("Unable to get X or Y size from raster!");
    }

    if (pixel < 0 || 
        line < 0 || 
        pixel >= xs || 
        line  >= ys
       )
    {
        // The x, y is not coincident with this raster
        return false;
    }
#endif

    return true;
}
Exemplo n.º 14
0
int msUVRASTERLayerGetExtent(layerObj *layer, rectObj *extent)

{
  char szPath[MS_MAXPATHLEN];
  mapObj *map = layer->map;
  double adfGeoTransform[6];
  int nXSize, nYSize;
  GDALDatasetH hDS;
  shapefileObj *tileshpfile;
  int tilelayerindex = -1;
  CPLErr eErr = CE_Failure;
  char *decrypted_path;

  if( (!layer->data || strlen(layer->data) == 0)
      && layer->tileindex == NULL) {
    /* should we be issuing a specific error about not supporting
       extents for tileindexed raster layers? */
    return MS_FAILURE;
  }

  if( map == NULL )
    return MS_FAILURE;

  /* If the layer use a tileindex, return the extent of the tileindex shapefile/referenced layer */
  if (layer->tileindex) {
    tilelayerindex = msGetLayerIndex(map, layer->tileindex);
    if(tilelayerindex != -1) /* does the tileindex reference another layer */
      return msLayerGetExtent(GET_LAYER(map, tilelayerindex), extent);
    else {
      tileshpfile = (shapefileObj *) malloc(sizeof(shapefileObj));
      MS_CHECK_ALLOC(tileshpfile, sizeof(shapefileObj), MS_FAILURE);

      if(msShapefileOpen(tileshpfile, "rb", msBuildPath3(szPath, map->mappath, map->shapepath, layer->tileindex), MS_TRUE) == -1)
        if(msShapefileOpen(tileshpfile, "rb", msBuildPath(szPath, map->mappath, layer->tileindex), MS_TRUE) == -1)
          return MS_FAILURE;

      *extent = tileshpfile->bounds;
      msShapefileClose(tileshpfile);
      free(tileshpfile);
      return MS_SUCCESS;
    }
  }

  msTryBuildPath3(szPath, map->mappath, map->shapepath, layer->data);
  decrypted_path = msDecryptStringTokens( map, szPath );

  msAcquireLock( TLOCK_GDAL );
  if( decrypted_path ) {
    hDS = GDALOpen(decrypted_path, GA_ReadOnly );
    msFree( decrypted_path );
  } else
    hDS = NULL;

  if( hDS != NULL ) {
    nXSize = GDALGetRasterXSize( hDS );
    nYSize = GDALGetRasterYSize( hDS );
    eErr = GDALGetGeoTransform( hDS, adfGeoTransform );

    GDALClose( hDS );
  }

  msReleaseLock( TLOCK_GDAL );

  if( hDS == NULL || eErr != CE_None ) {
    return MS_FAILURE;
  }

  /* If this appears to be an ungeoreferenced raster than flip it for
     mapservers purposes. */
  if( adfGeoTransform[5] == 1.0 && adfGeoTransform[3] == 0.0 ) {
    adfGeoTransform[5] = -1.0;
    adfGeoTransform[3] = nYSize;
  }

  extent->minx = adfGeoTransform[0];
  extent->maxy = adfGeoTransform[3];

  extent->maxx = adfGeoTransform[0] + nXSize * adfGeoTransform[1];
  extent->miny = adfGeoTransform[3] + nYSize * adfGeoTransform[5];

  return MS_SUCCESS;
}
Exemplo n.º 15
0
int main( int argc, char ** argv )

{
    GDALDatasetH hSrcDS;
    int         iY, iX, nOutLevel=0, nXSize, nYSize, iArg, nFillDist=0;
    void        *pStream;
    GInt16      *panData;
    const char  *pszFilename = NULL;
    GDALRasterBandH hSrcBand;
    double       adfGeoTransform[6];
    int          bEnableTrim = FALSE;
    GInt16       noDataValue = 0;
    int          bHasNoData;

/* -------------------------------------------------------------------- */
/*      Identify arguments.                                             */
/* -------------------------------------------------------------------- */

    for( iArg = 1; iArg < argc; iArg++ )
    {
        if( EQUAL(argv[iArg],"-trim") )
            bEnableTrim = TRUE;

        else if( EQUAL(argv[iArg],"-fill") )
            nFillDist = atoi(argv[++iArg]);

        else if( EQUAL(argv[iArg],"-level") )
            nOutLevel = atoi(argv[++iArg]);
        else
        {
            if( pszFilename != NULL )
                Usage();
            pszFilename = argv[iArg];
        }
    }

    if( pszFilename == NULL )
        Usage();

/* -------------------------------------------------------------------- */
/*      Open input file.                                                */
/* -------------------------------------------------------------------- */
    GDALAllRegister();
    hSrcDS = GDALOpen( pszFilename, GA_ReadOnly );
    if( hSrcDS == NULL )
        exit(1);

    hSrcBand = GDALGetRasterBand( hSrcDS, 1 );

    noDataValue = (GInt16)GDALGetRasterNoDataValue(hSrcBand, &bHasNoData);

    nXSize = GDALGetRasterXSize( hSrcDS );
    nYSize = GDALGetRasterYSize( hSrcDS );

    GDALGetGeoTransform( hSrcDS, adfGeoTransform );

/* -------------------------------------------------------------------- */
/*      Create output stream.                                           */
/* -------------------------------------------------------------------- */
    pStream = DTEDCreatePtStream( ".", nOutLevel );

    if( pStream == NULL )
        exit( 1 );

/* -------------------------------------------------------------------- */
/*      Process all the profiles.                                       */
/* -------------------------------------------------------------------- */
    panData = (GInt16 *) malloc(sizeof(GInt16) * nXSize);

    for( iY = 0; iY < nYSize; iY++ )
    {
        GDALRasterIO( hSrcBand, GF_Read, 0, iY, nXSize, 1,
                      panData, nXSize, 1, GDT_Int16, 0, 0 );

        if (bHasNoData)
        {
            for( iX = 0; iX < nXSize; iX++ )
            {
                if (panData[iX] == noDataValue)
                    panData[iX] = DTED_NODATA_VALUE;
            }
        }

        for( iX = 0; iX < nXSize; iX++ )
        {
            DTEDWritePt( pStream,
                         adfGeoTransform[0]
                         + adfGeoTransform[1] * (iX + 0.5)
                         + adfGeoTransform[2] * (iY + 0.5),
                         adfGeoTransform[3]
                         + adfGeoTransform[4] * (iX + 0.5)
                         + adfGeoTransform[5] * (iY + 0.5),
                         panData[iX] );
        }
    }

    free( panData );

/* -------------------------------------------------------------------- */
/*      Cleanup.                                                        */
/* -------------------------------------------------------------------- */
    if( bEnableTrim )
        DTEDPtStreamTrimEdgeOnlyTiles( pStream );

    if( nFillDist > 0 )
        DTEDFillPtStream( pStream, nFillDist );

    DTEDClosePtStream( pStream );
    GDALClose( hSrcDS );

    exit( 0 );
}
Exemplo n.º 16
0
int main( int argc, char ** argv )

{
    GDALDatasetH	hDataset, hOutDS;
    int			i;
    const char		*pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff";
    GDALDriverH		hDriver;
    GDALDataType	eOutputType = GDT_Unknown;
    char                **papszCreateOptions = NULL;
    GDALProgressFunc    pfnProgress = GDALTermProgress;
    int                 nLUTBins = 256;
    const char         *pszMethod = "minmax";
//    double              dfStdDevMult = 0.0;
    double             *padfScaleMin = NULL;
    double             *padfScaleMax = NULL;
    int               **papanLUTs = NULL;
    int                 iBand;
    const char         *pszConfigFile = NULL;

    /* Check strict compilation and runtime library version as we use C++ API */
    if (! GDAL_CHECK_VERSION(argv[0]))
        exit(1);
/* -------------------------------------------------------------------- */
/*      Register standard GDAL drivers, and process generic GDAL        */
/*      command options.                                                */
/* -------------------------------------------------------------------- */
    GDALAllRegister();
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Handle command line arguments.                                  */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i],"-of") && i < argc-1 )
            pszFormat = argv[++i];

        else if( EQUAL(argv[i],"-ot") && i < argc-1 )
        {
            int	iType;
            
            for( iType = 1; iType < GDT_TypeCount; iType++ )
            {
                if( GDALGetDataTypeName((GDALDataType)iType) != NULL
                    && EQUAL(GDALGetDataTypeName((GDALDataType)iType),
                             argv[i+1]) )
                {
                    eOutputType = (GDALDataType) iType;
                }
            }

            if( eOutputType == GDT_Unknown )
            {
                printf( "Unknown output pixel type: %s\n", argv[i+1] );
                Usage();
                GDALDestroyDriverManager();
                exit( 2 );
            }
            i++;
        }

        else if( EQUALN(argv[i],"-s_nodata",9) )
        {
            // TODO
            i += 1;
        }   

        else if( EQUAL(argv[i],"-co") && i < argc-1 )
        {
            papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] );
        }   

        else if( EQUALN(argv[i],"-src_scale",10) && i < argc-2)
        {
            // TODO
            i += 2;
        }

        else if( EQUALN(argv[i],"-dst_scale",10) && i < argc-2 )
        {
            // TODO
            i += 2;
        }

        else if( EQUAL(argv[i],"-config") && i < argc-1 )
        {
            pszConfigFile = argv[++i];
        }

        else if( EQUAL(argv[i],"-equalize") )
        {
            pszMethod = "equalize";
        }

        else if( EQUAL(argv[i],"-quiet") )
        {
            pfnProgress = GDALDummyProgress;
        }

        else if( argv[i][0] == '-' )
        {
            printf( "Option %s incomplete, or not recognised.\n\n", 
                    argv[i] );
            Usage();
            GDALDestroyDriverManager();
            exit( 2 );
        }
        else if( pszSource == NULL )
        {
            pszSource = argv[i];
        }
        else if( pszDest == NULL )
        {
            pszDest = argv[i];
        }

        else
        {
            printf( "Too many command options.\n\n" );
            Usage();
            GDALDestroyDriverManager();
            exit( 2 );
        }
    }

    if( pszSource == NULL )
    {
        Usage();
        GDALDestroyDriverManager();
        exit( 10 );
    }

/* -------------------------------------------------------------------- */
/*      Attempt to open source file.                                    */
/* -------------------------------------------------------------------- */

    hDataset = GDALOpenShared( pszSource, GA_ReadOnly );
    
    if( hDataset == NULL )
    {
        fprintf( stderr,
                 "GDALOpen failed - %d\n%s\n",
                 CPLGetLastErrorNo(), CPLGetLastErrorMsg() );
        GDALDestroyDriverManager();
        exit( 1 );
    }

    int nBandCount = GDALGetRasterCount(hDataset);

/* -------------------------------------------------------------------- */
/*      Find the output driver.                                         */
/* -------------------------------------------------------------------- */
    hDriver = GDALGetDriverByName( pszFormat );
    if( hDriver == NULL )
    {
        int	iDr;
        
        printf( "Output driver `%s' not recognised.\n", pszFormat );
        printf( "The following format drivers are configured and support output:\n" );
        for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
        {
            GDALDriverH hDriver = GDALGetDriver(iDr);

            if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL
                || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY,
                                        NULL ) != NULL )
            {
                printf( "  %s: %s\n",
                        GDALGetDriverShortName( hDriver  ),
                        GDALGetDriverLongName( hDriver ) );
            }
        }
        printf( "\n" );
        Usage();
        
        GDALClose( hDataset );
        GDALDestroyDriverManager();
        CSLDestroy( argv );
        CSLDestroy( papszCreateOptions );
        exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      If histogram equalization is requested, do it now.              */
/* -------------------------------------------------------------------- */
    if( EQUAL(pszMethod,"equalize") )
    {
        ComputeEqualizationLUTs( hDataset, nLUTBins, 
                                 &padfScaleMin, &padfScaleMax, 
                                 &papanLUTs, pfnProgress );
    }

/* -------------------------------------------------------------------- */
/*      If we have a config file, assume it is for input and read       */
/*      it.                                                             */
/* -------------------------------------------------------------------- */
    else if( pszConfigFile != NULL )
    {
        char **papszLines = CSLLoad( pszConfigFile );
        if( CSLCount(papszLines) == 0 )
            exit( 1 );

        if( CSLCount(papszLines) != nBandCount )
        {
            fprintf( stderr, "Did not get %d lines in config file as expected.\n", nBandCount );
            exit( 1 );
        }

        padfScaleMin = (double *) CPLCalloc(nBandCount,sizeof(double));
        padfScaleMax = (double *) CPLCalloc(nBandCount,sizeof(double));

        for( iBand = 0; iBand < nBandCount; iBand++ )
        {
            int iLUT;
            char **papszTokens = CSLTokenizeString( papszLines[iBand] );

            if( CSLCount(papszTokens) < 3 
                || atoi(papszTokens[0]) != iBand+1 )
            {
                fprintf( stderr, "Line %d seems to be corrupt.\n", iBand+1 );
                exit( 1 );
            }

            // Process scale min/max

            padfScaleMin[iBand] = atof(papszTokens[1]);
            padfScaleMax[iBand] = atof(papszTokens[2]);

            if( CSLCount(papszTokens) == 3 )
                continue;

            // process lut
            if( iBand == 0 )
            {
                nLUTBins = CSLCount(papszTokens) - 3;
                papanLUTs = (int **) CPLCalloc(sizeof(int*),nBandCount);
            }

            papanLUTs[iBand] = (int *) CPLCalloc(nLUTBins,sizeof(int));

            for( iLUT = 0; iLUT < nLUTBins; iLUT++ )
                papanLUTs[iBand][iLUT] = atoi(papszTokens[iLUT+3]);

            CSLDestroy( papszTokens );
        }
    }

/* -------------------------------------------------------------------- */
/*      If there is no destination, just report the scaling values      */
/*      and luts.                                                       */
/* -------------------------------------------------------------------- */
    if( pszDest == NULL )
    {
        FILE *fpConfig = stdout;
        if( pszConfigFile )
            fpConfig = fopen( pszConfigFile, "w" );
        
        for( iBand = 0; iBand < nBandCount; iBand++ )
        {
            fprintf( fpConfig, "%d:Band ", iBand+1 );
            if( padfScaleMin != NULL )
                fprintf( fpConfig, "%g:ScaleMin %g:ScaleMax ", 
                         padfScaleMin[iBand], padfScaleMax[iBand] );

            if( papanLUTs )
            {
                int iLUT;

                for( iLUT = 0; iLUT < nLUTBins; iLUT++ )
                    fprintf( fpConfig, "%d ", papanLUTs[iBand][iLUT] );
            }
            fprintf( fpConfig, "\n" );
        }

        if( pszConfigFile )
            fclose( fpConfig );

        exit( 0 );
    }

    if (padfScaleMin == NULL || padfScaleMax == NULL)
    {
        fprintf( stderr, "-equalize or -config filename command line options must be specified.\n");
        exit(1);
    }

/* ==================================================================== */
/*      Create a virtual dataset.                                       */
/* ==================================================================== */
    VRTDataset *poVDS;
    EnhanceCBInfo *pasEInfo = (EnhanceCBInfo *) 
        CPLCalloc(nBandCount, sizeof(EnhanceCBInfo));
        
/* -------------------------------------------------------------------- */
/*      Make a virtual clone.                                           */
/* -------------------------------------------------------------------- */
    poVDS = new VRTDataset( GDALGetRasterXSize(hDataset),
                            GDALGetRasterYSize(hDataset) );

    if( GDALGetGCPCount(hDataset) == 0 )
    {
        const char *pszProjection;
        double adfGeoTransform[6];

        pszProjection = GDALGetProjectionRef( hDataset );
        if( pszProjection != NULL && strlen(pszProjection) > 0 )
            poVDS->SetProjection( pszProjection );

        if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
            poVDS->SetGeoTransform( adfGeoTransform );
    }
    else
    {
        poVDS->SetGCPs( GDALGetGCPCount(hDataset), 
                        GDALGetGCPs(hDataset),
                        GDALGetGCPProjection( hDataset ) );
    }
    
    poVDS->SetMetadata( ((GDALDataset*)hDataset)->GetMetadata() );

    for( iBand = 0; iBand < nBandCount; iBand++ )
    {
        VRTSourcedRasterBand   *poVRTBand;
        GDALRasterBand  *poSrcBand;
        GDALDataType    eBandType;

        poSrcBand = ((GDALDataset *) hDataset)->GetRasterBand(iBand+1);

/* -------------------------------------------------------------------- */
/*      Select output data type to match source.                        */
/* -------------------------------------------------------------------- */
        if( eOutputType == GDT_Unknown )
            eBandType = GDT_Byte;
        else
            eBandType = eOutputType;

/* -------------------------------------------------------------------- */
/*      Create this band.                                               */
/* -------------------------------------------------------------------- */
        poVDS->AddBand( eBandType, NULL );
        poVRTBand = (VRTSourcedRasterBand *) poVDS->GetRasterBand( iBand+1 );
            
/* -------------------------------------------------------------------- */
/*      Create a function based source with info on how to apply the    */
/*      enhancement.                                                    */
/* -------------------------------------------------------------------- */
        pasEInfo[iBand].poSrcBand = poSrcBand;
        pasEInfo[iBand].eWrkType = eBandType;
        pasEInfo[iBand].dfScaleMin = padfScaleMin[iBand];
        pasEInfo[iBand].dfScaleMax = padfScaleMax[iBand];
        pasEInfo[iBand].nLUTBins = nLUTBins;

        if( papanLUTs )
            pasEInfo[iBand].panLUT = papanLUTs[iBand];
        
        poVRTBand->AddFuncSource( EnhancerCallback, pasEInfo + iBand );

/* -------------------------------------------------------------------- */
/*      copy over some other information of interest.                   */
/* -------------------------------------------------------------------- */
        poVRTBand->CopyCommonInfoFrom( poSrcBand );
    }

/* -------------------------------------------------------------------- */
/*      Write to the output file using CopyCreate().                    */
/* -------------------------------------------------------------------- */
    hOutDS = GDALCreateCopy( hDriver, pszDest, (GDALDatasetH) poVDS,
                             FALSE, papszCreateOptions, 
                             pfnProgress, NULL );
    if( hOutDS != NULL )
        GDALClose( hOutDS );

    GDALClose( (GDALDatasetH) poVDS );
        
    GDALClose( hDataset );
    
/* -------------------------------------------------------------------- */
/*      Cleanup and exit.                                               */
/* -------------------------------------------------------------------- */
    GDALDumpOpenDatasets( stderr );
    GDALDestroyDriverManager();
    CSLDestroy( argv );
    CSLDestroy( papszCreateOptions );

    exit( 0 );
}
Exemplo n.º 17
0
int main( int argc, char ** argv )

{
    GDALDatasetH	hDataset;
    GDALRasterBandH	hBand;
    int			i, iBand;
    double		adfGeoTransform[6];
    GDALDriverH		hDriver;
    char		**papszMetadata;
    int                 bComputeMinMax = FALSE;

    if( !GDALBridgeInitialize( "..", stderr ) )
    {
        fprintf( stderr, "Unable to intiailize GDAL bridge.\n" );
        exit( 10 );
    }

    if( argc > 1 && strcmp(argv[1],"-mm") == 0 )
    {
        bComputeMinMax = TRUE;
        argv++;
    }

    GDALAllRegister();

    hDataset = GDALOpen( argv[1], GA_ReadOnly );
    
    if( hDataset == NULL )
    {
        fprintf( stderr,
                 "GDALOpen failed - %d\n%s\n",
                 CPLGetLastErrorNo(), CPLGetLastErrorMsg() );
        exit( 1 );
    }
    
/* -------------------------------------------------------------------- */
/*      Report general info.                                            */
/* -------------------------------------------------------------------- */
    hDriver = GDALGetDatasetDriver( hDataset );
    printf( "Driver: %s/%s\n",
            GDALGetDriverShortName( hDriver ),
            GDALGetDriverLongName( hDriver ) );

    printf( "Size is %d, %d\n",
            GDALGetRasterXSize( hDataset ), 
            GDALGetRasterYSize( hDataset ) );

/* -------------------------------------------------------------------- */
/*      Report projection.                                              */
/* -------------------------------------------------------------------- */
    if( GDALGetProjectionRef( hDataset ) != NULL )
    {
        OGRSpatialReferenceH  hSRS;
        char		      *pszProjection;

        pszProjection = (char *) GDALGetProjectionRef( hDataset );

        hSRS = OSRNewSpatialReference(NULL);
        if( OSRImportFromWkt( hSRS, &pszProjection ) == CE_None )
        {
            char	*pszPrettyWkt = NULL;

            OSRExportToPrettyWkt( hSRS, &pszPrettyWkt, FALSE );
            printf( "Coordinate System is:\n%s\n", pszPrettyWkt );
        }
        else
            printf( "Coordinate System is `%s'\n",
                    GDALGetProjectionRef( hDataset ) );

        OSRDestroySpatialReference( hSRS );
    }

/* -------------------------------------------------------------------- */
/*      Report Geotransform.                                            */
/* -------------------------------------------------------------------- */
    if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
    {
        printf( "Origin = (%.6f,%.6f)\n",
                adfGeoTransform[0], adfGeoTransform[3] );

        printf( "Pixel Size = (%.6f,%.6f)\n",
                adfGeoTransform[1], adfGeoTransform[5] );
    }

/* -------------------------------------------------------------------- */
/*      Report GCPs.                                                    */
/* -------------------------------------------------------------------- */
    if( GDALGetGCPCount( hDataset ) > 0 )
    {
        printf( "GCP Projection = %s\n", GDALGetGCPProjection(hDataset) );
        for( i = 0; i < GDALGetGCPCount(hDataset); i++ )
        {
            const GDAL_GCP	*psGCP;
            
            psGCP = GDALGetGCPs( hDataset ) + i;

            printf( "GCP[%3d]: Id=%s, Info=%s\n"
                    "          (%g,%g) -> (%g,%g,%g)\n", 
                    i, psGCP->pszId, psGCP->pszInfo, 
                    psGCP->dfGCPPixel, psGCP->dfGCPLine, 
                    psGCP->dfGCPX, psGCP->dfGCPY, psGCP->dfGCPZ );
        }
    }

/* -------------------------------------------------------------------- */
/*      Report metadata.                                                */
/* -------------------------------------------------------------------- */
    papszMetadata = GDALGetMetadata( hDataset, NULL );
    if( papszMetadata != NULL )
    {
        printf( "Metadata:\n" );
        for( i = 0; papszMetadata[i] != NULL; i++ )
        {
            printf( "  %s\n", papszMetadata[i] );
        }
    }

/* -------------------------------------------------------------------- */
/*      Report subdatasets.                                             */
/* -------------------------------------------------------------------- */
    papszMetadata = GDALGetMetadata( hDataset, "SUBDATASETS" );
    if( papszMetadata != NULL )
    {
        printf( "Subdatasets:\n" );
        for( i = 0; papszMetadata[i] != NULL; i++ )
        {
            printf( "  %s\n", papszMetadata[i] );
        }
    }

/* -------------------------------------------------------------------- */
/*      Report corners.                                                 */
/* -------------------------------------------------------------------- */
    printf( "Corner Coordinates:\n" );
    GDALInfoReportCorner( hDataset, "Upper Left", 
                          0.0, 0.0 );
    GDALInfoReportCorner( hDataset, "Lower Left", 
                          0.0, GDALGetRasterYSize(hDataset));
    GDALInfoReportCorner( hDataset, "Upper Right", 
                          GDALGetRasterXSize(hDataset), 0.0 );
    GDALInfoReportCorner( hDataset, "Lower Right", 
                          GDALGetRasterXSize(hDataset), 
                          GDALGetRasterYSize(hDataset) );
    GDALInfoReportCorner( hDataset, "Center", 
                          GDALGetRasterXSize(hDataset)/2.0, 
                          GDALGetRasterYSize(hDataset)/2.0 );

/* ==================================================================== */
/*      Loop over bands.                                                */
/* ==================================================================== */
    for( iBand = 0; iBand < GDALGetRasterCount( hDataset ); iBand++ )
    {
        double      dfMin, dfMax, adfCMinMax[2], dfNoData;
        int         bGotMin, bGotMax, bGotNodata;
        int         nBlockXSize, nBlockYSize;

        hBand = GDALGetRasterBand( hDataset, iBand+1 );
        GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize );
        printf( "Band %d Block=%dx%d Type=%d, ColorInterp=%d\n", iBand+1,
                nBlockXSize, nBlockYSize,
                GDALGetRasterDataType(hBand),
                GDALGetRasterColorInterpretation(hBand) );

        dfMin = GDALGetRasterMinimum( hBand, &bGotMin );
        dfMax = GDALGetRasterMaximum( hBand, &bGotMax );
        printf( "  Min=%.3f/%d, Max=%.3f/%d",  dfMin, bGotMin, dfMax, bGotMax);
        
        if( bComputeMinMax )
        {
            GDALComputeRasterMinMax( hBand, TRUE, adfCMinMax );
            printf( ", Computed Min/Max=%.3f,%.3f", 
                    adfCMinMax[0], adfCMinMax[1] );
        }
        printf( "\n" );

        dfNoData = GDALGetRasterNoDataValue( hBand, &bGotNodata );
        if( bGotNodata )
        {
            printf( "  NoData Value=%g\n", dfNoData );
        }

        if( GDALGetOverviewCount(hBand) > 0 )
        {
            int		iOverview;

            printf( "  Overviews: " );
            for( iOverview = 0; 
                 iOverview < GDALGetOverviewCount(hBand);
                 iOverview++ )
            {
                GDALRasterBandH	hOverview;

                if( iOverview != 0 )
                    printf( ", " );

                hOverview = GDALGetOverview( hBand, iOverview );
                printf( "%dx%d", 
                        GDALGetRasterBandXSize( hOverview ),
                        GDALGetRasterBandYSize( hOverview ) );
            }
            printf( "\n" );
        }

        papszMetadata = GDALGetMetadata( hBand, NULL );
        if( papszMetadata != NULL )
        {
            printf( "Metadata:\n" );
            for( i = 0; papszMetadata[i] != NULL; i++ )
            {
                printf( "  %s\n", papszMetadata[i] );
            }
        }

        if( GDALGetRasterColorInterpretation(hBand) == GCI_PaletteIndex )
        {
            GDALColorTableH	hTable;
            int			i;

            hTable = GDALGetRasterColorTable( hBand );
            printf( "  Color Table (%s with %d entries)\n", 
                    GDALGetPaletteInterpretationName(
                        GDALGetPaletteInterpretation( hTable )), 
                    GDALGetColorEntryCount( hTable ) );

            for( i = 0; i < GDALGetColorEntryCount( hTable ); i++ )
            {
                GDALColorEntry	sEntry;

                GDALGetColorEntryAsRGB( hTable, i, &sEntry );
                printf( "  %3d: %d,%d,%d,%d\n", 
                        i, 
                        sEntry.c1,
                        sEntry.c2,
                        sEntry.c3,
                        sEntry.c4 );
            }
        }
    }

    GDALClose( hDataset );
    
    exit( 0 );
}
Exemplo n.º 18
0
int main( int argc, char ** argv )

{
    GDALDatasetH	hDataset;
    GDALRasterBandH	hBand;
    int			i, iBand;
    double		adfGeoTransform[6];
    GDALDriverH		hDriver;
    char		**papszMetadata;
    int                 bComputeMinMax = FALSE, bSample = FALSE;
    int                 bShowGCPs = TRUE, bShowMetadata = TRUE, bShowRAT=TRUE;
    int                 bStats = FALSE, bApproxStats = TRUE, iMDD;
    int                 bShowColorTable = TRUE, bComputeChecksum = FALSE;
    int                 bReportHistograms = FALSE;
    const char          *pszFilename = NULL;
    char              **papszExtraMDDomains = NULL, **papszFileList;
    const char  *pszProjection = NULL;
    OGRCoordinateTransformationH hTransform = NULL;

    /* Check that we are running against at least GDAL 1.5 */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1500)
    {
        fprintf(stderr, "At least, GDAL >= 1.5.0 is required for this version of %s, "
                "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME);
        exit(1);
    }


    /* Must process GDAL_SKIP before GDALAllRegister(), but we can't call */
    /* GDALGeneralCmdLineProcessor before it needs the drivers to be registered */
    /* for the --format or --formats options */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i],"--config") && i + 2 < argc && EQUAL(argv[i + 1], "GDAL_SKIP") )
        {
            CPLSetConfigOption( argv[i+1], argv[i+2] );

            i += 2;
        }
    }

    GDALAllRegister();

    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i], "-mm") )
            bComputeMinMax = TRUE;
        else if( EQUAL(argv[i], "-hist") )
            bReportHistograms = TRUE;
        else if( EQUAL(argv[i], "-stats") )
        {
            bStats = TRUE;
            bApproxStats = FALSE;
        }
        else if( EQUAL(argv[i], "-approx_stats") )
        {
            bStats = TRUE;
            bApproxStats = TRUE;
        }
        else if( EQUAL(argv[i], "-sample") )
            bSample = TRUE;
        else if( EQUAL(argv[i], "-checksum") )
            bComputeChecksum = TRUE;
        else if( EQUAL(argv[i], "-nogcp") )
            bShowGCPs = FALSE;
        else if( EQUAL(argv[i], "-nomd") )
            bShowMetadata = FALSE;
        else if( EQUAL(argv[i], "-norat") )
            bShowRAT = FALSE;
        else if( EQUAL(argv[i], "-noct") )
            bShowColorTable = FALSE;
        else if( EQUAL(argv[i], "-mdd") && i < argc-1 )
            papszExtraMDDomains = CSLAddString( papszExtraMDDomains,
                                                argv[++i] );
        else if( argv[i][0] == '-' )
            Usage();
        else if( pszFilename == NULL )
            pszFilename = argv[i];
        else
            Usage();
    }

    if( pszFilename == NULL )
        Usage();

/* -------------------------------------------------------------------- */
/*      Open dataset.                                                   */
/* -------------------------------------------------------------------- */
    hDataset = GDALOpen( pszFilename, GA_ReadOnly );
    
    if( hDataset == NULL )
    {
        fprintf( stderr,
                 "gdalinfo failed - unable to open '%s'.\n",
                 pszFilename );

        CSLDestroy( argv );
    
        GDALDumpOpenDatasets( stderr );

        GDALDestroyDriverManager();

        CPLDumpSharedList( NULL );

        exit( 1 );
    }
    
/* -------------------------------------------------------------------- */
/*      Report general info.                                            */
/* -------------------------------------------------------------------- */
    hDriver = GDALGetDatasetDriver( hDataset );
    printf( "Driver: %s/%s\n",
            GDALGetDriverShortName( hDriver ),
            GDALGetDriverLongName( hDriver ) );

    papszFileList = GDALGetFileList( hDataset );
    if( CSLCount(papszFileList) == 0 )
    {
        printf( "Files: none associated\n" );
    }
    else
    {
        printf( "Files: %s\n", papszFileList[0] );
        for( i = 1; papszFileList[i] != NULL; i++ )
            printf( "       %s\n", papszFileList[i] );
    }
    CSLDestroy( papszFileList );

    printf( "Size is %d, %d\n",
            GDALGetRasterXSize( hDataset ), 
            GDALGetRasterYSize( hDataset ) );

/* -------------------------------------------------------------------- */
/*      Report projection.                                              */
/* -------------------------------------------------------------------- */
    if( GDALGetProjectionRef( hDataset ) != NULL )
    {
        OGRSpatialReferenceH  hSRS;
        char		      *pszProjection;

        pszProjection = (char *) GDALGetProjectionRef( hDataset );

        hSRS = OSRNewSpatialReference(NULL);
        if( OSRImportFromWkt( hSRS, &pszProjection ) == CE_None )
        {
            char	*pszPrettyWkt = NULL;

            OSRExportToPrettyWkt( hSRS, &pszPrettyWkt, FALSE );
            printf( "Coordinate System is:\n%s\n", pszPrettyWkt );
            CPLFree( pszPrettyWkt );
        }
        else
            printf( "Coordinate System is `%s'\n",
                    GDALGetProjectionRef( hDataset ) );

        OSRDestroySpatialReference( hSRS );
    }

/* -------------------------------------------------------------------- */
/*      Report Geotransform.                                            */
/* -------------------------------------------------------------------- */
    if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
    {
        if( adfGeoTransform[2] == 0.0 && adfGeoTransform[4] == 0.0 )
        {
            printf( "Origin = (%.15f,%.15f)\n",
                    adfGeoTransform[0], adfGeoTransform[3] );

            printf( "Pixel Size = (%.15f,%.15f)\n",
                    adfGeoTransform[1], adfGeoTransform[5] );
        }
        else
            printf( "GeoTransform =\n"
                    "  %.16g, %.16g, %.16g\n"
                    "  %.16g, %.16g, %.16g\n", 
                    adfGeoTransform[0],
                    adfGeoTransform[1],
                    adfGeoTransform[2],
                    adfGeoTransform[3],
                    adfGeoTransform[4],
                    adfGeoTransform[5] );
    }

/* -------------------------------------------------------------------- */
/*      Report GCPs.                                                    */
/* -------------------------------------------------------------------- */
    if( bShowGCPs && GDALGetGCPCount( hDataset ) > 0 )
    {
        if (GDALGetGCPProjection(hDataset) != NULL)
        {
            OGRSpatialReferenceH  hSRS;
            char		      *pszProjection;

            pszProjection = (char *) GDALGetGCPProjection( hDataset );

            hSRS = OSRNewSpatialReference(NULL);
            if( OSRImportFromWkt( hSRS, &pszProjection ) == CE_None )
            {
                char	*pszPrettyWkt = NULL;

                OSRExportToPrettyWkt( hSRS, &pszPrettyWkt, FALSE );
                printf( "GCP Projection = \n%s\n", pszPrettyWkt );
                CPLFree( pszPrettyWkt );
            }
            else
                printf( "GCP Projection = %s\n",
                        GDALGetGCPProjection( hDataset ) );

            OSRDestroySpatialReference( hSRS );
        }

        for( i = 0; i < GDALGetGCPCount(hDataset); i++ )
        {
            const GDAL_GCP	*psGCP;
            
            psGCP = GDALGetGCPs( hDataset ) + i;

            printf( "GCP[%3d]: Id=%s, Info=%s\n"
                    "          (%.15g,%.15g) -> (%.15g,%.15g,%.15g)\n", 
                    i, psGCP->pszId, psGCP->pszInfo, 
                    psGCP->dfGCPPixel, psGCP->dfGCPLine, 
                    psGCP->dfGCPX, psGCP->dfGCPY, psGCP->dfGCPZ );
        }
    }

/* -------------------------------------------------------------------- */
/*      Report metadata.                                                */
/* -------------------------------------------------------------------- */
    papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, NULL ) : NULL;
    if( bShowMetadata && CSLCount(papszMetadata) > 0 )
    {
        printf( "Metadata:\n" );
        for( i = 0; papszMetadata[i] != NULL; i++ )
        {
            printf( "  %s\n", papszMetadata[i] );
        }
    }

    for( iMDD = 0; bShowMetadata && iMDD < CSLCount(papszExtraMDDomains); iMDD++ )
    {
        papszMetadata = GDALGetMetadata( hDataset, papszExtraMDDomains[iMDD] );
        if( CSLCount(papszMetadata) > 0 )
        {
            printf( "Metadata (%s):\n", papszExtraMDDomains[iMDD]);
            for( i = 0; papszMetadata[i] != NULL; i++ )
            {
                printf( "  %s\n", papszMetadata[i] );
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Report "IMAGE_STRUCTURE" metadata.                              */
/* -------------------------------------------------------------------- */
    papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, "IMAGE_STRUCTURE" ) : NULL;
    if( bShowMetadata && CSLCount(papszMetadata) > 0 )
    {
        printf( "Image Structure Metadata:\n" );
        for( i = 0; papszMetadata[i] != NULL; i++ )
        {
            printf( "  %s\n", papszMetadata[i] );
        }
    }

/* -------------------------------------------------------------------- */
/*      Report subdatasets.                                             */
/* -------------------------------------------------------------------- */
    papszMetadata = GDALGetMetadata( hDataset, "SUBDATASETS" );
    if( CSLCount(papszMetadata) > 0 )
    {
        printf( "Subdatasets:\n" );
        for( i = 0; papszMetadata[i] != NULL; i++ )
        {
            printf( "  %s\n", papszMetadata[i] );
        }
    }

/* -------------------------------------------------------------------- */
/*      Report geolocation.                                             */
/* -------------------------------------------------------------------- */
    papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, "GEOLOCATION" ) : NULL;
    if( bShowMetadata && CSLCount(papszMetadata) > 0 )
    {
        printf( "Geolocation:\n" );
        for( i = 0; papszMetadata[i] != NULL; i++ )
        {
            printf( "  %s\n", papszMetadata[i] );
        }
    }

/* -------------------------------------------------------------------- */
/*      Report RPCs                                                     */
/* -------------------------------------------------------------------- */
    papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, "RPC" ) : NULL;
    if( bShowMetadata && CSLCount(papszMetadata) > 0 )
    {
        printf( "RPC Metadata:\n" );
        for( i = 0; papszMetadata[i] != NULL; i++ )
        {
            printf( "  %s\n", papszMetadata[i] );
        }
    }

/* -------------------------------------------------------------------- */
/*      Setup projected to lat/long transform if appropriate.           */
/* -------------------------------------------------------------------- */
    if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
        pszProjection = GDALGetProjectionRef(hDataset);

    if( pszProjection != NULL && strlen(pszProjection) > 0 )
    {
        OGRSpatialReferenceH hProj, hLatLong = NULL;

        hProj = OSRNewSpatialReference( pszProjection );
        if( hProj != NULL )
            hLatLong = OSRCloneGeogCS( hProj );

        if( hLatLong != NULL )
        {
            CPLPushErrorHandler( CPLQuietErrorHandler );
            hTransform = OCTNewCoordinateTransformation( hProj, hLatLong );
            CPLPopErrorHandler();
            
            OSRDestroySpatialReference( hLatLong );
        }

        if( hProj != NULL )
            OSRDestroySpatialReference( hProj );
    }

/* -------------------------------------------------------------------- */
/*      Report corners.                                                 */
/* -------------------------------------------------------------------- */
    printf( "Corner Coordinates:\n" );
    GDALInfoReportCorner( hDataset, hTransform, "Upper Left", 
                          0.0, 0.0 );
    GDALInfoReportCorner( hDataset, hTransform, "Lower Left", 
                          0.0, GDALGetRasterYSize(hDataset));
    GDALInfoReportCorner( hDataset, hTransform, "Upper Right", 
                          GDALGetRasterXSize(hDataset), 0.0 );
    GDALInfoReportCorner( hDataset, hTransform, "Lower Right", 
                          GDALGetRasterXSize(hDataset), 
                          GDALGetRasterYSize(hDataset) );
    GDALInfoReportCorner( hDataset, hTransform, "Center", 
                          GDALGetRasterXSize(hDataset)/2.0, 
                          GDALGetRasterYSize(hDataset)/2.0 );

    if( hTransform != NULL )
    {
        OCTDestroyCoordinateTransformation( hTransform );
        hTransform = NULL;
    }
    
/* ==================================================================== */
/*      Loop over bands.                                                */
/* ==================================================================== */
    for( iBand = 0; iBand < GDALGetRasterCount( hDataset ); iBand++ )
    {
        double      dfMin, dfMax, adfCMinMax[2], dfNoData;
        int         bGotMin, bGotMax, bGotNodata, bSuccess;
        int         nBlockXSize, nBlockYSize, nMaskFlags;
        double      dfMean, dfStdDev;
        GDALColorTableH	hTable;
        CPLErr      eErr;

        hBand = GDALGetRasterBand( hDataset, iBand+1 );

        if( bSample )
        {
            float afSample[10000];
            int   nCount;

            nCount = GDALGetRandomRasterSample( hBand, 10000, afSample );
            printf( "Got %d samples.\n", nCount );
        }
        
        GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize );
        printf( "Band %d Block=%dx%d Type=%s, ColorInterp=%s\n", iBand+1,
                nBlockXSize, nBlockYSize,
                GDALGetDataTypeName(
                    GDALGetRasterDataType(hBand)),
                GDALGetColorInterpretationName(
                    GDALGetRasterColorInterpretation(hBand)) );

        if( GDALGetDescription( hBand ) != NULL 
            && strlen(GDALGetDescription( hBand )) > 0 )
            printf( "  Description = %s\n", GDALGetDescription(hBand) );

        dfMin = GDALGetRasterMinimum( hBand, &bGotMin );
        dfMax = GDALGetRasterMaximum( hBand, &bGotMax );
        if( bGotMin || bGotMax || bComputeMinMax )
        {
            printf( "  " );
            if( bGotMin )
                printf( "Min=%.3f ", dfMin );
            if( bGotMax )
                printf( "Max=%.3f ", dfMax );
        
            if( bComputeMinMax )
            {
                CPLErrorReset();
                GDALComputeRasterMinMax( hBand, FALSE, adfCMinMax );
                if (CPLGetLastErrorType() == CE_None)
                {
                  printf( "  Computed Min/Max=%.3f,%.3f", 
                          adfCMinMax[0], adfCMinMax[1] );
                }
            }

            printf( "\n" );
        }

        eErr = GDALGetRasterStatistics( hBand, bApproxStats, bStats, 
                                        &dfMin, &dfMax, &dfMean, &dfStdDev );
        if( eErr == CE_None )
        {
            printf( "  Minimum=%.3f, Maximum=%.3f, Mean=%.3f, StdDev=%.3f\n",
                    dfMin, dfMax, dfMean, dfStdDev );
        }

        if( bReportHistograms )
        {
            int nBucketCount, *panHistogram = NULL;

            eErr = GDALGetDefaultHistogram( hBand, &dfMin, &dfMax, 
                                            &nBucketCount, &panHistogram, 
                                            TRUE, GDALTermProgress, NULL );
            if( eErr == CE_None )
            {
                int iBucket;

                printf( "  %d buckets from %g to %g:\n  ",
                        nBucketCount, dfMin, dfMax );
                for( iBucket = 0; iBucket < nBucketCount; iBucket++ )
                    printf( "%d ", panHistogram[iBucket] );
                printf( "\n" );
                CPLFree( panHistogram );
            }
        }

        if ( bComputeChecksum)
        {
            printf( "  Checksum=%d\n",
                    GDALChecksumImage(hBand, 0, 0,
                                      GDALGetRasterXSize(hDataset),
                                      GDALGetRasterYSize(hDataset)));
        }

        dfNoData = GDALGetRasterNoDataValue( hBand, &bGotNodata );
        if( bGotNodata )
        {
            printf( "  NoData Value=%.18g\n", dfNoData );
        }

        if( GDALGetOverviewCount(hBand) > 0 )
        {
            int		iOverview;

            printf( "  Overviews: " );
            for( iOverview = 0; 
                 iOverview < GDALGetOverviewCount(hBand);
                 iOverview++ )
            {
                GDALRasterBandH	hOverview;
                const char *pszResampling = NULL;

                if( iOverview != 0 )
                    printf( ", " );

                hOverview = GDALGetOverview( hBand, iOverview );
                printf( "%dx%d", 
                        GDALGetRasterBandXSize( hOverview ),
                        GDALGetRasterBandYSize( hOverview ) );

                pszResampling = 
                    GDALGetMetadataItem( hOverview, "RESAMPLING", "" );

                if( pszResampling != NULL 
                    && EQUALN(pszResampling,"AVERAGE_BIT2",12) )
                    printf( "*" );
            }
            printf( "\n" );

            if ( bComputeChecksum)
            {
                printf( "  Overviews checksum: " );
                for( iOverview = 0; 
                    iOverview < GDALGetOverviewCount(hBand);
                    iOverview++ )
                {
                    GDALRasterBandH	hOverview;

                    if( iOverview != 0 )
                        printf( ", " );

                    hOverview = GDALGetOverview( hBand, iOverview );
                    printf( "%d",
                            GDALChecksumImage(hOverview, 0, 0,
                                      GDALGetRasterBandXSize(hOverview),
                                      GDALGetRasterBandYSize(hOverview)));
                }
                printf( "\n" );
            }
        }

        if( GDALHasArbitraryOverviews( hBand ) )
        {
            printf( "  Overviews: arbitrary\n" );
        }
        
        nMaskFlags = GDALGetMaskFlags( hBand );
        if( (nMaskFlags & (GMF_NODATA|GMF_ALL_VALID)) == 0 )
        {
            GDALRasterBandH hMaskBand = GDALGetMaskBand(hBand) ;

            printf( "  Mask Flags: " );
            if( nMaskFlags & GMF_PER_DATASET )
                printf( "PER_DATASET " );
            if( nMaskFlags & GMF_ALPHA )
                printf( "ALPHA " );
            if( nMaskFlags & GMF_NODATA )
                printf( "NODATA " );
            if( nMaskFlags & GMF_ALL_VALID )
                printf( "ALL_VALID " );
            printf( "\n" );

            if( hMaskBand != NULL &&
                GDALGetOverviewCount(hMaskBand) > 0 )
            {
                int		iOverview;

                printf( "  Overviews of mask band: " );
                for( iOverview = 0; 
                     iOverview < GDALGetOverviewCount(hMaskBand);
                     iOverview++ )
                {
                    GDALRasterBandH	hOverview;

                    if( iOverview != 0 )
                        printf( ", " );

                    hOverview = GDALGetOverview( hMaskBand, iOverview );
                    printf( "%dx%d", 
                            GDALGetRasterBandXSize( hOverview ),
                            GDALGetRasterBandYSize( hOverview ) );
                }
                printf( "\n" );
            }
        }

        if( strlen(GDALGetRasterUnitType(hBand)) > 0 )
        {
            printf( "  Unit Type: %s\n", GDALGetRasterUnitType(hBand) );
        }

        if( GDALGetRasterCategoryNames(hBand) != NULL )
        {
            char **papszCategories = GDALGetRasterCategoryNames(hBand);
            int i;

            printf( "  Categories:\n" );
            for( i = 0; papszCategories[i] != NULL; i++ )
                printf( "    %3d: %s\n", i, papszCategories[i] );
        }

        if( GDALGetRasterScale( hBand, &bSuccess ) != 1.0 
            || GDALGetRasterOffset( hBand, &bSuccess ) != 0.0 )
            printf( "  Offset: %.15g,   Scale:%.15g\n",
                    GDALGetRasterOffset( hBand, &bSuccess ),
                    GDALGetRasterScale( hBand, &bSuccess ) );

        papszMetadata = (bShowMetadata) ? GDALGetMetadata( hBand, NULL ) : NULL;
        if( bShowMetadata && CSLCount(papszMetadata) > 0 )
        {
            printf( "  Metadata:\n" );
            for( i = 0; papszMetadata[i] != NULL; i++ )
            {
                printf( "    %s\n", papszMetadata[i] );
            }
        }

        papszMetadata = (bShowMetadata) ? GDALGetMetadata( hBand, "IMAGE_STRUCTURE" ) : NULL;
        if( bShowMetadata && CSLCount(papszMetadata) > 0 )
        {
            printf( "  Image Structure Metadata:\n" );
            for( i = 0; papszMetadata[i] != NULL; i++ )
            {
                printf( "    %s\n", papszMetadata[i] );
            }
        }

        if( GDALGetRasterColorInterpretation(hBand) == GCI_PaletteIndex 
            && (hTable = GDALGetRasterColorTable( hBand )) != NULL )
        {
            int			i;

            printf( "  Color Table (%s with %d entries)\n", 
                    GDALGetPaletteInterpretationName(
                        GDALGetPaletteInterpretation( hTable )), 
                    GDALGetColorEntryCount( hTable ) );

            if (bShowColorTable)
            {
                for( i = 0; i < GDALGetColorEntryCount( hTable ); i++ )
                {
                    GDALColorEntry	sEntry;
    
                    GDALGetColorEntryAsRGB( hTable, i, &sEntry );
                    printf( "  %3d: %d,%d,%d,%d\n", 
                            i, 
                            sEntry.c1,
                            sEntry.c2,
                            sEntry.c3,
                            sEntry.c4 );
                }
            }
        }

        if( bShowRAT && GDALGetDefaultRAT( hBand ) != NULL )
        {
            GDALRasterAttributeTableH hRAT = GDALGetDefaultRAT( hBand );
            
            GDALRATDumpReadable( hRAT, NULL );
        }
    }

    GDALClose( hDataset );
    
    CSLDestroy( papszExtraMDDomains );
    CSLDestroy( argv );
    
    GDALDumpOpenDatasets( stderr );

    GDALDestroyDriverManager();

    CPLDumpSharedList( NULL );
    CPLCleanupTLS();

    exit( 0 );
}
Exemplo n.º 19
0
GvSymbolObj *
gv_symbol_manager_get_symbol(GvSymbolManager *manager, const char *symbol_name)
{
    gchar   *pszOpenEVHome = NULL;
    gchar   *pszSymbolsDir = NULL;
    gchar   *pszAbsolutePath = NULL;
    gchar   *pszPathSeparator = NULL;
    GDALDatasetH hDataset;
    GvSymbolObj *poSymbol;
    CPLXMLNode  *xml_shape = NULL;
    GByte *rgba_buffer;

/* -------------------------------------------------------------------- */
/*      Lookup the symbol in the hash table, and return it if found.    */
/* -------------------------------------------------------------------- */
    poSymbol = g_hash_table_lookup( manager->symbol_cache, symbol_name );
    if( poSymbol != NULL )
        return poSymbol;

/* -------------------------------------------------------------------- */
/*      We didn't already have it, so try to find a file to load it     */
/*      from.                                                           */
/* -------------------------------------------------------------------- */
#ifndef WIN32
    pszPathSeparator = "/";
#else
    pszPathSeparator = "\\";
#endif /* WIN32 */

    /* validate inputs */
    g_return_val_if_fail( manager != NULL, 0 );
    g_return_val_if_fail( symbol_name != NULL, 0 );

    /* get an absolute path */
    if ( !g_path_is_absolute( symbol_name ) )
    {
        /* check configuration option first */
        pszSymbolsDir = g_strdup( gv_manager_get_preference( gv_get_manager(),
                                                             "symbols_dir" ) );

        /* if not configured check $OPENEV_HOME */
        if ( !pszSymbolsDir )
        {
            pszOpenEVHome = g_getenv( "OPENEV_HOME" );
            if( pszOpenEVHome == NULL )
                pszOpenEVHome = g_getenv( "OPENEVHOME" );
            if ( pszOpenEVHome )
                pszSymbolsDir = g_strjoin( pszPathSeparator, pszOpenEVHome,
                                           "symbols", NULL );
        }
        
        /* get current directory as last resort */
        if ( !pszSymbolsDir )
            pszSymbolsDir = g_get_current_dir();

        pszAbsolutePath = g_strjoin( pszPathSeparator, pszSymbolsDir, 
                                     symbol_name, NULL );
        g_free( pszSymbolsDir );
    }
    else
        pszAbsolutePath = g_strdup( symbol_name );

/* -------------------------------------------------------------------- */
/*      pszAbsolutePath contains a newly allocated string that is       */
/*      suitable for using as a key in the hash table.  If a texture    */
/*      is found in the hash table then this string needs to be         */
/*      freed.  If one isn't found then the string is used in the       */
/*      hash table and should be freed when the associated hash         */
/*      table entry is released                                         */
/* -------------------------------------------------------------------- */
    CPLDebug( "OpenEV", 
              "gv_symbol_manager_get_symbol(%s) ... need to load.", 
                  pszAbsolutePath );
    
    /* 
     * validate path by opening with GDAL and looking for an error 
     * Disable CPL error handler to supress error reporting
     */
    
    CPLErrorReset();
    CPLPushErrorHandler( CPLQuietErrorHandler );
    hDataset = GDALOpen( pszAbsolutePath, GA_ReadOnly );
    CPLPopErrorHandler();
    
    if ( hDataset )
    {
        rgba_buffer = gdal_to_rgba( hDataset );
        
        if ( rgba_buffer )
        {
            gv_symbol_manager_inject_raster_symbol( 
                manager, symbol_name,
                GDALGetRasterXSize( hDataset ),
                GDALGetRasterYSize( hDataset ),
                rgba_buffer );
            CPLFree( rgba_buffer );
        }
        
        GDALClose( hDataset );
    }
    /* probably we have vector symbol? */
    else if ( ( xml_shape = CPLParseXMLFile( pszAbsolutePath ) ) )
    {
        GvShape     *shape;
        shape = gv_shape_from_xml_tree( xml_shape );
        
        CPLDestroyXMLNode( xml_shape );
        
        if( shape != NULL )
            gv_symbol_manager_inject_vector_symbol( manager, symbol_name,
                                                    shape );
        else
        {
            CPLDebug( "OpenEV", 
                      "Failed to instantiate GvSahpe from file %s, using simple point.", 
                      pszAbsolutePath );
        
            shape = gv_shape_new( GVSHAPE_POINT );
            gv_symbol_manager_inject_vector_symbol( manager, symbol_name,
                                                    shape );
        }
    }
    else
    {
        GvShape *shape;

        CPLDebug( "OpenEV", "Failed to open file %s, using simple point.", 
                  pszAbsolutePath );
        
        shape = gv_shape_new( GVSHAPE_POINT );
        gv_symbol_manager_inject_vector_symbol( manager, symbol_name,
                                                shape );
    }
    
    /* look up in the hash table again */
    poSymbol = g_hash_table_lookup(manager->symbol_cache, symbol_name );

    g_free( pszAbsolutePath );

    return poSymbol;
}
Exemplo n.º 20
0
static void DumpBand( GDALDatasetH hBaseDS, GDALRasterBandH hSrcOver,
                      const char *pszName )

{
/* -------------------------------------------------------------------- */
/*      Get base ds info.                                               */
/* -------------------------------------------------------------------- */
    double adfGeoTransform[6];
    bool bHaveGT = GDALGetGeoTransform( hBaseDS, adfGeoTransform ) == CE_None;

    int nOrigXSize = GDALGetRasterXSize( hBaseDS );
    int nOrigYSize = GDALGetRasterYSize( hBaseDS );

/* -------------------------------------------------------------------- */
/*      Create matching output file.                                    */
/* -------------------------------------------------------------------- */
    int nXSize = GDALGetRasterBandXSize( hSrcOver );
    int nYSize = GDALGetRasterBandYSize( hSrcOver );
    GDALDataType eDT = GDALGetRasterDataType( hSrcOver );
    GDALDriverH hDriver = GDALGetDriverByName( "GTiff" );

    GDALDatasetH hDstDS = GDALCreate( hDriver, pszName, nXSize, nYSize,
                                      1, eDT, NULL );

    if( hDstDS == NULL )
        exit( 1 );

/* -------------------------------------------------------------------- */
/*      Apply corresponding georeferencing, scaled to size.             */
/* -------------------------------------------------------------------- */
    if( bHaveGT )
    {
        double adfOvGeoTransform[6];

        memcpy( adfOvGeoTransform, adfGeoTransform,
                sizeof(double) * 6 );

        adfOvGeoTransform[1] *= (nOrigXSize / (double) nXSize);
        adfOvGeoTransform[2] *= (nOrigXSize / (double) nXSize);
        adfOvGeoTransform[4] *= (nOrigYSize / (double) nYSize);
        adfOvGeoTransform[5] *= (nOrigYSize / (double) nYSize);

        GDALSetGeoTransform( hDstDS, adfOvGeoTransform );

        GDALSetProjection( hDstDS, GDALGetProjectionRef( hBaseDS ) );
    }

/* -------------------------------------------------------------------- */
/*      Copy over all the image data.                                   */
/* -------------------------------------------------------------------- */
    void *pData = CPLMalloc(64 * nXSize);

    for( int iLine = 0; iLine < nYSize; iLine++ )
    {
        GDALRasterIO( hSrcOver, GF_Read, 0, iLine, nXSize, 1,
                      pData, nXSize, 1, eDT, 0, 0 );
        GDALRasterIO( GDALGetRasterBand( hDstDS, 1 ), GF_Write,
                      0, iLine, nXSize, 1,
                      pData, nXSize, 1, eDT, 0, 0 );
    }
    CPLFree( pData );

    GDALClose( hDstDS );
}
Exemplo n.º 21
0
void generateTexture(string fname, GLuint& tex, int bandnum)
{
   if(bandnum <= 0 )
   {
     bandnum = 1;
   }
   GDALDataset *poDataset;
   GDALAllRegister();
   poDataset= (GDALDataset*) GDALOpen(fname.c_str(),GA_ReadOnly);
   if(poDataset == NULL)
   {
      cout << "OUCH!" << endl;
      //exit(0);
      return;
   }
   cout << "Data size: " << GDALGetRasterXSize(poDataset) << " " << GDALGetRasterYSize(poDataset) << endl;

   GDALRasterBand  *poBand;
   int             nBlockXSize, nBlockYSize;
   int             bGotMin, bGotMax;
   double          adfMinMax[2];
  int bands = poDataset->GetRasterCount();
   bandnum = bandnum % bands + 1;
   if(bandnum > bands)
   {
      bandnum = 1;
   }
   poBand = poDataset->GetRasterBand( bandnum );
   poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
   printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
            nBlockXSize, nBlockYSize,
            GDALGetDataTypeName(poBand->GetRasterDataType()),
            GDALGetColorInterpretationName(
            poBand->GetColorInterpretation()) );

   float max = adfMinMax[0] = poBand->GetMinimum( &bGotMin );
   float min = adfMinMax[1] = poBand->GetMaximum( &bGotMax );
   if( ! (bGotMin && bGotMax) )
      GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
   int width = poBand->GetXSize(); 
   int height = poBand->GetYSize();

   float *pafScanline;
   std::cout << "Before allocation" << adfMinMax[0] << " " << adfMinMax[1] << endl;
   min = adfMinMax[0];
   max = adfMinMax[1];
   int dsize = 256;
   pafScanline = (float *) CPLMalloc(sizeof(float)*512*512);
   vector<vector<float>> out = vector<vector<float>>(height,vector<float> (width,0));
   //vector<vector<unsigned char>> texs = vector<vector<unsigned char>>(height,vector<unsigned char> (width,0));
   unsigned char texs[512*512];
   poBand->RasterIO(GF_Read,0,0,width,height,pafScanline,512,512,GDT_Float32,0,0);
   float no = poBand->GetNoDataValue();
   cout << "After allocation" << endl;
   for(int i = 0; i < 512; i++)
   {
    for(int j = 0; j < 512; j++)
    {
      //cout << i << j << endl << pafS;
      if(pafScanline[i*width+j] != no)
      {
        // set tex val
        texs[i*512+j] = (unsigned char)(255*((pafScanline[i*512+j] - min)/(max-min)));
        //if((int)texs[i*width] < 0)
        //cout << (int)texs[i*512 +j] << " " << pafScanline[i*512+j] << " " << no << " " << fname << " " << min << " " << max << endl;
      }
      else
      {
        // Set zero val
        texs[i*512+j] = 0;
        //cout << (int)texs[i*512 +j] << fname << endl;
      }
      //texs[i*512+j] = 255;

      //ut[i][j] = pafScanline[i*width+j];
    }
   }
   CPLFree(pafScanline);
   //exit(0);
   // Create a texture
   glGenTextures(1,&tex);
   glBindTexture(GL_TEXTURE_2D,tex);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 512,512, 0, GL_RED, GL_UNSIGNED_BYTE,texs);
   GDALClose( (GDALDatasetH) poDataset);
   return;
} 
Exemplo n.º 22
0
static gint print_handler( void * cb_data, void * scanline_in )

{
    unsigned char *scanline = (unsigned char *) scanline_in;
    static GDALDatasetH  working_ds = NULL;
    static int next_scanline = 0;
    static GDALRasterBandH red_band, green_band, blue_band;
    gint   width;

    if( cb_data == NULL && scanline_in == NULL )
    {
        next_scanline = 0;
        working_ds = NULL;
        return -1;
    }

    if( working_ds != cb_data )
    {
        working_ds = (GDALDatasetH) cb_data;
        next_scanline = 0;

        red_band = GDALGetRasterBand( working_ds, 1 );
        if( GDALGetRasterCount( working_ds ) >= 3 )
        {
            green_band = GDALGetRasterBand( working_ds, 2 );
            blue_band = GDALGetRasterBand( working_ds, 3 );
        }
        else
        {
            green_band = blue_band = NULL;
        }

        if( red_band == NULL )
            return -1;
    }

    width = GDALGetRasterXSize( working_ds );

    if( green_band == NULL )
    {
        GByte	*grey;
        int     i, value;

        grey = g_new( GByte, width );
        
        for( i = 0; i < width; i++ )
        {
            value = *(scanline++);
            value += *(scanline++);
            value += *(scanline++);
            value = (value+1) / 3;
            grey[i] = value;
        }
        
        GDALRasterIO( red_band, GF_Write, 0, next_scanline, width, 1, 
                      grey, width, 1, GDT_Byte, 1, 0 );
        g_free( grey );
    }
    else
    {
        GDALRasterIO( red_band, GF_Write, 0, next_scanline, width, 1, 
                      scanline+0, width, 1, GDT_Byte, 3, 0 );
        GDALRasterIO( green_band, GF_Write, 0, next_scanline, width, 1, 
                      scanline+1, width, 1, GDT_Byte, 3, 0 );
        GDALRasterIO( blue_band, GF_Write, 0, next_scanline, width, 1, 
                      scanline+2, width, 1, GDT_Byte, 3, 0 );
    }
    
    next_scanline++;

    return 0;
}
Exemplo n.º 23
0
void doTif2Con(char fileName[], int headerFormat, int BandNumber, char separator, char SHPMaskFile[])
{
	bool flMask = false;
	
	OGRDataSourceH poDS = NULL;
	OGRSFDriverH poDriver = NULL;
		
	if(strlen(SHPMaskFile)>0) 
	{
		flMask = true;
		poDS = OGROpen(SHPMaskFile, FALSE, &poDriver);
	}

	if(flMask && (poDS == NULL)) 
	{
		fputs("\nError open mask file!!!\n\n", stderr);
		return ;
	}

    GDALDatasetH  pDataset;
    GDALRasterBandH pBand;	
			
    pDataset = GDALOpen( fileName, GA_ReadOnly );

    if(pDataset!=NULL)
    {
		int bands = 0;
				
		if(0 == BandNumber) bands = GDALGetRasterCount( pDataset );
		else bands = 1;
		
		int cols = GDALGetRasterXSize(pDataset);
		int rows = GDALGetRasterYSize(pDataset);
				
		double adfGeoTransform[6];
		
		float xOrigin 	  = 0;
		float yOrigin 	  = 0;
		float pixelWidth  = 0;
		float pixelHeight = 0;
		
		if( GDALGetGeoTransform( pDataset, adfGeoTransform ) == CE_None )		
		{
			xOrigin 	= adfGeoTransform[0];
			yOrigin 	= adfGeoTransform[3];
			pixelWidth 	= adfGeoTransform[1];
			pixelHeight = adfGeoTransform[5];
		}
		
		float *** pdata = NULL;
		pdata = new float**[bands];
		for(int i=0; i<bands; i++) pdata[i] = new float*[rows];
		for(int i=0; i<bands; i++) for(int j=0; j<rows; j++) pdata[i][j] = new float[cols];
		for(int i=0; i<bands; i++) for(int j=0; j<rows; j++) for(int k=0; k<cols; k++) pdata[i][j][k] = 0;
		
		void *pbuf = NULL;
		pBand = GDALGetRasterBand(pDataset, 1);
		pbuf = CUtils::mallocData(pBand, pbuf, cols);
		
		printHeader(headerFormat, BandNumber, bands, rows, cols, separator);
		
		if(0 == BandNumber)
		{
			for(int i=1; i<=bands; i++)
			{
				pBand = GDALGetRasterBand(pDataset, i);
				for(int j=0; j<rows; j++)
				{					
					CUtils::getRasterLine(pBand, j, cols, pbuf);
					for(int k=0; k<cols; k++) pdata[i-1][j][k] = CUtils::getDataAsFloat(pBand, pbuf, k);
				}
			}
		}
		else
		{
				pBand = GDALGetRasterBand(pDataset, BandNumber);
				for(int j=0; j<rows; j++)
				{
					CUtils::getRasterLine(pBand, j, cols, pbuf);
					for(int k=0; k<cols; k++) pdata[0][j][k] = CUtils::getDataAsFloat(pBand, pbuf, k);
				}
		}
		
		CPLFree(pbuf);
		
		GDALClose(pDataset);
	
		printData((const float ***) pdata, headerFormat, bands, rows, cols,
				  xOrigin, yOrigin, pixelWidth, pixelHeight, separator, poDS);
		
		if(poDS != NULL) OGR_DS_Destroy(poDS);
		
		for(int i=0; i<bands; i++) for(int j=0; j<rows; j++) delete [] pdata[i][j];
		for(int i=0; i<bands; i++) delete [] pdata[i];
		delete [] pdata;
		pdata = NULL;
		fputs("\nProcessing COMPLETE.\n\n", stderr);
	}
	else
	fputs("\nError open input image!!!\n\n", stderr);
}
Exemplo n.º 24
0
static void msTransformToGeospatialPDF(imageObj *img, mapObj *map, cairo_renderer *r)
{
  /* We need a GDAL 1.10 PDF driver at runtime, but as far as the C API is concerned, GDAL 1.9 is */
  /* largely sufficient. */
#if defined(USE_GDAL) && defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1900
  GDALDatasetH hDS = NULL;
  const char* pszGEO_ENCODING = NULL;
  GDALDriverH hPDFDriver = NULL;
  const char* pszVirtualIO = NULL;
  int bVirtualIO = FALSE;
  char* pszTmpFilename = NULL;
  VSILFILE* fp = NULL;

  if (map == NULL)
    return;

  pszGEO_ENCODING = msGetOutputFormatOption(img->format, "GEO_ENCODING", NULL);
  if (pszGEO_ENCODING == NULL)
    return;

  msGDALInitialize();

  hPDFDriver = GDALGetDriverByName("PDF");
  if (hPDFDriver == NULL)
    return;

  /* When compiled against libpoppler, the PDF driver is VirtualIO capable */
  /* but not, when it is compiled against libpodofo. */
  pszVirtualIO = GDALGetMetadataItem( hPDFDriver, GDAL_DCAP_VIRTUALIO, NULL );
  if (pszVirtualIO)
    bVirtualIO = CSLTestBoolean(pszVirtualIO);

  if (bVirtualIO)
    pszTmpFilename = msTmpFile(map, NULL, "/vsimem/mscairopdf/", "pdf");
  else
    pszTmpFilename = msTmpFile(map, map->mappath, NULL, "pdf");

  /* Copy content of outputStream buffer into file */
  fp = VSIFOpenL(pszTmpFilename, "wb");
  if (fp == NULL) {
    msFree(pszTmpFilename);
    return;
  }
  VSIFWriteL(r->outputStream->data, 1, r->outputStream->size, fp);
  VSIFCloseL(fp);
  fp = NULL;

  hDS = GDALOpen(pszTmpFilename, GA_Update);
  if ( hDS != NULL ) {
    char* pszWKT = msProjectionObj2OGCWKT( &(map->projection) );
    if( pszWKT != NULL ) {
      double adfGeoTransform[6];
      int i;

      /* Add user-specified options */
      for( i = 0; i < img->format->numformatoptions; i++ ) {
        const char* pszOption = img->format->formatoptions[i];
        if( strncasecmp(pszOption,"METADATA_ITEM:",14) == 0 ) {
          char* pszKey = NULL;
          const char* pszValue = CPLParseNameValue(pszOption + 14,
                                 &pszKey);
          if( pszKey != NULL ) {
            GDALSetMetadataItem(hDS, pszKey, pszValue, NULL);
            CPLFree(pszKey);
          }
        }
      }

      /* We need to rescale the geotransform because GDAL will not necessary */
      /* open the PDF with the DPI that was used to generate it */
      memcpy(adfGeoTransform, map->gt.geotransform, 6 * sizeof(double));
      adfGeoTransform[1] = adfGeoTransform[1] * map->width / GDALGetRasterXSize(hDS);
      adfGeoTransform[5] = adfGeoTransform[5] * map->height / GDALGetRasterYSize(hDS);
      GDALSetGeoTransform(hDS, adfGeoTransform);
      GDALSetProjection(hDS, pszWKT);

      msFree( pszWKT );
      pszWKT = NULL;

      CPLSetThreadLocalConfigOption("GDAL_PDF_GEO_ENCODING", pszGEO_ENCODING);

      GDALClose(hDS);
      hDS = NULL;

      CPLSetThreadLocalConfigOption("GDAL_PDF_GEO_ENCODING", NULL);

      /* We need to replace the buffer with the content of the GDAL file */
      fp = VSIFOpenL(pszTmpFilename, "rb");
      if( fp != NULL ) {
        int nFileSize;

        VSIFSeekL(fp, 0, SEEK_END);
        nFileSize = (int)VSIFTellL(fp);

        msBufferResize(r->outputStream, nFileSize);

        VSIFSeekL(fp, 0, SEEK_SET);
        r->outputStream->size = VSIFReadL(r->outputStream->data, 1, nFileSize, fp);

        VSIFCloseL(fp);
        fp = NULL;
      }
    }
  }

  if ( hDS != NULL )
    GDALClose(hDS);

  VSIUnlink(pszTmpFilename);

  msFree(pszTmpFilename);
#endif
}
Exemplo n.º 25
0
/**
 * Read in output from Isaac and populate a sqlite db with the read in values
 * as well as calculated values using erc.  Calculated values include:
 */
int main( int argc, char *argv[] )
{
    GDALAllRegister();
    const char *pszInputfile = NULL;
    const char *pszOutputDB = NULL;
    const char *pszTableName = NULL;
    const char *pszOutputfile = NULL;
    int bDrop = FALSE;
    int bProgress = TRUE;

    int i = 1;
    while( i < argc )
    {
        if( EQUAL( argv[i], "-d" ) )
        {
            bDrop = TRUE;
        }
        else if( EQUAL( argv[i], "-p" ) )
        {
            bProgress = TRUE;
        }
        else if( EQUAL( argv[i], "-db" ) )
        {
            pszOutputDB = argv[++i];
        }
        else if( EQUAL( argv[i], "-p" ) )
        {
            pszTableName = argv[++i];
        }
        else if( EQUAL( argv[i], "-f" ) )
        {
            pszOutputfile = argv[++i];
        }
        else if( EQUAL( argv[i], "-h" ) )
        {
            Usage();
        }
        else if( pszInputfile == NULL )
        {
            pszInputfile = argv[i];
        }
        else
        {
            Usage();
        }
        i++;
    }

    if( pszInputfile == NULL )
    {
        fprintf( stderr, "No input file provided\n");
        Usage();
    }
    if( pszOutputfile == NULL && 
        ( pszOutputDB == NULL || pszTableName == NULL ) )
    {
        fprintf( stderr, "Invalid output selected, use database and table or "
                         "output file\n" );
    }
    // Setup outputs
    int bDbOut = FALSE;
    int bTextOut = FALSE;
    if( pszOutputfile != NULL )
    {
        bTextOut = TRUE;
    }
    if( pszOutputDB != NULL && pszTableName != NULL )
    {
        bDbOut = TRUE;
    }

    sqlite3 *db;
    char *zErr;
    int rc;
    char sql[BUF_SIZE];

    if( bDbOut )
    {
        rc = sqlite3_open( pszOutputDB, &db );

        if ( rc )
        {
            fprintf( stderr, "Can't open database: %s\n", sqlite3_errmsg( db ) );
            sqlite3_close( db );
            exit( 1 );
        }

        if( bDrop )
        {
            sprintf( sql, "drop table %s", pszTableName );

            rc = sqlite3_exec( db, sql, NULL, NULL, &zErr );

            if ( rc != SQLITE_OK )
            {
                if ( zErr != NULL )
                {
                    fprintf( stderr, "SQL error: %s\n", zErr );
                    sqlite3_free( zErr );
                }
            }
        }

        sprintf( sql, "create table %s ( day integer, year integer, x float, "
                      "y float, cause int, time int, erc float, bi float, ros float, "
                      "fuel int)", pszTableName );

        rc = sqlite3_exec( db, sql, NULL, NULL, &zErr );

        if ( rc != SQLITE_OK )
        {
            if ( zErr != NULL )
            {
                fprintf( stderr, "SQL error: %s\n", zErr );
                sqlite3_free( zErr );
            }
            exit( 1 );
        }
    }
    FILE *fout;
    if( bTextOut )
    {
        fout = fopen( pszOutputfile, "w" );
    }
    if( fout == NULL )
    {
        fprintf( stderr, "Could not open %s for writing\n", pszOutputfile );
        exit( 1 );
    }

    FILE *fin;
    char buffer[BUF_SIZE];
    fin = fopen( pszInputfile, "r" );
    if( fin == NULL )
    {
        fprintf( stderr, "Could not open %s for reading\n", pszInputfile );
        exit( 1 );
    }
    int nRecords = 0;
    if( bProgress )
    {
        while( fgets( buffer, BUF_SIZE - 1, fin ) )
            nRecords++;
        fseek( fin, 0, SEEK_SET );
    }
    /*
     * Isaac's fields:
     * day year lat long cause time erc
     */
    /* Skip header */
    if( fgets( buffer, BUF_SIZE - 1, fin ) == NULL )
    {
        fprintf( stderr, "Could not read data from file" );
        exit( 1 );
    }

        //int iNFDRSVersion = 78,iClimateClass = 1,iJulianLookFreeze = 365,iJulianGreenUp = 1,iLat = (int) 45,iHerbAnnual=0,iWoodyDeciduous=0,iOneIsTen=0,iStartKBDI=800;
    //double fStart100 = 20.0,fStart1000=20.0,fAvgPrecip = 45.0;
    //double fMC1 = 3,fMC10 = 4,fMC100 = 5,fMC1000 = 10,fMCWood = 120,fMCHerb = 120;
    //int iRainEvent = 0, iKBDI = 800,iGreenWoody = 20,iGreenHerb = 20,iSeason = 2,iSOW = 0;

    // Initialize the NFDRS calculator
    //nfdrs.iInitialize(iNFDRSVersion,iClimateClass,iJulianLookFreeze,
    //                  iJulianGreenUp,iLat,iHerbAnnual,
    //                  iWoodyDeciduous,iOneIsTen,
    //                  fStart100,fStart1000, 
    //                  iStartKBDI,fAvgPrecip);
    //double fROS=0,fERC=0,fFL=0;
    //int iSC=0,iFIL=0,iBI=0,iWS=0,iSlopeCls=1;

    NFDRCalc nfdr;
    nfdr.iSetFuelModel( FUEL_MODEL_G, 0 );
    nfdr.SetVersion( 78 );

    double one_hour, ten_hour, hundred_hour, thousand_hour, woody, herb;
    /* What we actually get */
    double nfdr_erc;
    int nfdr_bi, nfdr_sc;;
    double dfDummy;
    int nDummy;

    GDALDatasetH hFuelDS;
    hFuelDS = GDALOpen( "/home/kyle/src/omfrr/trunk/data/"
                        "small_fuel40.tif", GA_ReadOnly );
    if( hFuelDS == NULL )
    {
        fprintf( stderr, "Cannot open fuels data for query.\n" );
        exit( 1 );
    }
    GDALDatasetH hSlopeDS;
    hSlopeDS = GDALOpen( "/home/kyle/src/omfrr/trunk/data/"
                         "small_slope.tif", GA_ReadOnly );
    if( hSlopeDS == NULL )
    {
        fprintf( stderr, "Cannot open slope data for query.\n" );
        exit( 1 );
    }
    GDALDatasetH hNarrMaskDS;
    hNarrMaskDS = GDALOpen( "/home/kyle/src/omfrr/trunk/data/"
                            "narr_mask_byte.tif", GA_ReadOnly );
    if( hNarrMaskDS == NULL )
    {
        fprintf( stderr, "Cannot open NARR mask for query.\n" );
        exit( 1 );
    }
    int nMaskXSize = GDALGetRasterXSize( hNarrMaskDS );
    int nMaskYSize = GDALGetRasterYSize( hNarrMaskDS );

    const char *pszAlbersWkt =
        "PROJCS[\"USA_Contiguous_Albers_Equal_Area_Conic_USGS_version\","
        "GEOGCS[\"GCS_North_American_1983\",DATUM[\"D_North_American_1983\","
        "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]],"
        "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],"
        "PROJECTION[\"Albers\"],PARAMETER[\"False_Easting\",0.0],"
        "PARAMETER[\"False_Northing\",0.0],"
        "PARAMETER[\"Central_Meridian\",-96.0],"
        "PARAMETER[\"Standard_Parallel_1\",29.5],"
        "PARAMETER[\"Standard_Parallel_2\",45.5],"
        "PARAMETER[\"Latitude_Of_Origin\",23.0],UNIT[\"Meter\",1.0]]";
    /* Assume same srs */
    //const char *pszAlbersWkt = NULL;

    char out_buf[2048];
    int day, year, cause, time;
    double x, y, erc;
    int fuel, mask, slope, slope_class;
    ifstream frisk_stream( "/home/kyle/src/omfrr/trunk/data/"
                           "narr_32km_frisk.flt", ios::binary );

    FRisk oFRisk;
    int skip = 0;
    int done = 0;
    int wind_speed;
    long offset;
    int nPixel;
    int nLine;
    if( bProgress )
    {
        GDALTermProgress( 0.0, NULL, NULL );
    }
    while( fgets( buffer, BUF_SIZE - 1, fin ) ) 
    {
        //frisk_stream.seekg( 0, ios::beg );
        done++;
        /* Note that it *appears* that isaac writes x,y and not lat,lon */
        sscanf( buffer, "%d %d %lf %lf %d %d %lf", &day, &year, &x, &y,
                &cause, &time, &erc );

        /* Calculate fire behavior indices based on fire risk data.
         * Load all into the sqlite db.  We need:
         * | BI | ROS | ERC | Flame Length | Fuel Model |
         * ROS and Flame length need to be calculated with rothermel.
         * BI, ERC and SC are calculated with nfdrs and fuel model G
         */

        /* Get the slope and find the class */
        slope = (int)PixelValue( hSlopeDS, 1, x, y, pszAlbersWkt );
        if( slope <= 25 )
            slope_class = 1;
        else if( slope <= 40 )
            slope_class = 2;
        else if( slope <= 55 )
            slope_class = 3;
        else if( slope <= 75 )
            slope_class = 4;
        else
            slope_class = 5;

        /* Check the mask, if we don't have data, skip it and emit a
         * warning
         */

        mask = (int)PixelValue( hNarrMaskDS, 1, x, y, pszAlbersWkt );
        if( !mask )
        {
            fprintf( stderr, "NARR data not available, skipping record\n" );
            skip++;
            continue;
        }
        /* NFDRS Stuff */

        PixelIndex(hNarrMaskDS, x, y, pszAlbersWkt, &nPixel, &nLine);
        if( nPixel >= nMaskXSize || nLine >= nMaskYSize )
        {
            CPLDebug( "fig_load", "Invalid pixel x:%d y:%d", nPixel, nLine );
            continue;
        }

        /* We should always have data for our query */
        assert( mask );
        assert( nPixel < nMaskXSize );
        assert( nLine < nMaskYSize );

        offset = nPixel + nLine * nMaskXSize;
        frisk_stream.seekg( offset * FRISK_SIZE, ios::beg );
        oFRisk.ReadBinary( frisk_stream );

        wind_speed = (int)oFRisk.GetRandomWindSpeed( day );
        one_hour = (double)oFRisk.GetOneHour( erc );
        ten_hour = (double)oFRisk.GetTenHour( erc );
        hundred_hour = (double)oFRisk.GetHundredHour( erc );
        thousand_hour = (double)oFRisk.GetThousandHour( erc );
        woody = (double)oFRisk.GetWoody( erc );
        herb = (double)oFRisk.GetHerb( erc );

        nfdr.iSetMoistures( one_hour, ten_hour, hundred_hour, thousand_hour,
                            woody, herb, nDummy, nDummy, nDummy, nDummy,
                            nDummy, nDummy );

        nfdr_erc = nfdr_bi = nfdr_sc = 0.0;
        nfdr.iCalcIndexes( wind_speed, slope_class, &dfDummy, &nfdr_sc, &nfdr_erc,
                           &dfDummy, &nDummy, &nfdr_bi );

        /* Look up fuel model for fb calculations, *not* nfdr */
        fuel = (int)PixelValue( hFuelDS, 1, x, y, pszAlbersWkt );

        if( bDbOut )
        {
            sprintf( sql, "insert into %s values(%d, %d, %lf, %lf, %d, %d,"
                          "%lf, %d, %lf, %d)",
                     pszTableName, day, year, x, y, cause, time, erc, nfdr_bi,
                     erc, fuel);

            rc = sqlite3_exec( db, sql, NULL, NULL, &zErr );

            if ( rc != SQLITE_OK )
            {
                if ( zErr != NULL )
                {
                    fprintf( stderr, "SQL error: %s\n", zErr );
                    sqlite3_free( zErr );
                    break;
                }
            }
        }
        if( bTextOut )
        {
            sprintf( out_buf, "%d %d %lf %lf %d %d %lf %d %lf %d\n",
                     day, year, x, y, cause, time, erc, nfdr_bi, erc, fuel);
            fputs( out_buf, fout );
        }

        if( bProgress )
        {
            double percent = (float)done / (float) nRecords;
            GDALTermProgress( percent, NULL, NULL );
        }
    }
    if( bProgress )
    {
        GDALTermProgress( 1.0, NULL, NULL );
    }

    if( skip )
    {
        fprintf( stderr, "Skipped %d records\n", skip );
    }

    fclose( fin );
    if( bDbOut )
    {
        sqlite3_close( db );
    }
    if( bTextOut )
    {
        fclose( fout );
    }

    return 0;
}
Exemplo n.º 26
0
/**
 * GDALReprojectImage() method with a ChunkAndWarpImage replaced with ChunkAndWarpMulti
 */
CPLErr GDALReprojectImageMulti( GDALDatasetH hSrcDS, const char *pszSrcWKT,
                    GDALDatasetH hDstDS, const char *pszDstWKT,
                    GDALResampleAlg eResampleAlg,
                    double dfWarpMemoryLimit,
                    double dfMaxError,
                    GDALProgressFunc pfnProgress, void *pProgressArg,
                    GDALWarpOptions *psOptions )

{
    GDALWarpOptions *psWOptions;

/* -------------------------------------------------------------------- */
/*      Setup a reprojection based transformer.                         */
/* -------------------------------------------------------------------- */
    void *hTransformArg;

    hTransformArg = 
        GDALCreateGenImgProjTransformer( hSrcDS, pszSrcWKT, hDstDS, pszDstWKT, 
                                         TRUE, 1000.0, 0 );

    if( hTransformArg == NULL )
        return CE_Failure;

/* -------------------------------------------------------------------- */
/*      Create a copy of the user provided options, or a defaulted      */
/*      options structure.                                              */
/* -------------------------------------------------------------------- */
    if( psOptions == NULL )
        psWOptions = GDALCreateWarpOptions();
    else
        psWOptions = GDALCloneWarpOptions( psOptions );

    psWOptions->eResampleAlg = eResampleAlg;

/* -------------------------------------------------------------------- */
/*      Set transform.                                                  */
/* -------------------------------------------------------------------- */
    if( dfMaxError > 0.0 )
    {
        psWOptions->pTransformerArg = 
            GDALCreateApproxTransformer( GDALGenImgProjTransform, 
                                         hTransformArg, dfMaxError );

        psWOptions->pfnTransformer = GDALApproxTransform;
    }
    else
    {
        psWOptions->pfnTransformer = GDALGenImgProjTransform;
        psWOptions->pTransformerArg = hTransformArg;
    }

/* -------------------------------------------------------------------- */
/*      Set file and band mapping.                                      */
/* -------------------------------------------------------------------- */
    int  iBand;

    psWOptions->hSrcDS = hSrcDS;
    psWOptions->hDstDS = hDstDS;

    if( psWOptions->nBandCount == 0 )
    {
        psWOptions->nBandCount = MIN(GDALGetRasterCount(hSrcDS),
                                     GDALGetRasterCount(hDstDS));
        
        psWOptions->panSrcBands = (int *) 
            CPLMalloc(sizeof(int) * psWOptions->nBandCount);
        psWOptions->panDstBands = (int *) 
            CPLMalloc(sizeof(int) * psWOptions->nBandCount);

        for( iBand = 0; iBand < psWOptions->nBandCount; iBand++ )
        {
            psWOptions->panSrcBands[iBand] = iBand+1;
            psWOptions->panDstBands[iBand] = iBand+1;
        }
    }

/* -------------------------------------------------------------------- */
/*      Set source nodata values if the source dataset seems to have    */
/*      any. Same for target nodata values                              */
/* -------------------------------------------------------------------- */
    for( iBand = 0; iBand < psWOptions->nBandCount; iBand++ )
    {
        GDALRasterBandH hBand = GDALGetRasterBand( hSrcDS, iBand+1 );
        int             bGotNoData = FALSE;
        double          dfNoDataValue;

        if (GDALGetRasterColorInterpretation(hBand) == GCI_AlphaBand)
        {
            psWOptions->nSrcAlphaBand = iBand + 1;
        }

        dfNoDataValue = GDALGetRasterNoDataValue( hBand, &bGotNoData );
        if( bGotNoData )
        {
            if( psWOptions->padfSrcNoDataReal == NULL )
            {
                int  ii;

                psWOptions->padfSrcNoDataReal = (double *) 
                    CPLMalloc(sizeof(double) * psWOptions->nBandCount);
                psWOptions->padfSrcNoDataImag = (double *) 
                    CPLMalloc(sizeof(double) * psWOptions->nBandCount);

                for( ii = 0; ii < psWOptions->nBandCount; ii++ )
                {
                    psWOptions->padfSrcNoDataReal[ii] = -1.1e20;
                    psWOptions->padfSrcNoDataImag[ii] = 0.0;
                }
            }

            psWOptions->padfSrcNoDataReal[iBand] = dfNoDataValue;
        }

        // Deal with target band
        hBand = GDALGetRasterBand( hDstDS, iBand+1 );
        if (hBand && GDALGetRasterColorInterpretation(hBand) == GCI_AlphaBand)
        {
            psWOptions->nDstAlphaBand = iBand + 1;
        }

        dfNoDataValue = GDALGetRasterNoDataValue( hBand, &bGotNoData );
        if( bGotNoData )
        {
            if( psWOptions->padfDstNoDataReal == NULL )
            {
                int  ii;

                psWOptions->padfDstNoDataReal = (double *) 
                    CPLMalloc(sizeof(double) * psWOptions->nBandCount);
                psWOptions->padfDstNoDataImag = (double *) 
                    CPLMalloc(sizeof(double) * psWOptions->nBandCount);

                for( ii = 0; ii < psWOptions->nBandCount; ii++ )
                {
                    psWOptions->padfDstNoDataReal[ii] = -1.1e20;
                    psWOptions->padfDstNoDataImag[ii] = 0.0;
                }
            }

            psWOptions->padfDstNoDataReal[iBand] = dfNoDataValue;
        }
    }

/* -------------------------------------------------------------------- */
/*      Set the progress function.                                      */
/* -------------------------------------------------------------------- */
    if( pfnProgress != NULL )
    {
        psWOptions->pfnProgress = pfnProgress;
        psWOptions->pProgressArg = pProgressArg;
    }

/* -------------------------------------------------------------------- */
/*      Create a warp options based on the options.                     */
/* -------------------------------------------------------------------- */
    GDALWarpOperation  oWarper;
    CPLErr eErr;

    eErr = oWarper.Initialize( psWOptions );

    if( eErr == CE_None )
        eErr = oWarper.ChunkAndWarpMulti( 0, 0, 
                                          GDALGetRasterXSize(hDstDS),
                                          GDALGetRasterYSize(hDstDS) );

/* -------------------------------------------------------------------- */
/*      Cleanup.                                                        */
/* -------------------------------------------------------------------- */
    GDALDestroyGenImgProjTransformer( hTransformArg );

    if( dfMaxError > 0.0 )
        GDALDestroyApproxTransformer( psWOptions->pTransformerArg );
        
    GDALDestroyWarpOptions( psWOptions );

    return eErr;
}
Exemplo n.º 27
0
void CDialog3D::OnBnClickedBtnOpen()
{
	// TODO: 在此添加控件通知处理程序代码
	CFileDialog fileDlg(TRUE);
	if(fileDlg.DoModal()!=IDOK)
		return;
	CString strExt	   =fileDlg.GetFileExt();
	CString strPathName=fileDlg.GetPathName();
	if(strExt=="txt")
	{
		ifstream ifs(strPathName,ios_base::in);
		char tmpchr[2048];
		ifs.getline(tmpchr,2048);
		do 
		{
			PNT3D tmpPnt;
			ifs.getline(tmpchr,2048);
			sscanf(tmpchr,"%f,%f,%f",&tmpPnt.DX,&tmpPnt.DY,&tmpPnt.DZ);
			m_vec_PNT3Ds.push_back(tmpPnt);
		} while (!ifs.eof());
		ifs.close();
	}
	if(strExt=="BMP"||strExt=="bmp"||strExt=="JPG"||strExt=="jpg"||strExt=="TIF"||strExt=="tif")
	{
		GDALAllRegister();
		GDALDatasetH hSrcDS=GDALOpen(strPathName,GA_ReadOnly);
		double adfGeoTrans[6];
		double scalex=1,scaley=1;
		GDALGetGeoTransform(hSrcDS,adfGeoTrans);
		int xsize=GDALGetRasterXSize(hSrcDS);
		int ysize=GDALGetRasterYSize(hSrcDS);
		int tmpxsize=xsize,tmpysize=ysize;
		if(xsize>800)
		{
			tmpxsize=800;
			scalex=xsize/tmpxsize;
		}
		if(ysize>600)
		{
			tmpysize=600;
			scaley=ysize/tmpysize;
		}
		float *dataIn=new float[tmpxsize*tmpysize];
		GDALRasterIO(GDALGetRasterBand(hSrcDS,1),GF_Read,0,0,xsize,ysize,dataIn,tmpxsize,tmpysize,GDT_Float32,0,0);
		for(int i=0;i<tmpxsize;i++)
		{
			for (int j=0;j<tmpysize;j++)
			{
				PNT3D tmpPnt;
				tmpPnt.DX=adfGeoTrans[0]+adfGeoTrans[1]*i*scalex+adfGeoTrans[2]*j*scaley;
				tmpPnt.DY=adfGeoTrans[3]+adfGeoTrans[4]*i*scalex+adfGeoTrans[5]*j*scaley;
				//tmpPnt.DX=i;
				//tmpPnt.DY=j;
				tmpPnt.DZ=dataIn[j*tmpxsize+i];
				m_vec_PNT3Ds.push_back(tmpPnt);
			}
		}
		delete[]dataIn;
		GDALClose(hSrcDS);
	}
	if(!m_vec_PNT3Ds.empty())
	{
		m_min_DX=m_max_DX=m_vec_PNT3Ds[0].DX;
		m_min_DY=m_max_DY=m_vec_PNT3Ds[0].DY;
		m_min_DZ=m_max_DZ=m_vec_PNT3Ds[0].DZ;
		for (int i=0;i<m_vec_PNT3Ds.size();i++)
		{
			m_max_DX=max(m_vec_PNT3Ds[i].DX,m_max_DX);
			m_min_DX=min(m_vec_PNT3Ds[i].DX,m_min_DX);
			m_max_DY=max(m_vec_PNT3Ds[i].DY,m_max_DY);
			m_min_DY=min(m_vec_PNT3Ds[i].DY,m_min_DY);
			m_max_DZ=max(m_vec_PNT3Ds[i].DZ,m_max_DZ);
			m_min_DZ=min(m_vec_PNT3Ds[i].DZ,m_min_DZ);
		}
		AfxMessageBox("数据读取成功!\n");
		InvalidateRect(NULL,FALSE);
	}
}
Exemplo n.º 28
0
int QgsZonalStatistics::calculateStatistics( QProgressDialog* p )
{
  if ( !mPolygonLayer || mPolygonLayer->geometryType() != QGis::Polygon )
  {
    return 1;
  }

  QgsVectorDataProvider* vectorProvider = mPolygonLayer->dataProvider();
  if ( !vectorProvider )
  {
    return 2;
  }

  //open the raster layer and the raster band
  GDALAllRegister();
  GDALDatasetH inputDataset = GDALOpen( mRasterFilePath.toLocal8Bit().data(), GA_ReadOnly );
  if ( inputDataset == NULL )
  {
    return 3;
  }

  if ( GDALGetRasterCount( inputDataset ) < ( mRasterBand - 1 ) )
  {
    GDALClose( inputDataset );
    return 4;
  }

  GDALRasterBandH rasterBand = GDALGetRasterBand( inputDataset, mRasterBand );
  if ( rasterBand == NULL )
  {
    GDALClose( inputDataset );
    return 5;
  }
  mInputNodataValue = GDALGetRasterNoDataValue( rasterBand, NULL );

  //get geometry info about raster layer
  int nCellsX = GDALGetRasterXSize( inputDataset );
  int nCellsY = GDALGetRasterYSize( inputDataset );
  double geoTransform[6];
  if ( GDALGetGeoTransform( inputDataset, geoTransform ) != CE_None )
  {
    GDALClose( inputDataset );
    return 6;
  }
  double cellsizeX = geoTransform[1];
  if ( cellsizeX < 0 )
  {
    cellsizeX = -cellsizeX;
  }
  double cellsizeY = geoTransform[5];
  if ( cellsizeY < 0 )
  {
    cellsizeY = -cellsizeY;
  }
  QgsRectangle rasterBBox( geoTransform[0], geoTransform[3] - ( nCellsY * cellsizeY ), geoTransform[0] + ( nCellsX * cellsizeX ), geoTransform[3] );

  //add the new count, sum, mean fields to the provider
  QList<QgsField> newFieldList;
  QgsField countField( mAttributePrefix + "count", QVariant::Double );
  QgsField sumField( mAttributePrefix + "sum", QVariant::Double );
  QgsField meanField( mAttributePrefix + "mean", QVariant::Double );
  newFieldList.push_back( countField );
  newFieldList.push_back( sumField );
  newFieldList.push_back( meanField );
  if ( !vectorProvider->addAttributes( newFieldList ) )
  {
    return 7;
  }

  //index of the new fields
  int countIndex = vectorProvider->fieldNameIndex( mAttributePrefix + "count" );
  int sumIndex = vectorProvider->fieldNameIndex( mAttributePrefix + "sum" );
  int meanIndex = vectorProvider->fieldNameIndex( mAttributePrefix + "mean" );

  if ( countIndex == -1 || sumIndex == -1 || meanIndex == -1 )
  {
    return 8;
  }

  //progress dialog
  long featureCount = vectorProvider->featureCount();
  if ( p )
  {
    p->setMaximum( featureCount );
  }


  //iterate over each polygon
  vectorProvider->select( QgsAttributeList(), QgsRectangle(), true, false );
  vectorProvider->rewind();
  QgsFeature f;
  double count = 0;
  double sum = 0;
  double mean = 0;
  int featureCounter = 0;

  while ( vectorProvider->nextFeature( f ) )
  {
    qWarning( "%d", featureCounter );
    if ( p )
    {
      p->setValue( featureCounter );
    }

    if ( p && p->wasCanceled() )
    {
      break;
    }

    QgsGeometry* featureGeometry = f.geometry();
    if ( !featureGeometry )
    {
      ++featureCounter;
      continue;
    }

    int offsetX, offsetY, nCellsX, nCellsY;
    if ( cellInfoForBBox( rasterBBox, featureGeometry->boundingBox(), cellsizeX, cellsizeY, offsetX, offsetY, nCellsX, nCellsY ) != 0 )
    {
      ++featureCounter;
      continue;
    }

    statisticsFromMiddlePointTest_improved( rasterBand, featureGeometry, offsetX, offsetY, nCellsX, nCellsY, cellsizeX, cellsizeY,
                                            rasterBBox, sum, count );

    if ( count <= 1 )
    {
      //the cell resolution is probably larger than the polygon area. We switch to precise pixel - polygon intersection in this case
      statisticsFromPreciseIntersection( rasterBand, featureGeometry, offsetX, offsetY, nCellsX, nCellsY, cellsizeX, cellsizeY,
                                         rasterBBox, sum, count );
    }


    if ( count == 0 )
    {
      mean = 0;
    }
    else
    {
      mean = sum / count;
    }

    //write the statistics value to the vector data provider
    QgsChangedAttributesMap changeMap;
    QgsAttributeMap changeAttributeMap;
    changeAttributeMap.insert( countIndex, QVariant( count ) );
    changeAttributeMap.insert( sumIndex, QVariant( sum ) );
    changeAttributeMap.insert( meanIndex, QVariant( mean ) );
    changeMap.insert( f.id(), changeAttributeMap );
    vectorProvider->changeAttributeValues( changeMap );

    ++featureCounter;
  }

  if ( p )
  {
    p->setValue( featureCount );
  }

  GDALClose( inputDataset );
  return 0;
}
Exemplo n.º 29
0
GByte *
gdal_to_rgba( GDALDatasetH hDS )
{
    int  nXSize, nYSize;
    GByte *pabyRGBABuf = NULL;

    /* validation of input parameters */
    g_return_val_if_fail( hDS != NULL, NULL );

/* -------------------------------------------------------------------- */
/*      Allocate RGBA Raster buffer.                                    */
/* -------------------------------------------------------------------- */

    nXSize = GDALGetRasterXSize( hDS );
    nYSize = GDALGetRasterYSize( hDS );
    CPLDebug( "OpenEV", "creating buffer of (%d,%d)", nXSize, nYSize );
    pabyRGBABuf = (GByte *) CPLMalloc( nXSize * nYSize * 4 );

/* -------------------------------------------------------------------- */
/*      Handle case where source is already presumed to be RGBA.        */
/* -------------------------------------------------------------------- */
    if( GDALGetRasterCount(hDS) == 4 )
    {
        GDALRasterIO( GDALGetRasterBand( hDS, 1 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+0, nXSize, nYSize, GDT_Byte, 
                      4, nXSize * 4 );
                      
        GDALRasterIO( GDALGetRasterBand( hDS, 2 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+1, nXSize, nYSize, GDT_Byte, 4, 
                      nXSize * 4 );
                      
        GDALRasterIO( GDALGetRasterBand( hDS, 3 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+2, nXSize, nYSize, GDT_Byte, 4, 
                      nXSize * 4 );
                      
        GDALRasterIO( GDALGetRasterBand( hDS, 4 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+3, nXSize, nYSize, GDT_Byte, 4, 
                      nXSize * 4 );
    }
/* -------------------------------------------------------------------- */
/*      Source is RGB.  Set Alpha to 255.                               */
/* -------------------------------------------------------------------- */
    else if( GDALGetRasterCount(hDS) == 3 )
    {
        memset( pabyRGBABuf, 255, 4 * nXSize * nYSize );
        
        GDALRasterIO( GDALGetRasterBand( hDS, 1 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+0, nXSize, nYSize, GDT_Byte, 
                      4, nXSize * 4 );
                      
        GDALRasterIO( GDALGetRasterBand( hDS, 2 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+1, nXSize, nYSize, GDT_Byte, 4, 
                      nXSize * 4 );
                      
        GDALRasterIO( GDALGetRasterBand( hDS, 3 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+2, nXSize, nYSize, GDT_Byte, 4, 
                      nXSize * 4 );
    }
/* -------------------------------------------------------------------- */
/*      Source is pseudocolored.  Load and then convert to RGBA.        */
/* -------------------------------------------------------------------- */
    else if( GDALGetRasterCount(hDS) == 1 
             && GDALGetRasterColorTable( GDALGetRasterBand( hDS, 1 )) != NULL )
    {
        int        i;
        GDALColorTableH hTable;
        GByte      abyPCT[1024];

        /* Load color table, and produce 256 entry table to RGBA. */
        hTable = GDALGetRasterColorTable( GDALGetRasterBand( hDS, 1 ) );

        for( i = 0; i < MIN(256,GDALGetColorEntryCount( hTable )); i++ )
        {
            GDALColorEntry sEntry;

            GDALGetColorEntryAsRGB( hTable, i, &sEntry );
            abyPCT[i*4+0] = sEntry.c1;
            abyPCT[i*4+1] = sEntry.c2;
            abyPCT[i*4+2] = sEntry.c3;
            abyPCT[i*4+3] = sEntry.c4;
        }

        /* Fill in any missing colors with greyscale. */
        for( i = GDALGetColorEntryCount( hTable ); i < 256; i++ )
        {
            abyPCT[i*4+0] = i;
            abyPCT[i*4+1] = i;
            abyPCT[i*4+2] = i;
            abyPCT[i*4+3] = 255;
        }

        /* Read indexed raster */
        GDALRasterIO( GDALGetRasterBand( hDS, 1 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+0, nXSize, nYSize, GDT_Byte, 
                      4, nXSize * 4 );

        /* Convert to RGBA using palette. */
        for( i = nXSize * nYSize - 1; i >= 0; i-- )
        {
            memcpy( pabyRGBABuf + i*4, 
                    abyPCT + pabyRGBABuf[i*4]*4, 
                    4 );
        }
    }
/* -------------------------------------------------------------------- */
/*      Source band is greyscale.  Load it into Red, Green and Blue.    */
/* -------------------------------------------------------------------- */
    else if( GDALGetRasterCount(hDS) == 1 )
    {
        memset( pabyRGBABuf, 255, 4 * nXSize * nYSize );
        
        GDALRasterIO( GDALGetRasterBand( hDS, 1 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+0, nXSize, nYSize, GDT_Byte, 
                      4, nXSize * 4 );
        GDALRasterIO( GDALGetRasterBand( hDS, 1 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+1, nXSize, nYSize, GDT_Byte, 
                      4, nXSize * 4 );
        GDALRasterIO( GDALGetRasterBand( hDS, 1 ), GF_Read, 
                      0, 0, nXSize, nYSize, 
                      pabyRGBABuf+2, nXSize, nYSize, GDT_Byte, 
                      4, nXSize * 4 );
    }

    return pabyRGBABuf;
}
int main( int argc, const char* argv[] )
{
    GDALDriverH   hDriver;
    double        adfGeoTransform[6];
    GDALDatasetH  in_Dataset;
    GDALDatasetH  mask_Dataset;
    GDALDatasetH  out_Dataset;
    GDALRasterBandH mask_band;
    unsigned char   *out_scan_line, *data_scan_line;
    int             nBlockXSize, nBlockYSize;
    int             bGotMin, bGotMax;
    int             bands;
    int             xsize;
    double          adfMinMax[2];
    int             valid_data_pixels[10];
    int             saturated_data_pixels[10];
    int             y_index, x;
    GDALRasterBandH  out_band;
    
    
    if ( argc != 3 ) {
        ussage(argv[0]);
    }

    
    GDALAllRegister();
    
    /* Set cache to something reasonable.. - 1/2 gig*/
    CPLSetConfigOption( "GDAL_CACHEMAX", "512" );

    /* open datasets..*/
    in_Dataset = GDAL_open_read( argv[1]);
    out_Dataset = make_me_a_sandwitch(&in_Dataset, argv[2]);
    
    /* Basic info on source dataset..*/
    GDALGetBlockSize(GDALGetRasterBand( in_Dataset, 1 ) , &nBlockXSize, &nBlockYSize );
    
    /* Loop though bands, checking for saturated pixels .... */
    xsize = GDALGetRasterXSize( in_Dataset );
    data_scan_line = (char *) CPLMalloc(sizeof(char)*xsize);
    out_scan_line = (char *) CPLMalloc(sizeof(char)*xsize);
    
    /* The output band... */
    out_band =  GDALGetRasterBand( out_Dataset, 1);

   
    /* wipe counters.. */ 
    for (bands=1; bands <= GDALGetRasterCount( in_Dataset ); bands ++ ) {
        valid_data_pixels[bands] = 0;
        saturated_data_pixels[bands] = 0;
    }
    
    /* loop though the lines of the data, looking for no data and saturated pixels..*/
    for (y_index = 0; y_index <GDALGetRasterYSize( in_Dataset ); y_index ++ ) {
        for (bands=1; bands <= GDALGetRasterCount( in_Dataset ); bands ++ ) {
            GDALRasterBandH data_band;
            /* Read data..*/
            data_band =  GDALGetRasterBand( in_Dataset, bands);
            GDALRasterIO( data_band, GF_Read, 0, y_index, xsize , 1, data_scan_line, xsize , 1, GDT_Byte, 0, 0 );
            /* If first band, then copy into output slice.. */
            if (bands==1) {
                unsigned char  data_value;
                for(x=0; x < xsize; x++) {
                    /*shift to make darker...*/
                   out_scan_line[x] = data_scan_line[x] >> 1 ;
                   if ( out_scan_line[x] ==0 && data_scan_line[x] != 0) {out_scan_line[x] = 1;}
                }
            }
            
            /* Loop though, looking for saturated pixels and no-data values.. */
            for(x=0; x < xsize; x++) {
                if (  data_scan_line[x] != 0 )  {
                   valid_data_pixels[bands] += 1;
                   if ( data_scan_line[x] == 255 ) {
                    saturated_data_pixels[bands] += 1;
                    out_scan_line[x] = 255;
                   }
                }
            }
        }
        GDALRasterIO( out_band, GF_Write, 0, y_index, xsize , 1, out_scan_line, xsize , 1, GDT_Byte, 0, 0 );
    }