示例#1
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 );
}
示例#2
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 );
}
示例#3
0
文件: qgsrelief.cpp 项目: GeoCat/QGIS
QList< QgsRelief::ReliefColor > QgsRelief::calculateOptimizedReliefClasses()
{
  QList< QgsRelief::ReliefColor > resultList;

  int nCellsX, nCellsY;
  GDALDatasetH inputDataset = openInputFile( nCellsX, nCellsY );
  if ( !inputDataset )
  {
    return resultList;
  }

  //open first raster band for reading (elevation raster is always single band)
  GDALRasterBandH elevationBand = GDALGetRasterBand( inputDataset, 1 );
  if ( !elevationBand )
  {
    GDALClose( inputDataset );
    return resultList;
  }

  //1. get minimum and maximum of elevation raster -> 252 elevation classes
  int minOk, maxOk;
  double minMax[2];
  minMax[0] = GDALGetRasterMinimum( elevationBand, &minOk );
  minMax[1] = GDALGetRasterMaximum( elevationBand, &maxOk );

  if ( !minOk || !maxOk )
  {
    GDALComputeRasterMinMax( elevationBand, true, minMax );
  }

  //2. go through raster cells and get frequency of classes

  //store elevation frequency in 256 elevation classes
  double frequency[252];
  double frequencyClassRange = ( minMax[1] - minMax[0] ) / 252.0;
  //initialize to zero
  for ( int i = 0; i < 252; ++i )
  {
    frequency[i] = 0;
  }

  float *scanLine = ( float * ) CPLMalloc( sizeof( float ) *  nCellsX );
  int elevationClass = -1;

  for ( int i = 0; i < nCellsY; ++i )
  {
    if ( GDALRasterIO( elevationBand, GF_Read, 0, i, nCellsX, 1,
                       scanLine, nCellsX, 1, GDT_Float32,
                       0, 0 ) != CE_None )
    {
      QgsDebugMsg( "Raster IO Error" );
    }
    for ( int j = 0; j < nCellsX; ++j )
    {
      elevationClass = frequencyClassForElevation( scanLine[j], minMax[0], frequencyClassRange );
      if ( elevationClass < 0 )
      {
        elevationClass = 0;
      }
      else if ( elevationClass >= 252 )
      {
        elevationClass = 251;
      }
      frequency[elevationClass] += 1.0;
    }
  }

  CPLFree( scanLine );

  //log10 transformation for all frequency values
  for ( int i = 0; i < 252; ++i )
  {
    frequency[i] = std::log10( frequency[i] );
  }

  //start with 9 uniformly distributed classes
  QList<int> classBreaks;
  classBreaks.append( 0 );
  classBreaks.append( 28 );
  classBreaks.append( 56 );
  classBreaks.append( 84 );
  classBreaks.append( 112 );
  classBreaks.append( 140 );
  classBreaks.append( 168 );
  classBreaks.append( 196 );
  classBreaks.append( 224 );
  classBreaks.append( 252 );

  for ( int i = 0; i < 10; ++i )
  {
    optimiseClassBreaks( classBreaks, frequency );
  }

  //debug, print out all the classbreaks
  for ( int i = 0; i < classBreaks.size(); ++i )
  {
    qWarning( "%d", classBreaks[i] );
  }

  //set colors according to optimised class breaks
  QVector<QColor> colorList;
  colorList.push_back( QColor( 7, 165, 144 ) );
  colorList.push_back( QColor( 12, 221, 162 ) );
  colorList.push_back( QColor( 33, 252, 183 ) );
  colorList.push_back( QColor( 247, 252, 152 ) );
  colorList.push_back( QColor( 252, 196, 8 ) );
  colorList.push_back( QColor( 252, 166, 15 ) );
  colorList.push_back( QColor( 175, 101, 15 ) );
  colorList.push_back( QColor( 255, 133, 92 ) );
  colorList.push_back( QColor( 204, 204, 204 ) );

  resultList.reserve( classBreaks.size() );
  for ( int i = 1; i < classBreaks.size(); ++i )
  {
    double minElevation = minMax[0] + classBreaks[i - 1] * frequencyClassRange;
    double maxElevation = minMax[0] + classBreaks[i] * frequencyClassRange;
    resultList.push_back( QgsRelief::ReliefColor( colorList.at( i - 1 ), minElevation, maxElevation ) );
  }

  return resultList;
}
示例#4
0
文件: qgsrelief.cpp 项目: GeoCat/QGIS
//this function is mainly there for debugging
bool QgsRelief::exportFrequencyDistributionToCsv( const QString &file )
{
  int nCellsX, nCellsY;
  GDALDatasetH inputDataset = openInputFile( nCellsX, nCellsY );
  if ( !inputDataset )
  {
    return false;
  }

  //open first raster band for reading (elevation raster is always single band)
  GDALRasterBandH elevationBand = GDALGetRasterBand( inputDataset, 1 );
  if ( !elevationBand )
  {
    GDALClose( inputDataset );
    return false;
  }

  //1. get minimum and maximum of elevation raster -> 252 elevation classes
  int minOk, maxOk;
  double minMax[2];
  minMax[0] = GDALGetRasterMinimum( elevationBand, &minOk );
  minMax[1] = GDALGetRasterMaximum( elevationBand, &maxOk );

  if ( !minOk || !maxOk )
  {
    GDALComputeRasterMinMax( elevationBand, true, minMax );
  }

  //2. go through raster cells and get frequency of classes

  //store elevation frequency in 256 elevation classes
  double frequency[252];
  double frequencyClassRange = ( minMax[1] - minMax[0] ) / 252.0;
  //initialize to zero
  for ( int i = 0; i < 252; ++i )
  {
    frequency[i] = 0;
  }

  float *scanLine = ( float * ) CPLMalloc( sizeof( float ) *  nCellsX );
  int elevationClass = -1;

  for ( int i = 0; i < nCellsY; ++i )
  {
    if ( GDALRasterIO( elevationBand, GF_Read, 0, i, nCellsX, 1,
                       scanLine, nCellsX, 1, GDT_Float32,
                       0, 0 ) != CE_None )
    {
      QgsDebugMsg( "Raster IO Error" );
    }

    for ( int j = 0; j < nCellsX; ++j )
    {
      elevationClass = frequencyClassForElevation( scanLine[j], minMax[0], frequencyClassRange );
      if ( elevationClass >= 0 )
      {
        frequency[elevationClass] += 1.0;
      }
    }
  }

  CPLFree( scanLine );

  //log10 transformation for all frequency values
  for ( int i = 0; i < 252; ++i )
  {
    frequency[i] = std::log10( frequency[i] );
  }

  //write out frequency values to csv file for debugging
  QFile outFile( file );
  if ( !outFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
  {
    return false;
  }

  QTextStream outstream( &outFile );
  for ( int i = 0; i < 252; ++i )
  {
    outstream << QString::number( i ) + ',' + QString::number( frequency[i] ) << endl;
  }
  outFile.close();
  return true;
}
示例#5
0
int main(void)
{
	GDALAllRegister();
	/*Open a file*/
	GDALDatasetH hDataset;
	hDataset = GDALOpen( "./dem.tif", GA_ReadOnly );
	if( hDataset == NULL ) printf("The dataset is NULL!\n");
	/*Getting Dasetset Information*/
	GDALDriverH hDriver;
	double adfGeoTransform[6];
	hDriver = GDALGetDatasetDriver( hDataset );
	printf( "Driver: %s/%s\n",
			GDALGetDriverShortName( hDriver ),
			GDALGetDriverLongName( hDriver ));
	printf("Size is %dx%dx%d\n",
			GDALGetRasterXSize( hDataset ),
			GDALGetRasterYSize( hDataset ),
			GDALGetRasterCount( hDataset ));
	if( GDALGetProjectionRef( hDataset ) != NULL )
		printf("Projection is '%s'\n", GDALGetProjectionRef( hDataset ) );
	if (GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
	{
		printf("Origin = (%.6f,%.6f)\n",
				adfGeoTransform[0], adfGeoTransform[3]);
		printf( "Pixel Size = (%.6f,%.6f)\n",
				adfGeoTransform[0], adfGeoTransform[5]);
	}
	/*Fetching a Raster Band*/
	GDALRasterBandH hBand;
	int nBlockXSize, nBlockYSize;
	int bGotMin, bGotMax;
	double adfMinMax[2];
	hBand = GDALGetRasterBand( hDataset, 1);
	GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize);
	printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
			nBlockXSize, nBlockYSize,
			GDALGetDataTypeName(GDALGetRasterDataType(hBand)),
			GDALGetColorInterpretationName(
				GDALGetRasterColorInterpretation(hBand)) );
	adfMinMax[0] = GDALGetRasterMinimum( hBand, &bGotMin );
	adfMinMax[1] = GDALGetRasterMaximum( hBand, &bGotMax );
	if( !(bGotMin && bGotMax) )
	{
		GDALComputeRasterMinMax( hBand, TRUE, adfMinMax );
	}
	printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1]);
	if(GDALGetOverviewCount(hBand) > 0)
		printf( "Band has %d overviews.\n", GDALGetOverviewCount(hBand));
	if( GDALGetRasterColorTable( hBand ) != NULL)
		printf( "Band has a color table with %d entries.\n",
				GDALGetColorEntryCount(
					GDALGetRasterColorTable( hBand)));
	/*Reading Raster Data*/
	float *pafScanline;
	int nXSize = GDALGetRasterBandXSize( hBand );
	pafScanline = (float *)CPLMalloc(sizeof(float)*nXSize);
	GDALRasterIO(hBand, GF_Read, 0, 0, nXSize, 1,
			pafScanline, nXSize, 1, GDT_Float32, 0, 0);
	CPLFree(pafScanline);
	return 0;
}
示例#6
0
void toprsGadlReader::computeMinMax()
{
	toprs_uint32 bands = GDALGetRasterCount(theDataset);

	if(theMinPixValues)
	{
		delete [] theMinPixValues;
		theMinPixValues = 0;
	}
	if(theMaxPixValues)
	{
		delete [] theMaxPixValues;
		theMaxPixValues = 0;
	}
	if(theNullPixValues)
	{
		delete [] theNullPixValues;
		theNullPixValues = 0;
	}
	if(isIndexTo3Band())
	{
		int i = 0;
		theMinPixValues  = new double[3];
		theMaxPixValues  = new double[3];
		theNullPixValues = new double[3];

		for(i = 0; i < 3; ++i)
		{
			theMinPixValues[i] = 1;
			theMaxPixValues[i] = 255;
			theNullPixValues[i] = 0;
		}
	}
	else if(isIndexTo1Band())
	{
		theMinPixValues  = new double[1];
		theMaxPixValues  = new double[1];
		theNullPixValues = new double[1];

		*theNullPixValues = 0;
		*theMaxPixValues = 255;
		*theMinPixValues = 1;
	}
	else
	{
		if(!theMinPixValues && !theMaxPixValues&&bands)
		{
			theMinPixValues = new double[bands];
			theMaxPixValues = new double[bands];
			theNullPixValues = new double[bands];
		}
		for(toprs_int32 band = 0; band < (toprs_int32)bands; ++band)
		{
			GDALRasterBandH aBand=0;

			aBand = GDALGetRasterBand(theDataset, band+1);

			int minOk=1;
			int maxOk=1;
			int nullOk=1;

			if(aBand)
			{
				if(hasData())
				{
					theMinPixValues[band] = theData.getMinPix(band);
					theMaxPixValues[band] = theData.getMaxPix(band);
					theNullPixValues[band] = theData.getNullPix(band);
				}
				else 
				{
					std::string driverName = theDriver ? GDALGetDriverShortName( theDriver ) : "";

					// Allow to rescale the image data 
					// to the min/max values found in the raster data only 
					// if it was not acquired with the following drivers:
					if ( driverName.find("JP2KAK") != std::string::npos  ||
						driverName.find("JPEG2000") != std::string::npos||
						driverName.find("NITF") != std::string::npos)
					{
						theMinPixValues[band] = toprs::defaultMin(getOutputScalarType());
						theMaxPixValues[band] = toprs::defaultMax(getOutputScalarType());
						theNullPixValues[band] = toprs::defaultNull(getOutputScalarType());
					}
					else
					{
						theMinPixValues[band]  = GDALGetRasterMinimum(aBand, &minOk);
						theMaxPixValues[band]  = GDALGetRasterMaximum(aBand, &maxOk);
						theNullPixValues[band] = GDALGetRasterNoDataValue(aBand, &nullOk);
					}
					if((!nullOk)||(theNullPixValues[band] < toprs::defaultNull(getOutputScalarType())))
					{
						theNullPixValues[band] = toprs::defaultNull(getOutputScalarType());
					}
				}
				if(!minOk||!maxOk)
				{
					theMinPixValues[band] = toprs::defaultMin(getOutputScalarType());
					theMaxPixValues[band] = toprs::defaultMax(getOutputScalarType());
				}
			}
			else
			{
				theMinPixValues[band] = toprs::defaultMin(getOutputScalarType());
				theMaxPixValues[band] = toprs::defaultMax(getOutputScalarType());
			}
		}
	}
}
示例#7
0
/*
 * POPULATE_METADATA_STRUCT
 *
 * This routine just queries the GDAL raster file for all the metadata
 * that can be squeezed out of it.
 *
 * The resulting matlab structure is by necessity nested.  Each raster
 * file can have several bands, e.g. PNG files usually have 3, a red, a
 * blue, and a green channel.  Each band can have several overviews (tiffs
 * come to mind here).
 *
 * Fields:
 *    ProjectionRef:  a string describing the projection.  Not parsed.
 *    GeoTransform:
 *        a 6-tuple.  Entries are as follows.
 *            [0] --> top left x
 *            [1] --> w-e pixel resolution
 *            [2] --> rotation, 0 if image is "north up"
 *            [3] --> top left y
 *            [4] --> rotation, 0 if image is "north up"
 *            [5] --> n-s pixel resolution
 *
 *    DriverShortName:  describes the driver used to query *this* raster file
 *    DriverLongName:  describes the driver used to query *this* raster file
 *    RasterXSize, RasterYSize:
 *        These are the primary dimensions of the raster.  See "Overview", though.
 *    RasterCount:
 *        Number of raster bands present in the file.
 *    Driver:
 *        This itself is a structure array.  Each element describes a driver
 *        that the locally compiled GDAL library has available.  So you recompile
 *        GDAL with new format support, this structure will change.
 *
 *        Fields:
 *            DriverShortName, DriverLongName:
 *                Same as fields in top level structure with same name.
 *
 *    Band:
 *        Also a structure array.  One element for each raster band present in
 *        the GDAL file.  See "RasterCount".
 *
 *        Fields:
 *            XSize, YSize:
 *                Dimensions of the current raster band.
 *            Overview:
 *                A structure array, one element for each overview present.  If
 *                empty, then there are no overviews.
 *            NoDataValue:
 *                When passed back to MATLAB, one can set pixels with this value to NaN.
 *            ColorMap:
 *                A Mx3 double array with the colormap, or empty if it does not exists
 *
 * */
mxArray *populate_metadata_struct (GDALDatasetH hDataset, int correct_bounds) {

	/* These are used to define the metadata structure about available GDAL drivers. */
	mxArray *mxtmp;
	mxArray *mxProjectionRef;
	mxArray *mxGeoTransform;
	mxArray *mxGDALDriverShortName;
	mxArray *mxGDALDriverLongName;
	mxArray *mxGDALRasterCount;
	mxArray *mxGDALRasterXSize;
	mxArray *mxGDALRasterYSize;
	mxArray *mxCorners;
	mxArray *mxGMT_header;

	/*
	 * These will be matlab structures that hold the metadata.
	 * "metadata_struct" actually encompasses "band_struct",
	 * which encompasses "overview_struct"
	 * */
	mxArray *metadata_struct;
	mxArray *band_struct;
	mxArray *overview_struct;
	mxArray *corner_struct;

	int	overview, band_number;	/* Loop indices */
	double	*dptr;			/* short cut to the mxArray data */
	double	*dptr2;			/*        ""           */

	GDALDriverH hDriver;		/* This is the driver chosen by the GDAL library to query the dataset. */
	GDALRasterBandH hBand, overview_hBand;

	int num_overview_fields;	/* Number of metadata items for each overview structure. */
	int status;			/* success or failure */
	double 	adfGeoTransform[6];	/* bounds on the dataset */
	int num_overviews;		/* Number of overviews in the current band. */
	int num_struct_fields;		/* number of fields in the metadata structures. */
	int num_band_fields;
	int num_corner_fields;
	char *fieldnames[100];		/* this array contains the names of the fields of the metadata structure. */
	char *band_fieldnames[100];
	char *corner_fieldnames[100];
	char *overview_fieldnames[100];
	int xSize, ySize, raster_count; /* Dimensions of the dataset */
	int gdal_type;			/* Datatype of the bands. */
	double tmpdble;			/* temporary value */
	double	xy_c[2];		/* Corner coordinates */
	int	dims[2];
	int	bGotMin, bGotMax;	/* To know if driver transmited Min/Max */
	double	adfMinMax[2];		/* Dataset Min Max */
	double	z_min = 1e50, z_max = -1e50;

	/* Create the metadata structure. Just one element, with XXX fields. */
	num_struct_fields = 10;
	fieldnames[0] = strdup ("ProjectionRef");
	fieldnames[1] = strdup ("GeoTransform");
	fieldnames[2] = strdup ("DriverShortName");
	fieldnames[3] = strdup ("DriverLongName");
	fieldnames[4] = strdup ("RasterXSize");
	fieldnames[5] = strdup ("RasterYSize");
	fieldnames[6] = strdup ("RasterCount");
	fieldnames[7] = strdup ("Band");
	fieldnames[8] = strdup ("Corners");
	fieldnames[9] = strdup("GMT_hdr");
	metadata_struct = mxCreateStructMatrix ( 1, 1, num_struct_fields, (const char **)fieldnames );

	/* Record the ProjectionRef. */
	mxProjectionRef = mxCreateString ( GDALGetProjectionRef( hDataset ) );
	mxSetField ( metadata_struct, 0, "ProjectionRef", mxProjectionRef );

	/* Record the geotransform. */
	mxGeoTransform = mxCreateNumericMatrix ( 6, 1, mxDOUBLE_CLASS, mxREAL );
	dptr = mxGetPr ( mxGeoTransform );

	if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) {
		dptr[0] = adfGeoTransform[0];
		dptr[1] = adfGeoTransform[1];
		dptr[2] = adfGeoTransform[2];
		dptr[3] = adfGeoTransform[3];
		dptr[4] = adfGeoTransform[4];
		dptr[5] = adfGeoTransform[5];
		mxSetField ( metadata_struct, 0, "GeoTransform", mxGeoTransform );
	}

	/* Get driver information */
	hDriver = GDALGetDatasetDriver( hDataset );

	mxGDALDriverShortName = mxCreateString ( GDALGetDriverShortName( hDriver ) );
	mxSetField ( metadata_struct, 0, (const char *) "DriverShortName", mxGDALDriverShortName );

	mxGDALDriverLongName = mxCreateString ( GDALGetDriverLongName( hDriver ) );
	mxSetField ( metadata_struct, 0, (const char *) "DriverLongName", mxGDALDriverLongName );

	xSize = GDALGetRasterXSize( hDataset );
	ySize = GDALGetRasterYSize( hDataset );
	mxGDALRasterXSize = mxCreateDoubleScalar ( (double) xSize );
	mxSetField ( metadata_struct, 0, (const char *) "RasterXSize", mxGDALRasterXSize );

	mxGDALRasterYSize = mxCreateDoubleScalar ( (double) ySize );
	mxSetField ( metadata_struct, 0, (const char *) "RasterYSize", mxGDALRasterYSize );

	raster_count = GDALGetRasterCount( hDataset );
	mxGDALRasterCount = mxCreateDoubleScalar ( (double)raster_count );
	mxSetField ( metadata_struct, 0, (const char *) "RasterCount", mxGDALRasterCount );

	/* Get the metadata for each band. */
	num_band_fields = 5;
	band_fieldnames[0] = strdup ( "XSize" );
	band_fieldnames[1] = strdup ( "YSize" );
	band_fieldnames[2] = strdup ( "Overview" );
	band_fieldnames[3] = strdup ( "NoDataValue" );
	band_fieldnames[4] = strdup ( "DataType" );
	band_struct = mxCreateStructMatrix ( raster_count, 1, num_band_fields, (const char **)band_fieldnames );

	num_overview_fields = 2;
	overview_fieldnames[0] = strdup ( "XSize" );
	overview_fieldnames[1] = strdup ( "YSize" );
	for ( band_number = 1; band_number <= raster_count; ++band_number ) {	/* Loop over bands */

		hBand = GDALGetRasterBand( hDataset, band_number );

		mxtmp = mxCreateDoubleScalar ( (double) GDALGetRasterBandXSize( hBand ) );
		mxSetField ( band_struct, 0, "XSize", mxtmp );

		mxtmp = mxCreateDoubleScalar ( (double) GDALGetRasterBandYSize( hBand ) );
		mxSetField ( band_struct, 0, "YSize", mxtmp );
	
		gdal_type = GDALGetRasterDataType ( hBand );
		mxtmp = mxCreateString ( GDALGetDataTypeName ( (GDALDataType)gdal_type ) );
		mxSetField ( band_struct, 0, (const char *) "DataType", mxtmp );

		tmpdble = GDALGetRasterNoDataValue ( hBand, &status );
		mxtmp = mxCreateDoubleScalar ( (double) (GDALGetRasterNoDataValue ( hBand, &status ) ) );
		mxSetField ( band_struct, 0, "NoDataValue", mxtmp );
	
		num_overviews = GDALGetOverviewCount( hBand );	/* Can have multiple overviews per band. */
		if ( num_overviews > 0 ) {

			overview_struct = mxCreateStructMatrix ( num_overviews, 1, num_overview_fields,
						(const char **)overview_fieldnames );
	
			for ( overview = 0; overview < num_overviews; ++overview ) {
				overview_hBand = GDALGetOverview ( hBand, overview );
	
				xSize = GDALGetRasterBandXSize ( overview_hBand );
				mxtmp = mxCreateDoubleScalar ( xSize );
				mxSetField ( overview_struct, overview, "XSize", mxtmp );
	
				ySize = GDALGetRasterBandYSize ( overview_hBand );
				mxtmp = mxCreateDoubleScalar ( ySize );
				mxSetField ( overview_struct, overview, "YSize", mxtmp );
			}
			mxSetField ( band_struct, 0, "Overview", overview_struct );
		}

	}
	mxSetField ( metadata_struct, 0, "Band", band_struct );

	/* Record the GMT header. This will be interleaved with "corners" because they share somes values */
	mxGMT_header = mxCreateNumericMatrix(1, 9, mxDOUBLE_CLASS, mxREAL);
	dptr2 = mxGetPr(mxGMT_header);

	/* Record corners. */
	num_corner_fields = 4;
	corner_fieldnames[0] = strdup ("LL");
	corner_fieldnames[1] = strdup ("UL");
	corner_fieldnames[2] = strdup ("UR");
	corner_fieldnames[3] = strdup ("LR");

	corner_struct = mxCreateStructMatrix(1, 1, num_corner_fields, (const char **)corner_fieldnames);
	dims[0] = 1;	 dims[1] = 2;

	ReportCorner(hDataset, 0.0, GDALGetRasterYSize(hDataset), xy_c);	/* Lower Left */
	mxCorners = mxCreateNumericArray (2,dims,mxDOUBLE_CLASS, mxREAL);
	dptr = mxGetPr(mxCorners);
	dptr[0] = xy_c[0];		dptr[1] = xy_c[1];
	dptr2[0] = xy_c[0];		dptr2[2] = xy_c[1];	/* xmin, ymin */
	mxSetField(corner_struct, 0, "LL", mxCorners );

	ReportCorner(hDataset, 0.0, 0.0, xy_c);					/* Upper Left */
	mxCorners = mxCreateNumericArray (2,dims,mxDOUBLE_CLASS, mxREAL);
	dptr = mxGetPr(mxCorners);
	dptr[0] = xy_c[0];		dptr[1] = xy_c[1];
	mxSetField(corner_struct, 0, "UL", mxCorners );

	ReportCorner(hDataset, GDALGetRasterXSize(hDataset), 0.0, xy_c);	/* Upper Rigt */
	mxCorners = mxCreateNumericArray (2,dims,mxDOUBLE_CLASS, mxREAL);
	dptr = mxGetPr(mxCorners);
	dptr[0] = xy_c[0];		dptr[1] = xy_c[1];
	dptr2[1] = xy_c[0];		dptr2[3] = xy_c[1];	/* xmax, ymax */
	mxSetField(corner_struct, 0, "UR", mxCorners );

	ReportCorner(hDataset, GDALGetRasterXSize(hDataset), GDALGetRasterYSize(hDataset), xy_c);	/* Lower Rigt */
	mxCorners = mxCreateNumericArray (2,dims,mxDOUBLE_CLASS, mxREAL);
	dptr = mxGetPr(mxCorners);
	dptr[0] = xy_c[0];		dptr[1] = xy_c[1];
	mxSetField(corner_struct, 0, "LR", mxCorners );

	mxSetField (metadata_struct, 0, "Corners", corner_struct);

	/* Fill in the rest of the GMT header values */
	if (z_min == 1e50) {		/* We don't know yet the dataset Min/Max */
		adfMinMax[0] = GDALGetRasterMinimum( hBand, &bGotMin );
		adfMinMax[1] = GDALGetRasterMaximum( hBand, &bGotMax );
		if(!(bGotMin && bGotMax))
			GDALComputeRasterMinMax( hBand, TRUE, adfMinMax );
		dptr2[4] = adfMinMax[0];
		dptr2[5] = adfMinMax[1];
	}
	else {
		dptr2[4] = z_min;
		dptr2[5] = z_max;
	}	

	dptr2[6] = 0;
	dptr2[7] = adfGeoTransform[1];
	dptr2[8] = fabs(adfGeoTransform[5]);

	if (correct_bounds) {
		dptr2[0] += dptr2[7] / 2;	dptr2[1] -= dptr2[7] / 2;
		dptr2[2] += dptr2[8] / 2;	dptr2[3] -= dptr2[8] / 2;
	}

	mxSetField (metadata_struct, 0, "GMT_hdr", mxGMT_header);

	return ( metadata_struct );
}