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; }
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; } }
SEXP RGDAL_GetColorInterp(SEXP sxpRasterBand) { GDALRasterBand *pRasterBand = getGDALRasterPtr(sxpRasterBand); GDALColorInterp eCI = pRasterBand->GetColorInterpretation(); return(mkString_safe(GDALGetColorInterpretationName(eCI))); }
SEXP RGDAL_GetColorInterp(SEXP sxpRasterBand) { GDALRasterBand *pRasterBand = getGDALRasterPtr(sxpRasterBand); installErrorHandler(); GDALColorInterp eCI = pRasterBand->GetColorInterpretation(); uninstallErrorHandlerAndTriggerError(); installErrorHandler(); const char *desc = GDALGetColorInterpretationName(eCI); uninstallErrorHandlerAndTriggerError(); return(mkString_safe(desc)); }
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; }
CPLXMLNode *GDALPamRasterBand::SerializeToXML( const char *pszUnused ) { if( psPam == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Setup root node and attributes. */ /* -------------------------------------------------------------------- */ CPLString oFmt; CPLXMLNode *psTree; psTree = CPLCreateXMLNode( NULL, CXT_Element, "PAMRasterBand" ); if( GetBand() > 0 ) CPLSetXMLValue( psTree, "#band", oFmt.Printf( "%d", GetBand() ) ); /* -------------------------------------------------------------------- */ /* Serialize information of interest. */ /* -------------------------------------------------------------------- */ if( strlen(GetDescription()) > 0 ) CPLSetXMLValue( psTree, "Description", GetDescription() ); if( psPam->bNoDataValueSet ) { if (CPLIsNan(psPam->dfNoDataValue)) CPLSetXMLValue( psTree, "NoDataValue", "nan" ); else CPLSetXMLValue( psTree, "NoDataValue", oFmt.Printf( "%.14E", psPam->dfNoDataValue ) ); /* hex encode real floating point values */ if( psPam->dfNoDataValue != floor(psPam->dfNoDataValue) || psPam->dfNoDataValue != atof(oFmt) ) { double dfNoDataLittleEndian; dfNoDataLittleEndian = psPam->dfNoDataValue; CPL_LSBPTR64( &dfNoDataLittleEndian ); char *pszHexEncoding = CPLBinaryToHex( 8, (GByte *) &dfNoDataLittleEndian ); CPLSetXMLValue( psTree, "NoDataValue.#le_hex_equiv",pszHexEncoding); CPLFree( pszHexEncoding ); } } if( psPam->pszUnitType != NULL ) CPLSetXMLValue( psTree, "UnitType", psPam->pszUnitType ); if( psPam->dfOffset != 0.0 ) CPLSetXMLValue( psTree, "Offset", oFmt.Printf( "%.16g", psPam->dfOffset ) ); if( psPam->dfScale != 1.0 ) CPLSetXMLValue( psTree, "Scale", oFmt.Printf( "%.16g", psPam->dfScale ) ); if( psPam->eColorInterp != GCI_Undefined ) CPLSetXMLValue( psTree, "ColorInterp", GDALGetColorInterpretationName( psPam->eColorInterp )); /* -------------------------------------------------------------------- */ /* Category names. */ /* -------------------------------------------------------------------- */ if( psPam->papszCategoryNames != NULL ) { CPLXMLNode *psCT_XML = CPLCreateXMLNode( psTree, CXT_Element, "CategoryNames" ); for( int iEntry=0; psPam->papszCategoryNames[iEntry] != NULL; iEntry++) { CPLCreateXMLElementAndValue( psCT_XML, "Category", psPam->papszCategoryNames[iEntry] ); } } /* -------------------------------------------------------------------- */ /* Color Table. */ /* -------------------------------------------------------------------- */ if( psPam->poColorTable != NULL ) { CPLXMLNode *psCT_XML = CPLCreateXMLNode( psTree, CXT_Element, "ColorTable" ); for( int iEntry=0; iEntry < psPam->poColorTable->GetColorEntryCount(); iEntry++ ) { GDALColorEntry sEntry; CPLXMLNode *psEntry_XML = CPLCreateXMLNode( psCT_XML, CXT_Element, "Entry" ); psPam->poColorTable->GetColorEntryAsRGB( iEntry, &sEntry ); CPLSetXMLValue( psEntry_XML, "#c1", oFmt.Printf("%d",sEntry.c1) ); CPLSetXMLValue( psEntry_XML, "#c2", oFmt.Printf("%d",sEntry.c2) ); CPLSetXMLValue( psEntry_XML, "#c3", oFmt.Printf("%d",sEntry.c3) ); CPLSetXMLValue( psEntry_XML, "#c4", oFmt.Printf("%d",sEntry.c4) ); } } /* -------------------------------------------------------------------- */ /* Min/max. */ /* -------------------------------------------------------------------- */ if( psPam->bHaveMinMax ) { CPLSetXMLValue( psTree, "Minimum", oFmt.Printf( "%.16g", psPam->dfMin ) ); CPLSetXMLValue( psTree, "Maximum", oFmt.Printf( "%.16g", psPam->dfMax ) ); } /* -------------------------------------------------------------------- */ /* Statistics */ /* -------------------------------------------------------------------- */ if( psPam->bHaveStats ) { CPLSetXMLValue( psTree, "Mean", oFmt.Printf( "%.16g", psPam->dfMean ) ); CPLSetXMLValue( psTree, "StandardDeviation", oFmt.Printf( "%.16g", psPam->dfStdDev ) ); } /* -------------------------------------------------------------------- */ /* Histograms. */ /* -------------------------------------------------------------------- */ if( psPam->psSavedHistograms != NULL ) CPLAddXMLChild( psTree, CPLCloneXMLTree( psPam->psSavedHistograms ) ); /* -------------------------------------------------------------------- */ /* Raster Attribute Table */ /* -------------------------------------------------------------------- */ if( psPam->poDefaultRAT != NULL ) CPLAddXMLChild( psTree, psPam->poDefaultRAT->Serialize() ); /* -------------------------------------------------------------------- */ /* Metadata. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psMD; psMD = oMDMD.Serialize(); if( psMD != NULL ) { if( psMD->psChild == NULL ) CPLDestroyXMLNode( psMD ); else CPLAddXMLChild( psTree, psMD ); } /* -------------------------------------------------------------------- */ /* We don't want to return anything if we had no metadata to */ /* attach. */ /* -------------------------------------------------------------------- */ if( psTree->psChild == NULL || psTree->psChild->psNext == NULL ) { CPLDestroyXMLNode( psTree ); psTree = NULL; } return psTree; }
int main( int argc, char ** argv ) { GDALDatasetH hDataset; GDALRasterBandH hBand; int i, iBand; double adfGeoTransform[6]; GDALDriverH hDriver; char **papszMetadata; int bComputeMinMax = FALSE, bSample = FALSE; int bShowGCPs = TRUE, bShowMetadata = TRUE, bShowRAT=TRUE; int bStats = FALSE, bApproxStats = TRUE, iMDD; int bShowColorTable = TRUE, bComputeChecksum = FALSE; int bReportHistograms = FALSE; const char *pszFilename = NULL; char **papszExtraMDDomains = NULL, **papszFileList; const char *pszProjection = NULL; OGRCoordinateTransformationH hTransform = NULL; /* Check that we are running against at least GDAL 1.5 */ /* Note to developers : if we use newer API, please change the requirement */ if (atoi(GDALVersionInfo("VERSION_NUM")) < 1500) { fprintf(stderr, "At least, GDAL >= 1.5.0 is required for this version of %s, " "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME); exit(1); } /* Must process GDAL_SKIP before GDALAllRegister(), but we can't call */ /* GDALGeneralCmdLineProcessor before it needs the drivers to be registered */ /* for the --format or --formats options */ for( i = 1; i < argc; i++ ) { if( EQUAL(argv[i],"--config") && i + 2 < argc && EQUAL(argv[i + 1], "GDAL_SKIP") ) { CPLSetConfigOption( argv[i+1], argv[i+2] ); i += 2; } } GDALAllRegister(); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Parse arguments. */ /* -------------------------------------------------------------------- */ for( i = 1; i < argc; i++ ) { if( EQUAL(argv[i], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against GDAL %s\n", argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); return 0; } else if( EQUAL(argv[i], "-mm") ) bComputeMinMax = TRUE; else if( EQUAL(argv[i], "-hist") ) bReportHistograms = TRUE; else if( EQUAL(argv[i], "-stats") ) { bStats = TRUE; bApproxStats = FALSE; } else if( EQUAL(argv[i], "-approx_stats") ) { bStats = TRUE; bApproxStats = TRUE; } else if( EQUAL(argv[i], "-sample") ) bSample = TRUE; else if( EQUAL(argv[i], "-checksum") ) bComputeChecksum = TRUE; else if( EQUAL(argv[i], "-nogcp") ) bShowGCPs = FALSE; else if( EQUAL(argv[i], "-nomd") ) bShowMetadata = FALSE; else if( EQUAL(argv[i], "-norat") ) bShowRAT = FALSE; else if( EQUAL(argv[i], "-noct") ) bShowColorTable = FALSE; else if( EQUAL(argv[i], "-mdd") && i < argc-1 ) papszExtraMDDomains = CSLAddString( papszExtraMDDomains, argv[++i] ); else if( argv[i][0] == '-' ) Usage(); else if( pszFilename == NULL ) pszFilename = argv[i]; else Usage(); } if( pszFilename == NULL ) Usage(); /* -------------------------------------------------------------------- */ /* Open dataset. */ /* -------------------------------------------------------------------- */ hDataset = GDALOpen( pszFilename, GA_ReadOnly ); if( hDataset == NULL ) { fprintf( stderr, "gdalinfo failed - unable to open '%s'.\n", pszFilename ); CSLDestroy( argv ); GDALDumpOpenDatasets( stderr ); GDALDestroyDriverManager(); CPLDumpSharedList( NULL ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Report general info. */ /* -------------------------------------------------------------------- */ hDriver = GDALGetDatasetDriver( hDataset ); printf( "Driver: %s/%s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver ) ); papszFileList = GDALGetFileList( hDataset ); if( CSLCount(papszFileList) == 0 ) { printf( "Files: none associated\n" ); } else { printf( "Files: %s\n", papszFileList[0] ); for( i = 1; papszFileList[i] != NULL; i++ ) printf( " %s\n", papszFileList[i] ); } CSLDestroy( papszFileList ); printf( "Size is %d, %d\n", GDALGetRasterXSize( hDataset ), GDALGetRasterYSize( hDataset ) ); /* -------------------------------------------------------------------- */ /* Report projection. */ /* -------------------------------------------------------------------- */ if( GDALGetProjectionRef( hDataset ) != NULL ) { OGRSpatialReferenceH hSRS; char *pszProjection; pszProjection = (char *) GDALGetProjectionRef( hDataset ); hSRS = OSRNewSpatialReference(NULL); if( OSRImportFromWkt( hSRS, &pszProjection ) == CE_None ) { char *pszPrettyWkt = NULL; OSRExportToPrettyWkt( hSRS, &pszPrettyWkt, FALSE ); printf( "Coordinate System is:\n%s\n", pszPrettyWkt ); CPLFree( pszPrettyWkt ); } else printf( "Coordinate System is `%s'\n", GDALGetProjectionRef( hDataset ) ); OSRDestroySpatialReference( hSRS ); } /* -------------------------------------------------------------------- */ /* Report Geotransform. */ /* -------------------------------------------------------------------- */ if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) { if( adfGeoTransform[2] == 0.0 && adfGeoTransform[4] == 0.0 ) { printf( "Origin = (%.15f,%.15f)\n", adfGeoTransform[0], adfGeoTransform[3] ); printf( "Pixel Size = (%.15f,%.15f)\n", adfGeoTransform[1], adfGeoTransform[5] ); } else printf( "GeoTransform =\n" " %.16g, %.16g, %.16g\n" " %.16g, %.16g, %.16g\n", adfGeoTransform[0], adfGeoTransform[1], adfGeoTransform[2], adfGeoTransform[3], adfGeoTransform[4], adfGeoTransform[5] ); } /* -------------------------------------------------------------------- */ /* Report GCPs. */ /* -------------------------------------------------------------------- */ if( bShowGCPs && GDALGetGCPCount( hDataset ) > 0 ) { if (GDALGetGCPProjection(hDataset) != NULL) { OGRSpatialReferenceH hSRS; char *pszProjection; pszProjection = (char *) GDALGetGCPProjection( hDataset ); hSRS = OSRNewSpatialReference(NULL); if( OSRImportFromWkt( hSRS, &pszProjection ) == CE_None ) { char *pszPrettyWkt = NULL; OSRExportToPrettyWkt( hSRS, &pszPrettyWkt, FALSE ); printf( "GCP Projection = \n%s\n", pszPrettyWkt ); CPLFree( pszPrettyWkt ); } else printf( "GCP Projection = %s\n", GDALGetGCPProjection( hDataset ) ); OSRDestroySpatialReference( hSRS ); } for( i = 0; i < GDALGetGCPCount(hDataset); i++ ) { const GDAL_GCP *psGCP; psGCP = GDALGetGCPs( hDataset ) + i; printf( "GCP[%3d]: Id=%s, Info=%s\n" " (%.15g,%.15g) -> (%.15g,%.15g,%.15g)\n", i, psGCP->pszId, psGCP->pszInfo, psGCP->dfGCPPixel, psGCP->dfGCPLine, psGCP->dfGCPX, psGCP->dfGCPY, psGCP->dfGCPZ ); } } /* -------------------------------------------------------------------- */ /* Report metadata. */ /* -------------------------------------------------------------------- */ papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, NULL ) : NULL; if( bShowMetadata && CSLCount(papszMetadata) > 0 ) { printf( "Metadata:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } for( iMDD = 0; bShowMetadata && iMDD < CSLCount(papszExtraMDDomains); iMDD++ ) { papszMetadata = GDALGetMetadata( hDataset, papszExtraMDDomains[iMDD] ); if( CSLCount(papszMetadata) > 0 ) { printf( "Metadata (%s):\n", papszExtraMDDomains[iMDD]); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } } /* -------------------------------------------------------------------- */ /* Report "IMAGE_STRUCTURE" metadata. */ /* -------------------------------------------------------------------- */ papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, "IMAGE_STRUCTURE" ) : NULL; if( bShowMetadata && CSLCount(papszMetadata) > 0 ) { printf( "Image Structure Metadata:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } /* -------------------------------------------------------------------- */ /* Report subdatasets. */ /* -------------------------------------------------------------------- */ papszMetadata = GDALGetMetadata( hDataset, "SUBDATASETS" ); if( CSLCount(papszMetadata) > 0 ) { printf( "Subdatasets:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } /* -------------------------------------------------------------------- */ /* Report geolocation. */ /* -------------------------------------------------------------------- */ papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, "GEOLOCATION" ) : NULL; if( bShowMetadata && CSLCount(papszMetadata) > 0 ) { printf( "Geolocation:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } /* -------------------------------------------------------------------- */ /* Report RPCs */ /* -------------------------------------------------------------------- */ papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, "RPC" ) : NULL; if( bShowMetadata && CSLCount(papszMetadata) > 0 ) { printf( "RPC Metadata:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } /* -------------------------------------------------------------------- */ /* Setup projected to lat/long transform if appropriate. */ /* -------------------------------------------------------------------- */ if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) pszProjection = GDALGetProjectionRef(hDataset); if( pszProjection != NULL && strlen(pszProjection) > 0 ) { OGRSpatialReferenceH hProj, hLatLong = NULL; hProj = OSRNewSpatialReference( pszProjection ); if( hProj != NULL ) hLatLong = OSRCloneGeogCS( hProj ); if( hLatLong != NULL ) { CPLPushErrorHandler( CPLQuietErrorHandler ); hTransform = OCTNewCoordinateTransformation( hProj, hLatLong ); CPLPopErrorHandler(); OSRDestroySpatialReference( hLatLong ); } if( hProj != NULL ) OSRDestroySpatialReference( hProj ); } /* -------------------------------------------------------------------- */ /* Report corners. */ /* -------------------------------------------------------------------- */ printf( "Corner Coordinates:\n" ); GDALInfoReportCorner( hDataset, hTransform, "Upper Left", 0.0, 0.0 ); GDALInfoReportCorner( hDataset, hTransform, "Lower Left", 0.0, GDALGetRasterYSize(hDataset)); GDALInfoReportCorner( hDataset, hTransform, "Upper Right", GDALGetRasterXSize(hDataset), 0.0 ); GDALInfoReportCorner( hDataset, hTransform, "Lower Right", GDALGetRasterXSize(hDataset), GDALGetRasterYSize(hDataset) ); GDALInfoReportCorner( hDataset, hTransform, "Center", GDALGetRasterXSize(hDataset)/2.0, GDALGetRasterYSize(hDataset)/2.0 ); if( hTransform != NULL ) { OCTDestroyCoordinateTransformation( hTransform ); hTransform = NULL; } /* ==================================================================== */ /* Loop over bands. */ /* ==================================================================== */ for( iBand = 0; iBand < GDALGetRasterCount( hDataset ); iBand++ ) { double dfMin, dfMax, adfCMinMax[2], dfNoData; int bGotMin, bGotMax, bGotNodata, bSuccess; int nBlockXSize, nBlockYSize, nMaskFlags; double dfMean, dfStdDev; GDALColorTableH hTable; CPLErr eErr; hBand = GDALGetRasterBand( hDataset, iBand+1 ); if( bSample ) { float afSample[10000]; int nCount; nCount = GDALGetRandomRasterSample( hBand, 10000, afSample ); printf( "Got %d samples.\n", nCount ); } GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize ); printf( "Band %d Block=%dx%d Type=%s, ColorInterp=%s\n", iBand+1, nBlockXSize, nBlockYSize, GDALGetDataTypeName( GDALGetRasterDataType(hBand)), GDALGetColorInterpretationName( GDALGetRasterColorInterpretation(hBand)) ); if( GDALGetDescription( hBand ) != NULL && strlen(GDALGetDescription( hBand )) > 0 ) printf( " Description = %s\n", GDALGetDescription(hBand) ); dfMin = GDALGetRasterMinimum( hBand, &bGotMin ); dfMax = GDALGetRasterMaximum( hBand, &bGotMax ); if( bGotMin || bGotMax || bComputeMinMax ) { printf( " " ); if( bGotMin ) printf( "Min=%.3f ", dfMin ); if( bGotMax ) printf( "Max=%.3f ", dfMax ); if( bComputeMinMax ) { CPLErrorReset(); GDALComputeRasterMinMax( hBand, FALSE, adfCMinMax ); if (CPLGetLastErrorType() == CE_None) { printf( " Computed Min/Max=%.3f,%.3f", adfCMinMax[0], adfCMinMax[1] ); } } printf( "\n" ); } eErr = GDALGetRasterStatistics( hBand, bApproxStats, bStats, &dfMin, &dfMax, &dfMean, &dfStdDev ); if( eErr == CE_None ) { printf( " Minimum=%.3f, Maximum=%.3f, Mean=%.3f, StdDev=%.3f\n", dfMin, dfMax, dfMean, dfStdDev ); } if( bReportHistograms ) { int nBucketCount, *panHistogram = NULL; eErr = GDALGetDefaultHistogram( hBand, &dfMin, &dfMax, &nBucketCount, &panHistogram, TRUE, GDALTermProgress, NULL ); if( eErr == CE_None ) { int iBucket; printf( " %d buckets from %g to %g:\n ", nBucketCount, dfMin, dfMax ); for( iBucket = 0; iBucket < nBucketCount; iBucket++ ) printf( "%d ", panHistogram[iBucket] ); printf( "\n" ); CPLFree( panHistogram ); } } if ( bComputeChecksum) { printf( " Checksum=%d\n", GDALChecksumImage(hBand, 0, 0, GDALGetRasterXSize(hDataset), GDALGetRasterYSize(hDataset))); } dfNoData = GDALGetRasterNoDataValue( hBand, &bGotNodata ); if( bGotNodata ) { printf( " NoData Value=%.18g\n", dfNoData ); } if( GDALGetOverviewCount(hBand) > 0 ) { int iOverview; printf( " Overviews: " ); for( iOverview = 0; iOverview < GDALGetOverviewCount(hBand); iOverview++ ) { GDALRasterBandH hOverview; const char *pszResampling = NULL; if( iOverview != 0 ) printf( ", " ); hOverview = GDALGetOverview( hBand, iOverview ); printf( "%dx%d", GDALGetRasterBandXSize( hOverview ), GDALGetRasterBandYSize( hOverview ) ); pszResampling = GDALGetMetadataItem( hOverview, "RESAMPLING", "" ); if( pszResampling != NULL && EQUALN(pszResampling,"AVERAGE_BIT2",12) ) printf( "*" ); } printf( "\n" ); if ( bComputeChecksum) { printf( " Overviews checksum: " ); for( iOverview = 0; iOverview < GDALGetOverviewCount(hBand); iOverview++ ) { GDALRasterBandH hOverview; if( iOverview != 0 ) printf( ", " ); hOverview = GDALGetOverview( hBand, iOverview ); printf( "%d", GDALChecksumImage(hOverview, 0, 0, GDALGetRasterBandXSize(hOverview), GDALGetRasterBandYSize(hOverview))); } printf( "\n" ); } } if( GDALHasArbitraryOverviews( hBand ) ) { printf( " Overviews: arbitrary\n" ); } nMaskFlags = GDALGetMaskFlags( hBand ); if( (nMaskFlags & (GMF_NODATA|GMF_ALL_VALID)) == 0 ) { GDALRasterBandH hMaskBand = GDALGetMaskBand(hBand) ; printf( " Mask Flags: " ); if( nMaskFlags & GMF_PER_DATASET ) printf( "PER_DATASET " ); if( nMaskFlags & GMF_ALPHA ) printf( "ALPHA " ); if( nMaskFlags & GMF_NODATA ) printf( "NODATA " ); if( nMaskFlags & GMF_ALL_VALID ) printf( "ALL_VALID " ); printf( "\n" ); if( hMaskBand != NULL && GDALGetOverviewCount(hMaskBand) > 0 ) { int iOverview; printf( " Overviews of mask band: " ); for( iOverview = 0; iOverview < GDALGetOverviewCount(hMaskBand); iOverview++ ) { GDALRasterBandH hOverview; if( iOverview != 0 ) printf( ", " ); hOverview = GDALGetOverview( hMaskBand, iOverview ); printf( "%dx%d", GDALGetRasterBandXSize( hOverview ), GDALGetRasterBandYSize( hOverview ) ); } printf( "\n" ); } } if( strlen(GDALGetRasterUnitType(hBand)) > 0 ) { printf( " Unit Type: %s\n", GDALGetRasterUnitType(hBand) ); } if( GDALGetRasterCategoryNames(hBand) != NULL ) { char **papszCategories = GDALGetRasterCategoryNames(hBand); int i; printf( " Categories:\n" ); for( i = 0; papszCategories[i] != NULL; i++ ) printf( " %3d: %s\n", i, papszCategories[i] ); } if( GDALGetRasterScale( hBand, &bSuccess ) != 1.0 || GDALGetRasterOffset( hBand, &bSuccess ) != 0.0 ) printf( " Offset: %.15g, Scale:%.15g\n", GDALGetRasterOffset( hBand, &bSuccess ), GDALGetRasterScale( hBand, &bSuccess ) ); papszMetadata = (bShowMetadata) ? GDALGetMetadata( hBand, NULL ) : NULL; if( bShowMetadata && CSLCount(papszMetadata) > 0 ) { printf( " Metadata:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } papszMetadata = (bShowMetadata) ? GDALGetMetadata( hBand, "IMAGE_STRUCTURE" ) : NULL; if( bShowMetadata && CSLCount(papszMetadata) > 0 ) { printf( " Image Structure Metadata:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } if( GDALGetRasterColorInterpretation(hBand) == GCI_PaletteIndex && (hTable = GDALGetRasterColorTable( hBand )) != NULL ) { int i; printf( " Color Table (%s with %d entries)\n", GDALGetPaletteInterpretationName( GDALGetPaletteInterpretation( hTable )), GDALGetColorEntryCount( hTable ) ); if (bShowColorTable) { for( i = 0; i < GDALGetColorEntryCount( hTable ); i++ ) { GDALColorEntry sEntry; GDALGetColorEntryAsRGB( hTable, i, &sEntry ); printf( " %3d: %d,%d,%d,%d\n", i, sEntry.c1, sEntry.c2, sEntry.c3, sEntry.c4 ); } } } if( bShowRAT && GDALGetDefaultRAT( hBand ) != NULL ) { GDALRasterAttributeTableH hRAT = GDALGetDefaultRAT( hBand ); GDALRATDumpReadable( hRAT, NULL ); } } GDALClose( hDataset ); CSLDestroy( papszExtraMDDomains ); CSLDestroy( argv ); GDALDumpOpenDatasets( stderr ); GDALDestroyDriverManager(); CPLDumpSharedList( NULL ); CPLCleanupTLS(); exit( 0 ); }
/** Private method to calculate statistics for each band. Populates rasterStatsMap. */ void ImageWriter::calculateStats(RasterBandStats * theRasterBandStats,GDALDataset * gdalDataset) { std::cout << "Calculating statistics..." << std::endl; GDALRasterBand *myGdalBand = gdalDataset->GetRasterBand( 1 ); QString myColorInterpretation = GDALGetColorInterpretationName(myGdalBand->GetColorInterpretation()); theRasterBandStats->bandName=myColorInterpretation; theRasterBandStats->bandNo=1; // get the dimensions of the raster int myColsInt = myGdalBand->GetXSize(); int myRowsInt = myGdalBand->GetYSize(); theRasterBandStats->elementCountInt=myColsInt*myRowsInt; theRasterBandStats->noDataDouble=myGdalBand->GetNoDataValue(); //allocate a buffer to hold one row of ints int myAllocationSizeInt = sizeof(uint)*myColsInt; uint * myScanlineAllocInt = (uint*) CPLMalloc(myAllocationSizeInt); bool myFirstIterationFlag = true; //unfortunately we need to make two passes through the data to calculate stddev for (int myCurrentRowInt=0; myCurrentRowInt < myRowsInt;myCurrentRowInt++) { CPLErr myResult = myGdalBand->RasterIO( GF_Read, 0, myCurrentRowInt, myColsInt, 1, myScanlineAllocInt, myColsInt, 1, GDT_UInt32, 0, 0 ); for (int myCurrentColInt=0; myCurrentColInt < myColsInt; myCurrentColInt++) { //get the nth element from the current row double myDouble=myScanlineAllocInt[myCurrentColInt]; //only use this element if we have a non null element if (myDouble != theRasterBandStats->noDataDouble ) { if (myFirstIterationFlag) { //this is the first iteration so initialise vars myFirstIterationFlag=false; theRasterBandStats->minValDouble=myDouble; theRasterBandStats->maxValDouble=myDouble; } //end of true part for first iteration check else { //this is done for all subsequent iterations if (myDouble < theRasterBandStats->minValDouble) { theRasterBandStats->minValDouble=myDouble; } if (myDouble > theRasterBandStats->maxValDouble) { // printf ("Maxval updated to %f\n",myDouble); theRasterBandStats->maxValDouble=myDouble; } //only increment the running total if it is not a nodata value if (myDouble != theRasterBandStats->noDataDouble) { theRasterBandStats->sumDouble += myDouble; ++theRasterBandStats->elementCountInt; } } //end of false part for first iteration check } //end of nodata chec } //end of column wise loop } //end of row wise loop // //end of first pass through data now calculate the range theRasterBandStats->rangeDouble = theRasterBandStats->maxValDouble-theRasterBandStats->minValDouble; //calculate the mean theRasterBandStats->meanDouble = theRasterBandStats->sumDouble / theRasterBandStats->elementCountInt; //for the second pass we will get the sum of the squares / mean for (int myCurrentRowInt=0; myCurrentRowInt < myRowsInt;myCurrentRowInt++) { CPLErr myResult = myGdalBand->RasterIO( GF_Read, 0, myCurrentRowInt, myColsInt, 1, myScanlineAllocInt, myColsInt, 1, GDT_UInt32, 0, 0 ); for (int myCurrentColInt=0; myCurrentColInt < myColsInt; myCurrentColInt++) { //get the nth element from the current row double myDouble=myScanlineAllocInt[myCurrentColInt]; theRasterBandStats->sumSqrDevDouble += static_cast<double>(pow(myDouble - theRasterBandStats->meanDouble,2)); } //end of column wise loop } //end of row wise loop //divide result by sample size - 1 and get square root to get stdev theRasterBandStats->stdDevDouble = static_cast<double>(sqrt(theRasterBandStats->sumSqrDevDouble / (theRasterBandStats->elementCountInt - 1))); CPLFree(myScanlineAllocInt); //printf("CalculateStats::\n"); //std::cout << "Band Name : " << theRasterBandStats->bandName << std::endl; //printf("Band No : %i\n",theRasterBandStats->bandNo); //printf("Band min : %f\n",theRasterBandStats->minValDouble); //printf("Band max : %f\n",theRasterBandStats->maxValDouble); //printf("Band range: %f\n",theRasterBandStats->rangeDouble); //printf("Band mean : %f\n",theRasterBandStats->meanDouble); //printf("Band sum : %f\n",theRasterBandStats->sumDouble); return ; }
int fitGetColorModel(GDALColorInterp colorInterp, int nBands) { // XXX - shoould check colorInterp for all bands, not just first one switch(colorInterp) { case GCI_GrayIndex: switch (nBands) { case 1: return 2; // iflLuminance - luminance case 2: return 13; // iflLuminanceAlpha - Luminance plus alpha default: UNSUPPORTED_COMBO(); } // switch case GCI_PaletteIndex: CPLError(CE_Failure, CPLE_NotSupported, "FIT write - unsupported ColorInterp PaletteIndex\n"); return 0; case GCI_RedBand: switch (nBands) { case 3: return 3; // iflRGB - full color (Red, Green, Blue triplets) case 4: return 5; // iflRGBA - full color with transparency (alpha channel) default: UNSUPPORTED_COMBO(); } // switch case GCI_BlueBand: switch (nBands) { case 3: return 9; // iflBGR - full color (ordered Blue, Green, Red) default: UNSUPPORTED_COMBO(); } // switch case GCI_AlphaBand: switch (nBands) { case 4: return 10; // iflABGR - Alpha, Blue, Green, Red (SGI frame buffers) default: UNSUPPORTED_COMBO(); } // switch case GCI_HueBand: switch (nBands) { case 3: return 6; // iflHSV - Hue, Saturation, Value default: UNSUPPORTED_COMBO(); } // switch case GCI_CyanBand: switch (nBands) { case 3: return 7; // iflCMY - Cyan, Magenta, Yellow case 4: return 8; // iflCMYK - Cyan, Magenta, Yellow, Black default: UNSUPPORTED_COMBO(); } // switch case GCI_GreenBand: case GCI_SaturationBand: case GCI_LightnessBand: case GCI_MagentaBand: case GCI_YellowBand: case GCI_BlackBand: CPLError(CE_Failure, CPLE_NotSupported, "FIT write - unsupported combination (band 1 = %s) " "- ignoring color model", GDALGetColorInterpretationName(colorInterp)); return 0; default: CPLDebug("FIT write", "unrecognized colorInterp %i - deriving from " "number of bands (%i)", colorInterp, nBands); switch (nBands) { case 1: return 2; // iflLuminance - luminance case 2: return 13; // iflLuminanceAlpha - Luminance plus alpha case 3: return 3; // iflRGB - full color (Red, Green, Blue triplets) case 4: return 5; // iflRGBA - full color with transparency (alpha channel) } // switch CPLError(CE_Failure, CPLE_NotSupported, "FIT write - unrecognized colorInterp %i and " "unrecognized number of bands (%i)", colorInterp, nBands); return 0; } // switch }
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; }
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; }
bool GdalAdapter::loadImage(const QString& fn) { if (alreadyLoaded(fn)) return true; QFileInfo fi(fn); GdalImage img; QRectF bbox; poDataset = (GDALDataset *) GDALOpen( QDir::toNativeSeparators(fi.absoluteFilePath()).toUtf8().constData(), GA_ReadOnly ); if( poDataset == NULL ) { qDebug() << "GDAL Open failed: " << fn; return false; } bool hasGeo = false; QDir dir(fi.absoluteDir()); QString f = fi.baseName(); QStringList wldFilter; wldFilter << f+".tfw" << f+".tifw" << f+".tiffw" << f+".wld"; QFileInfoList fil = dir.entryInfoList(wldFilter); if (fil.count()) { QFile wld(fil[0].absoluteFilePath()); if (wld.open(QIODevice::ReadOnly)) { int i; for (i=0; i<6; ++i) { if (wld.atEnd()) break; QString l = wld.readLine(); bool ok; double d = l.toDouble(&ok); if (!ok) break; switch (i) { case 0: img.adfGeoTransform[1] = d; break; case 1: img.adfGeoTransform[4] = d; break; case 2: img.adfGeoTransform[2] = d; break; case 3: img.adfGeoTransform[5] = d; break; case 4: img.adfGeoTransform[0] = d; break; case 5: img.adfGeoTransform[3] = d; break; } } if (i == 6) hasGeo = true; } } if(!hasGeo) if ( poDataset->GetGeoTransform( img.adfGeoTransform ) != CE_None ) { GDALClose((GDALDatasetH)poDataset); return false; } qDebug( "Origin = (%.6f,%.6f)\n", img.adfGeoTransform[0], img.adfGeoTransform[3] ); qDebug( "Pixel Size = (%.6f,%.6f)\n", img.adfGeoTransform[1], img.adfGeoTransform[5] ); bbox.setTopLeft(QPointF(img.adfGeoTransform[0], img.adfGeoTransform[3])); bbox.setWidth(img.adfGeoTransform[1]*poDataset->GetRasterXSize()); bbox.setHeight(img.adfGeoTransform[5]*poDataset->GetRasterYSize()); isLatLon = false; if( strlen(poDataset->GetProjectionRef()) != 0 ) { qDebug( "Projection is `%s'\n", poDataset->GetProjectionRef() ); OGRSpatialReference* theSrs = new OGRSpatialReference(poDataset->GetProjectionRef()); if (theSrs && theSrs->Validate() == OGRERR_NONE) { theSrs->morphFromESRI(); char* theProj4; if (theSrs->exportToProj4(&theProj4) == OGRERR_NONE) { qDebug() << "GDAL: to proj4 : " << theProj4; } else { qDebug() << "GDAL: to proj4 error: " << CPLGetLastErrorMsg(); GDALClose((GDALDatasetH)poDataset); return false; } QString srsProj = QString(theProj4); if (!srsProj.isEmpty() && theProjection != srsProj) { cleanup(); theProjection = srsProj; } isLatLon = (theSrs->IsGeographic() == TRUE); } } if (theProjection.isEmpty()) { theProjection = ProjectionChooser::getProjection(QCoreApplication::translate("ImportExportGdal", "Unable to set projection; please specify one")); if (theProjection.isEmpty()) { GDALClose((GDALDatasetH)poDataset); return false; } } qDebug( "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); qDebug( "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() ); GdalAdapter::ImgType theType = GdalAdapter::Unknown; int bandCount = poDataset->GetRasterCount(); int ixA = -1; int ixR, ixG, ixB; int ixH, ixS, ixL; int ixC, ixM, ixY, ixK; int ixYuvY, ixYuvU, ixYuvV; double adfMinMax[2]; double UnknownUnit; GDALColorTable* colTable = NULL; for (int i=0; i<bandCount; ++i) { GDALRasterBand *poBand = poDataset->GetRasterBand( i+1 ); GDALColorInterp bandtype = poBand->GetColorInterpretation(); qDebug() << "Band " << i+1 << " Color: " << GDALGetColorInterpretationName(poBand->GetColorInterpretation()); switch (bandtype) { case GCI_Undefined: theType = GdalAdapter::Unknown; int bGotMin, bGotMax; adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); UnknownUnit = (adfMinMax[1] - adfMinMax[0]) / 256; break; case GCI_GrayIndex: theType = GdalAdapter::GrayScale; break; case GCI_RedBand: theType = GdalAdapter::Rgb; ixR = i; break; case GCI_GreenBand: theType = GdalAdapter::Rgb; ixG = i; break; case GCI_BlueBand : theType = GdalAdapter::Rgb; ixB = i; break; case GCI_HueBand: theType = GdalAdapter::Hsl; ixH = i; break; case GCI_SaturationBand: theType = GdalAdapter::Hsl; ixS = i; break; case GCI_LightnessBand: theType = GdalAdapter::Hsl; ixL = i; break; case GCI_CyanBand: theType = GdalAdapter::Cmyk; ixC = i; break; case GCI_MagentaBand: theType = GdalAdapter::Cmyk; ixM = i; break; case GCI_YellowBand: theType = GdalAdapter::Cmyk; ixY = i; break; case GCI_BlackBand: theType = GdalAdapter::Cmyk; ixK = i; break; case GCI_YCbCr_YBand: theType = GdalAdapter::YUV; ixYuvY = i; break; case GCI_YCbCr_CbBand: theType = GdalAdapter::YUV; ixYuvU = i; break; case GCI_YCbCr_CrBand: theType = GdalAdapter::YUV; ixYuvV = i; break; case GCI_AlphaBand: ixA = i; break; case GCI_PaletteIndex: colTable = poBand->GetColorTable(); switch (colTable->GetPaletteInterpretation()) { case GPI_Gray : theType = GdalAdapter::Palette_Gray; break; case GPI_RGB : theType = GdalAdapter::Palette_RGBA; break; case GPI_CMYK : theType = GdalAdapter::Palette_CMYK; break; case GPI_HLS : theType = GdalAdapter::Palette_HLS; break; } break; } } QSize theImgSize(poDataset->GetRasterXSize(), poDataset->GetRasterYSize()); QImage theImg = QImage(theImgSize, QImage::Format_ARGB32); // Make sure that lineBuf holds one whole line of data. float *lineBuf; lineBuf = (float *) CPLMalloc(theImgSize.width() * bandCount * sizeof(float)); int px, py; //every row loop for (int row = 0; row < theImgSize.height(); row++) { py = row; poDataset->RasterIO( GF_Read, 0, row, theImgSize.width(), 1, lineBuf, theImgSize.width(), 1, GDT_Float32, bandCount, NULL, sizeof(float) * bandCount, 0, sizeof(float) ); // every pixel in row. for (int col = 0; col < theImgSize.width(); col++){ px = col; switch (theType) { case GdalAdapter::Unknown: { float* v = lineBuf + (col*bandCount); float val = (*v - adfMinMax[0]) / UnknownUnit; theImg.setPixel(px, py, qRgb(val, val, val)); break; } case GdalAdapter::GrayScale: { float* v = lineBuf + (col*bandCount); theImg.setPixel(px, py, qRgb(*v, *v, *v)); break; } case GdalAdapter::Rgb: { float* r = lineBuf + (col*bandCount) + ixR; float* g = lineBuf + (col*bandCount) + ixG; float* b = lineBuf + (col*bandCount) + ixB; int a = 255; if (ixA != -1) { float* fa = lineBuf + (col*bandCount) + ixA; a = *fa; } theImg.setPixel(px, py, qRgba(*r, *g, *b, a)); break; } #if QT_VERSION >= 0x040600 case GdalAdapter::Hsl: { float* h = lineBuf + (col*bandCount) + ixH; float* s = lineBuf + (col*bandCount) + ixS; float* l = lineBuf + (col*bandCount) + ixL; int a = 255; if (ixA != -1) { float* fa = lineBuf + (col*bandCount) + ixA; a = *fa; } QColor C = QColor::fromHsl(*h, *s, *l, a); theImg.setPixel(px, py, C.rgba()); break; } #endif case GdalAdapter::Cmyk: { float* c = lineBuf + (col*bandCount) + ixC; float* m = lineBuf + (col*bandCount) + ixM; float* y = lineBuf + (col*bandCount) + ixY; float* k = lineBuf + (col*bandCount) + ixK; int a = 255; if (ixA != -1) { float* fa = lineBuf + (col*bandCount) + ixA; a = *fa; } QColor C = QColor::fromCmyk(*c, *m, *y, *k, a); theImg.setPixel(px, py, C.rgba()); break; } case GdalAdapter::YUV: { // From http://www.fourcc.org/fccyvrgb.php float* y = lineBuf + (col*bandCount) + ixYuvY; float* u = lineBuf + (col*bandCount) + ixYuvU; float* v = lineBuf + (col*bandCount) + ixYuvV; int a = 255; if (ixA != -1) { float* fa = lineBuf + (col*bandCount) + ixA; a = *fa; } float R = 1.164*(*y - 16) + 1.596*(*v - 128); float G = 1.164*(*y - 16) - 0.813*(*v - 128) - 0.391*(*u - 128); float B = 1.164*(*y - 16) + 2.018*(*u - 128); theImg.setPixel(px, py, qRgba(R, G, B, a)); break; } case GdalAdapter::Palette_Gray: { float* ix = (lineBuf + (col*bandCount)); const GDALColorEntry* color = colTable->GetColorEntry(*ix); theImg.setPixel(px, py, qRgb(color->c1, color->c1, color->c1)); break; } case GdalAdapter::Palette_RGBA: { float* ix = (lineBuf + (col*bandCount)); const GDALColorEntry* color = colTable->GetColorEntry(*ix); theImg.setPixel(px, py, qRgba(color->c1, color->c2, color->c3, color->c4)); break; } #if QT_VERSION >= 0x040600 case GdalAdapter::Palette_HLS: { float* ix = (lineBuf + (col*bandCount)); const GDALColorEntry* color = colTable->GetColorEntry(*ix); QColor C = QColor::fromHsl(color->c1, color->c2, color->c3, color->c4); theImg.setPixel(px, py, C.rgba()); break; } #endif case GdalAdapter::Palette_CMYK: { float* ix = (lineBuf + (col*bandCount)); const GDALColorEntry* color = colTable->GetColorEntry(*ix); QColor C = QColor::fromCmyk(color->c1, color->c2, color->c3, color->c4); theImg.setPixel(px, py, C.rgba()); break; } } } QCoreApplication::processEvents(); } img.theFilename = fn; img.theImg = QPixmap::fromImage(theImg); theImages.push_back(img); theBbox = theBbox.united(bbox); GDALClose((GDALDatasetH)poDataset); return true; }
int main(void) { GDALAllRegister(); /*Open a file*/ GDALDatasetH hDataset; hDataset = GDALOpen( "./dem.tif", GA_ReadOnly ); if( hDataset == NULL ) printf("The dataset is NULL!\n"); /*Getting Dasetset Information*/ GDALDriverH hDriver; double adfGeoTransform[6]; hDriver = GDALGetDatasetDriver( hDataset ); printf( "Driver: %s/%s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver )); printf("Size is %dx%dx%d\n", GDALGetRasterXSize( hDataset ), GDALGetRasterYSize( hDataset ), GDALGetRasterCount( hDataset )); if( GDALGetProjectionRef( hDataset ) != NULL ) printf("Projection is '%s'\n", GDALGetProjectionRef( hDataset ) ); if (GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) { printf("Origin = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3]); printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[5]); } /*Fetching a Raster Band*/ GDALRasterBandH hBand; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; double adfMinMax[2]; hBand = GDALGetRasterBand( hDataset, 1); GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(GDALGetRasterDataType(hBand)), GDALGetColorInterpretationName( GDALGetRasterColorInterpretation(hBand)) ); adfMinMax[0] = GDALGetRasterMinimum( hBand, &bGotMin ); adfMinMax[1] = GDALGetRasterMaximum( hBand, &bGotMax ); if( !(bGotMin && bGotMax) ) { GDALComputeRasterMinMax( hBand, TRUE, adfMinMax ); } printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1]); if(GDALGetOverviewCount(hBand) > 0) printf( "Band has %d overviews.\n", GDALGetOverviewCount(hBand)); if( GDALGetRasterColorTable( hBand ) != NULL) printf( "Band has a color table with %d entries.\n", GDALGetColorEntryCount( GDALGetRasterColorTable( hBand))); /*Reading Raster Data*/ float *pafScanline; int nXSize = GDALGetRasterBandXSize( hBand ); pafScanline = (float *)CPLMalloc(sizeof(float)*nXSize); GDALRasterIO(hBand, GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0); CPLFree(pafScanline); return 0; }
int main (int argc, const char *argv[]) { GDALDriverH hDriver; double adfGeoTransform[6]; GDALDatasetH in_Dataset; GDALDatasetH out_Dataset; double *data_scan_line; char *out_scan_line; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; int bands; int xsize; double lower_fiddle, upper_fiddle; double adfMinMax[2]; /* These are hard coded for now - need to figure out a better way to handle this.. */ double palette_in[256] = { 0.0, 1.00011, 1.9999649999999998, 3.000075, 3.9999299999999995, 5.00004, 5.999895, 7.000005, 8.000115, 8.99997, 10.00008, 10.999935, 12.000044999999998, 12.9999, 14.00001, 15.00012, 15.999975, 17.000085000000002, 17.99994, 19.00005, 19.999905000000002, 21.000014999999998, 22.000125, 22.99998, 24.000089999999997, 24.999945, 26.000055, 26.99991, 28.00002, 28.999875000000003, 29.999985, 31.000094999999998, 31.99995, 33.00006, 33.999915, 35.000024999999994, 35.99988, 36.999990000000004, 38.0001, 38.999955, 40.000065, 40.99992, 42.000029999999995, 42.999885, 43.999995000000006, 45.000105, 45.99996, 47.00007, 47.999925000000005, 49.000035, 49.99989, 51.0, 52.00011, 52.999965, 54.000075, 54.99993, 56.00004, 56.999895, 58.000004999999994, 59.000115, 59.99997, 61.000080000000004, 61.999935, 63.000045, 63.9999, 65.00001, 66.00012, 66.999975, 68.000085, 68.99994, 70.00004999999999, 70.999905, 72.000015, 73.000125, 73.99998000000001, 75.00009, 75.999945, 77.00005499999999, 77.99991, 79.00002, 79.99987499999999, 80.99998500000001, 82.000095, 82.99995, 84.00005999999999, 84.999915, 86.00002500000001, 86.99987999999999, 87.99999000000001, 89.0001, 89.999955, 91.00006499999999, 91.99992, 93.00003, 93.99988499999999, 94.999995, 96.000105, 96.99996, 98.00007, 98.999925, 100.000035, 100.99989, 102.0, 103.00011, 103.999965, 105.000075, 105.99993, 107.00004, 107.999895, 109.000005, 110.00011500000001, 110.99997, 112.00008, 112.99993500000001, 114.000045, 114.9999, 116.00000999999999, 117.00012, 117.999975, 119.000085, 119.99994, 121.00005, 121.999905, 123.00001499999999, 124.000125, 124.99998000000001, 126.00009, 126.999945, 128.000055, 128.99991, 130.00002, 130.999875, 131.99998499999998, 133.000095, 133.99995, 135.00006, 135.999915, 137.00002500000002, 137.99988, 138.99999, 140.00009999999997, 140.999955, 142.000065, 142.99991999999997, 144.00003, 144.999885, 145.99999499999998, 147.000105, 147.99996000000002, 149.00007, 149.999925, 151.00003500000003, 151.99989, 153.0, 154.00010999999998, 154.999965, 156.000075, 156.99992999999998, 158.00004, 158.999895, 160.000005, 161.000115, 161.99997000000002, 163.00008, 163.999935, 165.000045, 165.9999, 167.00001, 168.00011999999998, 168.999975, 170.000085, 170.99993999999998, 172.00005000000002, 172.999905, 174.000015, 175.000125, 175.99998000000002, 177.00009, 177.999945, 179.00005499999997, 179.99991, 181.00002, 181.999875, 182.999985, 184.00009500000002, 184.99994999999998, 186.00006, 186.99991500000002, 188.000025, 188.99988, 189.99999, 191.0001, 191.999955, 193.00006499999998, 193.99992, 195.00003, 195.99988499999998, 196.999995, 198.00010500000002, 198.99996, 200.00007, 200.99992500000002, 202.000035, 202.99989, 204.0, 205.00011, 205.999965, 207.00007499999998, 207.99993, 209.00004, 209.99989499999998, 211.00000500000002, 212.000115, 212.99997, 214.00008, 214.999935, 216.000045, 216.9999, 218.00001, 219.00012, 219.999975, 221.00008499999998, 221.99994, 223.00005000000002, 223.99990499999998, 225.00001500000002, 226.000125, 226.99998, 228.00009, 228.999945, 230.000055, 230.99991, 232.00001999999998, 232.999875, 233.999985, 235.000095, 235.99995, 237.00006, 237.999915, 239.000025, 239.99988, 240.99999, 242.0001, 242.999955, 244.000065, 244.99992, 246.00002999999998, 246.999885, 247.999995, 249.000105, 249.99996000000002, 251.00007, 251.999925, 253.000035, 253.99989, 255.0 }; double palette_out[256] = { 0.0, 0.042075, 0.08415, 0.126225, 0.169065, 0.21216, 0.255765, 0.29988, 0.345015, 0.390915, 0.437835, 0.48602999999999996, 0.5352450000000001, 0.58599, 0.63801, 0.69156, 0.7468950000000001, 0.804015, 0.8629199999999999, 0.9238649999999999, 0.98685, 1.05213, 1.119705, 1.18983, 1.26225, 1.337475, 1.415505, 1.49634, 1.580235, 1.6674449999999998, 1.75746, 1.851045, 1.9482, 2.04867, 2.152965, 2.2608300000000003, 2.3727750000000003, 2.4885450000000002, 2.6083950000000002, 2.73258, 2.8611000000000004, 2.993955, 3.1313999999999997, 3.27369, 3.42057, 3.572295, 3.72912, 3.891045, 4.05807, 4.23045, 4.408440000000001, 4.591785, 4.780995, 4.975815, 5.1765, 5.38305, 5.595975, 5.8150200000000005, 6.040185, 6.27198, 6.510405, 6.755205, 7.007145, 7.265715, 7.53117, 7.8040199999999995, 8.084010000000001, 8.37114, 8.66592, 8.968095, 9.27792, 9.59565, 9.92103, 10.25457, 10.596015, 10.945875, 11.30415, 11.670585, 12.04569, 12.429465, 12.82191, 13.223279999999999, 13.63383, 14.053305, 14.48196, 14.919794999999999, 15.36732, 15.82428, 16.29093, 16.767270000000003, 17.253555, 17.749785, 18.256215, 18.925845, 19.456245000000003, 19.99863, 20.552745, 21.11859, 21.696165, 22.285725, 22.887014999999998, 23.500035, 24.125295, 24.762285, 25.411260000000002, 26.071965, 26.74491, 27.42984, 28.12701, 28.835910000000002, 29.55705, 30.29043, 31.035795, 31.7934, 32.56299, 33.345075, 34.139145, 34.94571, 35.764514999999996, 36.595305, 37.438845, 38.294625, 39.162645, 40.04316, 40.935915, 41.84142, 42.759165, 43.68966, 44.632394999999995, 45.58788, 46.55586, 47.536335, 48.529560000000004, 49.535535, 50.554005000000004, 51.58497, 52.62894, 53.68566, 54.75513, 55.837095, 56.932064999999994, 58.040040000000005, 59.160765, 60.294239999999995, 61.44072, 62.59995000000001, 63.772439999999996, 64.95768000000001, 66.15592500000001, 67.36743, 68.591685, 69.82919999999999, 71.07972, 72.343245, 73.620285, 74.910075, 76.21337999999999, 77.52968999999999, 78.85926, 80.20209, 81.55843499999999, 82.927785, 84.31065, 85.66419, 87.10264500000001, 88.611225, 90.18712500000001, 91.82779500000001, 93.52992, 95.291205, 97.108845, 98.979525, 100.90095, 102.87006, 104.884305, 106.94037, 109.03596, 111.16827, 113.33424000000001, 115.531065, 117.756195, 120.00657, 122.27964, 124.572345, 126.88213499999999, 129.20595, 131.54124, 133.8852, 136.23477, 138.58714500000002, 140.939775, 143.289855, 145.63458, 147.97089, 150.296235, 152.60781, 154.902555, 157.17817499999998, 159.431355, 161.65929, 163.859685, 166.02948, 168.165615, 170.26554, 172.32645, 174.34554, 176.320005, 178.24704, 180.292905, 182.130945, 183.953685, 185.76138, 187.554285, 189.33291, 191.09751, 192.84834, 194.58591, 196.310475, 198.02229, 199.72161, 201.4092, 203.084805, 204.74944499999998, 206.402865, 208.04557499999999, 209.67808499999998, 211.30065, 212.913525, 214.516965, 216.11148, 217.69758000000002, 219.27501, 220.84479, 222.406665, 223.9614, 225.50924999999998, 227.05047000000002, 228.585315, 230.114295, 231.63766500000003, 233.15568000000002, 234.66885000000002, 236.17743, 237.681675, 239.18184, 240.67869, 242.172225, 243.66295499999998, 245.15088, 246.636765, 248.12061000000003, 249.602925, 251.083965, 252.56424, 254.04375, 255.0 }; GDALAllRegister (); /* ussage.. */ if (argc != 3) ussage (); /* Set cache to something reasonable.. - 1/2 gig */ CPLSetConfigOption ("GDAL_CACHEMAX", "512"); /* open datasets.. */ in_Dataset = GDAL_open_read (argv[1]); out_Dataset = make_me_a_sandwitch (&in_Dataset, argv[2]); /* Basic info on source dataset.. */ GDALGetBlockSize (GDALGetRasterBand (in_Dataset, 1), &nBlockXSize, &nBlockYSize); printf ("Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName (GDALGetRasterDataType (GDALGetRasterBand (in_Dataset, 1))), GDALGetColorInterpretationName (GDALGetRasterColorInterpretation (GDALGetRasterBand (in_Dataset, 1)))); /* Loop though bands, scaling the data.. */ xsize = GDALGetRasterXSize (in_Dataset); data_scan_line = (double *) CPLMalloc (sizeof (double) * xsize); out_scan_line = (char *) CPLMalloc (sizeof (char) * xsize); for (bands = 1; bands <= GDALGetRasterCount (in_Dataset); bands++) { int x; double min = 9999999.0, max = 0.0; /* probibly a better way to set these.. */ double dmin, dmax, middle; GDALRasterBandH data_band, out_band; int y_index = 0; data_band = GDALGetRasterBand (in_Dataset, bands); out_band = GDALGetRasterBand (out_Dataset, bands); /* Set nodata for that band */ GDALSetRasterNoDataValue (out_band, 0.0); /*Find Min,Max, required for scaling */ for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++) { /* Read data.. */ GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1, data_scan_line, xsize, 1, GDT_Float64, 0, 0); for (x = 0; x < xsize; x++) { if (data_scan_line[x] < MAX_MODIS && data_scan_line[x] > MIN_VALUE) { if (data_scan_line[x] > max) max = data_scan_line[x]; else if (data_scan_line[x] < min) min = data_scan_line[x]; } } } dmax = (double) max; dmin = (double) min; printf ("Info: For Band %d -> Min=%g,Max=%g\n", bands, dmin, dmax); for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++) { double scaled; /* Read data.. */ GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1, data_scan_line, xsize, 1, GDT_Float64, 0, 0); /* scale each .. */ for (x = 0; x < xsize; x++) { out_scan_line[x] = scale (palette_in, palette_out, data_scan_line[x], dmin, dmax); } /* now write out band.. */ GDALRasterIO (out_band, GF_Write, 0, y_index, xsize, 1, out_scan_line, xsize, 1, GDT_Byte, 0, 0); } } /* close file, and we are done. */ GDALClose (out_Dataset); }
NV_CHAR *get_geotiff (NV_CHAR *mosaic_file, MISC *misc) { static NV_CHAR string[512]; strcpy (string, "Success"); if (strstr (mosaic_file, ".tif") || strstr (mosaic_file, ".TIF")) { GDALDataset *poDataset; NV_FLOAT64 adfGeoTransform[6]; GDALAllRegister (); poDataset = (GDALDataset *) GDALOpen (mosaic_file, GA_ReadOnly); if (poDataset != NULL) { if (poDataset->GetProjectionRef () != NULL) { QString projRef = QString (poDataset->GetProjectionRef ()); if (projRef.contains ("GEOGCS")) { if (poDataset->GetGeoTransform (adfGeoTransform) == CE_None) { misc->lon_step = adfGeoTransform[1]; misc->lat_step = -adfGeoTransform[5]; misc->mosaic_width = poDataset->GetRasterXSize (); misc->mosaic_height = poDataset->GetRasterYSize (); misc->geotiff_area.min_x = adfGeoTransform[0]; misc->geotiff_area.max_y = adfGeoTransform[3]; misc->geotiff_area.min_y = misc->geotiff_area.max_y - misc->mosaic_height * misc->lat_step; misc->geotiff_area.max_x = misc->geotiff_area.min_x + misc->mosaic_width * misc->lon_step; } else { delete poDataset; sprintf (string, "File %s contains projected data", gen_basename (mosaic_file)); return (string); } } else { delete poDataset; sprintf (string, "File %s contains Non-geographic coordinate system", gen_basename (mosaic_file)); return (string); } } else { delete poDataset; sprintf (string, "File %s contains no datum/projection information", gen_basename (mosaic_file)); return (string); } if (misc->full_res_image != NULL) delete misc->full_res_image; /* This is how I used to read geoTIFFs but for some reason it stopped working along about Qt 4.7.2 so now I use GDAL to read it. I really need to keep testing to see if this starts working again because it's a bit faster and probably a lot more bullet proof. misc->full_res_image = new QImage (mosaic_file); if (misc->full_res_image == NULL || misc->full_res_image->width () == 0 || fmisc->ull_res_image->height () == 0) { sprintf (string, "Unable to read file %s", gen_basename (mosaic_file)); delete poDataset; return (string); } */ // This is how I read geoTIFFs now... GDALRasterBand *poBand[4]; QString dataType[4], colorInt[4]; NV_U_INT32 mult[4] = {0, 0, 0, 0}; NV_INT32 rasterCount = poDataset->GetRasterCount (); if (rasterCount < 3) { delete poDataset; sprintf (string, "Not enough raster bands in geoTIFF"); return (string); } for (NV_INT32 i = 0 ; i < rasterCount ; i++) { poBand[i] = poDataset->GetRasterBand (i + 1); dataType[i] = QString (GDALGetDataTypeName (poBand[i]->GetRasterDataType ())); colorInt[i] = QString (GDALGetColorInterpretationName (poBand[i]->GetColorInterpretation ())); // We can only handle Byte data (i.e. RGB or ARGB) if (dataType[i] != "Byte") { delete poDataset; sprintf (string, "Can only handle Byte data type"); return (string); } mult[i] = getColorOffset (colorInt[i]); } NV_INT32 nXSize = poBand[0]->GetXSize (); NV_INT32 nYSize = poBand[0]->GetYSize (); misc->full_res_image = new QImage (nXSize, nYSize, QImage::Format_ARGB32); if (misc->full_res_image == NULL || misc->full_res_image->width () == 0 || misc->full_res_image->height () == 0) { sprintf (string, "Unable to open image!"); delete poDataset; return (string); } NV_U_INT32 *color = new NV_U_INT32[nXSize]; NV_U_BYTE *pafScanline = (NV_U_BYTE *) CPLMalloc (sizeof (NV_U_BYTE) * nXSize); for (NV_INT32 i = 0 ; i < nYSize ; i++) { // If we don't have an alpha band set it to 255. for (NV_INT32 k = 0 ; k < nXSize ; k++) { if (rasterCount < 4) { color[k] = 0xff000000; } else { color[k] = 0x0; } } // Read the raster bands. for (NV_INT32 j = 0 ; j < rasterCount ; j++) { poBand[j]->RasterIO (GF_Read, 0, i, nXSize, 1, pafScanline, nXSize, 1, GDT_Byte, 0, 0); for (NV_INT32 k = 0 ; k < nXSize ; k++) color[k] += ((NV_U_INT32) pafScanline[k]) * mult[j]; } // Set the image pixels. for (NV_INT32 k = 0 ; k < nXSize ; k++) { misc->full_res_image->setPixel (k, i, color[k]); } } delete (color); CPLFree (pafScanline); delete poDataset; } else { sprintf (string, "Unable to open file %s", gen_basename (mosaic_file)); return (string); } } else { sprintf (string, "File %s is not a GeoTIFF file", gen_basename (mosaic_file)); return (string); } return (string); }
int main( int argc, const char* argv[] ) { GDALDriverH hDriver; double adfGeoTransform[6]; GDALDatasetH in_Dataset; GDALDatasetH mask_Dataset; GDALDatasetH out_Dataset; GDALRasterBandH mask_band; char *mask_scan_line, *data_scan_line; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; int bands; int xsize; double adfMinMax[2]; GDALAllRegister(); if ( argc != 2) { printf("Usage: %s <file to add mask to> \n", argv[0]); printf("This utility adds a nodata mask to a file, were the datadata value is \"0\"\n"); printf("contact/blame [email protected] for questions/problems.\n"); return 0; } /* open datasets..*/ in_Dataset = GDAL_open( argv[1]); /* add mask.. */ GDALCreateDatasetMaskBand( in_Dataset, 0); /* Basic info on source dataset..*/ GDALGetBlockSize(GDALGetRasterBand( in_Dataset, 1 ) , &nBlockXSize, &nBlockYSize ); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(GDALGetRasterDataType( GDALGetRasterBand( in_Dataset, 1 ))), GDALGetColorInterpretationName( GDALGetRasterColorInterpretation(GDALGetRasterBand( in_Dataset, 1 )))); /* Loop though bands, wiping values with mask values of 0.. */ xsize = GDALGetRasterXSize( in_Dataset ); mask_scan_line = (char *) CPLMalloc(sizeof(char)*xsize); data_scan_line = (char *) CPLMalloc(sizeof(char)*xsize); for (bands=1; bands <= GDALGetRasterCount( in_Dataset ); bands ++ ) { int x; GDALRasterBandH data_band, out_band; int y_index = 0; printf("INFO: Doing band %d of %d\n", bands,GDALGetRasterCount( in_Dataset ) ); data_band = GDALGetRasterBand( in_Dataset, bands); mask_band = GDALGetMaskBand(data_band); for (y_index = 0; y_index <GDALGetRasterYSize( in_Dataset ); y_index ++ ) { /* Read data..*/ GDALRasterIO( data_band, GF_Read, 0, y_index, xsize , 1, data_scan_line, xsize , 1, GDT_Byte, 0, 0 ); for(x=0; x < xsize; x++) { /* if mask is set to 0, then mask off...*/ /* lame nodata handleing, but such is life.. */ if ( data_scan_line[x] == 0 ) mask_scan_line[x]=0; else mask_scan_line[x]=255; } /* now write out band..*/ GDALRasterIO( mask_band, GF_Write, 0, y_index, xsize , 1, mask_scan_line, xsize , 1, GDT_Byte, 0, 0 ); } } GDALClose(in_Dataset); }
int main (int argc, const char *argv[]) { GDALDriverH hDriver; double adfGeoTransform[6]; GDALDatasetH in_Dataset; GDALDatasetH mask_Dataset; GDALDatasetH out_Dataset; GDALRasterBandH mask_band; char *mask_scan_line, *data_scan_line; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; int bands; int xsize; double adfMinMax[2]; GDALAllRegister (); /* Set cache to something reasonable.. - 1/2 gig */ CPLSetConfigOption ("GDAL_CACHEMAX", "512"); /* open datasets.. */ in_Dataset = GDAL_open_read (argv[1]); mask_Dataset = GDAL_open_read (argv[2]); out_Dataset = make_me_a_sandwitch (&in_Dataset, argv[3]); mask_band = GDALGetRasterBand (mask_Dataset, 1); /* Basic info on source dataset.. */ GDALGetBlockSize (GDALGetRasterBand (in_Dataset, 1), &nBlockXSize, &nBlockYSize); printf ("Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName (GDALGetRasterDataType (GDALGetRasterBand (in_Dataset, 1))), GDALGetColorInterpretationName (GDALGetRasterColorInterpretation (GDALGetRasterBand (in_Dataset, 1)))); /* Loop though bands, wiping values with mask values of 0.. */ xsize = GDALGetRasterXSize (in_Dataset); mask_scan_line = (char *) CPLMalloc (sizeof (char) * xsize); data_scan_line = (char *) CPLMalloc (sizeof (char) * xsize); for (bands = 1; bands <= GDALGetRasterCount (in_Dataset); bands++) { int x; GDALRasterBandH data_band, out_band; int y_index = 0; data_band = GDALGetRasterBand (in_Dataset, bands); out_band = GDALGetRasterBand (out_Dataset, bands); for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++) { /* Read data.. */ GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1, data_scan_line, xsize, 1, GDT_Byte, 0, 0); /* Read mask.. */ GDALRasterIO (mask_band, GF_Read, 0, y_index, xsize, 1, mask_scan_line, xsize, 1, GDT_Byte, 0, 0); GDALSetRasterNoDataValue (out_band, 0.0); for (x = 0; x < xsize; x++) { /* if mask is set to 0, then mask off... */ if (mask_scan_line[x] == 0) data_scan_line[x] = 0; /* if mask is not zero, and data is zero, then unmask.. */ if (mask_scan_line[x] != 0 && data_scan_line[x] == 0) data_scan_line[x] = 1; } /* now write out band.. */ GDALRasterIO (out_band, GF_Write, 0, y_index, xsize, 1, data_scan_line, xsize, 1, GDT_Byte, 0, 0); } } GDALClose (out_Dataset); }
void readFrames( int argc, char* argv[] ) { pfs::DOMIO pfsio; bool verbose = false; // Parse command line parameters static struct option cmdLineOptions[] = { { "help", no_argument, NULL, 'h' }, { "verbose", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char optstring[] = "hv"; pfs::FrameFileIterator it( argc, argv, "rb", NULL, NULL, optstring, cmdLineOptions ); int optionIndex = 0; while( 1 ) { int c = getopt_long (argc, argv, optstring, cmdLineOptions, &optionIndex); if( c == -1 ) break; switch( c ) { case 'h': printHelp(); throw QuietException(); case 'v': verbose = true; break; case '?': throw QuietException(); case ':': throw QuietException(); } } GDALAllRegister(); GDALDataset *poDataset; GDALRasterBand *poBand; double adfGeoTransform[6]; size_t nBlockXSize, nBlockYSize, nBands; int bGotMin, bGotMax; double adfMinMax[2]; float *pafScanline; while( true ) { pfs::FrameFile ff = it.getNextFrameFile(); if( ff.fh == NULL ) break; // No more frames it.closeFrameFile( ff ); VERBOSE_STR << "reading file '" << ff.fileName << "'" << std::endl; if( !( poDataset = (GDALDataset *) GDALOpen( ff.fileName, GA_ReadOnly ) ) ) { std::cerr << "input does not seem to be in a format supported by GDAL" << std::endl; throw QuietException(); } VERBOSE_STR << "GDAL driver: " << poDataset->GetDriver()->GetDescription() << " / " << poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) << std::endl; nBlockXSize = poDataset->GetRasterXSize(); nBlockYSize = poDataset->GetRasterYSize(); nBands = poDataset->GetRasterCount(); VERBOSE_STR << "Data size " << nBlockXSize << "x" << nBlockYSize << "x" << nBands << std::endl; if( poDataset->GetProjectionRef() ) { VERBOSE_STR << "Projection " << poDataset->GetProjectionRef() << std::endl; } if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { VERBOSE_STR << "Origin = (" << adfGeoTransform[0] << ", " << adfGeoTransform[3] << ")" << std::endl; VERBOSE_STR << "Pixel Size = (" << adfGeoTransform[1] << ", " << adfGeoTransform[5] << ")" << std::endl; } if( nBlockXSize==0 || nBlockYSize==0 || ( SIZE_MAX / nBlockYSize < nBlockXSize ) || ( SIZE_MAX / (nBlockXSize * nBlockYSize ) < 4 ) ) { std::cerr << "input data has invalid size" << std::endl; throw QuietException(); } if( !(pafScanline = (float *) CPLMalloc( sizeof(float) * nBlockXSize ) ) ) { std::cerr << "not enough memory" << std::endl; throw QuietException(); } pfs::Frame *frame = pfsio.createFrame( nBlockXSize, nBlockYSize ); pfs::Channel *C[nBands]; char channel_name[32]; frame->getTags()->setString( "X-GDAL_DRIVER_SHORTNAME", poDataset->GetDriver()->GetDescription() ); frame->getTags()->setString( "X-GDAL_DRIVER_LONGNAME", poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); frame->getTags()->setString( "X-PROJECTION", poDataset->GetProjectionRef() ); if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { frame->getTags()->setString( "X-ORIGIN_X", stringify(adfGeoTransform[0]).c_str() ); frame->getTags()->setString( "X-ORIGIN_Y", stringify(adfGeoTransform[3]).c_str() ); frame->getTags()->setString( "X-PIXEL_WIDTH", stringify(adfGeoTransform[1]).c_str() ); frame->getTags()->setString( "X-PIXEL_HEIGHT", stringify(adfGeoTransform[5]).c_str() ); } for ( size_t band = 1; band <= nBands; band++) { size_t nBandXSize, nBandYSize; VERBOSE_STR << "Band " << band << ": " << std::endl; snprintf( channel_name, 32, "X-GDAL%zu", band ); C[band - 1] = frame->createChannel( channel_name ); poBand = poDataset->GetRasterBand( band ); nBandXSize = poBand->GetXSize(); nBandYSize = poBand->GetYSize(); VERBOSE_STR << " " << nBandXSize << "x" << nBandYSize << std::endl; if( nBandXSize != (int)nBlockXSize || nBandYSize != (int)nBlockYSize ) { std::cerr << "data in band " << band << " has different size" << std::endl; throw QuietException(); } VERBOSE_STR << " Type " << GDALGetDataTypeName( poBand->GetRasterDataType() ) << ", " << "Color Interpretation " << GDALGetColorInterpretationName( poBand->GetColorInterpretation() ) << std::endl; adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) { GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); } VERBOSE_STR << " Min " << adfMinMax[0] << ", Max " << adfMinMax[1] << std::endl; C[band - 1]->getTags()->setString( "X-TYPE", GDALGetDataTypeName( poBand->GetRasterDataType() ) ); C[band - 1]->getTags()->setString( "X-COLOR_INTERPRETATION", GDALGetColorInterpretationName( poBand->GetColorInterpretation() ) ); C[band - 1]->getTags()->setString( "X-MIN", stringify(adfMinMax[0]).c_str() ); C[band - 1]->getTags()->setString( "X-MAX", stringify(adfMinMax[1]).c_str() ); for( size_t y = 0; y < nBlockYSize; y++ ) { if( poBand->RasterIO( GF_Read, 0, y, nBlockXSize, 1, pafScanline, nBlockXSize, 1, GDT_Float32, 0, 0) != CE_None ) { std::cerr << "input error" << std::endl; throw QuietException(); } memcpy( C[band - 1]->getRawData() + y * nBlockXSize, pafScanline, nBlockXSize * sizeof(float) ); } } CPLFree( pafScanline ); GDALClose( poDataset ); const char *fileNameTag = strcmp( "-", ff.fileName )==0 ? "stdin" : ff.fileName; frame->getTags()->setString( "FILE_NAME", fileNameTag ); pfsio.writeFrame( frame, stdout ); pfsio.freeFrame( frame ); } }
CPLXMLNode *VRTRasterBand::SerializeToXML( const char *pszVRTPath ) { CPLXMLNode *psTree; psTree = CPLCreateXMLNode( NULL, CXT_Element, "VRTRasterBand" ); /* -------------------------------------------------------------------- */ /* Various kinds of metadata. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psMD; CPLSetXMLValue( psTree, "#dataType", GDALGetDataTypeName( GetRasterDataType() ) ); if( nBand > 0 ) CPLSetXMLValue( psTree, "#band", CPLSPrintf( "%d", GetBand() ) ); psMD = oMDMD.Serialize(); if( psMD != NULL ) CPLAddXMLChild( psTree, psMD ); if( strlen(GetDescription()) > 0 ) CPLSetXMLValue( psTree, "Description", GetDescription() ); if( bNoDataValueSet ) { if (CPLIsNan(dfNoDataValue)) CPLSetXMLValue( psTree, "NoDataValue", "nan"); else CPLSetXMLValue( psTree, "NoDataValue", CPLSPrintf( "%.14E", dfNoDataValue ) ); } if( bHideNoDataValue ) CPLSetXMLValue( psTree, "HideNoDataValue", CPLSPrintf( "%d", bHideNoDataValue ) ); if( pszUnitType != NULL ) CPLSetXMLValue( psTree, "UnitType", pszUnitType ); if( dfOffset != 0.0 ) CPLSetXMLValue( psTree, "Offset", CPLSPrintf( "%.16g", dfOffset ) ); if( dfScale != 1.0 ) CPLSetXMLValue( psTree, "Scale", CPLSPrintf( "%.16g", dfScale ) ); if( eColorInterp != GCI_Undefined ) CPLSetXMLValue( psTree, "ColorInterp", GDALGetColorInterpretationName( eColorInterp ) ); /* -------------------------------------------------------------------- */ /* Category names. */ /* -------------------------------------------------------------------- */ if( papszCategoryNames != NULL ) { CPLXMLNode *psCT_XML = CPLCreateXMLNode( psTree, CXT_Element, "CategoryNames" ); CPLXMLNode* psLastChild = NULL; for( int iEntry=0; papszCategoryNames[iEntry] != NULL; iEntry++ ) { CPLXMLNode *psNode = CPLCreateXMLElementAndValue( NULL, "Category", papszCategoryNames[iEntry] ); if( psLastChild == NULL ) psCT_XML->psChild = psNode; else psLastChild->psNext = psNode; psLastChild = psNode; } } /* -------------------------------------------------------------------- */ /* Histograms. */ /* -------------------------------------------------------------------- */ if( psSavedHistograms != NULL ) CPLAddXMLChild( psTree, CPLCloneXMLTree( psSavedHistograms ) ); /* -------------------------------------------------------------------- */ /* Color Table. */ /* -------------------------------------------------------------------- */ if( poColorTable != NULL ) { CPLXMLNode *psCT_XML = CPLCreateXMLNode( psTree, CXT_Element, "ColorTable" ); CPLXMLNode* psLastChild = NULL; for( int iEntry=0; iEntry < poColorTable->GetColorEntryCount(); iEntry++ ) { GDALColorEntry sEntry; CPLXMLNode *psEntry_XML = CPLCreateXMLNode( NULL, CXT_Element, "Entry" ); if( psLastChild == NULL ) psCT_XML->psChild = psEntry_XML; else psLastChild->psNext = psEntry_XML; psLastChild = psEntry_XML; poColorTable->GetColorEntryAsRGB( iEntry, &sEntry ); CPLSetXMLValue( psEntry_XML, "#c1", CPLSPrintf("%d",sEntry.c1) ); CPLSetXMLValue( psEntry_XML, "#c2", CPLSPrintf("%d",sEntry.c2) ); CPLSetXMLValue( psEntry_XML, "#c3", CPLSPrintf("%d",sEntry.c3) ); CPLSetXMLValue( psEntry_XML, "#c4", CPLSPrintf("%d",sEntry.c4) ); } } /* ==================================================================== */ /* Overviews */ /* ==================================================================== */ for( int iOvr = 0; iOvr < (int)apoOverviews.size(); iOvr ++ ) { CPLXMLNode *psOVR_XML = CPLCreateXMLNode( psTree, CXT_Element, "Overview" ); int bRelativeToVRT; const char *pszRelativePath; VSIStatBufL sStat; if( VSIStatExL( apoOverviews[iOvr].osFilename, &sStat, VSI_STAT_EXISTS_FLAG ) != 0 ) { pszRelativePath = apoOverviews[iOvr].osFilename; bRelativeToVRT = FALSE; } else { pszRelativePath = CPLExtractRelativePath( pszVRTPath, apoOverviews[iOvr].osFilename, &bRelativeToVRT ); } CPLSetXMLValue( psOVR_XML, "SourceFilename", pszRelativePath ); CPLCreateXMLNode( CPLCreateXMLNode( CPLGetXMLNode( psOVR_XML, "SourceFilename" ), CXT_Attribute, "relativeToVRT" ), CXT_Text, bRelativeToVRT ? "1" : "0" ); CPLSetXMLValue( psOVR_XML, "SourceBand", CPLSPrintf("%d",apoOverviews[iOvr].nBand) ); } /* ==================================================================== */ /* Mask band (specific to that raster band) */ /* ==================================================================== */ if( poMaskBand != NULL ) { CPLXMLNode *psBandTree = poMaskBand->SerializeToXML(pszVRTPath); if( psBandTree != NULL ) { CPLXMLNode *psMaskBandElement = CPLCreateXMLNode( psTree, CXT_Element, "MaskBand" ); CPLAddXMLChild( psMaskBandElement, psBandTree ); } } return psTree; }
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)); }
const QString OmgGdal::Gdal2Ascii(const QString theFileName) { std::cout << "Running gdal to ascii conversion..." << std::endl; QFileInfo myFileInfo(theFileName); QString myExt("asc"); QString myOutFileName(QDir::convertSeparators(myFileInfo.dirPath(true)+"/"+myFileInfo.baseName() + "." + myExt)); QFile myFile( myOutFileName ); if ( !myFile.open( IO_WriteOnly ) ) { printf("Opening output file for write failed"); return QString(""); } QTextStream myStream( &myFile ); GDALAllRegister(); GDALDataset *gdalDataset = (GDALDataset *) GDALOpen( theFileName.local8Bit(), GA_ReadOnly ); if ( gdalDataset == NULL ) { std::cout << "Error couldn't open file: " << theFileName << std::endl; return QString(""); } //Write the ascii headers myStream << getAsciiHeader(theFileName); //assume to be working with first band in dataset only GDALRasterBand *myGdalBand = gdalDataset->GetRasterBand( 1 ); //find out the name of the band if any QString myColorInterpretation = GDALGetColorInterpretationName(myGdalBand->GetColorInterpretation()); // get the dimensions of the raster int myColsInt = myGdalBand->GetXSize(); int myRowsInt = myGdalBand->GetYSize(); double myNullValue=myGdalBand->GetNoDataValue(); //allocate a buffer to hold one row of ints int myAllocationSizeInt = sizeof(uint)*myColsInt; uint * myScanlineAllocInt = (uint*) CPLMalloc(myAllocationSizeInt); for (int myCurrentRowInt=0; myCurrentRowInt < myRowsInt;myCurrentRowInt++) { //get a scanline CPLErr myResult = myGdalBand->RasterIO( GF_Read, 0, myCurrentRowInt, myColsInt, 1, myScanlineAllocInt, myColsInt, 1, GDT_UInt32, 0, 0 ); for (int myCurrentColInt=0; myCurrentColInt < myColsInt; myCurrentColInt++) { //get the nth element from the current row double myDouble=myScanlineAllocInt[myCurrentColInt]; myStream << myDouble << " "; //pixel value } //end of column wise loop myStream << "\r\n"; //dos style new line } //end of row wise loop CPLFree(myScanlineAllocInt); myFile.close(); std::cout << "The output ascii file is: " << myOutFileName << std::endl; return myOutFileName; }