Raster* import_raster(string raster_filename, int band_number) {
    GDALAllRegister();
    GDALDataset*  poDataset = (GDALDataset *) GDALOpen( raster_filename.c_str(), GA_ReadOnly );
    if( poDataset == NULL ) { 
        cerr << "Error: Could not open raster data file" << endl;
        exit(1); 
    }

    fprintf(stderr, "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );
    fprintf(stderr, "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() );

    if( poDataset->GetProjectionRef()  != NULL ) cerr << "Projection is `" << poDataset->GetProjectionRef() << "'" << endl;;

    
    GDALRasterBand* poBand = poDataset->GetRasterBand( band_number );
    int nBlockXSize, nBlockYSize;
    poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
    fprintf(stderr, "Block=%dx%d Type=%s, ColorInterp=%s\n",
            nBlockXSize, nBlockYSize,
            GDALGetDataTypeName(poBand->GetRasterDataType()),
            GDALGetColorInterpretationName( poBand->GetColorInterpretation()) );

    Raster* raster = extract_raster_attributes( poDataset );
    raster->band = poBand;
    return raster;
}
Ejemplo n.º 2
0
void DemReader::MetaDataInfo(GDALDataset* gdalDataset, MapControllerPtr mapController)
{
	FileMetaData* header = mapController->GetMapModel()->GetMetaData();

	header->driverDesc = gdalDataset->GetDriver()->GetDescription();
	header->driverMetaData = gdalDataset->GetDriver()->GetMetadataItem(GDAL_DMD_LONGNAME);
	Log::Inst().Write("Driver: " + header->driverDesc + " \\ " + header->driverMetaData);

	header->xSize = gdalDataset->GetRasterXSize();
	header->ySize = gdalDataset->GetRasterYSize();
	header->bands = gdalDataset->GetRasterCount();
	Log::Inst().Write("Size (x,y): " + 
		StringTools::ToString(header->xSize) + ", " +
		StringTools::ToString(header->ySize));
	Log::Inst().Write("Bands: " + StringTools::ToString(header->bands));

	header->projection = std::string(gdalDataset->GetProjectionRef());
	Log::Inst().Write("Projection: " + header->projection);

	double adfGeoTransform[6];
	gdalDataset->GetGeoTransform( adfGeoTransform );

	header->originX = adfGeoTransform[0];
	header->originY = adfGeoTransform[3];
	Log::Inst().Write("Origin: " +
		StringTools::ToString(adfGeoTransform[0]) + ", " +
		StringTools::ToString(adfGeoTransform[3]));

	header->pixelSizeX = adfGeoTransform[1];
	header->pixelSizeY = adfGeoTransform[5];
	Log::Inst().Write("Pixel Size: " +
		StringTools::ToString(adfGeoTransform[1]) + ", " +
		StringTools::ToString(adfGeoTransform[5]));

	GDALRasterBand* gdalBand = gdalDataset->GetRasterBand(1);
	int nBlockXSize, nBlockYSize;
	gdalBand->GetBlockSize(&nBlockXSize, &nBlockYSize);

	header->dataType = std::string(GDALGetDataTypeName(gdalBand->GetRasterDataType()));
	Log::Inst().Write("Block, Type: " + StringTools::ToString(nBlockXSize) + ", " +
		StringTools::ToString(nBlockYSize) + ", " +
		std::string(header->dataType));

	header->colourInterpretation = std::string(GDALGetColorInterpretationName(gdalBand->GetColorInterpretation()));	
	Log::Inst().Write("Color Interpretation: " + header->colourInterpretation);

	header->extents.x = adfGeoTransform[0];
	header->extents.y = adfGeoTransform[3] + gdalBand->GetYSize()*adfGeoTransform[5];
	Log::Inst().Write("Lower, Left (x,y): " +
		StringTools::ToString(header->extents.x) + ", " +
		StringTools::ToString(header->extents.y));

	header->extents.dx = adfGeoTransform[0]+gdalBand->GetXSize()*adfGeoTransform[1];
	header->extents.dy = adfGeoTransform[3];
	Log::Inst().Write("Upper, Right (x,y): " +
		StringTools::ToString(header->extents.dx) + ", " +
		StringTools::ToString(header->extents.dy));

	Log::Inst().Write("");
}
Ejemplo n.º 3
0
TSXRasterBand::TSXRasterBand( TSXDataset *poDS, GDALDataType eDataType,
                              ePolarization ePol, GDALDataset *poBand )
{
    this->poDS = poDS;
    this->eDataType = eDataType;
    this->ePol = ePol;

	switch (ePol) {
		case HH:
	        SetMetadataItem( "POLARIMETRIC_INTERP", "HH" );
			break;
		case HV:
	        SetMetadataItem( "POLARIMETRIC_INTERP", "HV" );
			break;
		case VH:
	        SetMetadataItem( "POLARIMETRIC_INTERP", "VH" );
			break;
		case VV:
	        SetMetadataItem( "POLARIMETRIC_INTERP", "VV" );
			break;
	}


	/* now setup the actual raster reader */
	this->poBand = poBand;

	GDALRasterBand *poSrcBand = poBand->GetRasterBand( 1 );
	poSrcBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
}
Ejemplo n.º 4
0
TSXRasterBand::TSXRasterBand( TSXDataset *poDSIn, GDALDataType eDataTypeIn,
                              ePolarization ePolIn, GDALDataset *poBandIn ) :
    poBand(poBandIn),
    ePol(ePolIn)
{
    poDS = poDSIn;
    eDataType = eDataTypeIn;

    switch (ePol) {
        case HH:
            SetMetadataItem( "POLARIMETRIC_INTERP", "HH" );
            break;
        case HV:
            SetMetadataItem( "POLARIMETRIC_INTERP", "HV" );
            break;
        case VH:
            SetMetadataItem( "POLARIMETRIC_INTERP", "VH" );
            break;
        case VV:
            SetMetadataItem( "POLARIMETRIC_INTERP", "VV" );
            break;
    }

    /* now setup the actual raster reader */
    GDALRasterBand *poSrcBand = poBandIn->GetRasterBand( 1 );
    poSrcBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
}
Ejemplo n.º 5
0
 CALSRasterBand( CALSDataset* poDSIn )
 {
     poDS = poDSIn;
     poUnderlyingBand = poDSIn->poUnderlyingDS->GetRasterBand(1);
     poUnderlyingBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
     nBand = 1;
     eDataType = GDT_Byte;
 }
Ejemplo n.º 6
0
bool getRawValuesFromFile(string fname,vector<vector<float>>& vecs)
{
   
   //vector<float> temp = vector<float>()
   GDALDataset *poDataset;
   GDALAllRegister();
   poDataset= (GDALDataset*) GDALOpen(fname.c_str(),GA_ReadOnly);
   if(poDataset == NULL)
   {
      cout << "OUCH!" << endl;
      return false;
   }
   cout << "Data size: " << GDALGetRasterXSize(poDataset) << " " << GDALGetRasterYSize(poDataset) << endl;

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

   adfMinMax[0] = poBand->GetMinimum( &bGotMin );
   adfMinMax[1] = poBand->GetMaximum( &bGotMax );
   if( ! (bGotMin && bGotMax) )
      GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
   int width = poBand->GetXSize(); 
   int height = poBand->GetYSize();
   int bands = poDataset->GetRasterCount();
   float *pafScanline;
   std::cout << "Before allocation" << adfMinMax[0] << " " << adfMinMax[1] << endl;
   int dsize = 256;
   pafScanline = (float *) CPLMalloc(sizeof(float)*width*height);
   vector<vector<float>> out = vector<vector<float>>(height,vector<float> (width,0));
   poBand->RasterIO(GF_Read,0,0,width,height,pafScanline,width,height,GDT_Float32,0,0);
   cout << "After allocation" << endl;
   for(int i = 0; i < height; i++)
   {
    for(int j = 0; j < width; j++)
    {
      //cout << i << j << endl << pafS;
      out[i][j] = pafScanline[i*width+j];
    }
   }
   CPLFree(pafScanline);
   //for(auto i : out)
   //for(auto j : i)
   //		cout << j << endl;
  cout << "After allocation" << endl;
  vecs = out;
   return true;
}
Ejemplo n.º 7
0
int main()
{
    GDALDataset  *poDataset;
    GDALAllRegister();
    poDataset = (GDALDataset *) GDALOpen( "GE01.tif", GA_ReadOnly );
    printf("Working! \n");

    if( poDataset != NULL ){
    	//Get Dataset Information
        double adfGeoTransform[6];

		printf( "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );

		printf( "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() );

		if( poDataset->GetProjectionRef()  != NULL )
    		printf( "Projection is `%s'\n", poDataset->GetProjectionRef() );

		if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ){
    		printf( "Origin = (%.6f,%.6f)\n",
            adfGeoTransform[0], adfGeoTransform[3] );
    		printf( "Pixel Size = (%.6f,%.6f)\n",
            adfGeoTransform[1], adfGeoTransform[5] );
		}

		//Fetch Raster Band
		GDALRasterBand  *poBand;
		int             nBlockXSize, nBlockYSize;
		int             bGotMin, bGotMax;
		double          adfMinMax[2];
		poBand = poDataset->GetRasterBand( 1 );
		poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
		printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
		        nBlockXSize, nBlockYSize,
		        GDALGetDataTypeName(poBand->GetRasterDataType()),
		        GDALGetColorInterpretationName(
		            poBand->GetColorInterpretation()) );
		adfMinMax[0] = poBand->GetMinimum( &bGotMin );
		adfMinMax[1] = poBand->GetMaximum( &bGotMax );
		if( ! (bGotMin && bGotMax) )
		    GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
		printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1] );
		if( poBand->GetOverviewCount() > 0 )
		    printf( "Band has %d overviews.\n", poBand->GetOverviewCount() );
		if( poBand->GetColorTable() != NULL )
		    printf( "Band has a color table with %d entries.\n", 
		             poBand->GetColorTable()->GetColorEntryCount() );

		//Close Dataset
		GDALClose(poDataset);
		//Exit      
		return 0;
	}


}
Ejemplo n.º 8
0
int GDAL_EDBFile::ReadBlock( int channel,
                             int block_index, void *buffer,
                             int win_xoff, int win_yoff,
                             int win_xsize, int win_ysize )

{
    GDALRasterBand *poBand = poDS->GetRasterBand(channel);
    int nBlockXSize, nBlockYSize;
    int nBlockX, nBlockY;
    int nWidthInBlocks;
    int nPixelOffset;
    int nLineOffset;

    if( GetType(channel) == CHN_UNKNOWN )
    {
        ThrowPCIDSKException("%s channel type not supported for PCIDSK access.",
                             GDALGetDataTypeName(poBand->GetRasterDataType()) );
    }

    poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );

    nWidthInBlocks = (poBand->GetXSize() + nBlockXSize - 1) / nBlockXSize;
    
    nBlockX = block_index % nWidthInBlocks;
    nBlockY = block_index / nWidthInBlocks;

    nPixelOffset = GDALGetDataTypeSize(poBand->GetRasterDataType()) / 8;
    nLineOffset = win_xsize * nPixelOffset;

/* -------------------------------------------------------------------- */
/*      Are we reading a partial block at the edge of the database?     */
/*      If so, ensure we don't read off the database.                   */
/* -------------------------------------------------------------------- */
    if( nBlockX * nBlockXSize + win_xoff + win_xsize > poBand->GetXSize() )
        win_xsize = poBand->GetXSize() - nBlockX * nBlockXSize - win_xoff;

    if( nBlockY * nBlockYSize + win_yoff + win_ysize > poBand->GetYSize() )
        win_ysize = poBand->GetYSize() - nBlockY * nBlockYSize - win_yoff;

    CPLErr eErr = poBand->RasterIO( GF_Read, 
                                    nBlockX * nBlockXSize + win_xoff, 
                                    nBlockY * nBlockYSize + win_yoff,
                                    win_xsize, win_ysize, 
                                    buffer, win_xsize, win_ysize, 
                                    poBand->GetRasterDataType(),
                                    nPixelOffset, nLineOffset, NULL );

    if( eErr != CE_None )
    {
        ThrowPCIDSKException( "%s", CPLGetLastErrorMsg() );
    }

    return 1;
}
Ejemplo n.º 9
0
SEXP
RGDAL_GetRasterBlockSize(SEXP rasterObj) {
	
	 GDALRasterBand *raster = getGDALRasterPtr(rasterObj);
	 
	 SEXP blockSize = allocVector(INTSXP, 2);
	 
	 raster->GetBlockSize(INTEGER(blockSize) + 1, INTEGER(blockSize));
	 
	 return(blockSize);
	 
}
Ejemplo n.º 10
0
int GDAL_EDBFile::WriteBlock( int channel, int block_index, void *buffer)

{
    GDALRasterBand *poBand = poDS->GetRasterBand(channel);
    int nBlockXSize, nBlockYSize;
    int nBlockX, nBlockY;
    int nWinXSize, nWinYSize;
    int nWidthInBlocks;

    if( GetType(channel) == CHN_UNKNOWN )
    {
        ThrowPCIDSKException("%s channel type not supported for PCIDSK access.",
                             GDALGetDataTypeName(poBand->GetRasterDataType()) );
    }

    poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );

    nWidthInBlocks = (poBand->GetXSize() + nBlockXSize - 1) / nBlockXSize;
    
    nBlockX = block_index % nWidthInBlocks;
    nBlockY = block_index / nWidthInBlocks;

/* -------------------------------------------------------------------- */
/*      Are we reading a partial block at the edge of the database?     */
/*      If so, ensure we don't read off the database.                   */
/* -------------------------------------------------------------------- */
    if( nBlockX * nBlockXSize + nBlockXSize > poBand->GetXSize() )
        nWinXSize = poBand->GetXSize() - nBlockX * nBlockXSize;
    else
        nWinXSize = nBlockXSize;

    if( nBlockY * nBlockYSize + nBlockYSize > poBand->GetYSize() )
        nWinYSize = poBand->GetYSize() - nBlockY * nBlockYSize;
    else
        nWinYSize = nBlockYSize;

    CPLErr eErr = poBand->RasterIO( GF_Write, 
                                    nBlockX * nBlockXSize, 
                                    nBlockY * nBlockYSize,
                                    nWinXSize, nWinYSize,
                                    buffer, nWinXSize, nWinYSize,
                                    poBand->GetRasterDataType(), 0, 0, NULL );

    if( eErr != CE_None )
    {
        ThrowPCIDSKException( "%s", CPLGetLastErrorMsg() );
    }

    return 1;
}
Ejemplo n.º 11
0
SEXP
RGDAL_GetRasterBlockSize(SEXP rasterObj) {
	
	 GDALRasterBand *raster = getGDALRasterPtr(rasterObj);
	 
	 SEXP blockSize = allocVector(INTSXP, 2);
	 
  installErrorHandler();
	 raster->GetBlockSize(INTEGER(blockSize) + 1, INTEGER(blockSize));
  uninstallErrorHandlerAndTriggerError();
	 
	 return(blockSize);
	 
}
Ejemplo n.º 12
0
SAFERasterBand::SAFERasterBand( SAFEDataset *poDSIn,
                                GDALDataType eDataTypeIn,
                                const char *pszSwath,
                                const char *pszPolarisation,
                                GDALDataset *poBandFileIn ) :
    poBandFile(poBandFileIn)
{
    poDS = poDSIn;

    GDALRasterBand *poSrcBand = poBandFile->GetRasterBand( 1 );

    poSrcBand->GetBlockSize( &nBlockXSize, &nBlockYSize );

    eDataType = eDataTypeIn;

    if( *pszSwath != '\0' ) {
        SetMetadataItem( "SWATH", pszSwath );
    }
    if( *pszPolarisation != '\0' ) {
        SetMetadataItem( "POLARISATION", pszPolarisation );
    }
}
Ejemplo n.º 13
0
static int ProxyMain( int argc, char ** argv )

{
    // GDALDatasetH	hDataset, hOutDS;
    // int			i;
    // int			nRasterXSize, nRasterYSize;
    // const char		*pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff";
    // GDALDriverH		hDriver;
    // int			*panBandList = NULL; /* negative value of panBandList[i] means mask band of ABS(panBandList[i]) */
    // int         nBandCount = 0, bDefBands = TRUE;
    // double		adfGeoTransform[6];
    // GDALDataType	eOutputType = GDT_Unknown;
    // int			nOXSize = 0, nOYSize = 0;
    // char		*pszOXSize=NULL, *pszOYSize=NULL;
    // char                **papszCreateOptions = NULL;
    // int                 anSrcWin[4], bStrict = FALSE;
    // const char          *pszProjection;
    // int                 bScale = FALSE, bHaveScaleSrc = FALSE, bUnscale=FALSE;
    // double	        dfScaleSrcMin=0.0, dfScaleSrcMax=255.0;
    // double              dfScaleDstMin=0.0, dfScaleDstMax=255.0;
    // double              dfULX, dfULY, dfLRX, dfLRY;
    // char                **papszMetadataOptions = NULL;
    // char                *pszOutputSRS = NULL;
    // int                 bQuiet = FALSE, bGotBounds = FALSE;
    // GDALProgressFunc    pfnProgress = GDALTermProgress;
    // int                 nGCPCount = 0;
    // GDAL_GCP            *pasGCPs = NULL;
    // int                 iSrcFileArg = -1, iDstFileArg = -1;
    // int                 bCopySubDatasets = FALSE;
    // double              adfULLR[4] = { 0,0,0,0 };
    // int                 bSetNoData = FALSE;
    // int                 bUnsetNoData = FALSE;
    // double		dfNoDataReal = 0.0;
    // int                 nRGBExpand = 0;
    // int                 bParsedMaskArgument = FALSE;
    // int                 eMaskMode = MASK_AUTO;
    // int                 nMaskBand = 0; /* negative value means mask band of ABS(nMaskBand) */
    // int                 bStats = FALSE, bApproxStats = FALSE;

    // GDALDatasetH	hDataset, hOutDS;
  GDALDataset	*hDataset = NULL;
  GDALDataset	*hOutDS = NULL;

    int			i;
    int			nRasterXSize, nRasterYSize;
    const char		*pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff";
    // GDALDriverH		hDriver;
    GDALDriver		*hDriver;
    GDALDataType	eOutputType = GDT_Unknown;
    char                **papszCreateOptions = NULL;
    int                 bStrict = FALSE;
    int                 bQuiet = FALSE;
    GDALProgressFunc    pfnProgress = GDALTermProgress;
    int                 iSrcFileArg = -1, iDstFileArg = -1;
    int                 bSetNoData = FALSE;
    int                 bUnsetNoData = FALSE;
    double		dfNoDataReal = 0.0;

    GDALRasterBand  *inBand = NULL;    
    GDALRasterBand  *outBand = NULL;    
   GByte *srcBuffer;
   double adfGeoTransform[6];
   int nRasterCount;
    int bReplaceIds = FALSE;
    const char *pszReplaceFilename = NULL;
    const char *pszReplaceFieldFrom = NULL;
    const char *pszReplaceFieldTo = NULL;
    std::map<GByte,GByte> mReplaceTable;

    /* Check strict compilation and runtime library version as we use C++ API */
    if (! GDAL_CHECK_VERSION(argv[0]))
        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;
        }
    }

/* -------------------------------------------------------------------- */
/*      Register standard GDAL drivers, and process generic GDAL        */
/*      command options.                                                */
/* -------------------------------------------------------------------- */
    GDALAllRegister();
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Handle command line arguments.                                  */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i],"-of") && i < argc-1 )
            pszFormat = argv[++i];

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

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

            if( eOutputType == GDT_Unknown )
            {
                printf( "Unknown output pixel type: %s\n", argv[i+1] );
                Usage();
                GDALDestroyDriverManager();
                exit( 2 );
            }
            i++;
        }
        else if( EQUAL(argv[i],"-not_strict")  )
            bStrict = FALSE;
            
        else if( EQUAL(argv[i],"-strict")  )
            bStrict = TRUE;
            
        else if( EQUAL(argv[i],"-a_nodata") && i < argc - 1 )
        {
            if (EQUAL(argv[i+1], "none"))
            {
                bUnsetNoData = TRUE;
            }
            else
            {
                bSetNoData = TRUE;
                dfNoDataReal = CPLAtofM(argv[i+1]);
            }
            i += 1;
        }   

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


        else if( EQUAL(argv[i],"-replace_ids") && i < argc-3 )
	{
  	    bReplaceIds = TRUE;
            pszReplaceFilename = (argv[++i]);
            pszReplaceFieldFrom = (argv[++i]);
            pszReplaceFieldTo = (argv[++i]);
        }   

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

        else if( pszSource == NULL )
        {
            iSrcFileArg = i;
            pszSource = argv[i];
        }
        else if( pszDest == NULL )
        {
            pszDest = argv[i];
            iDstFileArg = i;
        }

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

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

    if ( strcmp(pszSource, pszDest) == 0)
    {
        fprintf(stderr, "Source and destination datasets must be different.\n");
        GDALDestroyDriverManager();
        exit( 1 );
    }

   if( bReplaceIds )
    {
      if ( ! pszReplaceFilename |  ! pszReplaceFieldFrom | ! pszReplaceFieldTo )
	      	  Usage();
      // FILE * ifile;
      // if (  (ifile = fopen(pszReplaceFilename, "r")) == NULL )
      // 	{
      // 	  fprintf( stderr, "Replace file %s cannot be read!\n\n", pszReplaceFilename );
      // 	  Usage();
      // 	}
      // else
      // 	fclose( ifile );
      mReplaceTable = InitReplaceTable(pszReplaceFilename,
				       pszReplaceFieldFrom,
				       pszReplaceFieldTo);
      printf("TMP ET size: %d\n",(int)mReplaceTable.size());
    }

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

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


/* -------------------------------------------------------------------- */
/*      Collect some information from the source file.                  */
/* -------------------------------------------------------------------- */
    // nRasterXSize = GDALGetRasterXSize( hDataset );
    // nRasterYSize = GDALGetRasterYSize( hDataset );
    nRasterXSize = hDataset->GetRasterXSize();
    nRasterYSize = hDataset->GetRasterYSize();

    if( !bQuiet )
        printf( "Input file size is %d, %d\n", nRasterXSize, nRasterYSize );


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

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


/* -------------------------------------------------------------------- */
/*      Create Dataset and copy info                                    */
/* -------------------------------------------------------------------- */

    nRasterCount = hDataset->GetRasterCount();
    printf("creating\n");
    hOutDS = hDriver->Create( pszDest, nRasterXSize, nRasterYSize,
			     nRasterCount, GDT_Byte, papszCreateOptions);
    printf("created\n");

 
    if( hOutDS != NULL )
       {

	 hDataset->GetGeoTransform( adfGeoTransform);
	 hOutDS->SetGeoTransform( adfGeoTransform );
	 hOutDS->SetProjection( hDataset->GetProjectionRef() );

/* ==================================================================== */
/*      Process all bands.                                              */
/* ==================================================================== */
	 // if (0)
    for( i = 1; i < nRasterCount+1; i++ )
    {
      inBand = hDataset->GetRasterBand( i ); 
      // hOutDS->AddBand(GDT_Byte);
      outBand = hOutDS->GetRasterBand( i );      
      CopyBandInfo( inBand, outBand, 0, 1, 1 );
      nRasterXSize = inBand->GetXSize( );
      nRasterYSize = inBand->GetYSize( );


	GByte old_value, new_value;
	// char tmp_value[255];
	// const char *tmp_value2;
	std::map<GByte,GByte>::iterator it;

	//tmp  
      int        nXBlocks, nYBlocks, nXBlockSize, nYBlockSize;
      int        iXBlock, iYBlock;
     inBand->GetBlockSize( &nXBlockSize, &nYBlockSize );
     // nXBlockSize = nXBlockSize / 4;
     // nYBlockSize = nYBlockSize / 4;

     nXBlocks = (inBand->GetXSize() + nXBlockSize - 1) / nXBlockSize;
     nYBlocks = (inBand->GetYSize() + nYBlockSize - 1) / nYBlockSize;

     printf("blocks: %d %d %d %d\n",nXBlockSize,nYBlockSize,nXBlocks,nYBlocks);

      printf("TMP ET creating raster %d x %d\n",nRasterXSize, nRasterYSize);
    //   srcBuffer = new GByte[nRasterXSize * nRasterYSize];
    // printf("reading\n");
    //   inBand->RasterIO( GF_Read, 0, 0, nRasterXSize, nRasterYSize, 
    //   			srcBuffer, nRasterXSize, nRasterYSize, GDT_Byte, 
    //   			0, 0 );
      // srcBuffer = (GByte *) CPLMalloc(sizeof(GByte)*nRasterXSize * nRasterYSize);

      srcBuffer = (GByte *) CPLMalloc(nXBlockSize * nYBlockSize);

      for( iYBlock = 0; iYBlock < nYBlocks; iYBlock++ )
      {
	  // if(iYBlock%1000 == 0)
	    // printf("iXBlock: %d iYBlock: %d\n",iXBlock,iYBlock);
          if(iYBlock%1000 == 0)
              printf("iYBlock: %d / %d\n",iYBlock,nYBlocks);
          for( iXBlock = 0; iXBlock < nXBlocks; iXBlock++ )
          {
              int        nXValid, nYValid;
	      
	      // inBand->ReadBlock( iXBlock, iYBlock, srcBuffer );
	      inBand->RasterIO( GF_Read,  iXBlock, iYBlock, nXBlockSize, nYBlockSize, 
	      			srcBuffer, nXBlockSize, nYBlockSize, GDT_Byte, 
	      			0, 0 );

             // Compute the portion of the block that is valid
             // for partial edge blocks.
	      if( (iXBlock+1) * nXBlockSize > inBand->GetXSize() )
		nXValid = inBand->GetXSize() - iXBlock * nXBlockSize;
	      else
		nXValid = nXBlockSize;

	      if( (iYBlock+1) * nYBlockSize > inBand->GetYSize() )
		nYValid = inBand->GetYSize() - iYBlock * nYBlockSize;
	      else
		nYValid = nYBlockSize;
	      // printf("iXBlock: %d iYBlock: %d read,  nXValid: %d nYValid: %d\n",iXBlock,iYBlock,nXValid, nYValid);

	   // if(0)
	      if ( pszReplaceFilename )
	   	{
	   	  for( int iY = 0; iY < nYValid; iY++ )
	   	    {
	   	      for( int iX = 0; iX < nXValid; iX++ )
	   		{
	   		  // panHistogram[pabyData[iX + iY * nXBlockSize]] += 1;
	   		   old_value = new_value = srcBuffer[iX + iY * nXBlockSize];
	   		  // sprintf(tmp_value,"%d",old_value);
	   		  it = mReplaceTable.find(old_value);
	   		  if ( it != mReplaceTable.end() ) new_value = it->second;
	   		  if ( old_value != new_value ) 
			    {
			      srcBuffer[iX + iY * nXBlockSize] = new_value;
	   		   // printf("old_value %d new_value %d  final %d\n",old_value,new_value, srcBuffer[iX + iY * nXBlockSize]);
			    }
	   		  // tmp_value2 = CSVGetField( pszReplaceFilename,pszReplaceFieldFrom, 
	   		  // 			     tmp_value, CC_Integer, pszReplaceFieldTo);
	   		  // if( tmp_value2 != NULL )
	   		  //   {
	   		  // 	new_value = atoi(tmp_value2);
	   		  //   }
	   		  // new_value = old_value +1;
	   		  // 
			  
	   		}
	   	    }
		  
	   	}
	      
	      // printf("writing\n");
	      // outBand->WriteBlock( iXBlock, iYBlock, srcBuffer );
	      outBand->RasterIO( GF_Write,  iXBlock, iYBlock, nXBlockSize, nYBlockSize, 
	      			srcBuffer, nXBlockSize, nYBlockSize, GDT_Byte, 
	      			0, 0 );
	      // printf("wrote\n");

	 }
     }

     CPLFree(srcBuffer);

    printf("read\n");

    printf("mod\n");

    // if ( pszReplaceFilename )
    //   {
    // 	GByte old_value, new_value;
    // 	// char tmp_value[255];
    // 	// const char *tmp_value2;
    // 	std::map<GByte,GByte>::iterator it;
    // 	for ( int j=0; j<nRasterXSize*nRasterYSize; j++ ) 
    // 	  {
    // 	    old_value = new_value = srcBuffer[j];
    // 	    // sprintf(tmp_value,"%d",old_value);
    // 	    it = mReplaceTable.find(old_value);
    // 	    if ( it != mReplaceTable.end() ) new_value = it->second;
    // 	    // tmp_value2 = CSVGetField( pszReplaceFilename,pszReplaceFieldFrom, 
    // 	    // 			     tmp_value, CC_Integer, pszReplaceFieldTo);
    // 	    // if( tmp_value2 != NULL )
    // 	    //   {
    // 	    // 	new_value = atoi(tmp_value2);
    // 	    //   }
    // 	    // new_value = old_value +1;
    // 	    if ( old_value != new_value ) srcBuffer[j] = new_value;
    // 	    // printf("old_value %d new_value %d  final %d\n",old_value,new_value, srcBuffer[j]);
    // 	  }
    // printf("writing\n");

    //   outBand->RasterIO( GF_Write, 0, 0, nRasterXSize, nRasterYSize, 
    //   			srcBuffer, nRasterXSize, nRasterYSize, GDT_Byte, 
    //   			0, 0 );
    // printf("wrote\n");

    //    delete [] srcBuffer;
    //   }
    }
       }
 

    if( hOutDS != NULL )
      GDALClose(  (GDALDatasetH) hOutDS );
    if( hDataset != NULL )
      GDALClose(  (GDALDatasetH) hDataset );


    GDALDumpOpenDatasets( stderr );
    // GDALDestroyDriverManager();
    CSLDestroy( argv );
    CSLDestroy( papszCreateOptions );
    
    return hOutDS == NULL;
}
Ejemplo n.º 14
0
T* GISToFloatArray(char* fname, int interpWidth, int interpHeight)
{
  // Important note ------ Gdal considers images to be north up
  // the origin of datasets takes place in the upper-left or North-West corner.
  // Now to create a GDAL dataset
  // auto ds = ((GDALDataset*) GDALOpen(fname,GA_ReadOnly));
  GDALDataset* ds = ((GDALDataset*) GDALOpen(fname,GA_ReadOnly));
  if(ds == NULL)
  {
    return NULL;
  }
  
  // Creating a Raster band variable
  // A band represents one whole dataset within a dataset
  // in your case your files have one band.
  GDALRasterBand  *poBand;
  int             nBlockXSize, nBlockYSize;
  int             bGotMin, bGotMax;
  double          adfMinMax[2];
  
  // Assign the band      
  poBand = ds->GetRasterBand( 1 );
  poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );

  // find the min and max
  adfMinMax[0] = poBand->GetMinimum( &bGotMin );
  adfMinMax[1] = poBand->GetMaximum( &bGotMax );
  if( ! (bGotMin && bGotMax) )
    GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
  int min = adfMinMax[0];
  int max = adfMinMax[1];

  // get the width and height of the band or dataset
  int width = poBand->GetXSize();
  int height = poBand->GetYSize();

  // GDAL can handle files that have multiple datasets jammed witin it
  int bands = ds->GetRasterCount();

  // the float variable to hold the DEM!
  T *pafScanline;
  // std::cout << "Min: " << adfMinMax[0] << " Max: " << adfMinMax[1] << endl;
  int dsize = 256;
  // pafScanline = (T *) CPLMalloc(sizeof(T)*width*height);
  pafScanline = (T *) CPLMalloc(sizeof(T)*interpWidth*interpHeight);

  // Lets acquire the data.  ..... this funciton will interpolate for you
  // poBand->RasterIO(GF_Read,0,0,width,height,pafScanline,width,height,GDT_Float32,0,0);
  poBand->RasterIO(GF_Read,0,0,width,height,pafScanline,interpWidth,interpHeight,GDT_Float32,0,0);
  //        chage these two to interpolate automatically ^      ^

  // The Geotransform gives information on where a dataset is located in the world
  // and the resolution.
  // for more information look at http://www.gdal.org/gdal_datamodel.html
  double geot[6];
  ds->GetGeoTransform(geot);

  // Get the x resolution per pixel(south and west) and y resolution per pixel (north and south)
  // float xres = geot[1];
  // float yres = geot[5];
  // string proj;
  // proj = string(ds->GetProjectionRef());

  // You can get the projection string
  // The projection gives information about the coordinate system a dataset is in
  // This is important to allow other GIS softwares to place datasets into the same
  // coordinate space 
  // char* test = &proj[0];

  // The origin of the dataset 
  // float startx = geot[0]; // east - west coord.
  // float starty = geot[3]; // north - south coord.

  
  // here is some code that I used to push that 1D array into a 2D array
  // I believe this puts everything in the correct order....
  /*for(int i = 0; i < hsize; i++)
  {
    for(int j = 0; j < wsize; j++)
    {
      //cout << i << j << endl << pafS;
      vecs[i][j] = pafScanline[((int)i)*(int)wsize+((int)j)];
      if(vecs[i][j]>0 && vecs[i][j] > max)
      {
          max = vecs[i][j];
      }
      if(vecs[i][j]>0 && vecs[i][j] < min)
      {
          min = vecs[i][j];
      }
    }
   }*/
   //CPLFree(pafScanline);
   return pafScanline;

}
Ejemplo n.º 15
0
CC_FILE_ERROR RasterGridFilter::loadFile(QString filename, ccHObject& container, bool alwaysDisplayLoadDialog/*=true*/, bool* coordinatesShiftEnabled/*=0*/, CCVector3d* coordinatesShift/*=0*/)
{
	GDALAllRegister();
	ccLog::PrintDebug("(GDAL drivers: %i)", GetGDALDriverManager()->GetDriverCount());

	GDALDataset* poDataset = static_cast<GDALDataset*>(GDALOpen( qPrintable(filename), GA_ReadOnly ));

	if( poDataset != NULL )
	{
		ccLog::Print(QString("Raster file: '%1'").arg(filename));
		ccLog::Print( "Driver: %s/%s",
			poDataset->GetDriver()->GetDescription(), 
			poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );

		int rasterCount = poDataset->GetRasterCount();
		int rasterX = poDataset->GetRasterXSize();
		int rasterY = poDataset->GetRasterYSize();
		ccLog::Print( "Size is %dx%dx%d", rasterX, rasterY, rasterCount );

		ccPointCloud* pc = new ccPointCloud();
		if (!pc->reserve(static_cast<unsigned>(rasterX * rasterY)))
		{
			delete pc;
			return CC_FERR_NOT_ENOUGH_MEMORY;
		}

		if( poDataset->GetProjectionRef() != NULL )
			ccLog::Print( "Projection is `%s'", poDataset->GetProjectionRef() );

		double adfGeoTransform[6] = {	 0, //top left x
										 1, //w-e pixel resolution (can be negative)
										 0, //0
										 0, //top left y
										 0, //0
										 1  //n-s pixel resolution (can be negative)
		};

		if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None )
		{
			ccLog::Print( "Origin = (%.6f,%.6f)", adfGeoTransform[0], adfGeoTransform[3] );
			ccLog::Print( "Pixel Size = (%.6f,%.6f)", adfGeoTransform[1], adfGeoTransform[5] );
		}

		if (adfGeoTransform[1] == 0 || adfGeoTransform[5] == 0)
		{
			ccLog::Warning("Invalid pixel size! Forcing it to (1,1)");
			adfGeoTransform[1] = adfGeoTransform[5] = 1;
		}

		CCVector3d origin( adfGeoTransform[0], adfGeoTransform[3], 0.0 );
		CCVector3d Pshift(0,0,0);
		//check for 'big' coordinates
		{
			bool shiftAlreadyEnabled = (coordinatesShiftEnabled && *coordinatesShiftEnabled && coordinatesShift);
			if (shiftAlreadyEnabled)
				Pshift = *coordinatesShift;
			bool applyAll = false;
			if (	sizeof(PointCoordinateType) < 8
				&&	ccCoordinatesShiftManager::Handle(origin,0,alwaysDisplayLoadDialog,shiftAlreadyEnabled,Pshift,0,&applyAll))
			{
				pc->setGlobalShift(Pshift);
				ccLog::Warning("[RasterFilter::loadFile] Raster has been recentered! Translation: (%.2f,%.2f,%.2f)",Pshift.x,Pshift.y,Pshift.z);

				//we save coordinates shift information
				if (applyAll && coordinatesShiftEnabled && coordinatesShift)
				{
					*coordinatesShiftEnabled = true;
					*coordinatesShift = Pshift;
				}
			}
		}

		//create blank raster 'grid'
		{
			double z = 0.0 /*+ Pshift.z*/;
			for (int j=0; j<rasterY; ++j)
			{
				double y = adfGeoTransform[3] + static_cast<double>(j) * adfGeoTransform[5] + Pshift.y;
				CCVector3 P(	0,
								static_cast<PointCoordinateType>(y),
								static_cast<PointCoordinateType>(z));
				for (int i=0; i<rasterX; ++i)
				{
					double x = adfGeoTransform[0] + static_cast<double>(i) * adfGeoTransform[1] + Pshift.x;

					P.x = static_cast<PointCoordinateType>(x);
					pc->addPoint(P);
				}
			}

			QVariant xVar = QVariant::fromValue<int>(rasterX);
			QVariant yVar = QVariant::fromValue<int>(rasterY);
			pc->setMetaData("raster_width",xVar);
			pc->setMetaData("raster_height",yVar);
		}

		//fetch raster bands
		bool zRasterProcessed = false;
		unsigned zInvalid = 0;
		double zMinMax[2] = {0, 0};

		for (int i=1; i<=rasterCount; ++i)
		{
			ccLog::Print( "Reading band #%i", i);
			GDALRasterBand* poBand = poDataset->GetRasterBand(i);

			GDALColorInterp colorInterp = poBand->GetColorInterpretation();
			GDALDataType bandType = poBand->GetRasterDataType();

			int nBlockXSize, nBlockYSize;
			poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
			ccLog::Print( "Block=%dx%d Type=%s, ColorInterp=%s", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName(colorInterp) );

			//fetching raster scan-line
			int nXSize = poBand->GetXSize();
			int nYSize = poBand->GetYSize();
			assert(nXSize == rasterX);
			assert(nYSize == rasterY);
			
			int bGotMin, bGotMax;
			double adfMinMax[2] = {0, 0};
			adfMinMax[0] = poBand->GetMinimum( &bGotMin );
			adfMinMax[1] = poBand->GetMaximum( &bGotMax );
			if (!bGotMin || !bGotMax )
				//DGM FIXME: if the file is corrupted (e.g. ASCII ArcGrid with missing rows) this method will enter in a infinite loop!
				GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
			ccLog::Print( "Min=%.3fd, Max=%.3f", adfMinMax[0], adfMinMax[1] );

			GDALColorTable* colTable = poBand->GetColorTable();
			if( colTable != NULL )
				printf( "Band has a color table with %d entries", colTable->GetColorEntryCount() );

			if( poBand->GetOverviewCount() > 0 )
				printf( "Band has %d overviews", poBand->GetOverviewCount() );

			if (colorInterp == GCI_Undefined && !zRasterProcessed/*&& !colTable*/) //probably heights?
			{
				zRasterProcessed = true;
				zMinMax[0] = adfMinMax[0];
				zMinMax[1] = adfMinMax[1];

				double* scanline = (double*) CPLMalloc(sizeof(double)*nXSize);
				//double* scanline = new double[nXSize];
				memset(scanline,0,sizeof(double)*nXSize);

				for (int j=0; j<nYSize; ++j)
				{
					if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/scanline, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Float64, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None)
					{
						delete pc;
						CPLFree(scanline);
						GDALClose(poDataset);
						return CC_FERR_READING;
					}

					for (int k=0; k<nXSize; ++k)
					{
						double z = static_cast<double>(scanline[k]) + Pshift[2];
						unsigned pointIndex = static_cast<unsigned>(k + j * rasterX);
						if (pointIndex <= pc->size())
						{
							if (z < zMinMax[0] || z > zMinMax[1])
							{
								z = zMinMax[0] - 1.0;
								++zInvalid;
							}
							const_cast<CCVector3*>(pc->getPoint(pointIndex))->z = static_cast<PointCoordinateType>(z);
						}
					}
				}

				//update bounding-box
				pc->invalidateBoundingBox();

				if (scanline)
					CPLFree(scanline);
				scanline = 0;
			}
			else //colors
			{
				bool isRGB = false;
				bool isScalar = false;
				bool isPalette = false;
				
				switch(colorInterp)
				{
				case GCI_Undefined:
					isScalar = true;
					break;
				case GCI_PaletteIndex:
					isPalette = true;
					break;
				case GCI_RedBand:
				case GCI_GreenBand:
				case GCI_BlueBand:
					isRGB = true;
					break;
				case GCI_AlphaBand:
					if (adfMinMax[0] != adfMinMax[1])
						isScalar = true;
					else
						ccLog::Warning(QString("Alpha band ignored as it has a unique value (%1)").arg(adfMinMax[0]));
					break;
				default:
					isScalar = true;
					break;
				}


				if (isRGB || isPalette)
				{
					//first check that a palette exists if the band is a palette index
					if (isPalette && !colTable)
					{
						ccLog::Warning(QString("Band is declared as a '%1' but no palette is associated!").arg(GDALGetColorInterpretationName(colorInterp)));
						isPalette = false;
					}
					else
					{
						//instantiate memory for RBG colors if necessary
						if (!pc->hasColors() && !pc->setRGBColor(MAX_COLOR_COMP,MAX_COLOR_COMP,MAX_COLOR_COMP))
						{
							ccLog::Warning(QString("Failed to instantiate memory for storing color band '%1'!").arg(GDALGetColorInterpretationName(colorInterp)));
						}
						else
						{
							assert(bandType <= GDT_Int32);

							int* colIndexes = (int*) CPLMalloc(sizeof(int)*nXSize);
							//double* scanline = new double[nXSize];
							memset(colIndexes,0,sizeof(int)*nXSize);

							for (int j=0; j<nYSize; ++j)
							{
								if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/colIndexes, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Int32, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None)
								{
									CPLFree(colIndexes);
									delete pc;
									return CC_FERR_READING;
								}

								for (int k=0; k<nXSize; ++k)
								{
									unsigned pointIndex = static_cast<unsigned>(k + j * rasterX);
									if (pointIndex <= pc->size())
									{
										colorType* C = const_cast<colorType*>(pc->getPointColor(pointIndex));

										switch(colorInterp)
										{
										case GCI_PaletteIndex:
											assert(colTable);
											{
												GDALColorEntry col;
												colTable->GetColorEntryAsRGB(colIndexes[k],&col);
												C[0] = static_cast<colorType>(col.c1 & MAX_COLOR_COMP);
												C[1] = static_cast<colorType>(col.c2 & MAX_COLOR_COMP);
												C[2] = static_cast<colorType>(col.c3 & MAX_COLOR_COMP);
											}
											break;

										case GCI_RedBand:
											C[0] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP);
											break;
										case GCI_GreenBand:
											C[1] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP);
											break;
										case GCI_BlueBand:
											C[2] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP);
											break;

										default:
											assert(false);
											break;
										}
									}
								}
							}

							if (colIndexes)
								CPLFree(colIndexes);
							colIndexes = 0;

							pc->showColors(true);
						}
					}
				}
				else if (isScalar)
				{
					ccScalarField* sf = new ccScalarField(GDALGetColorInterpretationName(colorInterp));
					if (!sf->resize(pc->size(),true,NAN_VALUE))
					{
						ccLog::Warning(QString("Failed to instantiate memory for storing '%1' as a scalar field!").arg(sf->getName()));
						sf->release();
						sf = 0;
					}
					else
					{
						double* colValues = (double*) CPLMalloc(sizeof(double)*nXSize);
						//double* scanline = new double[nXSize];
						memset(colValues,0,sizeof(double)*nXSize);

						for (int j=0; j<nYSize; ++j)
						{
							if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/colValues, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Float64, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None)
							{
								CPLFree(colValues);
								delete pc;
								return CC_FERR_READING;
							}

							for (int k=0; k<nXSize; ++k)
							{
								unsigned pointIndex = static_cast<unsigned>(k + j * rasterX);
								if (pointIndex <= pc->size())
								{
									ScalarType s = static_cast<ScalarType>(colValues[k]);
									sf->setValue(pointIndex,s);
								}
							}
						}

						if (colValues)
							CPLFree(colValues);
						colValues = 0;

						sf->computeMinAndMax();
						pc->addScalarField(sf);
						if (pc->getNumberOfScalarFields() == 1)
							pc->setCurrentDisplayedScalarField(0);
						pc->showSF(true);
					}
				}
			}
		}

		if (pc)
		{
			if (!zRasterProcessed)
			{
				ccLog::Warning("Raster has no height (Z) information: you can convert one of its scalar fields to Z with 'Edit > Scalar Fields > Set SF as coordinate(s)'");
			}
			else if (zInvalid != 0 && zInvalid < pc->size())
			{
				//shall we remove the points with invalid heights?
				if (QMessageBox::question(0,"Remove NaN points?","This raster has pixels with invalid heights. Shall we remove them?",QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
				{
					CCLib::ReferenceCloud validPoints(pc);
					unsigned count = pc->size();
					bool error = true;
					if (validPoints.reserve(count-zInvalid))
					{
						for (unsigned i=0; i<count; ++i)
						{
							if (pc->getPoint(i)->z >= zMinMax[0])
								validPoints.addPointIndex(i);
						}

						if (validPoints.size() > 0)
						{
							validPoints.resize(validPoints.size());
							ccPointCloud* newPC = pc->partialClone(&validPoints);
							if (newPC)
							{
								delete pc;
								pc = newPC;
								error = false;
							}
						}
						else
						{
							assert(false);
						}
					}

					if (error)
					{
						ccLog::Error("Not enough memory to remove the points with invalid heights!");
					}
				}
			}
			container.addChild(pc);
		}

		GDALClose(poDataset);
	}
	else
	{
		return CC_FERR_UNKNOWN_FILE;
	}

	return CC_FERR_NO_ERROR;
}
Ejemplo n.º 16
0
GDALDataset *IntergraphDataset::CreateCopy( const char *pszFilename,
        GDALDataset *poSrcDS,
        int bStrict,
        char **papszOptions,
        GDALProgressFunc pfnProgress,
        void *pProgressData )
{
    (void) bStrict;

    int nBands = poSrcDS->GetRasterCount();
    if (nBands == 0)
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "Intergraph driver does not support source dataset with zero band.\n");
        return NULL;
    }

    if( !pfnProgress( 0.0, NULL, pProgressData ) )
    {
        return NULL;
    }

    // --------------------------------------------------------------------
    // Query GDAL Data Type
    // --------------------------------------------------------------------

    GDALDataType eType = poSrcDS->GetRasterBand(1)->GetRasterDataType();

    // --------------------------------------------------------------------
    // Copy metadata
    // --------------------------------------------------------------------

    char **papszCreateOptions = CSLDuplicate( papszOptions );
    const char  *pszValue;

    pszValue = CSLFetchNameValue(papszCreateOptions, "RESOLUTION");
    if( pszValue == NULL )
    {
        const char *value = poSrcDS->GetMetadataItem("RESOLUTION");
        if (value)
        {
            papszCreateOptions = CSLSetNameValue( papszCreateOptions, "RESOLUTION",
                                                  value );
        }
    }

    // --------------------------------------------------------------------
    // Create IntergraphDataset
    // --------------------------------------------------------------------

    IntergraphDataset *poDstDS;

    poDstDS = (IntergraphDataset*) IntergraphDataset::Create( pszFilename,
              poSrcDS->GetRasterXSize(),
              poSrcDS->GetRasterYSize(),
              poSrcDS->GetRasterCount(),
              eType,
              papszCreateOptions );

    CSLDestroy( papszCreateOptions );

    if( poDstDS == NULL )
    {
        return NULL;
    }

    // --------------------------------------------------------------------
    // Copy Transformation Matrix to the dataset
    // --------------------------------------------------------------------

    double adfGeoTransform[6];

    poDstDS->SetProjection( poSrcDS->GetProjectionRef() );
    poSrcDS->GetGeoTransform( adfGeoTransform );
    poDstDS->SetGeoTransform( adfGeoTransform );

    // --------------------------------------------------------------------
    // Copy information to the raster band
    // --------------------------------------------------------------------

    GDALRasterBand *poSrcBand;
    GDALRasterBand *poDstBand;
    double dfMin;
    double dfMax;
    double dfMean;
    double dfStdDev = -1;

    for( int i = 1; i <= poDstDS->nBands; i++)
    {
        delete poDstDS->GetRasterBand(i);
    }
    poDstDS->nBands = 0;

    if( poDstDS->hHeaderOne.DataTypeCode == Uncompressed24bit )
    {
        poDstDS->SetBand( 1, new IntergraphRGBBand( poDstDS, 1, 0, 3 ) );
        poDstDS->SetBand( 2, new IntergraphRGBBand( poDstDS, 2, 0, 2 ) );
        poDstDS->SetBand( 3, new IntergraphRGBBand( poDstDS, 3, 0, 1 ) );
        poDstDS->nBands = 3;
    }
    else
    {
        for( int i = 1; i <= poSrcDS->GetRasterCount(); i++ )
        {
            poSrcBand = poSrcDS->GetRasterBand(i);
            eType = poSrcDS->GetRasterBand(i)->GetRasterDataType();

            poDstBand = new IntergraphRasterBand( poDstDS, i, 0, eType );
            poDstDS->SetBand( i, poDstBand );

            poDstBand->SetCategoryNames( poSrcBand->GetCategoryNames() );
            poDstBand->SetColorTable( poSrcBand->GetColorTable() );
            poSrcBand->GetStatistics( false, true, &dfMin, &dfMax, &dfMean, &dfStdDev );
            poDstBand->SetStatistics( dfMin, dfMax, dfMean, dfStdDev );
        }
    }

    // --------------------------------------------------------------------
    // Copy image data
    // --------------------------------------------------------------------

    int nXSize = poDstDS->GetRasterXSize();
    int nYSize = poDstDS->GetRasterYSize();

    int nBlockXSize;
    int nBlockYSize;

    CPLErr eErr = CE_None;

    for( int iBand = 1; iBand <= poSrcDS->GetRasterCount(); iBand++ )
    {
        GDALRasterBand *poDstBand = poDstDS->GetRasterBand( iBand );
        GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( iBand );

        // ------------------------------------------------------------
        // Copy Untiled / Uncompressed
        // ------------------------------------------------------------

        int   iYOffset, iXOffset;
        void *pData;

        poSrcBand->GetBlockSize( &nBlockXSize, &nBlockYSize );

        nBlockXSize = nXSize;
        nBlockYSize = 1;

        pData = CPLMalloc( nBlockXSize * nBlockYSize * GDALGetDataTypeSize( eType ) / 8 );

        for( iYOffset = 0; iYOffset < nYSize; iYOffset += nBlockYSize )
        {
            for( iXOffset = 0; iXOffset < nXSize; iXOffset += nBlockXSize )
            {
                eErr = poSrcBand->RasterIO( GF_Read,
                                            iXOffset, iYOffset,
                                            nBlockXSize, nBlockYSize,
                                            pData, nBlockXSize, nBlockYSize,
                                            eType, 0, 0, NULL );
                if( eErr != CE_None )
                {
                    return NULL;
                }
                eErr = poDstBand->RasterIO( GF_Write,
                                            iXOffset, iYOffset,
                                            nBlockXSize, nBlockYSize,
                                            pData, nBlockXSize, nBlockYSize,
                                            eType, 0, 0, NULL );
                if( eErr != CE_None )
                {
                    return NULL;
                }
            }
            if( ( eErr == CE_None ) && ( ! pfnProgress(
                                             ( iYOffset + 1 ) / ( double ) nYSize, NULL, pProgressData ) ) )
            {
                eErr = CE_Failure;
                CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated CreateCopy()" );
            }
        }
        CPLFree( pData );
    }

    // --------------------------------------------------------------------
    // Finalize
    // --------------------------------------------------------------------

    poDstDS->FlushCache();

    return poDstDS;
}
Ejemplo n.º 17
0
bool DemReader::Open(std::wstring fullPath, StudyControllerPtr studyController, MapControllerPtr mapController, ProgressDlgPtr progressDlg) 
{    
	GDALAllRegister();
	bool bElevationMap;
	uint numBands;
	double adfGeoTransform[6];
	GDALDataset* gdalDataset;
	int nBlockXSize, nBlockYSize;
	MapModelPtr mapModel = mapController->GetMapModel();
	FileHeader* header = mapModel->GetHeader();
	GDALRasterBand* gdalBand;

	if(App::Inst().GetLayerTreeController()->GetIsBlankRaster())
	{
		LayerTreeControllerPtr ltc = App::Inst().GetLayerTreeController();
		VectorMapLayerPtr vectorMapLayer =ltc->GetVectorMapLayer(0);
	    VectorMapModelPtr vectorMapModel= vectorMapLayer->GetVectorMapController()->GetVectorMapModel();			
		double vectorMinX = vectorMapModel->GetVectorBoundary_MinX();
		double vectorMinY = vectorMapModel->GetVectorBoundary_MinY();
		double vectorMaxX = vectorMapModel->GetVectorBoundary_MaxX();
		double vectorMaxY = vectorMapModel->GetVectorBoundary_MaxY();
		
		double bRaster_width = 1000;
		double bRaster_height=	1000;	

		double x_res = (vectorMaxX - vectorMinX) / bRaster_width;
		double y_res = (vectorMaxY - vectorMinY) / bRaster_height;
		numBands = 3;
		bElevationMap = false;
		header->nCols = 1000;
		header->nRows = 1000;
		header->noDataValue=0.0;
		//adfGeoTransform[6]= {vectorMinX, x_res, 0.0,  vectorMaxY, 0.0, -y_res};
		adfGeoTransform[0]= vectorMinX;
		adfGeoTransform[1]= x_res;
		adfGeoTransform[2]= 0.0;
		adfGeoTransform[3]= vectorMaxY;
		adfGeoTransform[4] = 0.0;
		adfGeoTransform[5]= -y_res;
	}	
		
	else
	{
		std::string tempStr(fullPath.begin(), fullPath.end());
		gdalDataset = (GDALDataset*) GDALOpen( tempStr.c_str(), GA_ReadOnly );
		if(gdalDataset == NULL) 
		{
			Log::Inst().Warning("(Warning) Failed to open file at " + tempStr + ".");
			return false;	
		}
	
	// determine type of file based on number of raster bands		
		numBands = gdalDataset->GetRasterCount();
		if(numBands == 1)
			bElevationMap = true;
		else if(numBands == 3 || numBands == 4)
			bElevationMap = false;
		else
		{
			Log::Inst().Warning("(Warning) File type not supported. Please contact the GenGIS to request support for the file format.");
		}
		CPLErr err = gdalDataset->GetGeoTransform( adfGeoTransform );

		// check if we have a map without any transformation information
		// in which case assume we have a custom image file where y should
		// be in the south (down) direction
		if(err == CE_Failure)
			adfGeoTransform[5] = -1;

		gdalBand = gdalDataset->GetRasterBand( 1 );		
		gdalBand->GetBlockSize( &nBlockXSize, &nBlockYSize );

		// get original data dimensions		
		header->nCols = gdalBand->GetXSize();
		header->nRows = gdalBand->GetYSize();
		header->noDataValue = gdalBand->GetNoDataValue();
		// Setup desired projection 
		if(!SetupProjection(gdalDataset, studyController, adfGeoTransform, header->nCols, header->nRows, bElevationMap))
		{
			GDALClose(gdalDataset);
			return false;
		}
	}
	if(progressDlg)
	{
		if(!App::Inst().GetLayerTreeController()->GetIsBlankRaster())
		{
			if(!progressDlg->Update(0, _T("Reading map file...")))
			{
				GDALClose(gdalDataset);
				return false;
			}
		}
		else
		{
			if(!progressDlg->Update(0, _T("Initializing the Visualization...")))
			{
				GDALClose(gdalDataset);
				return false;
			}
		}
	}
	// check whether it's too large to handle all the data
	float* elevations = NULL;
	if(bElevationMap && !App::Inst().GetLayerTreeController()->GetIsBlankRaster())
	{
		try
		{
			elevations = new float[gdalBand->GetXSize()* gdalBand->GetYSize()];
		}
		catch(std::bad_alloc&)
		{
			Log::Inst().Warning("(Warning) Insufficent memory for elevation map."); 

			GDALClose(gdalDataset);
			return false;
		}

		gdalBand->RasterIO( GF_Read, 0, 0, gdalBand->GetXSize(), gdalBand->GetYSize(), 
			elevations, gdalBand->GetXSize(), gdalBand->GetYSize(), 
			GDT_Float32, 
			0, 0 );
	}

	// project all map model cells
	Point3D* grid;
	try
	{
		grid = new Point3D[header->nCols*header->nRows];
	}
	catch(std::bad_alloc&)
	{
		Log::Inst().Warning("(Warning) Insufficent memory to load map."); 

		GDALClose(gdalDataset);
		delete[] elevations;
		return false;
	}

	// populate grid with projected points and find extents of projected map
	double xOffset = adfGeoTransform[0];
	double zOffset = adfGeoTransform[3];
	int index = 0;
	double x, z;
	
	header->projExtents.x = header->projExtents.y = std::numeric_limits<float>::max();
	header->projExtents.dx = header->projExtents.dy = -std::numeric_limits<float>::max();
	
	ProjectionToolPtr projTool = studyController->GetProjectionTool();
	
	for(int m = 0; m < header->nRows ; ++m) 
	{
		xOffset = adfGeoTransform[0];
		for(int n = 0; n < header->nCols; ++n) 
		{
			x = xOffset;
			z = zOffset;
			if(studyController->IsProjectData() && studyController->IsGeographic() && !App::Inst().GetLayerTreeController()->GetIsBlankRaster())
			{			
				double elevation = (double)elevations[index];				
				if(!projTool->Transform(1, &x, &z, &elevation))
				{
					Log::Inst().Warning("(Warning) Failed to project map.");
					GDALClose(gdalDataset);
					delete[] elevations;
					return false;
				}
				
			}

			xOffset += adfGeoTransform[1];
			if(App::Inst().GetLayerTreeController()->GetIsBlankRaster())
			{
				double X = x;
				double Z = z;

				grid[index].x = X;
				grid[index].z = Z;
				index++;	
				if(X < header->projExtents.x) header->projExtents.x = X;
				if(Z < header->projExtents.y) header->projExtents.y = Z;
				if(X > header->projExtents.dx) header->projExtents.dx = X;
				if(Z > header->projExtents.dy) header->projExtents.dy = Z;
			}
			else
			{
				float X = (float)x;
				float Z = (float)z;

				grid[index].x = X;
				grid[index].z = Z;
				index++;
				if(X < header->projExtents.x) header->projExtents.x = X;
				if(Z < header->projExtents.y) header->projExtents.y = Z;
				if(X > header->projExtents.dx) header->projExtents.dx = X;
				if(Z > header->projExtents.dy) header->projExtents.dy = Z;
			}
			
		}

		zOffset += adfGeoTransform[5];

		if(progressDlg)
		{
			if(!progressDlg->Update(int((float(m)/header->nRows)*50)))
			{
				GDALClose(gdalDataset);
				if(elevations != NULL)
					delete[] elevations;

				return false;
			}
		}
	}
		
	if(App::Inst().GetLayerTreeController()->GetIsBlankRaster())
	{
		
		LayerTreeControllerPtr ltc = App::Inst().GetLayerTreeController();
		VectorMapLayerPtr vectorMapLayer =ltc->GetVectorMapLayer(0);
	    VectorMapModelPtr vectorMapModel= vectorMapLayer->GetVectorMapController()->GetVectorMapModel();			
		header->projExtents.x = vectorMapModel->GetVectorBoundary_MinX();
		header->projExtents.dx = vectorMapModel->GetVectorBoundary_MaxX();
		header->projExtents.y = vectorMapModel->GetVectorBoundary_MinY();
		header->projExtents.dy = vectorMapModel->GetVectorBoundary_MaxY();
		
	}
	// transform all points into unit grid space	
	float minElevation = std::numeric_limits<float>::max();
	float maxElevation = -std::numeric_limits<float>::max();
		
	if(!TransformToGridSpace(grid, header, elevations, bElevationMap, minElevation, maxElevation, progressDlg))
	{ 
		GDALClose(gdalDataset);
		if(elevations != NULL)
			delete[] elevations;

		return false;
	}

	// setup map model
	mapModel->SetMinElevationGridSpace(minElevation);
	mapModel->SetMaxElevationGridSpace(maxElevation);

	mapModel->SetMinElevation(minElevation/header->scaleFactor);
	mapModel->SetMaxElevation(maxElevation/header->scaleFactor);

	
	mapModel->SetElevationMap(bElevationMap);	
	mapModel->SetGrid(grid);
	// report information in file to user
	if (!App::Inst().GetLayerTreeController()->GetIsBlankRaster())
		MetaDataInfo(gdalDataset, mapController);
	else
		MetaDataInfoForBlankRaster(mapController, adfGeoTransform);


	// build texture that will be mapped onto terrain
	if(!App::Inst().GetLayerTreeController()->GetIsBlankRaster()){
		if(!BuildTerrainTexture(gdalDataset, mapController, progressDlg))
		{
			GDALClose(gdalDataset);	
			if(elevations != NULL)
				delete[] elevations;

			return false;
		}
		// will free memory allocated to any GDALRasterBand objects
		GDALClose(gdalDataset);
	}

	// will free memory allocated to any GDALRasterBand objects		
	if(elevations != NULL)
		delete[] elevations;

	return true;
}
Ejemplo n.º 18
0
int main(int argc, const char * argv[]) {
    boost::filesystem::path p = boost::filesystem::current_path();
    
    fprintf(stdout,"cwp := %s\n",p.c_str());
    
    GDALAllRegister();
    
//    for (int i = 0; i < GDALGetDriverCount(); i++) {
//        GDALDriver * d = (GDALDriver *)GDALGetDriver(i);
//        const char * desc = d->GetDescription();
//        fprintf(stdout, "GDAL: %s\n",desc);
//    }
    
    GDALDataset *poDataset = (GDALDataset *) GDALOpen(DataPath.c_str(), GA_ReadOnly );
    std::string SupportedDriver = {"GTiff"};
    
    if (poDataset != NULL) {
        GDALDriver * drv = poDataset->GetDriver();
        assert(0 == SupportedDriver.compare(drv->GetDescription()));
        assert (1 == poDataset->GetRasterCount());
        
        fprintf(stdout,"RasterXSize := %d\n",poDataset->GetRasterXSize());
        fprintf(stdout,"RasterYSize := %d\n",poDataset->GetRasterYSize());
        fprintf(stdout,"ProjectionRef := %s\n",poDataset->GetProjectionRef());

        double adfGeoTransform[6];
        if ( poDataset->GetGeoTransform(adfGeoTransform) == CE_None ) {
            fprintf(stdout, "Origin = (%.6f, %.6f)\n",
                    adfGeoTransform[0],adfGeoTransform[3]); // upper left courner
            fprintf(stdout, "Pixel Size = (%.6f, %.6f)\n",
                    adfGeoTransform[1],adfGeoTransform[5]); // pixel width/height
        }
        
        GDALRasterBand *poBand = poDataset->GetRasterBand(1);
        int nBlockXSize, nBlockYSize;
        poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
        
        std::string SupportedDataType = {"Int16"};
        assert (GDT_Int16 == poBand->GetRasterDataType());
        
        printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
               nBlockXSize, nBlockYSize,
               GDALGetDataTypeName(poBand->GetRasterDataType()),
               GDALGetColorInterpretationName(
               poBand->GetColorInterpretation()) );
        
        FILE * patch = fopen("patch.txt","w");
        for (int i = 0; i < poBand->GetYSize(); i++) {
            int nXSize = poBand->GetXSize();
            float *pafScanline = (float *) CPLMalloc(sizeof(float)*nXSize);
            poBand->RasterIO( GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0);
            
            for (int j = 0; j < nXSize; j++) {
                fprintf(patch, "%f  ", pafScanline[j]);
            }
            fprintf(patch, "\n");
            
            CPLFree(pafScanline);
        }
        fclose(patch);
        
        GDALClose(poDataset);
    }
    
    DelaunayTriangulation dt;
    
    //std::srand(static_cast<unsigned int>(std::time(0))); // use current time as seed for random generator
    /*
    std::srand(static_cast<unsigned int>(3652123216145));
    for (int i = 0; i < 10 ; i++) {
        double x = 180.0 * static_cast <float> (rand()) / static_cast <float> (RAND_MAX);;
        double y = 180.0 * static_cast <float> (rand()) / static_cast <float> (RAND_MAX);;
        
        dt.addPt(x, y, 0.0);
    }
    */
    
    /*
    dt.addPt(-0.02222276248244826, -0.4979727817680433,  0.0);
    dt.addPt(-0.4285431913366012,   0.4745826469497594,  0.0);
    dt.addPt( 0.3105396575392593,   0.2400179190933871,  0.0);
    dt.addPt(-0.01883958887200765,  0.3630260628303755,  0.0);
    dt.addPt( 0.3790312361708201,   0.3779794437605696,  0.0);
    dt.addPt(-0.2994955874043476,   0.3776609263174803,  0.0);
    dt.addPt( 0.3471817493878135,   0.08365533089605659, 0.0);
    dt.addPt(-0.00485819764887746,  0.3482682405489201,  0.0);
    dt.addPt( 0.3443122672329771,  -0.1437312230875075,  0.0);
    dt.addPt( 0.309330780347186,   -0.07758103877080702, 0.0);
    
    dt.compute();
     */
    
    return 0;
}
Ejemplo n.º 19
0
CMapDEM::CMapDEM(const QString& filename, CCanvas * parent)
: IMap(eDEM, "",parent)
, canvas(parent)
, old_my_xscale(0)
, old_my_yscale(0)
, old_overlay(IMap::eNone)
, idxGrade(1)
{
#ifdef WIN32
    dataset = (GDALDataset*)GDALOpen(filename.toLocal8Bit(),GA_ReadOnly);
#else
    dataset = (GDALDataset*)GDALOpen(filename.toUtf8(),GA_ReadOnly);
#endif
    if(dataset == 0)
    {
        QMessageBox::warning(0, tr("Error..."),
            tr("Failed to load file: %1\n\n").arg(filename).append(tr(CPLGetLastErrorMsg())));
        status = 0;
        return;
    }

    GDALRasterBand * pBand;
    pBand = dataset->GetRasterBand(1);
    if(pBand == 0)
    {
        delete dataset; dataset = 0;
        QMessageBox::warning(0, tr("Error..."),
            tr("Failed to load file: %1").arg(filename).append(tr(CPLGetLastErrorMsg())));
        status = 0;
        return;
    }
    pBand->GetBlockSize(&tileWidth,&tileHeight);

    char str[1024]= {0};
    if(dataset->GetProjectionRef())
    {
        strncpy(str,dataset->GetProjectionRef(),sizeof(str));
    }
    char * ptr = str;
    oSRS.importFromWkt(&ptr);
    oSRS.exportToProj4(&ptr);
    QString strProj = ptr;

    qDebug() << "DEM:" << strProj;

    pjsrc = pj_init_plus(strProj.toLatin1());

    xsize_px = dataset->GetRasterXSize();
    ysize_px = dataset->GetRasterYSize();

    double adfGeoTransform[6];
    dataset->GetGeoTransform( adfGeoTransform );

    if (strProj.contains("longlat"))
    {
        xref1   = adfGeoTransform[0] * DEG_TO_RAD;
        yref1   = adfGeoTransform[3] * DEG_TO_RAD;

        xscale  = adfGeoTransform[1] * DEG_TO_RAD;
        yscale  = adfGeoTransform[5] * DEG_TO_RAD;

    }
    else
    {
        xref1   = adfGeoTransform[0];
        yref1   = adfGeoTransform[3];

        xscale  = adfGeoTransform[1];
        yscale  = adfGeoTransform[5];
    }
    xref2   = xref1 + xsize_px * xscale;
    yref2   = yref1 + ysize_px * yscale;

    //     qDebug() << xref1 << yref1 << xref2 << yref2 << xscale << yscale;

    int i;
    for(i = 0; i < 256; ++i)
    {
        graytable2 << qRgba(0,0,0,i);
    }

    for(i = 0; i < 128; ++i)
    {
        graytable1 << qRgba(0,0,0,(128 - i));
    }

    for(i = 128; i < 255; ++i)
    {
        graytable1 << qRgba(255,255,255, 1);
    }

    slopetable << slopeColorTable[0];
    slopetable << slopeColorTable[1];
    slopetable << slopeColorTable[2];
    slopetable << slopeColorTable[3];
    slopetable << slopeColorTable[4];
    slopetable << slopeColorTable[5];

    status = new CStatusDEM(theMainWindow->getCanvas());
    theMainWindow->statusBar()->insertPermanentWidget(0,status);

    SETTINGS;
    idxGrade = cfg.value("map/overlay/grade",idxGrade).toInt();

}
Ejemplo n.º 20
0
static GDALDataset *FITCreateCopy(const char * pszFilename,
                                  GDALDataset *poSrcDS,
                                  int bStrict, char ** papszOptions,
                                  GDALProgressFunc pfnProgress,
                                  void * pProgressData )
{
    CPLDebug("FIT", "CreateCopy %s - %i", pszFilename, bStrict);

    int nBands = poSrcDS->GetRasterCount();
    if (nBands == 0)
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "FIT driver does not support source dataset with zero band.\n");
        return nullptr;
    }

/* -------------------------------------------------------------------- */
/*      Create the dataset.                                             */
/* -------------------------------------------------------------------- */
    if( !pfnProgress( 0.0, nullptr, pProgressData ) )
    {
        CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" );
        return nullptr;
    }

    VSILFILE *fpImage = VSIFOpenL( pszFilename, "wb" );
    if( fpImage == nullptr )
    {
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "FIT - unable to create file %s.\n",
                  pszFilename );
        return nullptr;
    }

/* -------------------------------------------------------------------- */
/*      Generate header.                                                */
/* -------------------------------------------------------------------- */
    // XXX - should FIT_PAGE_SIZE be based on file page size ??

    const size_t size = std::max(sizeof(FIThead02), FIT_PAGE_SIZE);
    FIThead02 *head = (FIThead02 *) malloc(size);
    FreeGuard<FIThead02> guardHead( head );

    // clean header so padding (past real header) is all zeros
    memset( head, 0, size );

    memcpy((char *) &head->magic, "IT", 2);
    memcpy((char *) &head->version, "02", 2);

    head->xSize = poSrcDS->GetRasterXSize();
    gst_swapb(head->xSize);
    head->ySize = poSrcDS->GetRasterYSize();
    gst_swapb(head->ySize);
    head->zSize = 1;
    gst_swapb(head->zSize);

    head->cSize = nBands;
    gst_swapb(head->cSize);

    GDALRasterBand *firstBand = poSrcDS->GetRasterBand(1);
    if (! firstBand) {
        CPL_IGNORE_RET_VAL(VSIFCloseL(fpImage));
        return nullptr;
    }

    head->dtype = fitGetDataType(firstBand->GetRasterDataType());
    if (! head->dtype) {
        CPL_IGNORE_RET_VAL(VSIFCloseL(fpImage));
        return nullptr;
    }
    gst_swapb(head->dtype);
    head->order = 1; // interleaved - RGBRGB
    gst_swapb(head->order);
    head->space = 1; // upper left
    gst_swapb(head->space);

    // XXX - need to check all bands
    head->cm = fitGetColorModel(firstBand->GetColorInterpretation(), nBands);
    gst_swapb(head->cm);

    int blockX, blockY;
    firstBand->GetBlockSize(&blockX, &blockY);
    blockX = std::min(blockX, poSrcDS->GetRasterXSize());
    blockY = std::min(blockY, poSrcDS->GetRasterYSize());
    int nDTSize = GDALGetDataTypeSizeBytes(firstBand->GetRasterDataType());
    try
    {
        CPL_IGNORE_RET_VAL(
            CPLSM(blockX) * CPLSM(blockY) * CPLSM(nDTSize) * CPLSM(nBands));
        CPLDebug("FIT write", "inherited block size %ix%i", blockX, blockY);
    }
    catch( ... )
    {
        blockX = std::min(256, poSrcDS->GetRasterXSize());
        blockY = std::min(256, poSrcDS->GetRasterYSize());
    }

    if( CSLFetchNameValue(papszOptions,"PAGESIZE") != nullptr )
    {
        const char *str = CSLFetchNameValue(papszOptions,"PAGESIZE");
        int newBlockX, newBlockY;
        sscanf(str, "%i,%i", &newBlockX, &newBlockY);
        if (newBlockX && newBlockY) {
            blockX = newBlockX;
            blockY = newBlockY;
        }
        else {
            CPLError(CE_Failure, CPLE_OpenFailed,
                     "FIT - Unable to parse option PAGESIZE values [%s]", str);
        }
    }

    // XXX - need to do lots of checking of block size
    // * provide ability to override block size with options
    // * handle non-square block size (like scanline)
    //   - probably default from non-tiled image - have default block size
    // * handle block size bigger than image size
    // * undesirable block size (non power of 2, others?)
    // * mismatched block sizes for different bands
    // * image that isn't even pages (i.e. partially empty pages at edge)
    CPLDebug("FIT write", "using block size %ix%i", blockX, blockY);

    head->xPageSize = blockX;
    gst_swapb(head->xPageSize);
    head->yPageSize = blockY;
    gst_swapb(head->yPageSize);
    head->zPageSize = 1;
    gst_swapb(head->zPageSize);
    head->cPageSize = nBands;
    gst_swapb(head->cPageSize);

    // XXX - need to check all bands
    head->minValue = firstBand->GetMinimum();
    gst_swapb(head->minValue);
    // XXX - need to check all bands
    head->maxValue = firstBand->GetMaximum();
    gst_swapb(head->maxValue);
    head->dataOffset = static_cast<unsigned int>(size);
    gst_swapb(head->dataOffset);

    CPL_IGNORE_RET_VAL(VSIFWriteL(head, size, 1, fpImage));

/* -------------------------------------------------------------------- */
/*      Loop over image, copying image data.                            */
/* -------------------------------------------------------------------- */
    unsigned long bytesPerPixel = nBands * nDTSize;

    size_t pageBytes = blockX * blockY * bytesPerPixel;
    char *output = (char *) malloc(pageBytes);
    if (! output)
    {
        CPLError(CE_Failure, CPLE_OutOfMemory,
                 "FITRasterBand couldn't allocate %lu bytes",
                 static_cast<unsigned long>(pageBytes));
        CPL_IGNORE_RET_VAL(VSIFCloseL(fpImage));
        return nullptr;
    }
    FreeGuard<char> guardOutput( output );

    long maxx = (long) ceil(poSrcDS->GetRasterXSize() / (double) blockX);
    long maxy = (long) ceil(poSrcDS->GetRasterYSize() / (double) blockY);
    long maxx_full = (long) floor(poSrcDS->GetRasterXSize() / (double) blockX);
    long maxy_full = (long) floor(poSrcDS->GetRasterYSize() / (double) blockY);

    CPLDebug("FIT", "about to write %ld x %ld blocks", maxx, maxy);

    for(long y=0; y < maxy; y++)
        for(long x=0; x < maxx; x++) {
            long readX = blockX;
            long readY = blockY;
            int do_clean = FALSE;

            // handle cases where image size isn't an exact multiple
            // of page size
            if (x >= maxx_full) {
                readX = poSrcDS->GetRasterXSize() % blockX;
                do_clean = TRUE;
            }
            if (y >= maxy_full) {
                readY = poSrcDS->GetRasterYSize() % blockY;
                do_clean = TRUE;
            }

            // clean out image if only doing partial reads
            if (do_clean)
                memset( output, 0, pageBytes );

            for( int iBand = 0; iBand < nBands; iBand++ ) {
                GDALRasterBand * poBand = poSrcDS->GetRasterBand( iBand+1 );
                CPLErr eErr =
                    poBand->RasterIO( GF_Read, // eRWFlag
                                      static_cast<int>(x * blockX), // nXOff
                                      static_cast<int>(y * blockY), // nYOff
                                      static_cast<int>(readX), // nXSize
                                      static_cast<int>(readY), // nYSize
                                      output + iBand * nDTSize,
                                      // pData
                                      blockX, // nBufXSize
                                      blockY, // nBufYSize
                                      firstBand->GetRasterDataType(),
                                      // eBufType
                                      bytesPerPixel, // nPixelSpace
                                      bytesPerPixel * blockX, nullptr); // nLineSpace
                if (eErr != CE_None)
                {
                    CPLError(CE_Failure, CPLE_FileIO,
                             "FIT write - CreateCopy got read error %i", eErr);
                    CPL_IGNORE_RET_VAL(VSIFCloseL( fpImage ));
                    VSIUnlink( pszFilename );
                    return nullptr;
                }
            } // for iBand

#ifdef swapping
            char *p = output;
            unsigned long i;
            switch(nDTSize) {
            case 1:
                // do nothing
                break;
            case 2:
                for(i=0; i < pageBytes; i+= nDTSize)
                    gst_swap16(p + i);
                break;
            case 4:
                for(i=0; i < pageBytes; i+= nDTSize)
                    gst_swap32(p + i);
                break;
            case 8:
                for(i=0; i < pageBytes; i+= nDTSize)
                    gst_swap64(p + i);
                break;
            default:
                CPLError(CE_Failure, CPLE_NotSupported,
                         "FIT write - unsupported bytesPerPixel %d",
                         nDTSize);
            } // switch
#endif // swapping

            if( VSIFWriteL(output, 1, pageBytes, fpImage) != pageBytes )
            {
                CPLError( CE_Failure, CPLE_FileIO, "Write failed" );
                CPL_IGNORE_RET_VAL(VSIFCloseL( fpImage ));
                VSIUnlink( pszFilename );
                return nullptr;
            }

            double perc = ((double) (y * maxx + x)) / (maxx * maxy);
            if( !pfnProgress( perc, nullptr, pProgressData ) )
            {
                CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" );
                //free(output);
                CPL_IGNORE_RET_VAL(VSIFCloseL( fpImage ));
                VSIUnlink( pszFilename );
                return nullptr;
            }
        } // for x

    //free(output);

    CPL_IGNORE_RET_VAL(VSIFCloseL( fpImage ));

    pfnProgress( 1.0, nullptr, pProgressData );

/* -------------------------------------------------------------------- */
/*      Re-open dataset, and copy any auxiliary pam information.         */
/* -------------------------------------------------------------------- */
    GDALPamDataset *poDS = (GDALPamDataset *)
        GDALOpen( pszFilename, GA_ReadOnly );

    if( poDS )
        poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT );

    return poDS;
}
Ejemplo n.º 21
0
 PDSWrapperRasterBand( GDALRasterBand* poBaseBand ) 
     {
         this->poBaseBand = poBaseBand;
         eDataType = poBaseBand->GetRasterDataType();
         poBaseBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
     }
Ejemplo n.º 22
0
 explicit NGWWrapperRasterBand( GDALRasterBand* poBaseBandIn ) :
     poBaseBand( poBaseBandIn )
 {
     eDataType = poBaseBand->GetRasterDataType();
     poBaseBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
 }
bool GDALImageFileType::read(      Image       *OSG_GDAL_ARG(pImage), 
                             const Char8       *OSG_GDAL_ARG(fileName)) 
{
#ifdef OSG_WITH_GDAL
    bool returnValue = false;

    GDALDataset *pDataset;

    pDataset = static_cast<GDALDataset *>(GDALOpen(fileName, GA_ReadOnly));

    if(pDataset != NULL)
    {
        GeoReferenceAttachmentUnrecPtr pGeoRef = 
            GeoReferenceAttachment::create();

        pImage->addAttachment(pGeoRef);

        double        adfGeoTransform[6];
        
        if(pDataset->GetGeoTransform(adfGeoTransform) == CE_None)
        {
            pGeoRef->editOrigin().setValues(adfGeoTransform[0], 
                                            adfGeoTransform[3]);

            pGeoRef->editPixelSize().setValues(adfGeoTransform[1], 
                                               adfGeoTransform[5]);

            if(GDALGetProjectionRef(pDataset) != NULL)
            {
                OGRSpatialReferenceH  hSRS;

                Char8 *szProjection = 
                    const_cast<char *>(GDALGetProjectionRef(pDataset));
        
                hSRS = OSRNewSpatialReference(NULL);

                if(OSRImportFromWkt(hSRS, &szProjection) == CE_None)
                {
                    pGeoRef->editEllipsoidAxis().setValues(
                        OSRGetSemiMajor(hSRS, NULL),
                        OSRGetSemiMinor(hSRS, NULL));

                    const Char8 *szDatum = OSRGetAttrValue(hSRS, "DATUM", 0);

                    if(szDatum != NULL && 0 == strcmp(szDatum, "WGS_1984"))
                    {
                        pGeoRef->editDatum() = 
                            GeoReferenceAttachment::WGS84;
                    }
                    else
                    {
                        fprintf(stderr, "Unknow datum %s\n",
                                szDatum);

                        pGeoRef->editDatum() = 
                            GeoReferenceAttachment::UnknownDatum;
                    }
                }            

                OSRDestroySpatialReference(hSRS);
            }
        }

        GDALRasterBand *pBand;
        int             nBlockXSize, nBlockYSize;
        int             bGotMin, bGotMax;
        double          adfMinMax[2];
        
        pBand = pDataset->GetRasterBand( 1 );
        pBand->GetBlockSize( &nBlockXSize, &nBlockYSize );

        adfMinMax[0] = pBand->GetMinimum( &bGotMin );
        adfMinMax[1] = pBand->GetMaximum( &bGotMax );

        if(!(bGotMin && bGotMax))
            GDALComputeRasterMinMax(GDALRasterBandH(pBand), TRUE, adfMinMax);

        pBand = pDataset->GetRasterBand(1);

        if(pBand != NULL)
        {
            Image::PixelFormat ePF = Image::OSG_INVALID_PF;

            switch(pDataset->GetRasterCount())
            {
                case 1:
                    ePF = Image::OSG_L_PF;
                    break;
                case 2:
                    ePF = Image::OSG_LA_PF;
                    break;
                case 3:
                    ePF = Image::OSG_RGB_PF;
                    break;
                case 4:
                    ePF = Image::OSG_RGBA_PF;
                    break;
            }

            Image::Type eDT = Image::OSG_INVALID_IMAGEDATATYPE;

            switch(pBand->GetRasterDataType())
            {
                case GDT_Byte:
                    eDT = Image::OSG_UINT8_IMAGEDATA;
                    break;

                case GDT_UInt16:
                    eDT = Image::OSG_UINT16_IMAGEDATA;
                    break;

                case GDT_Int16:
                    eDT = Image::OSG_INT16_IMAGEDATA;
                    break;

                case GDT_UInt32:
                    eDT = Image::OSG_UINT32_IMAGEDATA;
                    break;

                case GDT_Int32:
                    eDT = Image::OSG_INT32_IMAGEDATA;
                    break;

                case GDT_Float32: 
                    eDT = Image::OSG_FLOAT32_IMAGEDATA;
                    break;

                case GDT_Float64:
                case GDT_CInt16: 
                case GDT_CInt32:
                case GDT_CFloat32:
                case GDT_CFloat64:
                default:
                    GDALClose(pDataset);
                    return returnValue;
                    break;
        
            }

            pImage->set(ePF,             
                        pDataset->GetRasterXSize(), 
                        pDataset->GetRasterYSize(),
                        1,
                        1,
                        1,
                        0.0,
                        NULL,
                        eDT);
            
            UChar8 *dst = pImage->editData();

            pBand->RasterIO(GF_Read,
                            0, 
                            0,
                            pDataset->GetRasterXSize(), 
                            pDataset->GetRasterYSize(),
                            dst,
                            pDataset->GetRasterXSize(), 
                            pDataset->GetRasterYSize(),
                            pBand->GetRasterDataType(),
                            0,
                            0);

            pGeoRef->setNoDataValue(pBand->GetNoDataValue());

            returnValue = true;
        }

        GDALClose(pDataset);
    }

    return returnValue;

#else

    SWARNING << getMimeType()
             << " read is not compiled into the current binary "
             << std::endl;
    return false;

#endif // OSG_WITH_GDAL
}
Ejemplo n.º 24
0
std::tuple<boost::shared_ptr<Map_Matrix<DataFormat> >, std::string, GeoTransform>  read_in_map(fs::path file_path, GDALDataType data_type, const bool doCategorise) throw(std::runtime_error)
{

    std::string projection;
    GeoTransform transformation;
    GDALDriver driver;
    
	//Check that the file name is valid
	if (!(fs::is_regular_file(file_path)))
	{
		throw std::runtime_error("Input file is not a regular file");
	}	

	// Get GDAL to open the file - code is based on the tutorial at http://www.gdal.org/gdal_tutorial.html
	GDALDataset *poDataset;
	GDALAllRegister(); //This registers all availble raster file formats for use with this utility. How neat is that. We can input any GDAL supported rater file format.

	//Open the Raster by calling GDALOpen. http://www.gdal.org/gdal_8h.html#a6836f0f810396c5e45622c8ef94624d4
	//char pszfilename[] = file_path.c_str(); //Set this to the file name, as GDALOpen requires the standard C char pointer as function parameter.
	poDataset = (GDALDataset *) GDALOpen (file_path.string().c_str(), GA_ReadOnly);
	if (poDataset == NULL)
	{
		throw std::runtime_error("Unable to open file");
	}
	
//	Print some general information about the raster
	double        adfGeoTransform[6]; //An array of doubles that will be used to save information about the raster - where the origin is, what the raster pizel size is.
    
    
    printf( "Driver: %s/%s\n",
            poDataset->GetDriver()->GetDescription(),
            poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );

    printf( "Size is %dx%dx%d\n", 
            poDataset->GetRasterXSize(), poDataset->GetRasterYSize(),
            poDataset->GetRasterCount() );

    if( poDataset->GetProjectionRef()  != NULL )
    {
        printf( "Projection is `%s'\n", poDataset->GetProjectionRef() );
        projection = poDataset->GetProjectionRef();
    }

    if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None )
    {
        printf( "Origin = (%.6f,%.6f)\n",
                adfGeoTransform[0], adfGeoTransform[3] );

        printf( "Pixel Size = (%.6f,%.6f)\n",
                adfGeoTransform[1], adfGeoTransform[5] );
        
        transformation.x_origin = adfGeoTransform[0];
        transformation.pixel_width = adfGeoTransform[1];
        transformation.x_line_space = adfGeoTransform[2];
        transformation.y_origin = adfGeoTransform[3];
        transformation.pixel_height = adfGeoTransform[4];
        transformation.y_line_space = adfGeoTransform[5];
        
    }


	/// Some raster file formats allow many layers of data (called a 'band', with each having the same pixel size and origin location and spatial extent). We will get the data for the first layer into a Boost Array.
	//Get the data from the first band, 
	// TODO implement method with input to specify what band.
	    GDALRasterBand  *poBand;
        int             nBlockXSize, nBlockYSize;
        int             bGotMin, bGotMax;
        double          adfMinMax[2];
        
        poBand = poDataset->GetRasterBand( 1 );
        poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
        printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
                nBlockXSize, nBlockYSize,
                GDALGetDataTypeName(poBand->GetRasterDataType()),
                GDALGetColorInterpretationName(
                    poBand->GetColorInterpretation()) );

        adfMinMax[0] = poBand->GetMinimum( &bGotMin );
        adfMinMax[1] = poBand->GetMaximum( &bGotMax );
        if( ! (bGotMin && bGotMax) )
            GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);

        printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1] );
        
        if( poBand->GetOverviewCount() > 0 )
            printf( "Band has %d overviews.\n", poBand->GetOverviewCount() );

        if( poBand->GetColorTable() != NULL )
            printf( "Band has a color table with %d entries.\n", 
                     poBand->GetColorTable()->GetColorEntryCount() );

		DataFormat * pafScanline;
        int   nXSize = poBand->GetXSize();
		int   nYSize = poBand->GetYSize();
		boost::shared_ptr<Map_Matrix<DataFormat> > in_map(new Map_Matrix<DataFormat>(nYSize, nXSize));
		//get a c array of this size and read into this.
		
		
		//pafScanline = new DataFormat[nXSize];
		//for (int i = 0; i < nYSize; i++) //rows
		//{
		//	poBand->RasterIO(GF_Read, 0, i, nXSize, 1,
		//		pafScanline, nXSize, 1, data_type,
		//		0, 0);
		//	for (int j = 0; j < nXSize; j++) //cols
		//	{
		//		in_map->Get(i, j) = pafScanline[j];
		//	}
		//}
    
        //get a c array of this size and read into this.
        pafScanline = new DataFormat[nXSize * nYSize];
        //pafScanline = (float *) CPLMalloc(sizeof(float)*nXSize);
        poBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, 
			pafScanline, nXSize, nYSize, data_type,
                          0, 0 );
    
        //Copy into Map_Matrix.
        int pafIterator = 0;
		// Note: Map Matrixes indexes are in opposite order to C arrays. e.g. map matrix is indexed by (row, Col) which is (y, x) and c matrices are done by (x, y) which is (Col, Row)
        
        //for (int i = 0; i < nXSize; i++)
        //{
        //    for(int j = 0; j < nYSize; j++)
        //    {
        //        in_map->Get(j, i) = pafScanline[pafIterator];
        //        pafIterator++;
        //    }
        //}		
		for (int i = 0; i < nYSize; i++) //rows
		{
			for (int j = 0; j < nXSize; j++) //cols
			{
				in_map->Get(i, j) = pafScanline[pafIterator];
				pafIterator++;
			}
		}


    
    //free the c array storage
    delete pafScanline;
    int pbsuccess; // can be used with get no data value
    in_map->SetNoDataValue(poBand->GetNoDataValue(&pbsuccess));
    //This creates a list (map?) listing all the unique values contained in the raster.
	if (doCategorise) in_map->updateCategories();

    
	//Close GDAL, freeing the memory GDAL is using
	GDALClose( (GDALDatasetH)poDataset);

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

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

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

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

      //ut[i][j] = pafScanline[i*width+j];
    }
   }
   CPLFree(pafScanline);
   //exit(0);
   // Create a texture
   glGenTextures(1,&tex);
   glBindTexture(GL_TEXTURE_2D,tex);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 512,512, 0, GL_RED, GL_UNSIGNED_BYTE,texs);
   GDALClose( (GDALDatasetH) poDataset);
   return;
} 
Ejemplo n.º 26
0
int readRaster(const char* pszFilename)
{
    // Set config options for GDAL (needs >= 2.0). Setting GTIFF_VIRTUAL_MEM_IO to "YES" can cause things bleed to
    // swap if enough RAM is not available. Use "IF_ENOUGH_RAM" for safer performance if unsure. NOTE that faster
    // mem io only works with *uncompressed* GeoTIFFs.
    // New in GDAL 2.0, from https://2015.foss4g-na.org/sites/default/files/slides/GDAL%202.0%20overview.pdf
    // GeoTIFF driver (with i7-4700 HQ (8 vCPUs)):with i7-4700 HQ (8 vCPUs)
    //   - Default: time ./testblockcache -ondisk: 7.5s
    //   - GTIFF_DIRECT_IO=YES: short circuit the block cache&libtiff for most RasterIO() operations (restricted to
    //     uncompressed stripped GeoTIFF). time ./testblockcache -ondisk: 2s
    //   - GTIFF_VIRTUAL_MEM_IO=YES: same as above, with tiled GeoTIFF as well. Uses memory-mapped file access. Linux
    //     only for now, 64bit recommended (could be extended to other platforms possible).
    //     time ./testblockcache -ondisk: 0.3s
    //
    CPLSetConfigOption("GTIFF_VIRTUAL_MEM_IO", "YES" );
    // Open the dataset
    GDALDataset *poDataset;
    GDALAllRegister();
    poDataset = (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly );

    if( poDataset == NULL )
    {
        std::cout << "Dataset " << pszFilename << " could not be opened." << std::endl;
        return -1;
    }
    else
    {
        GDALRasterBand  *poBand;
        int             nBlockXSize, nBlockYSize;
        int             bGotMin, bGotMax;
        double          adfMinMax[2];

        //  Get raster band and its size
        poBand = poDataset->GetRasterBand(1);
        poBand->GetBlockSize( &nBlockXSize, &nBlockYSize);

        std::cout << "Dataset: " << pszFilename << std::endl;

        std::cout << "Block=" << nBlockXSize << "x" << nBlockYSize << " Type=" <<
                GDALGetDataTypeName(poBand->GetRasterDataType()) << " ColorInterp=" <<
                GDALGetColorInterpretationName(poBand->GetColorInterpretation()) << std::endl;

        // Calculate some stats
        adfMinMax[0] = poBand->GetMinimum(&bGotMin);
        adfMinMax[1] = poBand->GetMaximum(&bGotMax);

        if(!(bGotMin && bGotMax)) {
            GDALComputeRasterMinMax((GDALRasterBandH) poBand, TRUE, adfMinMax);
        }
        std::cout << "Min=" << adfMinMax[0] << " Max=" << adfMinMax[1] << std::endl;

        if(poBand->GetOverviewCount() > 0) {
            std::cout << "Band has " << poBand->GetOverviewCount() << " overviews." << std::endl;
        }
        if( poBand->GetColorTable() != NULL ) {
            std::cout << "Band has a color table with " << poBand->GetColorTable()->GetColorEntryCount() <<
                    " entries." << std::endl;
        }

        // Get the actual data
        float *pafScanline;
        int   nXSize = poBand->GetXSize();
        pafScanline = (float *) CPLMalloc(sizeof(float) * nXSize);

        // RasterIO has a new argument psExtraArg in GDAL > 2.0. NOTE: that  GDALRasterBand::ReadBlock() probably has
        // better performance for reading the whole data at one go.
        #ifdef USE_GDAL_2
            GDALRasterIOExtraArg* arg = NULL;
            poBand->RasterIO(GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float3GDALRasterBand::ReadBlock 2,
               0, 0, arg);
        #else
            poBand->RasterIO(GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0);
        #endif

        // ... do something with the data ...

        // Free resources
        CPLFree(pafScanline);
        GDALClose((GDALDatasetH) poDataset);
        std::cout << std::endl;
    }
    return 0;
}
Ejemplo n.º 27
0
bool vtImageGeo::ReadTIF(const char *filename, bool progress_callback(int))
{
	// Use GDAL to read a TIF file (or any other format that GDAL is
	//  configured to read) into this OSG image.
	bool bRet = true;
	vtString message;

	setFileName(filename);

	g_GDALWrapper.RequestGDALFormats();

	GDALDataset *pDataset = NULL;
	GDALRasterBand *pBand;
	GDALRasterBand *pRed = NULL;
	GDALRasterBand *pGreen = NULL;
	GDALRasterBand *pBlue = NULL;
	GDALRasterBand *pAlpha = NULL;
	GDALColorTable *pTable;
	uchar *pScanline = NULL;
	uchar *pRedline = NULL;
	uchar *pGreenline = NULL;
	uchar *pBlueline = NULL;
	uchar *pAlphaline = NULL;

	CPLErr Err;
	bool bColorPalette = false;
	int iXSize, iYSize;
	int nxBlocks, nyBlocks;
	int xBlockSize, yBlockSize;

	try
	{
		pDataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly);
		if(pDataset == NULL )
			throw "Couldn't open that file.";

		// Get size
		iXSize = pDataset->GetRasterXSize();
		iYSize = pDataset->GetRasterYSize();

		// Try getting CRS
		vtProjection temp;
		bool bHaveProj = false;
		const char *pProjectionString = pDataset->GetProjectionRef();
		if (pProjectionString)
		{
			OGRErr err = temp.importFromWkt((char**)&pProjectionString);
			if (err == OGRERR_NONE)
			{
				m_proj = temp;
				bHaveProj = true;
			}
		}
		if (!bHaveProj)
		{
			// check for existence of .prj file
			bool bSuccess = temp.ReadProjFile(filename);
			if (bSuccess)
			{
				m_proj = temp;
				bHaveProj = true;
			}
		}

		// Try getting extents
		double affineTransform[6];
		if (pDataset->GetGeoTransform(affineTransform) == CE_None)
		{
			m_extents.left = affineTransform[0];
			m_extents.right = m_extents.left + affineTransform[1] * iXSize;
			m_extents.top = affineTransform[3];
			m_extents.bottom = m_extents.top + affineTransform[5] * iYSize;
		}

		// Raster count should be 3 for colour images (assume RGB)
		int iRasterCount = pDataset->GetRasterCount();

		if (iRasterCount != 1 && iRasterCount != 3 && iRasterCount != 4)
		{
			message.Format("Image has %d bands (not 1, 3, or 4).", iRasterCount);
			throw (const char *)message;
		}

		if (iRasterCount == 1)
		{
			pBand = pDataset->GetRasterBand(1);

			// Check the band's data type
			GDALDataType dtype = pBand->GetRasterDataType();
			if (dtype != GDT_Byte)
			{
				message.Format("Band is of type %s, but we support type Byte.", GDALGetDataTypeName(dtype));
				throw (const char *)message;
			}
			GDALColorInterp ci = pBand->GetColorInterpretation();

			if (ci == GCI_PaletteIndex)
			{
				if (NULL == (pTable = pBand->GetColorTable()))
					throw "Couldn't get color table.";
				bColorPalette = true;
			}
			else if (ci == GCI_GrayIndex)
			{
				// we will assume 0-255 is black to white
			}
			else
				throw "Unsupported color interpretation.";

			pBand->GetBlockSize(&xBlockSize, &yBlockSize);
			nxBlocks = (iXSize + xBlockSize - 1) / xBlockSize;
			nyBlocks = (iYSize + yBlockSize - 1) / yBlockSize;
			if (NULL == (pScanline = new uchar[xBlockSize * yBlockSize]))
				throw "Couldnt allocate scan line.";
		}

		if (iRasterCount == 3)
		{
			for (int i = 1; i <= 3; i++)
			{
				pBand = pDataset->GetRasterBand(i);

				// Check the band's data type
				GDALDataType dtype = pBand->GetRasterDataType();
				if (dtype != GDT_Byte)
				{
					message.Format("Band is of type %s, but we support type Byte.", GDALGetDataTypeName(dtype));
					throw (const char *)message;
				}
				switch (pBand->GetColorInterpretation())
				{
				case GCI_RedBand:
					pRed = pBand;
					break;
				case GCI_GreenBand:
					pGreen = pBand;
					break;
				case GCI_BlueBand:
					pBlue = pBand;
					break;
				}
			}
			if ((NULL == pRed) || (NULL == pGreen) || (NULL == pBlue))
				throw "Couldn't find bands for Red, Green, Blue.";

			pRed->GetBlockSize(&xBlockSize, &yBlockSize);
			nxBlocks = (iXSize + xBlockSize - 1) / xBlockSize;
			nyBlocks = (iYSize + yBlockSize - 1) / yBlockSize;

			pRedline = new uchar[xBlockSize * yBlockSize];
			pGreenline = new uchar[xBlockSize * yBlockSize];
			pBlueline = new uchar[xBlockSize * yBlockSize];
		}

		if (iRasterCount == 4)
		{
#if VTDEBUG
			VTLOG1("Band interpretations:");
#endif
			for (int i = 1; i <= 4; i++)
			{
				pBand = pDataset->GetRasterBand(i);

				// Check the band's data type
				GDALDataType dtype = pBand->GetRasterDataType();
				if (dtype != GDT_Byte)
				{
					message.Format("Band is of type %s, but we support type Byte.", GDALGetDataTypeName(dtype));
					throw (const char *)message;
				}
				GDALColorInterp ci = pBand->GetColorInterpretation();
#if VTDEBUG
				VTLOG(" %d", ci);
#endif
				switch (ci)
				{
				case GCI_RedBand:
					pRed = pBand;
					break;
				case GCI_GreenBand:
					pGreen = pBand;
					break;
				case GCI_BlueBand:
					pBlue = pBand;
					break;
				case GCI_AlphaBand:
					pAlpha = pBand;
					break;
				case GCI_Undefined:
					// If we have four bands: R,G,B,undefined, then assume that
					//  the undefined one is actually alpha
					if (pRed && pGreen && pBlue && !pAlpha)
						pAlpha = pBand;
					break;
				}
			}
#if VTDEBUG
			VTLOG1("\n");
#endif
			if ((NULL == pRed) || (NULL == pGreen) || (NULL == pBlue) || (NULL == pAlpha))
				throw "Couldn't find bands for Red, Green, Blue, Alpha.";

			pRed->GetBlockSize(&xBlockSize, &yBlockSize);
			nxBlocks = (iXSize + xBlockSize - 1) / xBlockSize;
			nyBlocks = (iYSize + yBlockSize - 1) / yBlockSize;

			pRedline = new uchar[xBlockSize * yBlockSize];
			pGreenline = new uchar[xBlockSize * yBlockSize];
			pBlueline = new uchar[xBlockSize * yBlockSize];
			pAlphaline = new uchar[xBlockSize * yBlockSize];
		}

		// Allocate the image buffer
		if (iRasterCount == 4)
		{
			Create(iXSize, iYSize, 32);
		}
		else if (iRasterCount == 3 || bColorPalette)
		{
			Create(iXSize, iYSize, 24);
		}
		else if (iRasterCount == 1)
			Create(iXSize, iYSize, 8);

		// Read the data
#if LOG_IMAGE_LOAD
		VTLOG("Reading the image data (%d x %d pixels)\n", iXSize, iYSize);
#endif

		int x, y;
		int ixBlock, iyBlock;
		int nxValid, nyValid;
		int iY, iX;
		RGBi rgb;
		RGBAi rgba;
		if (iRasterCount == 1)
		{
			GDALColorEntry Ent;
			for (iyBlock = 0; iyBlock < nyBlocks; iyBlock++)
			{
				if (progress_callback != NULL)
					progress_callback(iyBlock * 100 / nyBlocks);

				y = iyBlock * yBlockSize;
				for (ixBlock = 0; ixBlock < nxBlocks; ixBlock++)
				{
					x = ixBlock * xBlockSize;
					Err = pBand->ReadBlock(ixBlock, iyBlock, pScanline);
					if (Err != CE_None)
						throw "Problem reading the image data.";

					// Compute the portion of the block that is valid
					// for partial edge blocks.
					if ((ixBlock+1) * xBlockSize > iXSize)
						nxValid = iXSize - ixBlock * xBlockSize;
					else
						nxValid = xBlockSize;

					if( (iyBlock+1) * yBlockSize > iYSize)
						nyValid = iYSize - iyBlock * yBlockSize;
					else
						nyValid = yBlockSize;

					for( iY = 0; iY < nyValid; iY++ )
					{
						for( iX = 0; iX < nxValid; iX++ )
						{
							if (bColorPalette)
							{
								pTable->GetColorEntryAsRGB(pScanline[iY * xBlockSize + iX], &Ent);
								rgb.r = (uchar) Ent.c1;
								rgb.g = (uchar) Ent.c2;
								rgb.b = (uchar) Ent.c3;
								SetPixel24(x + iX, y + iY, rgb);
							}
							else
								SetPixel8(x + iX, y + iY, pScanline[iY * xBlockSize + iX]);
						}
					}
				}
			}
		}
		if (iRasterCount >= 3)
		{
			for (iyBlock = 0; iyBlock < nyBlocks; iyBlock++)
			{
				if (progress_callback != NULL)
					progress_callback(iyBlock * 100 / nyBlocks);

				y = iyBlock * yBlockSize;
				for (ixBlock = 0; ixBlock < nxBlocks; ixBlock++)
				{
					x = ixBlock * xBlockSize;
					Err = pRed->ReadBlock(ixBlock, iyBlock, pRedline);
					if (Err != CE_None)
						throw "Cannot read data.";
					Err = pGreen->ReadBlock(ixBlock, iyBlock, pGreenline);
					if (Err != CE_None)
						throw "Cannot read data.";
					Err = pBlue->ReadBlock(ixBlock, iyBlock, pBlueline);
					if (Err != CE_None)
						throw "Cannot read data.";
					if (iRasterCount == 4)
					{
						Err = pAlpha->ReadBlock(ixBlock, iyBlock, pAlphaline);
						if (Err != CE_None)
							throw "Cannot read data.";
					}

					// Compute the portion of the block that is valid
					// for partial edge blocks.
					if ((ixBlock+1) * xBlockSize > iXSize)
						nxValid = iXSize - ixBlock * xBlockSize;
					else
						nxValid = xBlockSize;

					if( (iyBlock+1) * yBlockSize > iYSize)
						nyValid = iYSize - iyBlock * yBlockSize;
					else
						nyValid = yBlockSize;

					for (int iY = 0; iY < nyValid; iY++)
					{
						for (int iX = 0; iX < nxValid; iX++)
						{
							if (iRasterCount == 3)
							{
								rgb.r = pRedline[iY * xBlockSize + iX];
								rgb.g = pGreenline[iY * xBlockSize + iX];
								rgb.b = pBlueline[iY * xBlockSize + iX];
								SetPixel24(x + iX, y + iY, rgb);
							}
							else if (iRasterCount == 4)
							{
								rgba.r = pRedline[iY * xBlockSize + iX];
								rgba.g = pGreenline[iY * xBlockSize + iX];
								rgba.b = pBlueline[iY * xBlockSize + iX];
								rgba.a = pAlphaline[iY * xBlockSize + iX];
								SetPixel32(x + iX, y + iY, rgba);
							}
						}
					}
				}
			}
		}
	}
	catch (const char *msg)
	{
		VTLOG1("Problem: ");
		VTLOG1(msg);
		VTLOG1("\n");
		bRet = false;
	}

	if (NULL != pDataset)
		GDALClose(pDataset);
	if (NULL != pScanline)
		delete pScanline;
	if (NULL != pRedline)
		delete pRedline;
	if (NULL != pGreenline)
		delete pGreenline;
	if (NULL != pBlueline)
		delete pBlueline;
	if (NULL != pAlphaline)
		delete pAlphaline;

	return bRet;
}
Ejemplo n.º 28
0
CPLErr GDALDefaultOverviews::CreateMaskBand( int nFlags, int nBand )

{
    if( nBand < 1 )
        nFlags |= GMF_PER_DATASET;

/* -------------------------------------------------------------------- */
/*      ensure existing file gets opened if there is one.               */
/* -------------------------------------------------------------------- */
    HaveMaskFile();

/* -------------------------------------------------------------------- */
/*      Try creating the mask file.                                     */
/* -------------------------------------------------------------------- */
    if( poMaskDS == NULL )
    {
        CPLString osMskFilename;
        GDALDriver *poDr = (GDALDriver *) GDALGetDriverByName( "GTiff" );
        char **papszOpt = NULL;
        int  nBX, nBY;
        int  nBands;
        
        if( poDr == NULL )
            return CE_Failure;

        GDALRasterBand *poTBand = poDS->GetRasterBand(1);
        if( poTBand == NULL )
            return CE_Failure;

        if( nFlags & GMF_PER_DATASET )
            nBands = 1;
        else
            nBands = poDS->GetRasterCount();


        papszOpt = CSLSetNameValue( papszOpt, "COMPRESS", "DEFLATE" );
        papszOpt = CSLSetNameValue( papszOpt, "INTERLEAVE", "BAND" );

        poTBand->GetBlockSize( &nBX, &nBY );

        // try to create matching tile size if legal in TIFF.
        if( (nBX % 16) == 0 && (nBY % 16) == 0 )
        {
            papszOpt = CSLSetNameValue( papszOpt, "TILED", "YES" );
            papszOpt = CSLSetNameValue( papszOpt, "BLOCKXSIZE",
                                        CPLString().Printf("%d",nBX) );
            papszOpt = CSLSetNameValue( papszOpt, "BLOCKYSIZE",
                                        CPLString().Printf("%d",nBY) );
        }

        osMskFilename.Printf( "%s.msk", poDS->GetDescription() );
        poMaskDS = poDr->Create( osMskFilename, 
                                 poDS->GetRasterXSize(),
                                 poDS->GetRasterYSize(),
                                 nBands, GDT_Byte, papszOpt );
        CSLDestroy( papszOpt );

        if( poMaskDS == NULL ) // presumably error already issued.
            return CE_Failure;

        bOwnMaskDS = TRUE;
    }
        
/* -------------------------------------------------------------------- */
/*      Save the mask flags for this band.                              */
/* -------------------------------------------------------------------- */
    if( nBand > poMaskDS->GetRasterCount() )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Attempt to create a mask band for band %d of %s,\n"
                  "but the .msk file has a PER_DATASET mask.", 
                  nBand, poDS->GetDescription() );
        return CE_Failure;
    }
    
    int iBand; 

    for( iBand = 0; iBand < poDS->GetRasterCount(); iBand++ )
    {
        // we write only the info for this band, unless we are
        // using PER_DATASET in which case we write for all.
        if( nBand != iBand + 1 && !(nFlags | GMF_PER_DATASET) )
            continue;

        poMaskDS->SetMetadataItem( 
            CPLString().Printf("INTERNAL_MASK_FLAGS_%d", iBand+1 ),
            CPLString().Printf("%d", nFlags ) );
    }

    return CE_None;
}
Ejemplo n.º 29
0
GDALDataset *ARGDataset::CreateCopy( const char *pszFilename,
                                     GDALDataset *poSrcDS,
                                     int /* bStrict */ ,
                                     char ** /* papszOptions */ ,
                                     GDALProgressFunc /* pfnProgress */ ,
                                     void * /*pProgressData */ )
{
    const int nBands = poSrcDS->GetRasterCount();
    if( nBands != 1 )
    {
        CPLError( CE_Failure, CPLE_NotSupported,
              "ARG driver doesn't support %d bands.  Must be 1 band.", nBands );
        return nullptr;
    }

    CPLString pszDataType;
    int nPixelOffset = 0;

    GDALDataType eType = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    if( eType == GDT_Unknown ||
        eType == GDT_CInt16 ||
        eType == GDT_CInt32 ||
        eType == GDT_CFloat32 ||
        eType == GDT_CFloat64 )
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "ARG driver doesn't support data type %s.",
                  GDALGetDataTypeName(eType) );
        return nullptr;
    }
    else if (eType == GDT_Int16) {
        pszDataType = "int16";
        nPixelOffset = 2;
    }
    else if (eType == GDT_Int32) {
        pszDataType = "int32";
        nPixelOffset = 4;
    }
    else if (eType == GDT_Byte) {
        pszDataType = "uint8";
        nPixelOffset = 1;
    }
    else if (eType == GDT_UInt16) {
        pszDataType = "uint16";
        nPixelOffset = 2;
    }
    else if (eType == GDT_UInt32) {
        pszDataType = "uint32";
        nPixelOffset = 4;
    }
    else if (eType == GDT_Float32) {
        pszDataType = "float32";
        nPixelOffset = 4;
    }
    else if (eType == GDT_Float64) {
        pszDataType = "float64";
        nPixelOffset = 8;
    }

    double adfTransform[6];
    poSrcDS->GetGeoTransform( adfTransform );

    const char *pszWKT = poSrcDS->GetProjectionRef();
    OGRSpatialReference oSRS;
    OGRErr nErr = oSRS.importFromWkt(pszWKT);
    if (nErr != OGRERR_NONE) {
        CPLError( CE_Failure, CPLE_NotSupported,
              "Cannot import spatial reference WKT from source dataset.");
        return nullptr;
    }

    int nSrs = 0;
    if (oSRS.GetAuthorityCode("PROJCS") != nullptr) {
        nSrs = atoi(oSRS.GetAuthorityCode("PROJCS"));
    }
    else if (oSRS.GetAuthorityCode("GEOGCS") != nullptr) {
        nSrs = atoi(oSRS.GetAuthorityCode("GEOGCS"));
    }
    else {
        // could not determine projected or geographic code
        // default to EPSG:3857 if no code could be found
        nSrs = 3857;
    }

    /********************************************************************/
    /* Create JSON companion file.                                      */
    /********************************************************************/
    const CPLString osJSONFilename = GetJsonFilename(pszFilename);

    json_object *poJSONObject = json_object_new_object();

    char **pszTokens = poSrcDS->GetMetadata();
    const char *pszLayer = CSLFetchNameValue(pszTokens, "LAYER");

    if ( pszLayer == nullptr) {
        // Set the layer
        json_object_object_add(poJSONObject, "layer", json_object_new_string(
            CPLGetBasename(osJSONFilename)
        ));
    }
    else {
        // Set the layer
        json_object_object_add(poJSONObject, "layer", json_object_new_string(
            pszLayer
        ));
    }

    // Set the type
    json_object_object_add(poJSONObject, "type", json_object_new_string("arg"));
    // Set the datatype
    json_object_object_add(poJSONObject, "datatype", json_object_new_string(pszDataType));

    const int nXSize = poSrcDS->GetRasterXSize();
    const int nYSize = poSrcDS->GetRasterYSize();

    // Set the number of rows
    json_object_object_add(poJSONObject, "rows", json_object_new_int(nYSize));
    // Set the number of columns
    json_object_object_add(poJSONObject, "cols", json_object_new_int(nXSize));
    // Set the xmin
    json_object_object_add(poJSONObject, "xmin", json_object_new_double(adfTransform[0]));
    // Set the ymax
    json_object_object_add(poJSONObject, "ymax", json_object_new_double(adfTransform[3]));
    // Set the cellwidth
    json_object_object_add(poJSONObject, "cellwidth", json_object_new_double(adfTransform[1]));
    // Set the cellheight
    json_object_object_add(poJSONObject, "cellheight", json_object_new_double(-adfTransform[5]));
    // Set the xmax
    json_object_object_add(poJSONObject, "xmax", json_object_new_double(adfTransform[0] + nXSize * adfTransform[1]));
    // Set the ymin
    json_object_object_add(poJSONObject, "ymin", json_object_new_double(adfTransform[3] + nYSize * adfTransform[5]));
    // Set the xskew
    json_object_object_add(poJSONObject, "xskew", json_object_new_double(adfTransform[2]));
    // Set the yskew
    json_object_object_add(poJSONObject, "yskew", json_object_new_double(adfTransform[4]));
    if (nSrs > 0) {
        // Set the epsg
        json_object_object_add(poJSONObject, "epsg", json_object_new_int(nSrs));
    }

    if (json_object_to_file(const_cast<char *>(osJSONFilename.c_str()), poJSONObject) < 0) {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "ARG driver can't write companion file.");

        json_object_put(poJSONObject);
        poJSONObject = nullptr;

        return nullptr;
    }

    json_object_put(poJSONObject);
    poJSONObject = nullptr;

    VSILFILE *fpImage = VSIFOpenL(pszFilename, "wb");
    if (fpImage == nullptr)
    {
        CPLError( CE_Failure, CPLE_NotSupported,
              "ARG driver can't create data file %s.", pszFilename);

        // remove JSON file
        VSIUnlink( osJSONFilename.c_str() );

        return nullptr;
    }

    // only 1 raster band
    GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( 1 );

#ifdef CPL_LSB
    bool bNative = false;
#else
    bool bNative = true;
#endif

    RawRasterBand *poDstBand = new RawRasterBand( fpImage, 0, nPixelOffset,
                                                  nPixelOffset * nXSize, eType,
                                                  bNative,
                                                  nXSize, nYSize,
                                                  RawRasterBand::OwnFP::NO);

    int nXBlockSize, nYBlockSize;
    poSrcBand->GetBlockSize(&nXBlockSize, &nYBlockSize);

    void *pabyData = CPLMalloc(nXBlockSize * nPixelOffset);

    // convert any blocks into scanlines
    for (int nYBlock = 0; nYBlock * nYBlockSize < nYSize; nYBlock++) {
        for (int nYScanline = 0; nYScanline < nYBlockSize; nYScanline++) {
            if ((nYScanline+1) + nYBlock * nYBlockSize > poSrcBand->GetYSize() )
            {
                continue;
            }

            for (int nXBlock = 0; nXBlock * nXBlockSize < nXSize; nXBlock++) {
                int nXValid;

                if( (nXBlock+1) * nXBlockSize > poSrcBand->GetXSize() )
                    nXValid = poSrcBand->GetXSize() - nXBlock * nXBlockSize;
                else
                    nXValid = nXBlockSize;

                CPLErr eErr = poSrcBand->RasterIO(GF_Read, nXBlock * nXBlockSize,
                    nYBlock * nYBlockSize + nYScanline, nXValid, 1, pabyData, nXBlockSize,
                    1, eType, 0, 0, nullptr);

                if (eErr != CE_None) {
                    CPLError(CE_Failure, CPLE_AppDefined, "Error reading.");

                    CPLFree( pabyData );
                    delete poDstBand;
                    VSIFCloseL( fpImage );

                    return nullptr;
                }

                eErr = poDstBand->RasterIO(GF_Write, nXBlock * nXBlockSize,
                    nYBlock * nYBlockSize + nYScanline, nXValid, 1, pabyData, nXBlockSize,
                    1, eType, 0, 0, nullptr);

                if (eErr != CE_None) {
                    CPLError(CE_Failure, CPLE_AppDefined, "Error writing.");

                    CPLFree( pabyData );
                    delete poDstBand;
                    VSIFCloseL( fpImage );

                    return nullptr;
                }
            }
        }
    }

    CPLFree( pabyData );
    delete poDstBand;
    VSIFCloseL( fpImage );

    return reinterpret_cast<GDALDataset *>( GDALOpen( pszFilename, GA_ReadOnly ) );
}
Ejemplo n.º 30
0
	bool DEM::load(const std::string& filename) {
		GDALAllRegister();

		GDALDataset* poDS;
		poDS = (GDALDataset*)GDALOpenEx(filename.c_str(), GDAL_OF_RASTER, NULL, NULL, NULL);
		if (poDS == NULL) return false;

		double adfGeoTransform[6];
		if (poDS->GetGeoTransform(adfGeoTransform) == CE_None) {
			origin.x = adfGeoTransform[0];
			origin.y = adfGeoTransform[3];

			pixelSize.x = adfGeoTransform[1];
			pixelSize.y = abs(adfGeoTransform[5]);
		}

		width = poDS->GetRasterXSize() * pixelSize.x;
		height = poDS->GetRasterYSize() * pixelSize.y;
		data.resize(width * height);
		min_val = std::numeric_limits<float>::max();
		max_val = -std::numeric_limits<float>::max();

		// bandが存在しない場合は、エラー
		if (poDS->GetRasterCount() == 0) return false;

		// 最初のbandのみを読み込む。複数bandは未対応
		GDALRasterBand* poBand = poDS->GetRasterBand(1);

		int nBlockXSize, nBlockYSize;
		poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
		//printf("Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName(poBand->GetColorInterpretation()));

		// 最低、最高の値を取得
		int bGotMin, bGotMax;
		double adfMinMax[2];
		adfMinMax[0] = poBand->GetMinimum(&bGotMin);
		adfMinMax[1] = poBand->GetMaximum(&bGotMax);
		if (!(bGotMin && bGotMax)) GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
		//printf("Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1]);
		min_val = adfMinMax[0];
		max_val = adfMinMax[1];
			
		//int nXSize = poBand->GetXSize();
		//int nYSize = poBand->GetYSize();

		int nXBlocks = (poBand->GetXSize() + nBlockXSize - 1) / nBlockXSize;
		int nYBlocks = (poBand->GetYSize() + nBlockYSize - 1) / nBlockYSize;
		float *pData = (float *)CPLMalloc(sizeof(float*) * nBlockXSize * nBlockYSize);
		for (int iYBlock = 0; iYBlock < nYBlocks; iYBlock++) {
			for (int iXBlock = 0; iXBlock < nXBlocks; iXBlock++) {
				int nXValid, nYValid;

				poBand->ReadBlock(iXBlock, iYBlock, pData);

				// Compute the portion of the block that is valid
				// for partial edge blocks.
				if ((iXBlock + 1) * nBlockXSize > poBand->GetXSize())
					nXValid = poBand->GetXSize() - iXBlock * nBlockXSize;
				else
					nXValid = nBlockXSize;
				if ((iYBlock + 1) * nBlockYSize > poBand->GetYSize())
					nYValid = poBand->GetYSize() - iYBlock * nBlockYSize;
				else
					nYValid = nBlockYSize;

				for (int iY = 0; iY < nYValid; iY++) {
					for (int iX = 0; iX < nXValid; iX++) {
						float val;
						if (pData[iY * nBlockXSize + iX] > max_val) {
							val = max_val;
						}
						else if (pData[iY * nBlockXSize + iX] < min_val) {
							val = min_val;
						}
						else {
							val = pData[iY * nBlockXSize + iX];
						}

						for (int y = 0; y < pixelSize.y; ++y) {
							for (int x = 0; x < pixelSize.x; ++x) {
								data[((iYBlock * nBlockYSize + iY) * pixelSize.y + y) * width + (iXBlock * nBlockXSize + iX) * pixelSize.x + x] = val;
							}
						}
						
					}
				}
			}
		}

		GDALClose(poDS);

		return true;
	}