Пример #1
0
void fill_image_data(GDALImage *image)
{
    GDALResult result;
    // Open GDAL File
    image->dataset = GDALOpen(image->filepath, GA_ReadOnly);
    FAILIF(image->dataset, NULL, "Unable to open file.");
    // Get file information
    image->driver         = GDALGetDatasetDriver(image->dataset);
    image->original_width  = GDALGetRasterXSize(image->dataset);
    image->original_height = GDALGetRasterYSize(image->dataset);
    image->band_count      = limit_band_count(GDALGetRasterCount(image->dataset));

    // Open first band to get block information
    image->current_band = GDALGetRasterBand(image->dataset, 1);
    result = GDALGetGeoTransform(image->dataset, image->geo_transform);
    FAILIF(result, CE_Failure, "Failed to get GeoTransform data");
    GDALGetBlockSize(image->current_band, &image->block_size.x, &image->block_size.y);
    image->output_size.x = image->block_size.x/image->scale;
    image->output_size.y = image->block_size.y/image->scale;
    image->num_blocks.x = image->original_width/image->block_size.x;
    image->num_blocks.y = image->original_height/image->block_size.y;

    DEFAULT(image->num_blocks.x, 0, 1);
    DEFAULT(image->num_blocks.y, 0, 1);
    DEFAULT(image->output_size.x, 0, 1);
    DEFAULT(image->output_size.y, 0, 1);
}
Пример #2
0
static Read *
read_new( const char *filename, VipsImage *out )
{
	Read *read;
	int64_t w, h;

	read = VIPS_NEW( out, Read );
	memset( read, 0, sizeof( *read ) );
	g_signal_connect( out, "close", G_CALLBACK( read_destroy_cb ),
		read );

  GDALAllRegister();
  read->hDataset = GDALOpen( filename, GA_ReadOnly );
	if( read->hDataset == NULL ) {
		vips_error( "gdal2vips", 
			"%s", _( "unsupported gdal format" ) );
		return( NULL );
	}

	vips_image_pipelinev( out, VIPS_DEMAND_STYLE_SMALLTILE, NULL );

	w = GDALGetRasterXSize (read->hDataset);
	h = GDALGetRasterYSize (read->hDataset);

	GDALRasterBandH hBand;
	hBand = GDALGetRasterBand( read->hDataset, 1 );
	if( hBand == NULL ) {
		vips_error( "gdal2vips", 
			"%s", _( "can not open raster band" ) );
		return( NULL );
	}

	GDALGetBlockSize( hBand, &read->tile_width, &read->tile_height );

	read->data_type = GDALGetRasterDataType( hBand );
	// int vipsFormat = VIPS_FORMAT_UCHAR;

	// switch( dataType ) {
	// 	case GDT_Byte: vipsFormat = VIPS_FORMAT_UCHAR; break;
	// 	case GDT_UInt16: vipsFormat = VIPS_FORMAT_USHORT; break;

	// }

	vips_image_init_fields( out, w, h, 3, VIPS_FORMAT_UCHAR,
		VIPS_CODING_NONE, VIPS_INTERPRETATION_RGB, 1.0, 1.0 );

	return( read );
}
Пример #3
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 );
}
Пример #4
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 );
}
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 );
    }
static CPLErr ProcessLayer( OGRLayerH hSrcLayer, GDALDatasetH hDstDS,
                          OGRGeometry *poClipSrc,
                          GUInt32 nXSize, GUInt32 nYSize, int nBand,
                          int& bIsXExtentSet, int& bIsYExtentSet,
                          double& dfXMin, double& dfXMax,
                          double& dfYMin, double& dfYMax,
                          const char *pszBurnAttribute,
                          const double dfIncreaseBurnValue,
                          const double dfMultiplyBurnValue,
                          GDALDataType eType,
                          GDALGridAlgorithm eAlgorithm, void *pOptions,
                          int bQuiet, GDALProgressFunc pfnProgress )

{
/* -------------------------------------------------------------------- */
/*      Get field index, and check.                                     */
/* -------------------------------------------------------------------- */
    int iBurnField = -1;

    if ( pszBurnAttribute )
    {
        iBurnField = OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hSrcLayer ),
                                           pszBurnAttribute );
        if( iBurnField == -1 )
        {
            printf( "Failed to find field %s on layer %s, skipping.\n",
                    pszBurnAttribute, 
                    OGR_FD_GetName( OGR_L_GetLayerDefn( hSrcLayer ) ) );
            return CE_Failure;
        }
    }

/* -------------------------------------------------------------------- */
/*      Collect the geometries from this layer, and build list of       */
/*      values to be interpolated.                                      */
/* -------------------------------------------------------------------- */
    OGRFeature *poFeat;
    std::vector<double> adfX, adfY, adfZ;

    OGR_L_ResetReading( hSrcLayer );

    while( (poFeat = (OGRFeature *)OGR_L_GetNextFeature( hSrcLayer )) != NULL )
    {
        OGRGeometry *poGeom = poFeat->GetGeometryRef();
        double  dfBurnValue = 0.0;

        if ( iBurnField >= 0 )
            dfBurnValue = poFeat->GetFieldAsDouble( iBurnField );

        ProcessCommonGeometry(poGeom, poClipSrc, iBurnField, dfBurnValue,
            dfIncreaseBurnValue, dfMultiplyBurnValue, adfX, adfY, adfZ);

        OGRFeature::DestroyFeature( poFeat );
    }

    if ( adfX.size() == 0 )
    {
        printf( "No point geometry found on layer %s, skipping.\n",
                OGR_FD_GetName( OGR_L_GetLayerDefn( hSrcLayer ) ) );
        return CE_None;
    }

/* -------------------------------------------------------------------- */
/*      Compute grid geometry.                                          */
/* -------------------------------------------------------------------- */
    if ( !bIsXExtentSet || !bIsYExtentSet )
    {
        OGREnvelope sEnvelope;
        OGR_L_GetExtent( hSrcLayer, &sEnvelope, TRUE );

        if ( !bIsXExtentSet )
        {
            dfXMin = sEnvelope.MinX;
            dfXMax = sEnvelope.MaxX;
            bIsXExtentSet = TRUE;
        }

        if ( !bIsYExtentSet )
        {
            dfYMin = sEnvelope.MinY;
            dfYMax = sEnvelope.MaxY;
            bIsYExtentSet = TRUE;
        }
    }

/* -------------------------------------------------------------------- */
/*      Perform gridding.                                               */
/* -------------------------------------------------------------------- */

    const double    dfDeltaX = ( dfXMax - dfXMin ) / nXSize;
    const double    dfDeltaY = ( dfYMax - dfYMin ) / nYSize;

    if ( !bQuiet )
    {
        printf( "Grid data type is \"%s\"\n", GDALGetDataTypeName(eType) );
        printf( "Grid size = (%lu %lu).\n",
                (unsigned long)nXSize, (unsigned long)nYSize );
        printf( "Corner coordinates = (%f %f)-(%f %f).\n",
                dfXMin - dfDeltaX / 2, dfYMax + dfDeltaY / 2,
                dfXMax + dfDeltaX / 2, dfYMin - dfDeltaY / 2 );
        printf( "Grid cell size = (%f %f).\n", dfDeltaX, dfDeltaY );
        printf( "Source point count = %lu.\n", (unsigned long)adfX.size() );
        PrintAlgorithmAndOptions( eAlgorithm, pOptions );
        printf("\n");
    }

    GDALRasterBandH hBand = GDALGetRasterBand( hDstDS, nBand );

    if (adfX.size() == 0)
    {
        // FIXME: Shoulda' set to nodata value instead
        GDALFillRaster( hBand, 0.0 , 0.0 );
        return CE_None;
    }

    GUInt32 nXOffset, nYOffset;
    int     nBlockXSize, nBlockYSize;
    int     nDataTypeSize = GDALGetDataTypeSize(eType) / 8;

    // Try to grow the work buffer up to 16 MB if it is smaller
    GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize );
    const GUInt32 nDesiredBufferSize = 16*1024*1024;
    if( (GUInt32)nBlockXSize < nXSize && (GUInt32)nBlockYSize < nYSize &&
        (GUInt32)nBlockXSize < nDesiredBufferSize / (nBlockYSize * nDataTypeSize) )
    {
        int nNewBlockXSize  = nDesiredBufferSize / (nBlockYSize * nDataTypeSize);
        nBlockXSize = (nNewBlockXSize / nBlockXSize) * nBlockXSize;
        if( (GUInt32)nBlockXSize > nXSize )
            nBlockXSize = nXSize;
    }
    else if( (GUInt32)nBlockXSize == nXSize && (GUInt32)nBlockYSize < nYSize &&
             (GUInt32)nBlockYSize < nDesiredBufferSize / (nXSize * nDataTypeSize) )
    {
        int nNewBlockYSize = nDesiredBufferSize / (nXSize * nDataTypeSize);
        nBlockYSize = (nNewBlockYSize / nBlockYSize) * nBlockYSize;
        if( (GUInt32)nBlockYSize > nYSize )
            nBlockYSize = nYSize;
    }
    CPLDebug("GDAL_GRID", "Work buffer: %d * %d", nBlockXSize, nBlockYSize);

    void    *pData =
        VSIMalloc3( nBlockXSize, nBlockYSize, nDataTypeSize );
    if( pData == NULL )
    {
        CPLError(CE_Failure, CPLE_OutOfMemory, "Cannot allocate work buffer");
        return CE_Failure;
    }

    GUInt32 nBlock = 0;
    GUInt32 nBlockCount = ((nXSize + nBlockXSize - 1) / nBlockXSize)
        * ((nYSize + nBlockYSize - 1) / nBlockYSize);

    CPLErr eErr = CE_None;
    for ( nYOffset = 0; nYOffset < nYSize && eErr == CE_None; nYOffset += nBlockYSize )
    {
        for ( nXOffset = 0; nXOffset < nXSize && eErr == CE_None; nXOffset += nBlockXSize )
        {
            void *pScaledProgress;
            pScaledProgress =
                GDALCreateScaledProgress( (double)nBlock / nBlockCount,
                                          (double)(nBlock + 1) / nBlockCount,
                                          pfnProgress, NULL );
            nBlock ++;

            int nXRequest = nBlockXSize;
            if (nXOffset + nXRequest > nXSize)
                nXRequest = nXSize - nXOffset;

            int nYRequest = nBlockYSize;
            if (nYOffset + nYRequest > nYSize)
                nYRequest = nYSize - nYOffset;

            eErr = GDALGridCreate( eAlgorithm, pOptions,
                            adfX.size(), &(adfX[0]), &(adfY[0]), &(adfZ[0]),
                            dfXMin + dfDeltaX * nXOffset,
                            dfXMin + dfDeltaX * (nXOffset + nXRequest),
                            dfYMin + dfDeltaY * nYOffset,
                            dfYMin + dfDeltaY * (nYOffset + nYRequest),
                            nXRequest, nYRequest, eType, pData,
                            GDALScaledProgress, pScaledProgress );

            if( eErr == CE_None )
                eErr = GDALRasterIO( hBand, GF_Write, nXOffset, nYOffset,
                          nXRequest, nYRequest, pData,
                          nXRequest, nYRequest, eType, 0, 0 );

            GDALDestroyScaledProgress( pScaledProgress );
        }
    }

    CPLFree( pData );
    return eErr;
}
Пример #7
0
SVImage init(int xLow, int xHigh, int yLow, int yHigh, const char *filepath){

    GDALDatasetH  hDataset;
    // Register drivers
    GDALAllRegister();
    
    // open the given file as Read Only
    hDataset = GDALOpen(filepath, GA_ReadOnly );
    // if opening failed
    if( hDataset == NULL )
    {
        fprintf(stderr, "Unable to open file.");
        exit(EXIT_FAILURE);
    }

    /*      Declare some variables to be used later     */
    int *xBlockSize = malloc(sizeof(int));
    int *yBlockSize = malloc(sizeof(int));
    int xOutputSize;
    int yOutputSize;
    int numXBlocks;
    int numYBlocks;
    int origWidth;
    int origHeight;
    int origBandCount;
    
    /*Get some information on the image*/
    origWidth = GDALGetRasterXSize( hDataset );                 // Get raster pixel width
    origHeight = GDALGetRasterYSize( hDataset );                // Get raster pixel height
    origBandCount = GDALGetRasterCount( hDataset );             // Get number of raster bands in the image
    GDALRasterBandH hBand = GDALGetRasterBand( hDataset, 1 );   // Get raster band with id 1
    GDALGetBlockSize( hBand, xBlockSize, yBlockSize);           // Fetch the block size for this band

    /*TODO make sure scale is set somewhere*/
    
    /*Store some information on what the output should have*/
    xOutputSize = ((*xBlockSize) / scale); // get the new x block size
    yOutputSize = ((*yBlockSize) / scale); // get the new y block size
    numXBlocks = origWidth/(*xBlockSize);  // Get x block count
    numYBlocks = origHeight/(*yBlockSize); // Get y block count

    int bandCount;
    if (origBandCount >= 3) // Just a guess, limit bands to RGB?
    {
        bandCount = 3;
    }
    else                    // Otherwise image is probably grayscale, one band?
    {
        bandCount = 1;
    }

    /*TODO edit this or remove it since we aren't using focusing on openGL*/
    /*
     *int format;
     *if (bandCount == 3)
     *{
     *    format = GL_RGBA;
     *}
     *else
     *{
     *    format = GL_LUMINANCE_ALPHA;
     *}
     */
    
    int usedBlocks;
    int usedXBlocks;
    int usedYBlocks;
    /*
     *This is odd, xHigh and yHigh are
     *passed as parameters but changed here
     *TODO see if we can remove parameters or just use this
     */

    if ((xHigh < 0) || (xHigh < xLow))
    {
        xHigh = numXBlocks;
    }
    if ((yHigh < 0)|| (yHigh < yLow))
    {
        yHigh = numYBlocks;
    }
    
    usedXBlocks = (xHigh - xLow); // This is probably the part of the image that should be displayed on screen
    usedYBlocks = (yHigh - yLow); // Y part on screen?
    usedBlocks = (usedXBlocks * usedYBlocks); // Total blocks on screen?
    
    SVImage svip = 
        {
            .Width = xOutputSize*usedXBlocks,
            .Height = yOutputSize*usedYBlocks,
            .BytesPerPixel = 1, 
            .Data = (CPLMalloc((sizeof(char) * xOutputSize * yOutputSize * usedBlocks * (bandCount+1))))
            // Data = xOutputSize * yOutputSize = pixels/block * usedBlocks = totalpixels 
        };

    free(xBlockSize);
    free(yBlockSize);
    return svip;
}


/*
Uses stochastic sampling to fill the data section of an SVImage struct.
*/
void sample(params *in)		//TODO handle 32 bit representations
{
    /*Set variables from the params struct*/
    SVImage* out = in->target;
    int xLow = in->xLow;
    int xHigh = in->xHigh;
    int yLow = in->yLow;
    int yHigh = in->yHigh;
    const char *file = in->file;

    GDALDatasetH  hDataset;
    GDALRasterBandH hBand;
    /*Register drivers*/
    GDALAllRegister();
	
    //TODO Dynamically calculate sample count?
    int avgSampleCount = 25;
 
    //Open GDAL File
    //------------------------------------------------
    hDataset = GDALOpen(file, GA_ReadOnly );
    if( hDataset == NULL )
    {
    	fprintf(stderr, "Unable to open file.\n"); 
        exit(EXIT_FAILURE);
    }
    
    //GDAL FILE INFO
    //---------------------------------------------
    GDALDriverH   hDriver;
    hDriver = GDALGetDatasetDriver( hDataset ); // Get driver for this file

    double adfGeoTransform[6];

    //Print GDAL Driver 
    printf( "Driver: %s/%s\n",
            GDALGetDriverShortName( hDriver ),
            GDALGetDriverLongName( hDriver ) );

    //Get original raster size
    int origWidth = GDALGetRasterXSize( hDataset ); 
    int origHeight = GDALGetRasterYSize( hDataset ); 
    printf("width = %i\n", origWidth);
    printf("height = %i\n", origHeight);  

    //Get Raster band count	
    int origBandCount = GDALGetRasterCount( hDataset );
    printf("origBandCount = %i\n", origBandCount);
    int bandCount;
    if (origBandCount >= 3)
    {
        bandCount = 3;
    }
    else
    {
        bandCount = 1;
    }

    //Target output Width and Height
    float stride = (scale * scale);				
    stride /= (avgSampleCount);

    //the greatest number of pixels that can be skipped in a single iteration
    int maxStride = ((int)stride) + 1;				

    //Load band 1
    hBand = GDALGetRasterBand( hDataset, 1 );

    if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
    {
        printf( "Pixel Size = (%.6f,%.6f)\n",
                    adfGeoTransform[1], adfGeoTransform[5] );
    }
    else
    {
        fprintf(stderr, "Failed to get pixel size\n");
    }

    int* xBlockSize = malloc(sizeof(int));
    int* yBlockSize = malloc(sizeof(int));
    //get block size
    GDALGetBlockSize( hBand, xBlockSize, yBlockSize);
    printf("xBlockSize = %i\n", *xBlockSize);
    printf("yBlockSize = %i\n", *yBlockSize);  
    int xOutputSize = ((*xBlockSize) / scale);
    int yOutputSize = ((*yBlockSize) / scale);
    printf("X Output Size%i\n", xOutputSize);
    int numXBlocks = origWidth/(*xBlockSize);
    int numYBlocks = origHeight/(*yBlockSize);
    printf("numXBlocks = %i\n", numXBlocks);
    printf("numYBlocks = %i\n", numYBlocks);
    
    if ((xHigh < 0) || (xHigh < xLow))
    {
        xHigh = numXBlocks;
    }
    if ((yHigh < 0)|| (yHigh < yLow))
    {
        yHigh = numYBlocks;
    }
    
    int usedXBlocks = (xHigh - xLow);
    int usedYBlocks = (yHigh - yLow);
    int usedBlocks = (usedXBlocks * usedYBlocks);
    
    unsigned char* output = CPLMalloc((sizeof(char) * xOutputSize* yOutputSize *usedBlocks  * (bandCount+1)));  // Allocate space for the output
    float* vals = calloc( xOutputSize* yOutputSize *usedBlocks * (bandCount+1), sizeof(float));			//stores pixel values
    unsigned long* valsPerIndex = calloc( xOutputSize* yOutputSize * usedBlocks * (bandCount+1), sizeof(unsigned long));		//stores number of pixel values per output index
    unsigned long rseed = 0;
    unsigned long rowIndex = 0;		//the index of the row to which we will output our value
    unsigned long colIndex = 0;		//the index of the column to which we will output our value
    unsigned long outIndex = 0;
    unsigned long sampledIndex = 0;	//One dimensional representation of column/row index
    
    //iterate through each pixel, jump to the last pixel we sampled.
    long long i = 0;
    int outputXOffset = 0;
    int outputYOffset = 0;
    int outputIndexOffset = 0;
    if (GDALGetRasterDataType(hBand) == GDT_Int16)
    {
        short* data = (short *) CPLMalloc(sizeof(unsigned short) * (*xBlockSize)*(*yBlockSize)); //TODO: GDAL Raster can be 16 bit pixel representation
        int band;
        for (band = 1; band <= bandCount; band++){
            hBand = GDALGetRasterBand( hDataset, band );
            int yBlock, xBlock;
            for(yBlock = yLow; yBlock < yHigh; yBlock++){
                for(xBlock = xLow; xBlock < xHigh; xBlock++){
                    if(GDALReadBlock(hBand,xBlock,yBlock, data) != CE_None)
                    {
                        fprintf(stderr, "Read block failed\n");
                        exit(EXIT_FAILURE);
                    }
                    for(i = 0 ; i < ((*xBlockSize)*(*yBlockSize)-1) ; i += rseed){
                        rseed = (214013 * rseed + 2531011); // Magic numbers.
                        rseed %= maxStride;	
                        sampledIndex = i;
                        i = (maxStride ==1) ? (i+1) : i;
                        rowIndex = (sampledIndex/(xOutputSize*scale* scale)) + ((yBlock - yLow)* yOutputSize);
                        colIndex = ((sampledIndex % (xOutputSize * scale))/scale) + ((xBlock - xLow) * xOutputSize);
                        outIndex = ((rowIndex * (xOutputSize * usedXBlocks ) + colIndex) * (bandCount+1) ) + (band -1);
                        vals[outIndex] += (*(data + sampledIndex));
                        vals[outIndex] += 118.450588 + ((*(data + sampledIndex))/128);
                        if (vals[outIndex]/valsPerIndex[outIndex] < 0) {
                            vals[outIndex] =0;
                        }else if (vals[outIndex]/valsPerIndex[outIndex] > 255){
                            vals[outIndex] = 255;
                        }
                    }
                }
            }
        }
    }
    else
    {
        unsigned char* data = (unsigned char *) CPLMalloc(sizeof(char) * (*xBlockSize)*(*yBlockSize));
        int band;
        for (band = 1; band <= bandCount; band++)
        {
            hBand = GDALGetRasterBand( hDataset, band );
            int yBlock, xBlock;
            outputYOffset = 0;
            for(yBlock = yLow; yBlock < yHigh; yBlock++){
                outputYOffset = ((yBlock - yLow) * yOutputSize * xOutputSize * usedXBlocks * (bandCount + 1));
                outputXOffset = 0;
                for(xBlock = xLow; xBlock < xHigh; xBlock++){
                    outputXOffset = ((xBlock - xLow) * xOutputSize * (bandCount + 1));
                    if(GDALReadBlock(hBand,xBlock,yBlock, data) != CE_None)
                    {
                        fprintf(stderr, "Read block failed\n");
                        exit(EXIT_FAILURE);
                    }
                    for(i = 0 ; i < ((*xBlockSize)*(*yBlockSize)) ; i += rseed){
                        rseed = (214013 * rseed + 2531011);
                        rseed %= maxStride;	
                        sampledIndex = i;
                        i = (maxStride ==1) ? (i+1) : i;
                        rowIndex = (sampledIndex/(xOutputSize*scale* scale)) + ((yBlock - yLow)* yOutputSize);
                        colIndex = ((sampledIndex % (xOutputSize * scale))/scale) + ((xBlock - xLow) * xOutputSize);
                        outIndex = ((rowIndex * (xOutputSize * usedXBlocks ) + colIndex) * (bandCount+1) ) + (band -1);
                        vals[outIndex] += (*(data + sampledIndex));
                        valsPerIndex[outIndex] +=1;
                    }
                    outputIndexOffset = (outputYOffset + outputXOffset);
                    int j;
                    for (j = 0; j<yOutputSize; j++){
                        i = outputIndexOffset;
                        int k = (i + (xOutputSize * (bandCount+1)));
                        for (i = 0; i<k;i++){
                            int x = (i+(j*(xOutputSize * (bandCount + 1) * (usedXBlocks))));
                            if(((x+1)%4==0&&bandCount==3)||((x+1)%2==0&&bandCount==1)){
                                output[x] = (unsigned char) 1; //Sets the alpha to opaque
                            }else{
                                output[x] = (unsigned char) (vals[x]/valsPerIndex[x]);	//calculate final output by averaging each color value
                            }
                        }
                    }
                    out->Data = output;
                }
            }
        }
    }

    printf("sampling complete\n");
    GDALClose(hDataset);
}
Пример #8
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;
}
int
main (int argc, const char *argv[])
{
  GDALDriverH hDriver;
  double adfGeoTransform[6];
  GDALDatasetH in_Dataset;
  GDALDatasetH out_Dataset;
  double *data_scan_line;
  char *out_scan_line;
  int nBlockXSize, nBlockYSize;
  int bGotMin, bGotMax;
  int bands;
  int xsize;
  double lower_fiddle, upper_fiddle;
  double adfMinMax[2];
  /* These are hard coded for now - need to figure out a better way to handle this.. */
  double palette_in[256] =
    { 0.0, 1.00011, 1.9999649999999998, 3.000075, 3.9999299999999995, 5.00004,
    5.999895, 7.000005, 8.000115, 8.99997, 10.00008, 10.999935,
    12.000044999999998, 12.9999,
    14.00001, 15.00012, 15.999975, 17.000085000000002, 17.99994, 19.00005,
    19.999905000000002,
    21.000014999999998, 22.000125, 22.99998, 24.000089999999997, 24.999945,
    26.000055, 26.99991,
    28.00002, 28.999875000000003, 29.999985, 31.000094999999998, 31.99995,
    33.00006, 33.999915,
    35.000024999999994, 35.99988, 36.999990000000004, 38.0001, 38.999955,
    40.000065, 40.99992,
    42.000029999999995, 42.999885, 43.999995000000006, 45.000105, 45.99996,
    47.00007,
    47.999925000000005, 49.000035, 49.99989, 51.0, 52.00011, 52.999965,
    54.000075, 54.99993,
    56.00004, 56.999895, 58.000004999999994, 59.000115, 59.99997,
    61.000080000000004, 61.999935,
    63.000045, 63.9999, 65.00001, 66.00012, 66.999975, 68.000085, 68.99994,
    70.00004999999999,
    70.999905, 72.000015, 73.000125, 73.99998000000001, 75.00009, 75.999945,
    77.00005499999999,
    77.99991, 79.00002, 79.99987499999999, 80.99998500000001, 82.000095,
    82.99995,
    84.00005999999999, 84.999915, 86.00002500000001, 86.99987999999999,
    87.99999000000001, 89.0001,
    89.999955, 91.00006499999999, 91.99992, 93.00003, 93.99988499999999,
    94.999995, 96.000105,
    96.99996, 98.00007, 98.999925, 100.000035, 100.99989, 102.0, 103.00011,
    103.999965, 105.000075,
    105.99993, 107.00004, 107.999895, 109.000005, 110.00011500000001,
    110.99997, 112.00008,
    112.99993500000001, 114.000045, 114.9999, 116.00000999999999, 117.00012,
    117.999975,
    119.000085, 119.99994, 121.00005, 121.999905, 123.00001499999999,
    124.000125,
    124.99998000000001, 126.00009, 126.999945, 128.000055, 128.99991,
    130.00002, 130.999875,
    131.99998499999998, 133.000095, 133.99995, 135.00006, 135.999915,
    137.00002500000002,
    137.99988, 138.99999, 140.00009999999997, 140.999955, 142.000065,
    142.99991999999997,
    144.00003, 144.999885, 145.99999499999998, 147.000105, 147.99996000000002,
    149.00007,
    149.999925, 151.00003500000003, 151.99989, 153.0, 154.00010999999998,
    154.999965, 156.000075,
    156.99992999999998, 158.00004, 158.999895, 160.000005, 161.000115,
    161.99997000000002,
    163.00008, 163.999935, 165.000045, 165.9999, 167.00001,
    168.00011999999998, 168.999975,
    170.000085, 170.99993999999998, 172.00005000000002, 172.999905,
    174.000015, 175.000125,
    175.99998000000002, 177.00009, 177.999945, 179.00005499999997, 179.99991,
    181.00002,
    181.999875, 182.999985, 184.00009500000002, 184.99994999999998, 186.00006,
    186.99991500000002,
    188.000025, 188.99988, 189.99999, 191.0001, 191.999955,
    193.00006499999998, 193.99992,
    195.00003, 195.99988499999998, 196.999995, 198.00010500000002, 198.99996,
    200.00007,
    200.99992500000002, 202.000035, 202.99989, 204.0, 205.00011, 205.999965,
    207.00007499999998,
    207.99993, 209.00004, 209.99989499999998, 211.00000500000002, 212.000115,
    212.99997, 214.00008,
    214.999935, 216.000045, 216.9999, 218.00001, 219.00012, 219.999975,
    221.00008499999998,
    221.99994, 223.00005000000002, 223.99990499999998, 225.00001500000002,
    226.000125, 226.99998,
    228.00009, 228.999945, 230.000055, 230.99991, 232.00001999999998,
    232.999875, 233.999985,
    235.000095, 235.99995, 237.00006, 237.999915, 239.000025, 239.99988,
    240.99999, 242.0001,
    242.999955, 244.000065, 244.99992, 246.00002999999998, 246.999885,
    247.999995, 249.000105,
    249.99996000000002, 251.00007, 251.999925, 253.000035, 253.99989, 255.0
  };
  double palette_out[256] =
    { 0.0, 0.042075, 0.08415, 0.126225, 0.169065, 0.21216, 0.255765, 0.29988,
    0.345015, 0.390915, 0.437835, 0.48602999999999996, 0.5352450000000001,
    0.58599, 0.63801,
    0.69156, 0.7468950000000001, 0.804015, 0.8629199999999999,
    0.9238649999999999, 0.98685, 1.05213,
    1.119705, 1.18983, 1.26225, 1.337475, 1.415505, 1.49634, 1.580235,
    1.6674449999999998, 1.75746,
    1.851045, 1.9482, 2.04867, 2.152965, 2.2608300000000003,
    2.3727750000000003, 2.4885450000000002,
    2.6083950000000002, 2.73258, 2.8611000000000004, 2.993955,
    3.1313999999999997, 3.27369, 3.42057,
    3.572295, 3.72912, 3.891045, 4.05807, 4.23045, 4.408440000000001,
    4.591785, 4.780995, 4.975815,
    5.1765, 5.38305, 5.595975, 5.8150200000000005, 6.040185, 6.27198,
    6.510405, 6.755205, 7.007145,
    7.265715, 7.53117, 7.8040199999999995, 8.084010000000001, 8.37114,
    8.66592, 8.968095, 9.27792,
    9.59565, 9.92103, 10.25457, 10.596015, 10.945875, 11.30415, 11.670585,
    12.04569, 12.429465,
    12.82191, 13.223279999999999, 13.63383, 14.053305, 14.48196,
    14.919794999999999, 15.36732,
    15.82428, 16.29093, 16.767270000000003, 17.253555, 17.749785, 18.256215,
    18.925845,
    19.456245000000003, 19.99863, 20.552745, 21.11859, 21.696165, 22.285725,
    22.887014999999998,
    23.500035, 24.125295, 24.762285, 25.411260000000002, 26.071965, 26.74491,
    27.42984, 28.12701,
    28.835910000000002, 29.55705, 30.29043, 31.035795, 31.7934, 32.56299,
    33.345075, 34.139145,
    34.94571, 35.764514999999996, 36.595305, 37.438845, 38.294625, 39.162645,
    40.04316, 40.935915,
    41.84142, 42.759165, 43.68966, 44.632394999999995, 45.58788, 46.55586,
    47.536335,
    48.529560000000004, 49.535535, 50.554005000000004, 51.58497, 52.62894,
    53.68566, 54.75513,
    55.837095, 56.932064999999994, 58.040040000000005, 59.160765,
    60.294239999999995, 61.44072,
    62.59995000000001, 63.772439999999996, 64.95768000000001,
    66.15592500000001, 67.36743,
    68.591685, 69.82919999999999, 71.07972, 72.343245, 73.620285, 74.910075,
    76.21337999999999,
    77.52968999999999, 78.85926, 80.20209, 81.55843499999999, 82.927785,
    84.31065, 85.66419,
    87.10264500000001, 88.611225, 90.18712500000001, 91.82779500000001,
    93.52992, 95.291205,
    97.108845, 98.979525, 100.90095, 102.87006, 104.884305, 106.94037,
    109.03596, 111.16827,
    113.33424000000001, 115.531065, 117.756195, 120.00657, 122.27964,
    124.572345,
    126.88213499999999, 129.20595, 131.54124, 133.8852, 136.23477,
    138.58714500000002, 140.939775,
    143.289855, 145.63458, 147.97089, 150.296235, 152.60781, 154.902555,
    157.17817499999998,
    159.431355, 161.65929, 163.859685, 166.02948, 168.165615, 170.26554,
    172.32645, 174.34554,
    176.320005, 178.24704, 180.292905, 182.130945, 183.953685, 185.76138,
    187.554285, 189.33291,
    191.09751, 192.84834, 194.58591, 196.310475, 198.02229, 199.72161,
    201.4092, 203.084805,
    204.74944499999998, 206.402865, 208.04557499999999, 209.67808499999998,
    211.30065, 212.913525,
    214.516965, 216.11148, 217.69758000000002, 219.27501, 220.84479,
    222.406665, 223.9614,
    225.50924999999998, 227.05047000000002, 228.585315, 230.114295,
    231.63766500000003,
    233.15568000000002, 234.66885000000002, 236.17743, 237.681675, 239.18184,
    240.67869, 242.172225,
    243.66295499999998, 245.15088, 246.636765, 248.12061000000003, 249.602925,
    251.083965,
    252.56424, 254.04375, 255.0
  };


  GDALAllRegister ();


  /* ussage.. */
  if (argc != 3)
    ussage ();

  /* 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);
  printf ("Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize,
	  GDALGetDataTypeName (GDALGetRasterDataType
			       (GDALGetRasterBand (in_Dataset, 1))),
	  GDALGetColorInterpretationName (GDALGetRasterColorInterpretation
					  (GDALGetRasterBand
					   (in_Dataset, 1))));

  /* Loop though bands, scaling the data.. */
  xsize = GDALGetRasterXSize (in_Dataset);
  data_scan_line = (double *) CPLMalloc (sizeof (double) * xsize);
  out_scan_line = (char *) CPLMalloc (sizeof (char) * xsize);

  for (bands = 1; bands <= GDALGetRasterCount (in_Dataset); bands++)
    {
      int x;
      double min = 9999999.0, max = 0.0;	/* probibly a better way to set these.. */
      double dmin, dmax, middle;
      GDALRasterBandH data_band, out_band;
      int y_index = 0;
      data_band = GDALGetRasterBand (in_Dataset, bands);
      out_band = GDALGetRasterBand (out_Dataset, bands);

      /* Set nodata for that band */
      GDALSetRasterNoDataValue (out_band, 0.0);

      /*Find Min,Max, required for scaling */
      for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++)
	{
	  /* Read data.. */
	  GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1,
			data_scan_line, xsize, 1, GDT_Float64, 0, 0);
	  for (x = 0; x < xsize; x++)
	    {
	      if (data_scan_line[x] < MAX_MODIS
		  && data_scan_line[x] > MIN_VALUE)
		{
		  if (data_scan_line[x] > max)
		    max = data_scan_line[x];
		  else if (data_scan_line[x] < min)
		    min = data_scan_line[x];
		}
	    }
	}

      dmax = (double) max;
      dmin = (double) min;

      printf ("Info: For Band %d -> Min=%g,Max=%g\n", bands, dmin, dmax);

      for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++)
	{
	  double scaled;

	  /* Read data.. */
	  GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1,
			data_scan_line, xsize, 1, GDT_Float64, 0, 0);

	  /* scale each .. */
	  for (x = 0; x < xsize; x++)
	    {
	      out_scan_line[x] =
		scale (palette_in, palette_out, data_scan_line[x], dmin,
		       dmax);
	    }

	  /* now write out band.. */
	  GDALRasterIO (out_band, GF_Write, 0, y_index, xsize, 1,
			out_scan_line, xsize, 1, GDT_Byte, 0, 0);
	}

    }


  /* close file, and we are done. */
  GDALClose (out_Dataset);

}
Пример #10
0
std::shared_ptr<toprsImg> toprsGadlReader::getTileBlockRead( const toprsIRect& tileRect,int resLevel )
{
	std::shared_ptr<toprsImg> result;
	toprsIRect imageBound = getBoundingRect(resLevel);
	theTile->setImgRect(tileRect);

	// Compute clip rectangle with respect to the image bounds.
	toprsIRect clipRect   = tileRect.clipToRect(imageBound);

	if (tileRect.completely_within(clipRect) == false)
	{
		// Not filling whole tile so blank it out first.
		theTile->makeBlank();
	}
	if(m_isBlocked)
	{
		int xSize=0, ySize=0;
		GDALGetBlockSize(resolveRasterBand( resLevel, 1 ),
			&xSize,
			&ySize);
		toprsIRect blockRect = clipRect;
		blockRect.stretchToTileBoundary(toprsIpt(xSize, ySize));
		blockRect = blockRect.clipToRect(getBoundingRect(resLevel));

		// we need to cache here
		//
		toprs_int64 x = blockRect.left_up().x;
		toprs_int64 y = blockRect.left_up().y;
		toprs_int64 maxx = blockRect.right_down().x;
		toprs_int64 maxy = blockRect.right_down().y;
		toprs_uint32 aGdalBandIndex   = 1;
		toprs_uint32 rasterCount = GDALGetRasterCount(theDataset);
		if (m_outputBandList.size() > 0)
		{
			rasterCount = m_outputBandList.size();
		}

		toprs_uint32 outputBandIndex = 0;
		for(;x < maxx;x+=xSize)
		{
			for(;y < maxy;y+=ySize)
			{
				toprsIpt origin(x,y);

				//std::shared_ptr<toprsImg> cacheTile = toprsAppFixedTileCache::instance()->getTile(m_rlevelBlockCache[resLevel], origin);//xizhi

				//if(!cacheTile.valid())
				//{
				//	toprsIRect rect(origin.x,origin.y,origin.x+xSize-1, origin.y+ySize-1);
				//	theSingleBandTile->setImgRect(rect);
				//	toprsIRect validRect = rect.clipToRect(imageBound);
				//	cacheTile = toprsImgFactory::instance()->create(this);
				//	cacheTile->setImgRect(validRect);
				//	cacheTile->initialize();                          
				//	for(toprs_uint32 aBandIndex =1; aBandIndex <= rasterCount; ++aBandIndex)
				//	{
				//		if (m_outputBandList.size() > 0)
				//		{
				//			aGdalBandIndex = m_outputBandList[outputBandIndex] + 1;
				//			outputBandIndex++;
				//		}
				//		else
				//		{
				//			aGdalBandIndex = aBandIndex;
				//		}
				//		GDALRasterBandH aBand = resolveRasterBand( resLevel, aGdalBandIndex );
				//		if ( aBand )
				//		{
				//			try{

				//				bool bReadSuccess =  (GDALReadBlock(aBand, x/xSize, y/ySize, theSingleBandTile->getBuf() )== CE_None) ? true : false;
				//				if(bReadSuccess)
				//				{
				//					//cacheTile->loadBand(theSingleBandTile->getBuf(), theSingleBandTile->getImgRect(), aBandIndex-1);
				//				}
				//			}
				//			catch(...)
				//			{
				//			}
				//		}
				//	}
				//	//cacheTile->validate();
				//	//toprsAppFixedTileCache::instance()->addTile(m_rlevelBlockCache[resLevel], cacheTile.get(), false);
				//}
				//theTile->loadTile(cacheTile->getBuf(), cacheTile->getImageRectangle(), TOPRS_BSQ);
				result = theTile;
			}
		}
	}
	if(result) result->validate();

	return result;
}
Пример #11
0
bool toprsGadlReader::open()
{
	if(isOpen())
	{
		close();
	}
	std::string driverNameTmp;

	if (theSubDatasets.size() == 0)
	{
		// Note:  Cannot feed GDALOpen a NULL string!
		if (theImageFile.size())
		{
			theDataset = GDALOpen(theImageFile.c_str(), GA_ReadOnly); 
			if( theDataset == 0 )
			{
				return false;
			}
		}
		else
		{
			return false;
		}


		// Check if it is nitf data for deciding whether or not open each sub-dataset
		//This will be removed eventually when toprs can handle 2GB nitf file.
		GDALDriverH driverTmp = GDALGetDatasetDriver(theDataset);
		bool isNtif = false;
		if (driverTmp != 0)
		{
			driverNameTmp = std::string(GDALGetDriverShortName(driverTmp));
			std::transform(driverNameTmp.begin(), driverNameTmp.end(), driverNameTmp.begin(), [&](char ch){return toupper(ch);});
			if (driverNameTmp == "NITF")
			{
				isNtif = true;
			}
		}

		// Check for sub data sets...
		char** papszMetadata = GDALGetMetadata( theDataset, "SUBDATASETS" );
		if( CSLCount(papszMetadata) > 0 )
		{
			theSubDatasets.clear();

			for( int i = 0; papszMetadata[i] != 0; ++i )
			{
				std::string os = papszMetadata[i];
				if (os.find("_NAME=") != std::string::npos)
				{
					//Sub sets have already been set. Open each sub-dataset really slow down the process
					//specially for hdf data which sometimes has over 100 sub-datasets. Since following code
					//only for ntif cloud checking, so only open each sub-dataset here if the dataset is
					//nitf. This will be removed eventually when toprs can handle 2GB nitf file. 
					//Otherwise open a sub-dataset when setCurrentEntry() gets called.
					if (isNtif)
					{
						GDALDatasetH subDataset = GDALOpen(filterSubDatasetsString(os).c_str(),
							GA_ReadOnly);
						if ( subDataset != 0 )
						{
							// "Worldview ingest should ignore subimages when NITF_ICAT=CLOUD"
							// Hack: Ignore NITF subimages marked as cloud layers.
							std::string nitfIcatTag( GDALGetMetadataItem( subDataset, "NITF_ICAT", "" ) );
							if ( nitfIcatTag.find("CLOUD") == std::string::npos )
							{
								theSubDatasets.push_back(filterSubDatasetsString(os));
							}
						}
						GDALClose(subDataset);
					}
					else
					{
						theSubDatasets.push_back(filterSubDatasetsString(os));
					}
				}
			}
			//---
			// Have multiple entries.  We're going to default to open the first
			// entry like cidcadrg.
			//---
			close();

			theDataset = GDALOpen(theSubDatasets[theEntryNumberToRender].c_str(),
				GA_ReadOnly);
			if (theDataset == 0)
			{

				return false;
			}
		}  // End of has subsets block.

	}  // End of "if (theSubdatasets.size() == 0)"
	else
	{
		// Sub sets have already been set.
		theDataset = GDALOpen(theSubDatasets[theEntryNumberToRender].c_str(),
			GA_ReadOnly);
		if (theDataset == 0)
		{
			return false;
		}
	}

	// Set the driver.
	theDriver = GDALGetDatasetDriver( theDataset );

	if(!theDriver) return false;


	theGdtType = GDT_Byte;
	theOutputGdtType = GDT_Byte;

	if(getNumberOfInputBands() < 1 )
	{
		if(CSLCount(GDALGetMetadata(theDataset, "SUBDATASETS")))
		{
			std::cout
				<< "torsGdalReader::open WARNING:"
				<< "\nHas multiple sub datasets and need to set the data before"
				<< " we can get to the bands" << std::endl;
		}

		close();
		std::cout
			<< "torsGdalReader::open WARNING:"
			<< "\nNo band data present in torsGdalReader::open" << std::endl;
		return false;
	}

	toprs_int32 i = 0;
	GDALRasterBandH bBand = GDALGetRasterBand( theDataset, 1 );
	theGdtType  = GDALGetRasterDataType(bBand);


	char** papszMetadata = GDALGetMetadata( bBand, NULL );
	if (CSLCount(papszMetadata) > 0)
	{
		for(int i = 0; papszMetadata[i] != NULL; i++ )
		{
			std::string metaStr = papszMetadata[i];

			if (metaStr.find("AREA_OR_POINT") != std::string::npos)
			{
				//std::string pixel_is_point_or_area = metaStr.split("=")[1];
				//pixel_is_point_or_area.downcase();
				//if (pixel_is_point_or_area.contains("area"))
				//	thePixelType = TOPRS_PIXEL_IS_AREA;
				break;
			}
		}
	}

	if(!isIndexed(1))
	{
		for(i = 0; i  < GDALGetRasterCount(theDataset); ++i)
		{
			if(theGdtType != GDALGetRasterDataType(GDALGetRasterBand( theDataset,i+1 )))
			{
				std::cout
					<< "torsGdalReader::open WARNING"
					<< "\nWe currently do not support different scalar type bands."
					<< std::endl;
				close();
				return false;
			}

		}
	}
	theOutputGdtType = theGdtType;
	switch(theGdtType)
	{
	case GDT_CInt16:
		{
			//          theOutputGdtType = GDT_Int16;
			theIsComplexFlag = true;
			break;
		}
	case GDT_CInt32:
		{
			//          theOutputGdtType = GDT_Int32;
			theIsComplexFlag = true;
			break;
		}
	case GDT_CFloat32:
		{
			//          theOutputGdtType = GDT_Float32;
			theIsComplexFlag = true;
			break;
		}
	case GDT_CFloat64:
		{
			//          theOutputGdtType = GDT_Float64;
			theIsComplexFlag = true;
			break;
		}
	default:
		{
			theIsComplexFlag = false;
			break;
		}
	}

	if((std::string(GDALGetDriverShortName( theDriver )) == "PNG")&&
		(getNumberOfInputBands() == 4))
	{
		theAlphaChannelFlag = true;
	}
	populateLut();
	computeMinMax();
	completeOpen();

	theTile = toprsImgFactory::instance()->create(this);
	theSingleBandTile = toprsImgFactory::instance()->create(getInputScalarType(), 1);

	if ( m_preservePaletteIndexesFlag )
	{
		theTile->setIndexedFlag(true);
		theSingleBandTile->setIndexedFlag(true);
	}

	theTile->initialize();
	theSingleBandTile->initialize();
	theGdalBuffer.resize(0);
	if(theIsComplexFlag)
	{
		theGdalBuffer.resize(theSingleBandTile->getSizePerBandInBytes()*2);
	}

	theImageBound = toprsIRect(0
		,0
		,GDALGetRasterXSize(theDataset)-1
		,GDALGetRasterYSize(theDataset)-1);
	int xSize=0, ySize=0;
	GDALGetBlockSize(GDALGetRasterBand( theDataset, 1 ),
		&xSize,
		&ySize);
 
	if (driverNameTmp.find("JPIP")!= std::string::npos || driverNameTmp.find("JP2")!= std::string::npos)
	{
		m_isBlocked = ((xSize > 1)&&(ySize > 1));
	}
	else
	{
		m_isBlocked = false;
	}
	//if(m_isBlocked)
	//{
	//	setRlevelCache();
	//}
	return true;
}
int main( int argc, const char* argv[] )
{
    GDALDriverH   hDriver;
    double        adfGeoTransform[6];
    GDALDatasetH  in_Dataset;
    GDALDatasetH  mask_Dataset;
    GDALDatasetH  out_Dataset;
    GDALRasterBandH mask_band;
    char            *mask_scan_line, *data_scan_line;
    int             nBlockXSize, nBlockYSize;
    int             bGotMin, bGotMax;
    int             bands;
    int             xsize;
    double          adfMinMax[2];
    
    GDALAllRegister();
    
    if ( argc != 2) {
        printf("Usage: %s <file to add mask to> \n", argv[0]);
        printf("This utility adds a nodata mask to a file, were the datadata value is \"0\"\n");
        printf("contact/blame [email protected] for questions/problems.\n");
        return 0;
    }
    
    /* open datasets..*/
    in_Dataset = GDAL_open( argv[1]);
    
    /* add mask.. */
    GDALCreateDatasetMaskBand( in_Dataset, 0);
    
    /* Basic info on source dataset..*/
    GDALGetBlockSize(GDALGetRasterBand( in_Dataset, 1 ) , &nBlockXSize, &nBlockYSize );
    printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
                nBlockXSize, nBlockYSize,
                GDALGetDataTypeName(GDALGetRasterDataType( GDALGetRasterBand( in_Dataset, 1 ))),
                GDALGetColorInterpretationName(
                    GDALGetRasterColorInterpretation(GDALGetRasterBand( in_Dataset, 1 ))));
    
    /* Loop though bands, wiping values with mask values of 0.. */
    xsize = GDALGetRasterXSize( in_Dataset );
    mask_scan_line = (char *) CPLMalloc(sizeof(char)*xsize);
    data_scan_line = (char *) CPLMalloc(sizeof(char)*xsize);
    for (bands=1; bands <= GDALGetRasterCount( in_Dataset ); bands ++ ) {
        int x;
        GDALRasterBandH data_band, out_band;
        int y_index = 0;
        
        printf("INFO: Doing band %d of %d\n", bands,GDALGetRasterCount( in_Dataset ) );
        data_band =  GDALGetRasterBand( in_Dataset, bands);
        mask_band = GDALGetMaskBand(data_band);
        for (y_index = 0; y_index <GDALGetRasterYSize( in_Dataset ); y_index ++ ) {
            /* Read data..*/
            GDALRasterIO( data_band, GF_Read, 0, y_index, xsize , 1, data_scan_line, xsize , 1, GDT_Byte, 0, 0 );
            
            for(x=0; x < xsize; x++) {
                /* if mask is set to 0, then mask off...*/
                /* lame nodata handleing, but such is life.. */
                if ( data_scan_line[x] == 0 )
                    mask_scan_line[x]=0;
                else
                    mask_scan_line[x]=255;
            }
            
            /* now write out band..*/
            GDALRasterIO( mask_band, GF_Write, 0, y_index, xsize , 1, mask_scan_line, xsize , 1, GDT_Byte, 0, 0 );
        }
        
    }
    
    GDALClose(in_Dataset);
}
Пример #13
0
int
main (int argc, const char *argv[])
{
  GDALDriverH hDriver;
  double adfGeoTransform[6];
  GDALDatasetH in_Dataset;
  GDALDatasetH mask_Dataset;
  GDALDatasetH out_Dataset;
  GDALRasterBandH mask_band;
  char *mask_scan_line, *data_scan_line;
  int nBlockXSize, nBlockYSize;
  int bGotMin, bGotMax;
  int bands;
  int xsize;
  double adfMinMax[2];

  GDALAllRegister ();

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

  /* open datasets.. */
  in_Dataset = GDAL_open_read (argv[1]);
  mask_Dataset = GDAL_open_read (argv[2]);
  out_Dataset = make_me_a_sandwitch (&in_Dataset, argv[3]);

  mask_band = GDALGetRasterBand (mask_Dataset, 1);

  /* Basic info on source dataset.. */
  GDALGetBlockSize (GDALGetRasterBand (in_Dataset, 1), &nBlockXSize,
		    &nBlockYSize);
  printf ("Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize,
	  GDALGetDataTypeName (GDALGetRasterDataType
			       (GDALGetRasterBand (in_Dataset, 1))),
	  GDALGetColorInterpretationName (GDALGetRasterColorInterpretation
					  (GDALGetRasterBand
					   (in_Dataset, 1))));

  /* Loop though bands, wiping values with mask values of 0.. */
  xsize = GDALGetRasterXSize (in_Dataset);
  mask_scan_line = (char *) CPLMalloc (sizeof (char) * xsize);
  data_scan_line = (char *) CPLMalloc (sizeof (char) * xsize);
  for (bands = 1; bands <= GDALGetRasterCount (in_Dataset); bands++)
    {
      int x;
      GDALRasterBandH data_band, out_band;
      int y_index = 0;
      data_band = GDALGetRasterBand (in_Dataset, bands);
      out_band = GDALGetRasterBand (out_Dataset, bands);
      for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++)
	{
	  /* Read data.. */
	  GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1,
			data_scan_line, xsize, 1, GDT_Byte, 0, 0);

	  /* Read mask.. */
	  GDALRasterIO (mask_band, GF_Read, 0, y_index, xsize, 1,
			mask_scan_line, xsize, 1, GDT_Byte, 0, 0);
	  GDALSetRasterNoDataValue (out_band, 0.0);


	  for (x = 0; x < xsize; x++)
	    {
	      /* if mask is set to 0, then mask off... */
	      if (mask_scan_line[x] == 0)
		data_scan_line[x] = 0;
	      /* if mask is not zero, and data is zero, then unmask.. */
	      if (mask_scan_line[x] != 0 && data_scan_line[x] == 0)
		data_scan_line[x] = 1;
	    }

	  /* now write out band.. */
	  GDALRasterIO (out_band, GF_Write, 0, y_index, xsize, 1,
			data_scan_line, xsize, 1, GDT_Byte, 0, 0);
	}

    }


  GDALClose (out_Dataset);

}
Пример #14
0
int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len)
{
    VSILFILE* fp = VSIFileFromMemBuffer( "/vsimem/test.tar",
            reinterpret_cast<GByte*>(const_cast<uint8_t*>(buf)), len, FALSE );
    VSIFCloseL(fp);

    CPLPushErrorHandler(CPLQuietErrorHandler);

    char** papszArgv = nullptr;

    // Prevent generating too big output raster. Make sure they are set at
    // the beginning to avoid being accidentally eaten by invalid arguments
    // afterwards.
    papszArgv = CSLAddString(papszArgv, "-limit_outsize");
    papszArgv = CSLAddString(papszArgv, "1000000");

    fp = VSIFOpenL("/vsitar//vsimem/test.tar/cmd.txt", "rb");
    if( fp != nullptr )
    {
        const char* pszLine = nullptr;
        while( (pszLine = CPLReadLineL(fp)) != nullptr )
        {
            if( !EQUAL(pszLine, "-limit_outsize") )
                papszArgv = CSLAddString(papszArgv, pszLine);
        }
        VSIFCloseL(fp);
    }

    int nXDim = -1;
    int nYDim = -1;
    bool bXDimPct = false;
    bool bYDimPct = false;
    bool bNonNearestResampling = false;
    int nBlockXSize = 0;
    int nBlockYSize = 0;
    bool bStatsEnabled = false;
    bool bHFA = false;
    if( papszArgv != nullptr )
    {
        int nCount = CSLCount(papszArgv);
        for( int i = 0; i < nCount; i++ )
        {
            if( EQUAL(papszArgv[i], "-outsize") && i + 2 < nCount )
            {
                nXDim = atoi(papszArgv[i+1]);
                bXDimPct = (papszArgv[i+1][0] != '\0' &&
                            papszArgv[i+1][strlen(papszArgv[i+1])-1] == '%');
                nYDim = atoi(papszArgv[i+2]);
                bYDimPct = (papszArgv[i+2][0] != '\0' &&
                            papszArgv[i+2][strlen(papszArgv[i+2])-1] == '%');
            }
            else if( EQUAL(papszArgv[i], "-r") && i + 1 < nCount )
            {
                bNonNearestResampling = !STARTS_WITH_CI(papszArgv[i+1], "NEAR");
            }
            else if( EQUAL(papszArgv[i], "-co") && i + 1 < nCount )
            {
                if( STARTS_WITH_CI(papszArgv[i+1], "BLOCKSIZE=") )
                {
                    nBlockXSize = std::max(nBlockXSize,
                                atoi(papszArgv[i+1]+strlen("BLOCKSIZE=")));
                    nBlockYSize = std::max(nBlockYSize,
                                atoi(papszArgv[i+1]+strlen("BLOCKSIZE=")));
                }
                else if( STARTS_WITH_CI(papszArgv[i+1], "BLOCKXSIZE=") )
                {
                    nBlockXSize = std::max(nBlockXSize,
                                atoi(papszArgv[i+1]+strlen("BLOCKXSIZE=")));
                }
                else if( STARTS_WITH_CI(papszArgv[i+1], "BLOCKYSIZE=") )
                {
                    nBlockYSize = std::max(nBlockYSize,
                                atoi(papszArgv[i+1]+strlen("BLOCKYSIZE=")));
                }
            }
            else if( EQUAL(papszArgv[i], "-stats") )
            {
                bStatsEnabled = true;
            }
            else if( EQUAL(papszArgv[i], "-of") && i + 1 < nCount )
            {
                bHFA = EQUAL( papszArgv[i+1], "HFA" );
            }
        }
        if( bHFA )
        {
            // Disable statistics computation for HFA, as it can be time
            // consuming.
            // See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=10067
            papszArgv = CSLInsertString(papszArgv, 0, "-co");
            papszArgv = CSLInsertString(papszArgv, 1, "STATISTICS=NO");
        }
    }

    if( papszArgv != nullptr )
    {
        GDALTranslateOptions* psOptions = GDALTranslateOptionsNew(papszArgv, nullptr);
        if( psOptions )
        {
            GDALDatasetH hSrcDS = GDALOpen( "/vsitar//vsimem/test.tar/in", GA_ReadOnly );
            if( hSrcDS != nullptr )
            {
                // Also check that reading the source doesn't involve too
                // much memory
                GDALDataset* poSrcDS = reinterpret_cast<GDALDataset*>(hSrcDS);
                int nBands = poSrcDS->GetRasterCount();
                if( nBands < 10 )
                {
                    // Prevent excessive downsampling which might require huge
                    // memory allocation
                    bool bOKForResampling = true;
                    if( bNonNearestResampling && nXDim >= 0 && nYDim >= 0 )
                    {
                        if( bXDimPct && nXDim > 0 )
                        {
                            nXDim = static_cast<int>(
                                poSrcDS->GetRasterXSize() / 100.0 * nXDim);
                        }
                        if( bYDimPct && nYDim > 0 )
                        {
                            nYDim = static_cast<int>(
                                poSrcDS->GetRasterYSize() / 100.0 * nYDim);
                        }
                        if( nXDim > 0 && poSrcDS->GetRasterXSize() / nXDim > 100 )
                            bOKForResampling = false;
                        if( nYDim > 0 && poSrcDS->GetRasterYSize() / nYDim > 100 )
                            bOKForResampling = false;
                    }

                    bool bOKForSrc = true;
                    if( nBands )
                    {
                        const int nDTSize = GDALGetDataTypeSizeBytes(
                            poSrcDS->GetRasterBand(1)->GetRasterDataType() );
                        vsi_l_offset nSize =
                            static_cast<vsi_l_offset>(nBands) *
                                poSrcDS->GetRasterXSize() *
                                poSrcDS->GetRasterYSize() * nDTSize;
                        if( nSize > 10 * 1024 * 1024 )
                        {
                            bOKForSrc = false;
                        }

                        int nBXSize = 0, nBYSize = 0;
                        GDALGetBlockSize( GDALGetRasterBand(hSrcDS, 1), &nBXSize,
                                          &nBYSize );
                        const char* pszInterleave =
                            GDALGetMetadataItem( hSrcDS, "INTERLEAVE",
                                                 "IMAGE_STRUCTURE" );
                        int nSimultaneousBands =
                            (pszInterleave && EQUAL(pszInterleave, "PIXEL")) ?
                                        nBands : 1;
                        if( static_cast<GIntBig>(nSimultaneousBands)*
                                nBXSize * nBYSize * nDTSize > 10 * 1024 * 1024 )
                        {
                            bOKForSrc = false;
                        }

                        if( static_cast<GIntBig>(nBlockXSize) * nBlockYSize
                                    > 10 * 1024 * 1024 / (nBands * nDTSize) )
                        {
                            bOKForSrc = false;
                        }
                    }

                    bool bOKForStats = true;
                    if( nBands && bStatsEnabled )
                    {
                        // Other types might be too slow with sanitization enabled
                        // See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=10029
                        bOKForStats = poSrcDS->GetRasterBand(1)->GetRasterDataType() == GDT_Byte;
                    }

                    if( bOKForSrc && bOKForResampling && bOKForStats )
                    {
                        GDALDatasetH hOutDS = GDALTranslate("/vsimem/out", hSrcDS,
                                                            psOptions, nullptr);
                        if( hOutDS )
                            GDALClose(hOutDS);
                    }
                }
                GDALClose(hSrcDS);
            }
            GDALTranslateOptionsFree(psOptions);
        }
    }
    CSLDestroy(papszArgv);

    VSIRmdirRecursive("/vsimem/");

    CPLPopErrorHandler();

    return 0;
}