ImageProperties::ImageProperties(GDALDataset* dataset, const std::string& filename) : width(0), height(0), numBands(0), driverName(NULL), driverLongName(NULL), imageFileName(filename) { assert(dataset != NULL); driverName = (char *) GDALGetDescription(GDALGetDatasetDriver(dataset)); driverLongName = (char *) GDALGetMetadataItem(GDALGetDatasetDriver(dataset), GDAL_DMD_LONGNAME,0); width = GDALGetRasterXSize(dataset); height = GDALGetRasterYSize(dataset); numBands = GDALGetRasterCount(dataset); string::size_type position = imageFileName.find_last_of("\\"); if (position != string::npos) { shortFileName = imageFileName.substr(position + 1); } else { shortFileName = imageFileName; } }
void fill_image_data(GDALImage *image) { GDALResult result; // Open GDAL File image->dataset = GDALOpen(image->filepath, GA_ReadOnly); FAILIF(image->dataset, NULL, "Unable to open file."); // Get file information image->driver = GDALGetDatasetDriver(image->dataset); image->original_width = GDALGetRasterXSize(image->dataset); image->original_height = GDALGetRasterYSize(image->dataset); image->band_count = limit_band_count(GDALGetRasterCount(image->dataset)); // Open first band to get block information image->current_band = GDALGetRasterBand(image->dataset, 1); result = GDALGetGeoTransform(image->dataset, image->geo_transform); FAILIF(result, CE_Failure, "Failed to get GeoTransform data"); GDALGetBlockSize(image->current_band, &image->block_size.x, &image->block_size.y); image->output_size.x = image->block_size.x/image->scale; image->output_size.y = image->block_size.y/image->scale; image->num_blocks.x = image->original_width/image->block_size.x; image->num_blocks.y = image->original_height/image->block_size.y; DEFAULT(image->num_blocks.x, 0, 1); DEFAULT(image->num_blocks.y, 0, 1); DEFAULT(image->output_size.x, 0, 1); DEFAULT(image->output_size.y, 0, 1); }
static QgsOgrLayerItem *dataItemForLayer( QgsDataItem *parentItem, QString name, QString path, GDALDatasetH hDataSource, int layerId, bool isSubLayer, bool uniqueNames ) { OGRLayerH hLayer = GDALDatasetGetLayer( hDataSource, layerId ); OGRFeatureDefnH hDef = OGR_L_GetLayerDefn( hLayer ); QgsLayerItem::LayerType layerType = QgsLayerItem::Vector; GDALDriverH hDriver = GDALGetDatasetDriver( hDataSource ); QString driverName = QString::fromUtf8( GDALGetDriverShortName( hDriver ) ); OGRwkbGeometryType ogrType = QgsOgrProvider::getOgrGeomType( driverName, hLayer ); QgsWkbTypes::Type wkbType = QgsOgrProviderUtils::qgisTypeFromOgrType( ogrType ); switch ( QgsWkbTypes::geometryType( wkbType ) ) { case QgsWkbTypes::UnknownGeometry: break; case QgsWkbTypes::NullGeometry: layerType = QgsLayerItem::TableLayer; break; case QgsWkbTypes::PointGeometry: layerType = QgsLayerItem::Point; break; case QgsWkbTypes::LineGeometry: layerType = QgsLayerItem::Line; break; case QgsWkbTypes::PolygonGeometry: layerType = QgsLayerItem::Polygon; break; } QgsDebugMsgLevel( QStringLiteral( "ogrType = %1 layertype = %2" ).arg( ogrType ).arg( layerType ), 2 ); QString layerUri = path; if ( isSubLayer ) { // we are in a collection name = QString::fromUtf8( OGR_FD_GetName( hDef ) ); QgsDebugMsg( "OGR layer name : " + name ); if ( !uniqueNames ) { layerUri += "|layerid=" + QString::number( layerId ); } else { layerUri += "|layername=" + name; } path += '/' + name; } Q_ASSERT( !name.isEmpty() ); QgsDebugMsgLevel( "OGR layer uri : " + layerUri, 2 ); return new QgsOgrLayerItem( parentItem, name, path, layerUri, layerType, isSubLayer ); }
QVector<QgsDataItem *> QgsOgrDataCollectionItem::createChildren() { QVector<QgsDataItem *> children; QStringList skippedLayerNames; char **papszOptions = nullptr; papszOptions = CSLSetNameValue( papszOptions, "@LIST_ALL_TABLES", "YES" ); gdal::dataset_unique_ptr hDataSource( GDALOpenEx( mPath.toUtf8().constData(), GDAL_OF_VECTOR, nullptr, papszOptions, nullptr ) ); CSLDestroy( papszOptions ); GDALDriverH hDriver = GDALGetDatasetDriver( hDataSource.get() ); QString driverName = QString::fromUtf8( GDALGetDriverShortName( hDriver ) ); if ( driverName == QStringLiteral( "SQLite" ) ) { skippedLayerNames = QgsSqliteUtils::systemTables(); } if ( !hDataSource ) return children; int numLayers = GDALDatasetGetLayerCount( hDataSource.get() ); // Check if layer names are unique, so we can use |layername= in URI QMap< QString, int > mapLayerNameToCount; QList< int > skippedLayers; bool uniqueNames = true; for ( int i = 0; i < numLayers; ++i ) { OGRLayerH hLayer = GDALDatasetGetLayer( hDataSource.get(), i ); OGRFeatureDefnH hDef = OGR_L_GetLayerDefn( hLayer ); QString layerName = QString::fromUtf8( OGR_FD_GetName( hDef ) ); ++mapLayerNameToCount[layerName]; if ( mapLayerNameToCount[layerName] > 1 ) { uniqueNames = false; break; } if ( ( driverName == QStringLiteral( "SQLite" ) && layerName.contains( QRegularExpression( QStringLiteral( "idx_.*_geometry($|_.*)" ) ) ) ) || skippedLayerNames.contains( layerName ) ) { skippedLayers << i; } } children.reserve( numLayers ); for ( int i = 0; i < numLayers; ++i ) { if ( !skippedLayers.contains( i ) ) { QgsOgrLayerItem *item = dataItemForLayer( this, QString(), mPath, hDataSource.get(), i, true, uniqueNames ); children.append( item ); } } return children; }
OGRDataSourceH OGROpenShared( const char *pszName, int bUpdate, OGRSFDriverH *pahDriverList ) { VALIDATE_POINTER1( pszName, "OGROpenShared", NULL ); GDALDatasetH hDS = GDALOpenEx(pszName, GDAL_OF_VECTOR | ((bUpdate) ? GDAL_OF_UPDATE: 0) | GDAL_OF_SHARED, NULL, NULL, NULL); if( hDS != NULL && pahDriverList != NULL ) *pahDriverList = (OGRSFDriverH) GDALGetDatasetDriver(hDS); return (OGRDataSourceH) hDS; }
OGRDataSourceH OGROpen( const char *pszName, int bUpdate, OGRSFDriverH *pahDriverList ) { VALIDATE_POINTER1( pszName, "OGROpen", NULL ); #ifdef OGRAPISPY_ENABLED int iSnapshot = OGRAPISpyOpenTakeSnapshot(pszName, bUpdate); #endif GDALDatasetH hDS = GDALOpenEx(pszName, GDAL_OF_VECTOR | ((bUpdate) ? GDAL_OF_UPDATE: 0), NULL, NULL, NULL); if( hDS != NULL && pahDriverList != NULL ) *pahDriverList = (OGRSFDriverH) GDALGetDatasetDriver(hDS); #ifdef OGRAPISPY_ENABLED OGRAPISpyOpen(pszName, bUpdate, iSnapshot, &hDS); #endif return (OGRDataSourceH) hDS; }
int main( int nArgc, char ** papszArgv ) { GDALDatasetH hDS = NULL; GDALDatasetH hODS = NULL; int bCloseODS = TRUE; int bUsageError = FALSE; GDALDatasetH hDstDS; int nRetCode = 1; GDALVectorTranslateOptionsForBinary* psOptionsForBinary; GDALVectorTranslateOptions *psOptions; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(papszArgv[0])) exit(1); EarlySetConfigOptions(nArgc, papszArgv); /* -------------------------------------------------------------------- */ /* Register format(s). */ /* -------------------------------------------------------------------- */ OGRRegisterAll(); /* -------------------------------------------------------------------- */ /* Processing command line arguments. */ /* -------------------------------------------------------------------- */ nArgc = OGRGeneralCmdLineProcessor( nArgc, &papszArgv, 0 ); if( nArgc < 1 ) { papszArgv = NULL; nRetCode = -nArgc; goto exit; } for( int iArg = 1; iArg < nArgc; iArg++ ) { if( EQUAL(papszArgv[iArg], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against GDAL %s\n", papszArgv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); nRetCode = 0; goto exit; } else if( EQUAL(papszArgv[iArg],"--help") ) { Usage(); goto exit; } else if ( EQUAL(papszArgv[iArg], "--long-usage") ) { Usage(FALSE); goto exit; } } psOptionsForBinary = GDALVectorTranslateOptionsForBinaryNew(); psOptions = GDALVectorTranslateOptionsNew(papszArgv + 1, psOptionsForBinary); if( psOptions == NULL ) { Usage(); GDALVectorTranslateOptionsForBinaryFree(psOptionsForBinary); goto exit; } if( psOptionsForBinary->pszDataSource == NULL || psOptionsForBinary->pszDestDataSource == NULL ) { if( psOptionsForBinary->pszDestDataSource == NULL ) Usage("no target datasource provided"); else Usage("no source datasource provided"); GDALVectorTranslateOptionsFree(psOptions); GDALVectorTranslateOptionsForBinaryFree(psOptionsForBinary); goto exit; } if( strcmp(psOptionsForBinary->pszDestDataSource, "/vsistdout/") == 0 ) psOptionsForBinary->bQuiet = TRUE; if (!psOptionsForBinary->bQuiet && !psOptionsForBinary->bFormatExplicitlySet && psOptionsForBinary->eAccessMode == ACCESS_CREATION) { CheckDestDataSourceNameConsistency(psOptionsForBinary->pszDestDataSource, psOptionsForBinary->pszFormat); } /* -------------------------------------------------------------------- */ /* Open data source. */ /* -------------------------------------------------------------------- */ /* Avoid opening twice the same datasource if it is both the input and output */ /* Known to cause problems with at least FGdb, SQlite and GPKG drivers. See #4270 */ if (psOptionsForBinary->eAccessMode != ACCESS_CREATION && strcmp(psOptionsForBinary->pszDestDataSource, psOptionsForBinary->pszDataSource) == 0) { hODS = GDALOpenEx( psOptionsForBinary->pszDataSource, GDAL_OF_UPDATE | GDAL_OF_VECTOR, NULL, psOptionsForBinary->papszOpenOptions, NULL ); GDALDriverH hDriver = NULL; if( hODS != NULL ) hDriver = GDALGetDatasetDriver(hODS); /* Restrict to those 3 drivers. For example it is known to break with */ /* the PG driver due to the way it manages transactions... */ if (hDriver && !(EQUAL(GDALGetDescription(hDriver), "FileGDB") || EQUAL(GDALGetDescription(hDriver), "SQLite") || EQUAL(GDALGetDescription(hDriver), "GPKG"))) { hDS = GDALOpenEx( psOptionsForBinary->pszDataSource, GDAL_OF_VECTOR, NULL, psOptionsForBinary->papszOpenOptions, NULL ); } else { hDS = hODS; bCloseODS = FALSE; } } else { hDS = GDALOpenEx( psOptionsForBinary->pszDataSource, GDAL_OF_VECTOR, NULL, psOptionsForBinary->papszOpenOptions, NULL ); } /* -------------------------------------------------------------------- */ /* Report failure */ /* -------------------------------------------------------------------- */ if( hDS == NULL ) { OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); fprintf( stderr, "FAILURE:\n" "Unable to open datasource `%s' with the following drivers.\n", psOptionsForBinary->pszDataSource ); for( int iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { fprintf( stderr, " -> %s\n", poR->GetDriver(iDriver)->GetDescription() ); } GDALVectorTranslateOptionsFree(psOptions); GDALVectorTranslateOptionsForBinaryFree(psOptionsForBinary); goto exit; } if( !(psOptionsForBinary->bQuiet) ) { GDALVectorTranslateOptionsSetProgress(psOptions, GDALTermProgress, NULL); } hDstDS = GDALVectorTranslate(psOptionsForBinary->pszDestDataSource, hODS, 1, &hDS, psOptions, &bUsageError); if( bUsageError ) Usage(); else nRetCode = (hDstDS) ? 0 : 1; GDALVectorTranslateOptionsFree(psOptions); GDALVectorTranslateOptionsForBinaryFree(psOptionsForBinary); if(hDS) GDALClose(hDS); if(bCloseODS) GDALClose(hDstDS); exit: CSLDestroy( papszArgv ); OGRCleanupAll(); return nRetCode; }
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; }
bool toprsGadlReader::open() { if(isOpen()) { close(); } std::string driverNameTmp; if (theSubDatasets.size() == 0) { // Note: Cannot feed GDALOpen a NULL string! if (theImageFile.size()) { theDataset = GDALOpen(theImageFile.c_str(), GA_ReadOnly); if( theDataset == 0 ) { return false; } } else { return false; } // Check if it is nitf data for deciding whether or not open each sub-dataset //This will be removed eventually when toprs can handle 2GB nitf file. GDALDriverH driverTmp = GDALGetDatasetDriver(theDataset); bool isNtif = false; if (driverTmp != 0) { driverNameTmp = std::string(GDALGetDriverShortName(driverTmp)); std::transform(driverNameTmp.begin(), driverNameTmp.end(), driverNameTmp.begin(), [&](char ch){return toupper(ch);}); if (driverNameTmp == "NITF") { isNtif = true; } } // Check for sub data sets... char** papszMetadata = GDALGetMetadata( theDataset, "SUBDATASETS" ); if( CSLCount(papszMetadata) > 0 ) { theSubDatasets.clear(); for( int i = 0; papszMetadata[i] != 0; ++i ) { std::string os = papszMetadata[i]; if (os.find("_NAME=") != std::string::npos) { //Sub sets have already been set. Open each sub-dataset really slow down the process //specially for hdf data which sometimes has over 100 sub-datasets. Since following code //only for ntif cloud checking, so only open each sub-dataset here if the dataset is //nitf. This will be removed eventually when toprs can handle 2GB nitf file. //Otherwise open a sub-dataset when setCurrentEntry() gets called. if (isNtif) { GDALDatasetH subDataset = GDALOpen(filterSubDatasetsString(os).c_str(), GA_ReadOnly); if ( subDataset != 0 ) { // "Worldview ingest should ignore subimages when NITF_ICAT=CLOUD" // Hack: Ignore NITF subimages marked as cloud layers. std::string nitfIcatTag( GDALGetMetadataItem( subDataset, "NITF_ICAT", "" ) ); if ( nitfIcatTag.find("CLOUD") == std::string::npos ) { theSubDatasets.push_back(filterSubDatasetsString(os)); } } GDALClose(subDataset); } else { theSubDatasets.push_back(filterSubDatasetsString(os)); } } } //--- // Have multiple entries. We're going to default to open the first // entry like cidcadrg. //--- close(); theDataset = GDALOpen(theSubDatasets[theEntryNumberToRender].c_str(), GA_ReadOnly); if (theDataset == 0) { return false; } } // End of has subsets block. } // End of "if (theSubdatasets.size() == 0)" else { // Sub sets have already been set. theDataset = GDALOpen(theSubDatasets[theEntryNumberToRender].c_str(), GA_ReadOnly); if (theDataset == 0) { return false; } } // Set the driver. theDriver = GDALGetDatasetDriver( theDataset ); if(!theDriver) return false; theGdtType = GDT_Byte; theOutputGdtType = GDT_Byte; if(getNumberOfInputBands() < 1 ) { if(CSLCount(GDALGetMetadata(theDataset, "SUBDATASETS"))) { std::cout << "torsGdalReader::open WARNING:" << "\nHas multiple sub datasets and need to set the data before" << " we can get to the bands" << std::endl; } close(); std::cout << "torsGdalReader::open WARNING:" << "\nNo band data present in torsGdalReader::open" << std::endl; return false; } toprs_int32 i = 0; GDALRasterBandH bBand = GDALGetRasterBand( theDataset, 1 ); theGdtType = GDALGetRasterDataType(bBand); char** papszMetadata = GDALGetMetadata( bBand, NULL ); if (CSLCount(papszMetadata) > 0) { for(int i = 0; papszMetadata[i] != NULL; i++ ) { std::string metaStr = papszMetadata[i]; if (metaStr.find("AREA_OR_POINT") != std::string::npos) { //std::string pixel_is_point_or_area = metaStr.split("=")[1]; //pixel_is_point_or_area.downcase(); //if (pixel_is_point_or_area.contains("area")) // thePixelType = TOPRS_PIXEL_IS_AREA; break; } } } if(!isIndexed(1)) { for(i = 0; i < GDALGetRasterCount(theDataset); ++i) { if(theGdtType != GDALGetRasterDataType(GDALGetRasterBand( theDataset,i+1 ))) { std::cout << "torsGdalReader::open WARNING" << "\nWe currently do not support different scalar type bands." << std::endl; close(); return false; } } } theOutputGdtType = theGdtType; switch(theGdtType) { case GDT_CInt16: { // theOutputGdtType = GDT_Int16; theIsComplexFlag = true; break; } case GDT_CInt32: { // theOutputGdtType = GDT_Int32; theIsComplexFlag = true; break; } case GDT_CFloat32: { // theOutputGdtType = GDT_Float32; theIsComplexFlag = true; break; } case GDT_CFloat64: { // theOutputGdtType = GDT_Float64; theIsComplexFlag = true; break; } default: { theIsComplexFlag = false; break; } } if((std::string(GDALGetDriverShortName( theDriver )) == "PNG")&& (getNumberOfInputBands() == 4)) { theAlphaChannelFlag = true; } populateLut(); computeMinMax(); completeOpen(); theTile = toprsImgFactory::instance()->create(this); theSingleBandTile = toprsImgFactory::instance()->create(getInputScalarType(), 1); if ( m_preservePaletteIndexesFlag ) { theTile->setIndexedFlag(true); theSingleBandTile->setIndexedFlag(true); } theTile->initialize(); theSingleBandTile->initialize(); theGdalBuffer.resize(0); if(theIsComplexFlag) { theGdalBuffer.resize(theSingleBandTile->getSizePerBandInBytes()*2); } theImageBound = toprsIRect(0 ,0 ,GDALGetRasterXSize(theDataset)-1 ,GDALGetRasterYSize(theDataset)-1); int xSize=0, ySize=0; GDALGetBlockSize(GDALGetRasterBand( theDataset, 1 ), &xSize, &ySize); if (driverNameTmp.find("JPIP")!= std::string::npos || driverNameTmp.find("JP2")!= std::string::npos) { m_isBlocked = ((xSize > 1)&&(ySize > 1)); } else { m_isBlocked = false; } //if(m_isBlocked) //{ // setRlevelCache(); //} return true; }
static ERL_NIF_TERM gdal_nif_get_meta(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { gdal_img_handle* handle; if (enif_get_resource(env, argv[0], gdal_img_RESOURCE, (void**)&handle)) { GDALDatasetH in_ds = handle->in_ds; if (in_ds != NULL) { ERL_NIF_TERM terms[8]; int idx = 0; terms[idx++] = enif_make_tuple2(env, enif_make_atom(env, "description"), enif_make_string(env, GDALGetDescription(in_ds), ERL_NIF_LATIN1)); GDALDriverH hDriver = GDALGetDatasetDriver(in_ds); char buf[256]; sprintf(buf, "%s/%s", GDALGetDriverShortName(hDriver), GDALGetDriverLongName(hDriver)); terms[idx++] = enif_make_tuple2(env, enif_make_atom(env, "driver"), enif_make_string(env, buf, ERL_NIF_LATIN1)); terms[idx++] = enif_make_tuple2(env, enif_make_atom(env, "rasterSize"), enif_make_tuple2(env, enif_make_int(env, GDALGetRasterXSize(in_ds)), enif_make_int(env, GDALGetRasterYSize(in_ds)))); terms[idx++] = enif_make_tuple2(env, enif_make_atom(env, "rasterCount"), enif_make_int(env, GDALGetRasterCount(in_ds))); double adfGeoTransform[6]; if( GDALGetGeoTransform( in_ds, adfGeoTransform ) == CE_None ) { terms[idx++] = enif_make_tuple2(env, enif_make_atom(env, "origin"), enif_make_tuple2(env, enif_make_double(env, adfGeoTransform[0]), enif_make_double(env, adfGeoTransform[3]))); terms[idx++] = enif_make_tuple2(env, enif_make_atom(env, "pixelSize"), enif_make_tuple2(env, enif_make_double(env, adfGeoTransform[1]), enif_make_double(env, adfGeoTransform[5]))); } if (GDALGetProjectionRef(in_ds) != NULL) { terms[idx++] = enif_make_tuple2(env, enif_make_atom(env, "projection"), enif_make_string(env, GDALGetProjectionRef(in_ds), ERL_NIF_LATIN1)); } char** fileList = GDALGetFileList(in_ds); if (fileList != NULL) { ERL_NIF_TERM fileTerms[16]; int fileIdx = 0; char** files = fileList; do { fileTerms[ fileIdx++ ] = enif_make_string(env, *files, ERL_NIF_LATIN1); } while(*(++files)) ; CSLDestroy(fileList); terms[idx++] = enif_make_tuple2(env, enif_make_atom(env, "fileList"), enif_make_list_from_array(env, fileTerms, fileIdx)); } return enif_make_list_from_array(env, terms, idx); } else { return ATOM_NOT_OPEN; } } else { return enif_make_badarg(env); } }
int main( int argc, char *argv[] ) { if( argc < 5 ) { usage(); return 1; } int i, row, col; char *in[MAXFILES]; char *out; int imgs_per_year; int n_imgs; int n_null_pix; GDALDatasetH hD[MAXFILES+1]; GDALAllRegister(); GDALDriverH hDr[MAXFILES+1]; GDALRasterBandH hB[MAXFILES+1]; float *l[MAXFILES+1]; int nX, nY; out = argv[1]; printf("Loading input files:\n"); n_imgs = argc - 2; for (i=0;i<n_imgs;i++){ printf("%i / %i %s\r",i,n_imgs,argv[i+2]); in[i] = argv[i+2]; hD[i] = GDALOpen(in[i],GA_ReadOnly); hDr[i] = GDALGetDatasetDriver(hD[i]); hB[i] = GDALGetRasterBand(hD[i],1); nX = GDALGetRasterBandXSize(hB[0]); l[i] = (float *) malloc(sizeof(float)*nX); } nY = GDALGetRasterBandYSize(hB[0]); //Creating output file hD[n_imgs] = GDALCreateCopy( hDr[0], out,hD[0],FALSE,NULL,NULL,NULL); hB[n_imgs] = GDALGetRasterBand(hD[n_imgs],1); l[n_imgs] = (float *) malloc(sizeof(float)*nX); //Accessing the data rowxrow //--------------------------- for(row=0;row<nY;row++){ for (i=0;i<n_imgs;i++){ GDALRasterIO(hB[i],GF_Read,0,row,nX,1,l[i],nX,1,GDT_Float32,0,0); } //Processing the data cellxcell //----------------------------- for(col=0;col<nX;col++){ if(l[i][col] < 0) l[n_imgs][col] = -28768 ; else{ l[n_imgs][col] = 0.0; n_null_pix = 0; for (i=0;i<n_imgs;i++){ if(l[i][col] > 1) n_null_pix++; else l[n_imgs][col] += l[i][col]; } l[n_imgs][col] /= (n_imgs - n_null_pix); } } for(col=0;col<nX;col++){ l[n_imgs][col] *= 32000 ; /*to recover any positive pixel*/ //if(l[n_imgs][col]>0&&l[n_imgs][col]<1) // l[n_imgs][col]=1; } GDALRasterIO(hB[n_imgs],GF_Write,0,row,nX,1,l[n_imgs],nX,1,GDT_Float32,0,0); } for (i=0;i<n_imgs+1;i++){ if( l[i] != NULL ) free( l[i] ); GDALClose(hD[i]); } }
ossimProjection* ossimGdalProjectionFactory::createProjection(const ossimFilename& filename, ossim_uint32 entryIdx)const { ossimKeywordlist kwl; if(ossimString(filename).trim().empty()) return 0; // ossimRefPtr<ossimImageHandler> h = new ossimGdalTileSource; GDALDatasetH h = GDALOpen(filename.c_str(), GA_ReadOnly); GDALDriverH driverH = 0; ossimProjection* proj = 0; if(h) { driverH = GDALGetDatasetDriver( h ); ossimString driverName( driverH ? GDALGetDriverShortName( driverH ) : "" ); // use OSSIM's projection loader for NITF // if(driverName == "NITF") { GDALClose(h); return 0; } if(entryIdx != 0) { char** papszMetadata = GDALGetMetadata( h, "SUBDATASETS" ); //--- // ??? (drb) Should this be: // if ( entryIdx >= CSLCount(papszMetadata) ) close... //--- if( papszMetadata&&(CSLCount(papszMetadata) < static_cast<ossim_int32>(entryIdx)) ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimGdalProjectionFactory::createProjection: We don't support multi entry handlers through the factory yet, only through the handler!"; GDALClose(h); return 0; } else { GDALClose(h); return 0; } } ossimString wkt(GDALGetProjectionRef( h )); double geoTransform[6]; bool transOk = GDALGetGeoTransform( h, geoTransform ) == CE_None; bool wktTranslatorOk = wkt.empty()?false:wktTranslator.toOssimKwl(wkt, kwl); if(!wktTranslatorOk) { ossim_uint32 gcpCount = GDALGetGCPCount(h); if(gcpCount > 3) { ossim_uint32 idx = 0; const GDAL_GCP* gcpList = GDALGetGCPs(h); ossimTieGptSet tieSet; if(gcpList) { for(idx = 0; idx < gcpCount; ++idx) { ossimDpt dpt(gcpList[idx].dfGCPPixel, gcpList[idx].dfGCPLine); ossimGpt gpt(gcpList[idx].dfGCPY, gcpList[idx].dfGCPX, gcpList[idx].dfGCPZ); tieSet.addTiePoint(new ossimTieGpt(gpt, dpt, .5)); } //ossimPolynomProjection* tempProj = new ossimPolynomProjection; ossimBilinearProjection* tempProj = new ossimBilinearProjection; //tempProj->setupOptimizer("1 x y x2 xy y2 x3 y3 xy2 x2y z xz yz"); tempProj->optimizeFit(tieSet); proj = tempProj; } } } if ( transOk && proj==0 ) { ossimString proj_type(kwl.find(ossimKeywordNames::TYPE_KW)); ossimString datum_type(kwl.find(ossimKeywordNames::DATUM_KW)); ossimString units(kwl.find(ossimKeywordNames::UNITS_KW)); if ( proj_type.trim().empty() && (driverName == "MrSID" || driverName == "JP2MrSID") ) { bool bClose = true; // ESH 04/2008, #54: if no rotation factors use geographic system if( geoTransform[2] == 0.0 && geoTransform[4] == 0.0 ) { ossimString projTag( GDALGetMetadataItem( h, "IMG__PROJECTION_NAME", "" ) ); if ( projTag.contains("Geographic") ) { bClose = false; kwl.add(ossimKeywordNames::TYPE_KW, "ossimEquDistCylProjection", true); proj_type = kwl.find( ossimKeywordNames::TYPE_KW ); // Assign units if set in Metadata ossimString unitTag( GDALGetMetadataItem( h, "IMG__HORIZONTAL_UNITS", "" ) ); if ( unitTag.contains("dd") ) // decimal degrees { units = "degrees"; } else if ( unitTag.contains("dm") ) // decimal minutes { units = "minutes"; } else if ( unitTag.contains("ds") ) // decimal seconds { units = "seconds"; } } } if ( bClose == true ) { GDALClose(h); return 0; } } // Pixel-is-point of pixel-is area affects the location of the tiepoint since OSSIM is // always pixel-is-point so 1/2 pixel shift may be necessary: if((driverName == "MrSID") || (driverName == "JP2MrSID") || (driverName == "AIG")) { const char* rasterTypeStr = GDALGetMetadataItem( h, "GEOTIFF_CHAR__GTRasterTypeGeoKey", "" ); ossimString rasterTypeTag( rasterTypeStr ); // If the raster type is pixel_is_area, shift the tie point by // half a pixel to locate it at the pixel center. if ((driverName == "AIG") || (rasterTypeTag.contains("RasterPixelIsArea"))) { geoTransform[0] += fabs(geoTransform[1]) / 2.0; geoTransform[3] -= fabs(geoTransform[5]) / 2.0; } } else { // Conventionally, HFA stores the pixel alignment type for each band. Here assume all // bands are the same. Consider only the first band: GDALRasterBandH bBand = GDALGetRasterBand( h, 1 ); char** papszMetadata = GDALGetMetadata( bBand, NULL ); if (CSLCount(papszMetadata) > 0) { for(int i = 0; papszMetadata[i] != NULL; i++ ) { ossimString metaStr = papszMetadata[i]; metaStr.upcase(); if (metaStr.contains("AREA_OR_POINT")) { ossimString pixel_is_point_or_area = metaStr.split("=")[1]; pixel_is_point_or_area.upcase(); if (pixel_is_point_or_area.contains("AREA")) { // Need to shift the tie point so that pixel is point: geoTransform[0] += fabs(geoTransform[1]) / 2.0; geoTransform[3] -= fabs(geoTransform[5]) / 2.0; } break; } } } } kwl.remove(ossimKeywordNames::UNITS_KW); ossimDpt gsd(fabs(geoTransform[1]), fabs(geoTransform[5])); ossimDpt tie(geoTransform[0], geoTransform[3]); ossimUnitType savedUnitType = static_cast<ossimUnitType>(ossimUnitTypeLut::instance()->getEntryNumber(units)); ossimUnitType unitType = savedUnitType; if(unitType == OSSIM_UNIT_UNKNOWN) unitType = OSSIM_METERS; if((proj_type == "ossimLlxyProjection") || (proj_type == "ossimEquDistCylProjection")) { // ESH 09/2008 -- Add the orig_lat and central_lon if the image // is using geographic coordsys. This is used to convert the // gsd to linear units. // Half the number of pixels in lon/lat directions int nPixelsLon = GDALGetRasterXSize(h)/2.0; int nPixelsLat = GDALGetRasterYSize(h)/2.0; // Shift from image corner to center in lon/lat double shiftLon = nPixelsLon * fabs(gsd.x); double shiftLat = -nPixelsLat * fabs(gsd.y); // lon/lat of center pixel of the image double centerLon = tie.x + shiftLon; double centerLat = tie.y + shiftLat; kwl.add(ossimKeywordNames::ORIGIN_LATITUDE_KW, centerLat, true); kwl.add(ossimKeywordNames::CENTRAL_MERIDIAN_KW, centerLon, true); kwl.add(ossimKeywordNames::TIE_POINT_LAT_KW, tie.y, true); kwl.add(ossimKeywordNames::TIE_POINT_LON_KW, tie.x, true); kwl.add(ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, gsd.y, true); kwl.add(ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, gsd.x, true); if(savedUnitType == OSSIM_UNIT_UNKNOWN) { unitType = OSSIM_DEGREES; } } kwl.add(ossimKeywordNames::PIXEL_SCALE_XY_KW, gsd.toString(), true); kwl.add(ossimKeywordNames::PIXEL_SCALE_UNITS_KW, units, true); kwl.add(ossimKeywordNames::TIE_POINT_XY_KW, tie.toString(), true); kwl.add(ossimKeywordNames::TIE_POINT_UNITS_KW, units, true); std::stringstream mString; // store as a 4x4 matrix mString << ossimString::toString(geoTransform[1], 20) << " " << ossimString::toString(geoTransform[2], 20) << " " << 0 << " " << ossimString::toString(geoTransform[0], 20) << " " << ossimString::toString(geoTransform[4], 20) << " " << ossimString::toString(geoTransform[5], 20) << " " << 0 << " " << ossimString::toString(geoTransform[3], 20) << " " << 0 << " " << 0 << " " << 1 << " " << 0 << " " << 0 << " " << 0 << " " << 0 << " " << 1; kwl.add(ossimKeywordNames::IMAGE_MODEL_TRANSFORM_MATRIX_KW, mString.str().c_str(), true); //--- // SPECIAL CASE: ArcGrid in British National Grid //--- if(driverName == "AIG" && datum_type == "OSGB_1936") { ossimFilename prj_file = filename.path() + "/prj.adf"; if(prj_file.exists()) { ossimKeywordlist prj_kwl(' '); prj_kwl.addFile(prj_file); ossimString proj = prj_kwl.find("Projection"); // Reset projection and Datum correctly for BNG. if(proj.upcase().contains("GREATBRITAIN")) { kwl.add(ossimKeywordNames::TYPE_KW, "ossimBngProjection", true); ossimString datum = prj_kwl.find("Datum"); if(datum != "") { if(datum == "OGB_A") datum = "OGB-A"; else if(datum == "OGB_B") datum = "OGB-B"; else if(datum == "OGB_C") datum = "OGB-C"; else if(datum == "OGB_D") datum = "OGB-D"; else if(datum == "OGB_M") datum = "OGB-M"; else if(datum == "OGB_7") datum = "OGB-7"; kwl.add(ossimKeywordNames::DATUM_KW, datum, true); } } } } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGdalProjectionFactory: createProjection KWL = \n " << kwl << std::endl; } GDALClose(h); proj = ossimProjectionFactoryRegistry::instance()->createProjection(kwl); } return proj; }
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 ); }
/* * POPULATE_METADATA_STRUCT * * This routine just queries the GDAL raster file for all the metadata * that can be squeezed out of it. * * The resulting matlab structure is by necessity nested. Each raster * file can have several bands, e.g. PNG files usually have 3, a red, a * blue, and a green channel. Each band can have several overviews (tiffs * come to mind here). * * Fields: * ProjectionRef: a string describing the projection. Not parsed. * GeoTransform: * a 6-tuple. Entries are as follows. * [0] --> top left x * [1] --> w-e pixel resolution * [2] --> rotation, 0 if image is "north up" * [3] --> top left y * [4] --> rotation, 0 if image is "north up" * [5] --> n-s pixel resolution * * DriverShortName: describes the driver used to query *this* raster file * DriverLongName: describes the driver used to query *this* raster file * RasterXSize, RasterYSize: * These are the primary dimensions of the raster. See "Overview", though. * RasterCount: * Number of raster bands present in the file. * Driver: * This itself is a structure array. Each element describes a driver * that the locally compiled GDAL library has available. So you recompile * GDAL with new format support, this structure will change. * * Fields: * DriverShortName, DriverLongName: * Same as fields in top level structure with same name. * * Band: * Also a structure array. One element for each raster band present in * the GDAL file. See "RasterCount". * * Fields: * XSize, YSize: * Dimensions of the current raster band. * Overview: * A structure array, one element for each overview present. If * empty, then there are no overviews. * NoDataValue: * When passed back to MATLAB, one can set pixels with this value to NaN. * ColorMap: * A Mx3 double array with the colormap, or empty if it does not exists * * */ mxArray *populate_metadata_struct (GDALDatasetH hDataset, int correct_bounds) { /* These are used to define the metadata structure about available GDAL drivers. */ mxArray *mxtmp; mxArray *mxProjectionRef; mxArray *mxGeoTransform; mxArray *mxGDALDriverShortName; mxArray *mxGDALDriverLongName; mxArray *mxGDALRasterCount; mxArray *mxGDALRasterXSize; mxArray *mxGDALRasterYSize; mxArray *mxCorners; mxArray *mxGMT_header; /* * These will be matlab structures that hold the metadata. * "metadata_struct" actually encompasses "band_struct", * which encompasses "overview_struct" * */ mxArray *metadata_struct; mxArray *band_struct; mxArray *overview_struct; mxArray *corner_struct; int overview, band_number; /* Loop indices */ double *dptr; /* short cut to the mxArray data */ double *dptr2; /* "" */ GDALDriverH hDriver; /* This is the driver chosen by the GDAL library to query the dataset. */ GDALRasterBandH hBand, overview_hBand; int num_overview_fields; /* Number of metadata items for each overview structure. */ int status; /* success or failure */ double adfGeoTransform[6]; /* bounds on the dataset */ int num_overviews; /* Number of overviews in the current band. */ int num_struct_fields; /* number of fields in the metadata structures. */ int num_band_fields; int num_corner_fields; char *fieldnames[100]; /* this array contains the names of the fields of the metadata structure. */ char *band_fieldnames[100]; char *corner_fieldnames[100]; char *overview_fieldnames[100]; int xSize, ySize, raster_count; /* Dimensions of the dataset */ int gdal_type; /* Datatype of the bands. */ double tmpdble; /* temporary value */ double xy_c[2]; /* Corner coordinates */ int dims[2]; int bGotMin, bGotMax; /* To know if driver transmited Min/Max */ double adfMinMax[2]; /* Dataset Min Max */ double z_min = 1e50, z_max = -1e50; /* Create the metadata structure. Just one element, with XXX fields. */ num_struct_fields = 10; fieldnames[0] = strdup ("ProjectionRef"); fieldnames[1] = strdup ("GeoTransform"); fieldnames[2] = strdup ("DriverShortName"); fieldnames[3] = strdup ("DriverLongName"); fieldnames[4] = strdup ("RasterXSize"); fieldnames[5] = strdup ("RasterYSize"); fieldnames[6] = strdup ("RasterCount"); fieldnames[7] = strdup ("Band"); fieldnames[8] = strdup ("Corners"); fieldnames[9] = strdup("GMT_hdr"); metadata_struct = mxCreateStructMatrix ( 1, 1, num_struct_fields, (const char **)fieldnames ); /* Record the ProjectionRef. */ mxProjectionRef = mxCreateString ( GDALGetProjectionRef( hDataset ) ); mxSetField ( metadata_struct, 0, "ProjectionRef", mxProjectionRef ); /* Record the geotransform. */ mxGeoTransform = mxCreateNumericMatrix ( 6, 1, mxDOUBLE_CLASS, mxREAL ); dptr = mxGetPr ( mxGeoTransform ); if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) { dptr[0] = adfGeoTransform[0]; dptr[1] = adfGeoTransform[1]; dptr[2] = adfGeoTransform[2]; dptr[3] = adfGeoTransform[3]; dptr[4] = adfGeoTransform[4]; dptr[5] = adfGeoTransform[5]; mxSetField ( metadata_struct, 0, "GeoTransform", mxGeoTransform ); } /* Get driver information */ hDriver = GDALGetDatasetDriver( hDataset ); mxGDALDriverShortName = mxCreateString ( GDALGetDriverShortName( hDriver ) ); mxSetField ( metadata_struct, 0, (const char *) "DriverShortName", mxGDALDriverShortName ); mxGDALDriverLongName = mxCreateString ( GDALGetDriverLongName( hDriver ) ); mxSetField ( metadata_struct, 0, (const char *) "DriverLongName", mxGDALDriverLongName ); xSize = GDALGetRasterXSize( hDataset ); ySize = GDALGetRasterYSize( hDataset ); mxGDALRasterXSize = mxCreateDoubleScalar ( (double) xSize ); mxSetField ( metadata_struct, 0, (const char *) "RasterXSize", mxGDALRasterXSize ); mxGDALRasterYSize = mxCreateDoubleScalar ( (double) ySize ); mxSetField ( metadata_struct, 0, (const char *) "RasterYSize", mxGDALRasterYSize ); raster_count = GDALGetRasterCount( hDataset ); mxGDALRasterCount = mxCreateDoubleScalar ( (double)raster_count ); mxSetField ( metadata_struct, 0, (const char *) "RasterCount", mxGDALRasterCount ); /* Get the metadata for each band. */ num_band_fields = 5; band_fieldnames[0] = strdup ( "XSize" ); band_fieldnames[1] = strdup ( "YSize" ); band_fieldnames[2] = strdup ( "Overview" ); band_fieldnames[3] = strdup ( "NoDataValue" ); band_fieldnames[4] = strdup ( "DataType" ); band_struct = mxCreateStructMatrix ( raster_count, 1, num_band_fields, (const char **)band_fieldnames ); num_overview_fields = 2; overview_fieldnames[0] = strdup ( "XSize" ); overview_fieldnames[1] = strdup ( "YSize" ); for ( band_number = 1; band_number <= raster_count; ++band_number ) { /* Loop over bands */ hBand = GDALGetRasterBand( hDataset, band_number ); mxtmp = mxCreateDoubleScalar ( (double) GDALGetRasterBandXSize( hBand ) ); mxSetField ( band_struct, 0, "XSize", mxtmp ); mxtmp = mxCreateDoubleScalar ( (double) GDALGetRasterBandYSize( hBand ) ); mxSetField ( band_struct, 0, "YSize", mxtmp ); gdal_type = GDALGetRasterDataType ( hBand ); mxtmp = mxCreateString ( GDALGetDataTypeName ( (GDALDataType)gdal_type ) ); mxSetField ( band_struct, 0, (const char *) "DataType", mxtmp ); tmpdble = GDALGetRasterNoDataValue ( hBand, &status ); mxtmp = mxCreateDoubleScalar ( (double) (GDALGetRasterNoDataValue ( hBand, &status ) ) ); mxSetField ( band_struct, 0, "NoDataValue", mxtmp ); num_overviews = GDALGetOverviewCount( hBand ); /* Can have multiple overviews per band. */ if ( num_overviews > 0 ) { overview_struct = mxCreateStructMatrix ( num_overviews, 1, num_overview_fields, (const char **)overview_fieldnames ); for ( overview = 0; overview < num_overviews; ++overview ) { overview_hBand = GDALGetOverview ( hBand, overview ); xSize = GDALGetRasterBandXSize ( overview_hBand ); mxtmp = mxCreateDoubleScalar ( xSize ); mxSetField ( overview_struct, overview, "XSize", mxtmp ); ySize = GDALGetRasterBandYSize ( overview_hBand ); mxtmp = mxCreateDoubleScalar ( ySize ); mxSetField ( overview_struct, overview, "YSize", mxtmp ); } mxSetField ( band_struct, 0, "Overview", overview_struct ); } } mxSetField ( metadata_struct, 0, "Band", band_struct ); /* Record the GMT header. This will be interleaved with "corners" because they share somes values */ mxGMT_header = mxCreateNumericMatrix(1, 9, mxDOUBLE_CLASS, mxREAL); dptr2 = mxGetPr(mxGMT_header); /* Record corners. */ num_corner_fields = 4; corner_fieldnames[0] = strdup ("LL"); corner_fieldnames[1] = strdup ("UL"); corner_fieldnames[2] = strdup ("UR"); corner_fieldnames[3] = strdup ("LR"); corner_struct = mxCreateStructMatrix(1, 1, num_corner_fields, (const char **)corner_fieldnames); dims[0] = 1; dims[1] = 2; ReportCorner(hDataset, 0.0, GDALGetRasterYSize(hDataset), xy_c); /* Lower Left */ mxCorners = mxCreateNumericArray (2,dims,mxDOUBLE_CLASS, mxREAL); dptr = mxGetPr(mxCorners); dptr[0] = xy_c[0]; dptr[1] = xy_c[1]; dptr2[0] = xy_c[0]; dptr2[2] = xy_c[1]; /* xmin, ymin */ mxSetField(corner_struct, 0, "LL", mxCorners ); ReportCorner(hDataset, 0.0, 0.0, xy_c); /* Upper Left */ mxCorners = mxCreateNumericArray (2,dims,mxDOUBLE_CLASS, mxREAL); dptr = mxGetPr(mxCorners); dptr[0] = xy_c[0]; dptr[1] = xy_c[1]; mxSetField(corner_struct, 0, "UL", mxCorners ); ReportCorner(hDataset, GDALGetRasterXSize(hDataset), 0.0, xy_c); /* Upper Rigt */ mxCorners = mxCreateNumericArray (2,dims,mxDOUBLE_CLASS, mxREAL); dptr = mxGetPr(mxCorners); dptr[0] = xy_c[0]; dptr[1] = xy_c[1]; dptr2[1] = xy_c[0]; dptr2[3] = xy_c[1]; /* xmax, ymax */ mxSetField(corner_struct, 0, "UR", mxCorners ); ReportCorner(hDataset, GDALGetRasterXSize(hDataset), GDALGetRasterYSize(hDataset), xy_c); /* Lower Rigt */ mxCorners = mxCreateNumericArray (2,dims,mxDOUBLE_CLASS, mxREAL); dptr = mxGetPr(mxCorners); dptr[0] = xy_c[0]; dptr[1] = xy_c[1]; mxSetField(corner_struct, 0, "LR", mxCorners ); mxSetField (metadata_struct, 0, "Corners", corner_struct); /* Fill in the rest of the GMT header values */ if (z_min == 1e50) { /* We don't know yet the dataset Min/Max */ adfMinMax[0] = GDALGetRasterMinimum( hBand, &bGotMin ); adfMinMax[1] = GDALGetRasterMaximum( hBand, &bGotMax ); if(!(bGotMin && bGotMax)) GDALComputeRasterMinMax( hBand, TRUE, adfMinMax ); dptr2[4] = adfMinMax[0]; dptr2[5] = adfMinMax[1]; } else { dptr2[4] = z_min; dptr2[5] = z_max; } dptr2[6] = 0; dptr2[7] = adfGeoTransform[1]; dptr2[8] = fabs(adfGeoTransform[5]); if (correct_bounds) { dptr2[0] += dptr2[7] / 2; dptr2[1] -= dptr2[7] / 2; dptr2[2] += dptr2[8] / 2; dptr2[3] -= dptr2[8] / 2; } mxSetField (metadata_struct, 0, "GMT_hdr", mxGMT_header); return ( metadata_struct ); }
double *DEM_LOADER(char *DEMfilename, DataCell ***grid, char *modeltype) { /*Module DEM_LOADER_GDAL Accepts a file name and a null data grid Checks for validity of raster file loads raster file metadata into array (DEMGeoTransform) Loads Raster Data into Global Data Grid depending on Raster Type given: TOPOG: Digital Elevation Model, put into DEMgrid.dem_elev T_UNC: DEM Uncertainty , put into DEMgrid.elev_uncert RESID: Flow Residual Thickness, put into DEMgrid.residual passes data grid back through a pointer returns metadata array, or a NULL Double for errors */ GDALDatasetH DEMDataset;/*The raster file*/ GDALDriverH DEMDriver; /*essentially the raster File Type*/ GDALRasterBandH DEMBand; double *DEMGeoTransform; float *pafScanline; //DataCell **DEMgrid; //DataCell fu[5][5]; unsigned YOff; unsigned i,j; float k; if((DEMGeoTransform = malloc (sizeof (double) * 6))==NULL) { fprintf(stdout, "ERROR [DEM_LOADER]: Out of Memory creating Metadata Array!\n"); return (double*) NULL; } /*DEMGeoTransform[0] lower left x DEMGeoTransform[1] w-e pixel resolution DEMGeoTransform[2] number of cols, assigned manually in this module DEMGeoTransform[3] lower left y DEMGeoTransform[4] number of lines, assigned manually in this module DEMGeoTransform[5] n-s pixel resolution (negative value) */ GDALAllRegister(); /*Open DEM raster file*/ DEMDataset = GDALOpen( DEMfilename, GA_ReadOnly ); if(DEMDataset==NULL){ fprintf(stderr,"ERROR [DEM_LOADER]: DEM file could not be loaded!\n"); fprintf(stderr," File: %s\n", DEMfilename); return((double*) NULL); } /*Make sure Projection metadata is valid (that the raster is a valid raster)*/ if( GDALGetProjectionRef( DEMDataset ) == NULL ) { fprintf(stderr, "ERROR [DEM_LOADER]: DEM Projection metadata could not be read!\n"); fprintf(stderr," File: %s\n", DEMfilename); return((double*) NULL); } /*Read DEM raster metadata into DEMGeoTransform*/ if( GDALGetGeoTransform( DEMDataset, DEMGeoTransform ) != CE_None ) { fprintf(stderr, "ERROR [DEM_LOADER]: DEM GeoTransform metadata could not be read!\n"); fprintf(stderr," File: %s\n", DEMfilename); return((double*) NULL); } /*Find out the raster type (e.g. tiff, netcdf)*/ DEMDriver = GDALGetDatasetDriver( DEMDataset ); /*Modify Metadata for use in this program*/ DEMGeoTransform[5] = -1 * DEMGeoTransform[5]; /*row height*/ /*DEMGeoTransform[1]; col width*/ DEMGeoTransform[4] = GDALGetRasterYSize( DEMDataset ); /*number of rows*/ DEMGeoTransform[2] = GDALGetRasterXSize( DEMDataset ); /*number of cols*/ DEMGeoTransform[3] -= (DEMGeoTransform[5] * DEMGeoTransform[4]);/*Lower left Y value*/ /*DEMGeoTransform[0]; Lower left X value*/ /*Output DEM metadata to the screen*/ fprintf(stdout, "\nRaster read from %s file successfully.\n\nraster information:\n", GDALGetDriverLongName( DEMDriver ) ); fprintf(stdout," File: %s\n", DEMfilename); fprintf(stdout," Lower Left Origin: (%.6f,%.6f)\n", DEMGeoTransform[0], DEMGeoTransform[3]); fprintf(stdout," GMT Range Code: -R%.3f/%.3f/%.3f/%.3f\n", DEMGeoTransform[0], (DEMGeoTransform[0]+((DEMGeoTransform[2]-1)*DEMGeoTransform[1])), DEMGeoTransform[3], (DEMGeoTransform[3]+((DEMGeoTransform[4]-1)*DEMGeoTransform[5]))); fprintf(stdout," Pixel Size: (%.6f,%.6f)\n", DEMGeoTransform[5], DEMGeoTransform[1]); fprintf(stdout," Grid Size: (%u,%u)\n", (unsigned) DEMGeoTransform[4], (unsigned) DEMGeoTransform[2]); /*Create 2D global data grid from DEM information*/ fprintf(stdout, "\nAllocating Memory for Global Data Grid of dimensions [%u]x[%u].\n", (unsigned) DEMGeoTransform[4], (unsigned) DEMGeoTransform[2]); /*allocate memory for data grid*/ if((!strcmp(modeltype,"TOPOG")) || (!strcmp(modeltype,"DENSITY"))) { *grid = (DataCell**) GC_MALLOC((size_t)(DEMGeoTransform[4])*sizeof(DataCell*)); if (*grid==NULL){ fprintf(stderr,"[GLOBALDATA_INIT]\n"); fprintf(stderr, " NO MORE MEMORY: Tried to allocate memory for %u Rows!! Exiting\n", (int)DEMGeoTransform[4]); exit(0); } for(i=0;i < DEMGeoTransform[2]; i++){ *(*grid+i) = (DataCell*) GC_MALLOC_ATOMIC((size_t)(DEMGeoTransform[2]) * sizeof(DataCell) ); if (*(*grid+i)==NULL) { fprintf(stderr,"[GLOBALDATA_INIT]\n"); fprintf(stderr, " NO MORE MEMORY: Tried to allocate memory for %u Cols!! Exiting\n", (int) DEMGeoTransform[2]); exit(0); } } } //DEMgrid = *grid; Assign pointer position to DEMgrid variable /*Load elevation information into DEMBand. DEM should be only band in raster*/ DEMBand = GDALGetRasterBand(DEMDataset, 1); /*Allocate memory the length of a single row in the DEM*/ pafScanline = (float *) CPLMalloc(sizeof(float)*DEMGeoTransform[2]); if(!strcmp(modeltype,"TOPOG")) { fprintf(stdout," Loading DEM into Global Data Grid...\n"); for(i=0;i<DEMGeoTransform[4];i++) { /*For each row*/ /*calculate row so bottom row is read into data array first*/ YOff = (DEMGeoTransform[4]-1) - i; /*Read elevation data from row in input raster*/ if((GDALRasterIO(DEMBand, GF_Read, 0, YOff, DEMGeoTransform[2], 1, pafScanline, DEMGeoTransform[2], 1, GDT_Float32, 0, 0)) != CE_None) { fprintf(stdout, "\nERROR [DEM_LOADER]: DEM Elevation Data could not be read!\n"); fprintf(stdout," File: %s\n", DEMfilename); return((double*) NULL); } /*Status Bar*/ if((i%50)==0) { k=0; fprintf(stdout,"\r"); while(k<(DEMGeoTransform[4]-1)){ if (k<i) fprintf(stdout,"="); else if((k-((DEMGeoTransform[4]-1)/60))<i) fprintf(stdout,">"); else fprintf(stdout," "); k+=DEMGeoTransform[4]/60; } fprintf(stdout,"| %3d%%",(int) (100*i/(DEMGeoTransform[4]-1))); } /*Write elevation data column by column into 2D array using DEMgrid variable*/ for(j=0;j<DEMGeoTransform[2];j++) { (*(*grid+i)+j)->dem_elev = pafScanline[j]; //Initialize a few more variables here (*(*grid+i)+j)->active = 0; (*(*grid+i)+j)->hit_count = 0; } } } else if(strcmp(modeltype,"RESID")==0) { fprintf(stdout, " Loading RESIDUAL THICKNESS MODEL into Global Data Grid...\n"); //DEMgrid = *grid; /*Assign pointer position to DEMgrid variable*/ for(i=0;i<(DEMGeoTransform[4]);i++) { /*For each row*/ /*calculate row so bottom row is read into data array first*/ YOff = (DEMGeoTransform[4]-1) - i; /*Read elevation data from row in input raster*/ if((GDALRasterIO(DEMBand, GF_Read, 0, YOff, DEMGeoTransform[2], 1, pafScanline, DEMGeoTransform[2], 1, GDT_Float32, 0, 0)) != CE_None) { fprintf(stderr, "\nERROR [DEM_LOADER]: Residual Thickness Data (raster) could not be read!\n"); fprintf(stderr," File: %s\n", DEMfilename); return((double*) NULL); } /*Status Bar*/ if((i%50)==0) { k=0; fprintf(stdout,"\r"); while(k<(DEMGeoTransform[4]-1)){ if (k<i) fprintf(stdout,"="); else if((k-((DEMGeoTransform[4]-1)/60))<i) fprintf(stdout,">"); else fprintf(stdout," "); k+=DEMGeoTransform[4]/60; } fprintf(stdout,"| %3d%%",(int) (100*i/(DEMGeoTransform[4]-1))); } /*Write elevation data column by column into 2D array using DEMgrid variable*/ for(j=0;j<DEMGeoTransform[2];j++) { (*(*grid+i)+j)->residual = pafScanline[j]; } } } else if(strcmp(modeltype,"T_UNC")==0) { fprintf(stdout, " Loading ELEVATION UNCERTAINTY into Global Data Grid...\n"); //DEMgrid = *grid; /*Assign pointer position to DEMgrid variable*/ for(i=0;i<DEMGeoTransform[4];i++) { /*For each row*/ /*calculate row so bottom row is read into data array first*/ YOff = (DEMGeoTransform[4]-1) - i; /*Read elevation data from row in input raster*/ if((GDALRasterIO(DEMBand, GF_Read, 0, YOff, DEMGeoTransform[2], 1, pafScanline, DEMGeoTransform[2], 1, GDT_Float32, 0, 0)) != CE_None) { fprintf(stderr,"\nERROR [DEM_LOADER]: Elevation Uncertainty Data (raster) could not be read!\n"); fprintf(stderr," File: %s\n", DEMfilename); return((double*) NULL); } /*Status Bar*/ if((i%50)==0) { k=0; fprintf(stdout,"\r"); while(k<(DEMGeoTransform[4]-1)){ if (k<i) fprintf(stdout,"="); else if((k-((DEMGeoTransform[4]-1)/60))<i) fprintf(stdout,">"); else fprintf(stdout," "); k+=DEMGeoTransform[4]/60; } fprintf(stdout,"| %3d%%",(int) (100*i/(DEMGeoTransform[4]-1))); } /*Write elevation data column by column into 2D array using DEMgrid variable*/ for(j=0;j<DEMGeoTransform[2];j++) { (*(*grid+i)+j)->elev_uncert = pafScanline[j]; } } } else if(!strcmp(modeltype,"DENSITY")) { fprintf(stdout," Loading Spatial Density Map into Data Grid...\n"); for(i=0;i<DEMGeoTransform[4];i++) { /*For each row*/ /*calculate row so bottom row is read into data array first*/ YOff = (DEMGeoTransform[4]-1) - i; /*Read elevation data from row in input raster*/ if((GDALRasterIO(DEMBand, GF_Read, 0, YOff, DEMGeoTransform[2], 1, pafScanline, DEMGeoTransform[2], 1, GDT_Float32, 0, 0)) != CE_None) { fprintf(stderr,"\nERROR [DEM_LOADER]: DEM Elevation Data could not be read!\n"); fprintf(stderr," File: %s\n", DEMfilename); return((double*) NULL); } /*Status Bar*/ if((i%50)==0) { k=0; fprintf(stdout,"\r"); while(k<(DEMGeoTransform[4]-1)){ if (k<i) fprintf(stdout,"="); else if((k-((DEMGeoTransform[4]-1)/60))<i) fprintf(stdout,">"); else fprintf(stdout," "); k+=DEMGeoTransform[4]/60; } fprintf(stdout,"| %3d%%",(int) (100*i/(DEMGeoTransform[4]-1))); } /*Write elevation data column by column into 2D array using DEMgrid variable*/ for(j=0;j<DEMGeoTransform[2];j++) { (*(*grid+i)+j)->prob = pafScanline[j]; } } } else { CPLFree(pafScanline); fprintf(stderr,"\nERROR [DEM_LOADER]: Modeltype '%s' not known!\n", modeltype); return((double*) NULL); } CPLFree(pafScanline); fprintf(stdout,"\r==========================================================:)| 100%%"); fprintf(stdout,"\n Raster Loaded.\n\n"); return(DEMGeoTransform); }
int main( int argc, char *argv[] ) { if( argc < 3 ) { usage(); return 1; } //Loading the input files names //----------------------------- char *inB1 = argv[1]; //ETpotd char *inB2 = argv[2]; //ETa char *inB3 = argv[3]; //FC char *taF = argv[4]; //Ta Gap Outfile //Loading the input files //----------------------- GDALAllRegister(); GDALDatasetH hD1 = GDALOpen(inB1,GA_ReadOnly);//ETpotd GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//ETa GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//FC if(hD1==NULL||hD2==NULL||hD3==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(EXIT_FAILURE); } //Loading the file infos //---------------------- GDALDriverH hDr1 = GDALGetDatasetDriver(hD1); GDALDatasetH hDOut = GDALCreateCopy(hDr1,taF,hD1,FALSE,NULL,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); GDALRasterBandH hB1 = GDALGetRasterBand(hD1,1);//ETpotd GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//ETa GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//FC int nX = GDALGetRasterBandXSize(hB1); int nY = GDALGetRasterBandYSize(hB1); int N = nX*nY; float *l1 = (float *) malloc(sizeof(float)*N); float *l2 = (float *) malloc(sizeof(float)*N); short int *l3 = (short int *) malloc(sizeof(short int)*N); float *lOut = (float *) malloc(sizeof(float)*N); int rowcol; GDALRasterIO(hB1,GF_Read,0,0,nX,nY,l1,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB2,GF_Read,0,0,nX,nY,l2,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB3,GF_Read,0,0,nX,nY,l3,nX,nY,GDT_Int16,0,0); #pragma omp parallel for default(none) \ private (rowcol) shared (N, l1, l2, l3, lOut) for(rowcol=0;rowcol<N;rowcol++){ if(l1[rowcol] < 0 || l2[rowcol] < 0 || l3[rowcol] < 0) lOut[rowcol] = -28768; else //FC is in percentage lOut[rowcol] = (l1[rowcol] - l2[rowcol]) * l3[rowcol] / 100.0; } #pragma omp barrier GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,lOut,nX,nY,GDT_Float32,0,0); if( l1 != NULL ) free( l1 ); if( l2 != NULL ) free( l2 ); if( l3 != NULL ) free( l3 ); GDALClose(hD1); GDALClose(hD2); GDALClose(hD3); GDALClose(hDOut); return(EXIT_SUCCESS); }
int main( int argc, char *argv[] ) { if( argc < 9 ) { usage(); return 1; } char *inB1 = argv[1]; //Albedo char *inB2 = argv[2]; //Sunza char *inB3 = argv[3]; //e0-1-b31 char *inB4 = argv[4]; //e0-2-b32 char *inB5 = argv[5]; //LST char *inB6 = argv[6]; //DEM char *rnetF = argv[7]; float doy = atof( argv[8] ); float tmax = atof( argv[9] ); //MDB Farm A // double phase_max=sin(2*3.1415927*(doy+365/3.3)/365); // tmax=31.17+(36.9-24.1)/2*((1+1/3+1/5+1/7)*phase_max); // // double phase_min=sin(2*PI*(doy+365/3.5)/365); // // double tmin=31.17+(36.9-24.1)/2*((1+1/3+1/5+1/7)*phase_min); //Convert Tmax from C to K // if(tmax<100.0) tmax+=273.15; // printf("\ndoy\t= %7.2f\ntmax\t= %7.2f\n\n",doy, tmax); GDALAllRegister(); GDALDatasetH hD1 = GDALOpen(inB1,GA_ReadOnly);//Albedo GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//Sunza GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//e31 GDALDatasetH hD4 = GDALOpen(inB4,GA_ReadOnly);//e32 GDALDatasetH hD5 = GDALOpen(inB5,GA_ReadOnly);//LST GDALDatasetH hD6 = GDALOpen(inB6,GA_ReadOnly);//DEM if(hD1==NULL||hD2==NULL||hD3==NULL|| hD4==NULL||hD5==NULL||hD6==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(1); } GDALDriverH hDr6 = GDALGetDatasetDriver(hD6); GDALDatasetH hDOut = GDALCreateCopy(hDr6,rnetF,hD6,FALSE,NULL,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); GDALRasterBandH hB1 = GDALGetRasterBand(hD1,1);//Albedo GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//Sunza GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//e31 GDALRasterBandH hB4 = GDALGetRasterBand(hD4,1);//e32 GDALRasterBandH hB5 = GDALGetRasterBand(hD5,1);//LST GDALRasterBandH hB6 = GDALGetRasterBand(hD6,1);//DEM int nX = GDALGetRasterBandXSize(hB1); int nY = GDALGetRasterBandYSize(hB1); int N=nX*nY; float *mat1 = (float *) malloc(sizeof(float)*N); float *mat2 = (float *) malloc(sizeof(float)*N); float *mat3 = (float *) malloc(sizeof(float)*N); float *mat4 = (float *) malloc(sizeof(float)*N); float *mat5 = (float *) malloc(sizeof(float)*N); float *mat6 = (float *) malloc(sizeof(float)*N); float *matOut = (float *) malloc(sizeof(float)*N); float e0, rnet; int rowcol; GDALRasterIO(hB1,GF_Read,0,0,nX,nY,mat1,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB2,GF_Read,0,0,nX,nY,mat2,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB3,GF_Read,0,0,nX,nY,mat3,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB4,GF_Read,0,0,nX,nY,mat4,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB5,GF_Read,0,0,nX,nY,mat5,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB6,GF_Read,0,0,nX,nY,mat6,nX,nY,GDT_Float32,0,0); #pragma omp parallel for default(none) \ private(rowcol, e0, rnet)\ shared(N, tmax, doy,\ mat1,mat2,mat3,mat4,mat5,mat6, \ matOut ) for(rowcol=0;rowcol<N;rowcol++){ if(mat1[rowcol]==-28768||mat5[rowcol]==-28768||mat5[rowcol]==0) matOut[rowcol] = -28768; else { e0 = 0.5*((mat3[rowcol]*0.002+0.49)+(mat4[rowcol]*0.002+0.49)); rnet = r_net(mat1[rowcol]*0.001,mat2[rowcol]*0.01,e0,mat5[rowcol]*0.02,mat6[rowcol],doy,tmax); matOut[rowcol]=rnet; } } #pragma omp barrier GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,matOut,nX,nY,GDT_Float32,0,0); GDALClose(hDOut); //free memory close unused files if(mat1 != NULL) free(mat1); if(mat2 != NULL) free(mat2); if(mat3 != NULL) free(mat3); if(mat4 != NULL) free(mat4); if(mat5 != NULL) free(mat5); if(mat6 != NULL) free(mat6); if(matOut != NULL) free(matOut); GDALClose(hD1); GDALClose(hD2); GDALClose(hD3); GDALClose(hD4); GDALClose(hD5); GDALClose(hD6); return(EXIT_SUCCESS); }
int main( int argc, char *argv[] ) { if( argc < 7 ) { usage(); return 1; } int row, col; double geomx[6]={0.0}; char *inB1 = argv[1]; //Albedo char *inB2 = argv[2]; //DEM char *inB3 = argv[3]; //e0 31 char *inB4 = argv[4]; //e0 32 char *inB5 = argv[5]; //LST char *rnetdF = argv[6]; float doy = atof( argv[7] ); // printf("\ndoy\t= %7.2f\n\n",doy); // printf("%s %s %s %s %s\n",inB1, inB2, inB3, inB4, inB5); GDALAllRegister(); GDALDatasetH hD1 = GDALOpen(inB1,GA_ReadOnly);//Albedo GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//DEM GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//E 31 GDALDatasetH hD4 = GDALOpen(inB4,GA_ReadOnly);//E 32 GDALDatasetH hD5 = GDALOpen(inB5,GA_ReadOnly);//LST if(hD1==NULL||hD2==NULL||hD3==NULL||hD4==NULL||hD5==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(1); } if(GDALGetGeoTransform(hD1,geomx)==CE_None){ /* Do Nothing */ // printf( "Origin (ULx,ULy) = (%.6f,%.6f)\n", geomx[0], geomx[3] ); // printf( "Pixel Size = (%.6f,%.6f)\n", geomx[1], geomx[5] ); // printf( "Rot0 = (%.6f,%.6f)\n", geomx[2], geomx[4] ); } else { printf("ERROR: Projection acquisition problem from Band1\n"); exit(1); } GDALDriverH hDr2 = GDALGetDatasetDriver(hD2); //RNETD out GDALDatasetH hDOut = GDALCreateCopy( hDr2, rnetdF,hD2,FALSE,NULL,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); GDALRasterBandH hB1 = GDALGetRasterBand(hD1,1);//Albedo GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//DEM GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//E 31 GDALRasterBandH hB4 = GDALGetRasterBand(hD4,1);//E 32 GDALRasterBandH hB5 = GDALGetRasterBand(hD5,1);//LST int nX = GDALGetRasterBandXSize(hB1); int nY = GDALGetRasterBandYSize(hB1); float *mat1 = (float *) malloc(sizeof(float)*nX); float *mat2 = (float *) malloc(sizeof(float)*nX); float *mat3 = (float *) malloc(sizeof(float)*nX); float *mat4 = (float *) malloc(sizeof(float)*nX); float *mat5 = (float *) malloc(sizeof(float)*nX); float *matOut = (float *) malloc(sizeof(float)*nX); /* int i,temp,histogramT[512]; for (i=0;i<512;i++){ histogramT[i]=0; }*/ float solar, rnetd, e0; for(row=0;row<nY;row++){ GDALRasterIO(hB1,GF_Read,0,row,nX,1,mat1,nX,1,GDT_Float32,0,0); GDALRasterIO(hB2,GF_Read,0,row,nX,1,mat2,nX,1,GDT_Float32,0,0); GDALRasterIO(hB3,GF_Read,0,row,nX,1,mat3,nX,1,GDT_Float32,0,0); GDALRasterIO(hB4,GF_Read,0,row,nX,1,mat4,nX,1,GDT_Float32,0,0); GDALRasterIO(hB5,GF_Read,0,row,nX,1,mat5,nX,1,GDT_Float32,0,0); #pragma omp parallel for default(none) \ private(col, solar, rnetd, e0)\ shared( row, doy, geomx,nX, \ mat1, mat2, mat3, mat4, mat5, matOut ) for(col=0;col<nX;col++){ if(mat1[col]==-28768||mat5[col]==-28768||mat5[col]==0){ matOut[col] = -28768; }else { /*temp = (int) (mat1[col]); if(temp>0) histogramT[temp]=histogramT[temp]+1.0;*/ // printf("lat=%f\n", geomx[3]+geomx[4]*col+geomx[5]*row); // printf("%f \n",e0); e0 = 0.5*((mat3[col]*0.002+0.49)+(mat4[col]*0.002+0.49)); solar = solar_day(geomx[3]+geomx[4]*col+geomx[5]*row, doy, mat2[col] ); //rnetd = r_net_d( mat1[col]*0.001, solar, e0, mat5[col]*0.02, mat2[col]); rnetd = r_net_day( mat1[col]*0.001, solar, mat2[col]); matOut[col]=rnetd; } } #pragma omp barrier GDALRasterIO(hBOut,GF_Write,0,row,nX,1,matOut,nX,1,GDT_Float32,0,0); } GDALClose(hDOut); /* for (i=0;i<512;i++){ printf("%i\t%i\n",i,histogramT[i]); }*/ //free memory close unused files if(mat1 != NULL) free(mat1); if(mat2 != NULL) free(mat2); if(mat3 != NULL) free(mat3); if(mat4 != NULL) free(mat4); if(mat5 != NULL) free(mat5); if(matOut != NULL) free(matOut); GDALClose(hD1); GDALClose(hD2); GDALClose(hD3); GDALClose(hD4); GDALClose(hD5); return(EXIT_SUCCESS); }
SVImage init(int xLow, int xHigh, int yLow, int yHigh, const char *filepath){ GDALDatasetH hDataset; // Register drivers GDALAllRegister(); // open the given file as Read Only hDataset = GDALOpen(filepath, GA_ReadOnly ); // if opening failed if( hDataset == NULL ) { fprintf(stderr, "Unable to open file."); exit(EXIT_FAILURE); } /* Declare some variables to be used later */ int *xBlockSize = malloc(sizeof(int)); int *yBlockSize = malloc(sizeof(int)); int xOutputSize; int yOutputSize; int numXBlocks; int numYBlocks; int origWidth; int origHeight; int origBandCount; /*Get some information on the image*/ origWidth = GDALGetRasterXSize( hDataset ); // Get raster pixel width origHeight = GDALGetRasterYSize( hDataset ); // Get raster pixel height origBandCount = GDALGetRasterCount( hDataset ); // Get number of raster bands in the image GDALRasterBandH hBand = GDALGetRasterBand( hDataset, 1 ); // Get raster band with id 1 GDALGetBlockSize( hBand, xBlockSize, yBlockSize); // Fetch the block size for this band /*TODO make sure scale is set somewhere*/ /*Store some information on what the output should have*/ xOutputSize = ((*xBlockSize) / scale); // get the new x block size yOutputSize = ((*yBlockSize) / scale); // get the new y block size numXBlocks = origWidth/(*xBlockSize); // Get x block count numYBlocks = origHeight/(*yBlockSize); // Get y block count int bandCount; if (origBandCount >= 3) // Just a guess, limit bands to RGB? { bandCount = 3; } else // Otherwise image is probably grayscale, one band? { bandCount = 1; } /*TODO edit this or remove it since we aren't using focusing on openGL*/ /* *int format; *if (bandCount == 3) *{ * format = GL_RGBA; *} *else *{ * format = GL_LUMINANCE_ALPHA; *} */ int usedBlocks; int usedXBlocks; int usedYBlocks; /* *This is odd, xHigh and yHigh are *passed as parameters but changed here *TODO see if we can remove parameters or just use this */ if ((xHigh < 0) || (xHigh < xLow)) { xHigh = numXBlocks; } if ((yHigh < 0)|| (yHigh < yLow)) { yHigh = numYBlocks; } usedXBlocks = (xHigh - xLow); // This is probably the part of the image that should be displayed on screen usedYBlocks = (yHigh - yLow); // Y part on screen? usedBlocks = (usedXBlocks * usedYBlocks); // Total blocks on screen? SVImage svip = { .Width = xOutputSize*usedXBlocks, .Height = yOutputSize*usedYBlocks, .BytesPerPixel = 1, .Data = (CPLMalloc((sizeof(char) * xOutputSize * yOutputSize * usedBlocks * (bandCount+1)))) // Data = xOutputSize * yOutputSize = pixels/block * usedBlocks = totalpixels }; free(xBlockSize); free(yBlockSize); return svip; } /* Uses stochastic sampling to fill the data section of an SVImage struct. */ void sample(params *in) //TODO handle 32 bit representations { /*Set variables from the params struct*/ SVImage* out = in->target; int xLow = in->xLow; int xHigh = in->xHigh; int yLow = in->yLow; int yHigh = in->yHigh; const char *file = in->file; GDALDatasetH hDataset; GDALRasterBandH hBand; /*Register drivers*/ GDALAllRegister(); //TODO Dynamically calculate sample count? int avgSampleCount = 25; //Open GDAL File //------------------------------------------------ hDataset = GDALOpen(file, GA_ReadOnly ); if( hDataset == NULL ) { fprintf(stderr, "Unable to open file.\n"); exit(EXIT_FAILURE); } //GDAL FILE INFO //--------------------------------------------- GDALDriverH hDriver; hDriver = GDALGetDatasetDriver( hDataset ); // Get driver for this file double adfGeoTransform[6]; //Print GDAL Driver printf( "Driver: %s/%s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver ) ); //Get original raster size int origWidth = GDALGetRasterXSize( hDataset ); int origHeight = GDALGetRasterYSize( hDataset ); printf("width = %i\n", origWidth); printf("height = %i\n", origHeight); //Get Raster band count int origBandCount = GDALGetRasterCount( hDataset ); printf("origBandCount = %i\n", origBandCount); int bandCount; if (origBandCount >= 3) { bandCount = 3; } else { bandCount = 1; } //Target output Width and Height float stride = (scale * scale); stride /= (avgSampleCount); //the greatest number of pixels that can be skipped in a single iteration int maxStride = ((int)stride) + 1; //Load band 1 hBand = GDALGetRasterBand( hDataset, 1 ); if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) { printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5] ); } else { fprintf(stderr, "Failed to get pixel size\n"); } int* xBlockSize = malloc(sizeof(int)); int* yBlockSize = malloc(sizeof(int)); //get block size GDALGetBlockSize( hBand, xBlockSize, yBlockSize); printf("xBlockSize = %i\n", *xBlockSize); printf("yBlockSize = %i\n", *yBlockSize); int xOutputSize = ((*xBlockSize) / scale); int yOutputSize = ((*yBlockSize) / scale); printf("X Output Size%i\n", xOutputSize); int numXBlocks = origWidth/(*xBlockSize); int numYBlocks = origHeight/(*yBlockSize); printf("numXBlocks = %i\n", numXBlocks); printf("numYBlocks = %i\n", numYBlocks); if ((xHigh < 0) || (xHigh < xLow)) { xHigh = numXBlocks; } if ((yHigh < 0)|| (yHigh < yLow)) { yHigh = numYBlocks; } int usedXBlocks = (xHigh - xLow); int usedYBlocks = (yHigh - yLow); int usedBlocks = (usedXBlocks * usedYBlocks); unsigned char* output = CPLMalloc((sizeof(char) * xOutputSize* yOutputSize *usedBlocks * (bandCount+1))); // Allocate space for the output float* vals = calloc( xOutputSize* yOutputSize *usedBlocks * (bandCount+1), sizeof(float)); //stores pixel values unsigned long* valsPerIndex = calloc( xOutputSize* yOutputSize * usedBlocks * (bandCount+1), sizeof(unsigned long)); //stores number of pixel values per output index unsigned long rseed = 0; unsigned long rowIndex = 0; //the index of the row to which we will output our value unsigned long colIndex = 0; //the index of the column to which we will output our value unsigned long outIndex = 0; unsigned long sampledIndex = 0; //One dimensional representation of column/row index //iterate through each pixel, jump to the last pixel we sampled. long long i = 0; int outputXOffset = 0; int outputYOffset = 0; int outputIndexOffset = 0; if (GDALGetRasterDataType(hBand) == GDT_Int16) { short* data = (short *) CPLMalloc(sizeof(unsigned short) * (*xBlockSize)*(*yBlockSize)); //TODO: GDAL Raster can be 16 bit pixel representation int band; for (band = 1; band <= bandCount; band++){ hBand = GDALGetRasterBand( hDataset, band ); int yBlock, xBlock; for(yBlock = yLow; yBlock < yHigh; yBlock++){ for(xBlock = xLow; xBlock < xHigh; xBlock++){ if(GDALReadBlock(hBand,xBlock,yBlock, data) != CE_None) { fprintf(stderr, "Read block failed\n"); exit(EXIT_FAILURE); } for(i = 0 ; i < ((*xBlockSize)*(*yBlockSize)-1) ; i += rseed){ rseed = (214013 * rseed + 2531011); // Magic numbers. rseed %= maxStride; sampledIndex = i; i = (maxStride ==1) ? (i+1) : i; rowIndex = (sampledIndex/(xOutputSize*scale* scale)) + ((yBlock - yLow)* yOutputSize); colIndex = ((sampledIndex % (xOutputSize * scale))/scale) + ((xBlock - xLow) * xOutputSize); outIndex = ((rowIndex * (xOutputSize * usedXBlocks ) + colIndex) * (bandCount+1) ) + (band -1); vals[outIndex] += (*(data + sampledIndex)); vals[outIndex] += 118.450588 + ((*(data + sampledIndex))/128); if (vals[outIndex]/valsPerIndex[outIndex] < 0) { vals[outIndex] =0; }else if (vals[outIndex]/valsPerIndex[outIndex] > 255){ vals[outIndex] = 255; } } } } } } else { unsigned char* data = (unsigned char *) CPLMalloc(sizeof(char) * (*xBlockSize)*(*yBlockSize)); int band; for (band = 1; band <= bandCount; band++) { hBand = GDALGetRasterBand( hDataset, band ); int yBlock, xBlock; outputYOffset = 0; for(yBlock = yLow; yBlock < yHigh; yBlock++){ outputYOffset = ((yBlock - yLow) * yOutputSize * xOutputSize * usedXBlocks * (bandCount + 1)); outputXOffset = 0; for(xBlock = xLow; xBlock < xHigh; xBlock++){ outputXOffset = ((xBlock - xLow) * xOutputSize * (bandCount + 1)); if(GDALReadBlock(hBand,xBlock,yBlock, data) != CE_None) { fprintf(stderr, "Read block failed\n"); exit(EXIT_FAILURE); } for(i = 0 ; i < ((*xBlockSize)*(*yBlockSize)) ; i += rseed){ rseed = (214013 * rseed + 2531011); rseed %= maxStride; sampledIndex = i; i = (maxStride ==1) ? (i+1) : i; rowIndex = (sampledIndex/(xOutputSize*scale* scale)) + ((yBlock - yLow)* yOutputSize); colIndex = ((sampledIndex % (xOutputSize * scale))/scale) + ((xBlock - xLow) * xOutputSize); outIndex = ((rowIndex * (xOutputSize * usedXBlocks ) + colIndex) * (bandCount+1) ) + (band -1); vals[outIndex] += (*(data + sampledIndex)); valsPerIndex[outIndex] +=1; } outputIndexOffset = (outputYOffset + outputXOffset); int j; for (j = 0; j<yOutputSize; j++){ i = outputIndexOffset; int k = (i + (xOutputSize * (bandCount+1))); for (i = 0; i<k;i++){ int x = (i+(j*(xOutputSize * (bandCount + 1) * (usedXBlocks)))); if(((x+1)%4==0&&bandCount==3)||((x+1)%2==0&&bandCount==1)){ output[x] = (unsigned char) 1; //Sets the alpha to opaque }else{ output[x] = (unsigned char) (vals[x]/valsPerIndex[x]); //calculate final output by averaging each color value } } } out->Data = output; } } } } printf("sampling complete\n"); GDALClose(hDataset); }
MAIN_START(argc, argv) { // Check that we are running against at least GDAL 1.4. // Note to developers: if we use newer API, please change the requirement. if( atoi(GDALVersionInfo("VERSION_NUM")) < 1400 ) { fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, " "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME); exit(1); } GDALAllRegister(); OGRRegisterAll(); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Get commandline arguments other than the GDAL raster filenames. */ /* -------------------------------------------------------------------- */ const char* pszIndexLayerName = nullptr; const char *index_filename = nullptr; const char *tile_index = "location"; const char* pszDriverName = nullptr; size_t nMaxFieldSize = 254; bool write_absolute_path = false; char* current_path = nullptr; bool skip_different_projection = false; const char *pszTargetSRS = ""; bool bSetTargetSRS = false; const char* pszSrcSRSName = nullptr; int i_SrcSRSName = -1; bool bSrcSRSFormatSpecified = false; SrcSRSFormat eSrcSRSFormat = FORMAT_AUTO; int iArg = 1; // Used after for. for( ; iArg < argc; iArg++ ) { if( EQUAL(argv[iArg], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against " "GDAL %s\n", argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); CSLDestroy( argv ); return 0; } else if( EQUAL(argv[iArg],"--help") ) Usage(nullptr); else if( (strcmp(argv[iArg],"-f") == 0 || strcmp(argv[iArg],"-of") == 0) ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszDriverName = argv[++iArg]; } else if( strcmp(argv[iArg],"-lyr_name") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszIndexLayerName = argv[++iArg]; } else if( strcmp(argv[iArg],"-tileindex") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); tile_index = argv[++iArg]; } else if( strcmp(argv[iArg],"-t_srs") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszTargetSRS = argv[++iArg]; bSetTargetSRS = true; } else if ( strcmp(argv[iArg],"-write_absolute_path") == 0 ) { write_absolute_path = true; } else if ( strcmp(argv[iArg],"-skip_different_projection") == 0 ) { skip_different_projection = true; } else if( strcmp(argv[iArg], "-src_srs_name") == 0 ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszSrcSRSName = argv[++iArg]; } else if( strcmp(argv[iArg], "-src_srs_format") == 0 ) { const char* pszFormat; bSrcSRSFormatSpecified = true; CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszFormat = argv[++iArg]; if( EQUAL(pszFormat, "AUTO") ) eSrcSRSFormat = FORMAT_AUTO; else if( EQUAL(pszFormat, "WKT") ) eSrcSRSFormat = FORMAT_WKT; else if( EQUAL(pszFormat, "EPSG") ) eSrcSRSFormat = FORMAT_EPSG; else if( EQUAL(pszFormat, "PROJ") ) eSrcSRSFormat = FORMAT_PROJ; } else if( argv[iArg][0] == '-' ) Usage(CPLSPrintf("Unknown option name '%s'", argv[iArg])); else if( index_filename == nullptr ) { index_filename = argv[iArg]; iArg++; break; } } if( index_filename == nullptr ) Usage("No index filename specified."); if( iArg == argc ) Usage("No file to index specified."); if( bSrcSRSFormatSpecified && pszSrcSRSName == nullptr ) Usage("-src_srs_name must be specified when -src_srs_format is " "specified."); /* -------------------------------------------------------------------- */ /* Create and validate target SRS if given. */ /* -------------------------------------------------------------------- */ OGRSpatialReferenceH hTargetSRS = nullptr; if( bSetTargetSRS ) { if( skip_different_projection ) { fprintf( stderr, "Warning : -skip_different_projection does not apply " "when -t_srs is requested.\n" ); } hTargetSRS = OSRNewSpatialReference(""); OSRSetAxisMappingStrategy(hTargetSRS, OAMS_TRADITIONAL_GIS_ORDER); // coverity[tainted_data] if( OSRSetFromUserInput( hTargetSRS, pszTargetSRS ) != CE_None ) { OSRDestroySpatialReference( hTargetSRS ); fprintf( stderr, "Invalid target SRS `%s'.\n", pszTargetSRS ); exit(1); } } /* -------------------------------------------------------------------- */ /* Open or create the target datasource */ /* -------------------------------------------------------------------- */ GDALDatasetH hTileIndexDS = GDALOpenEx( index_filename, GDAL_OF_VECTOR | GDAL_OF_UPDATE, nullptr, nullptr, nullptr ); OGRLayerH hLayer = nullptr; CPLString osFormat; if( hTileIndexDS != nullptr ) { GDALDriverH hDriver = GDALGetDatasetDriver(hTileIndexDS); if( hDriver ) osFormat = GDALGetDriverShortName(hDriver); if( GDALDatasetGetLayerCount(hTileIndexDS) == 1 ) { hLayer = GDALDatasetGetLayer(hTileIndexDS, 0); } else { if( pszIndexLayerName == nullptr ) { printf( "-lyr_name must be specified.\n" ); exit( 1 ); } CPLPushErrorHandler(CPLQuietErrorHandler); hLayer = GDALDatasetGetLayerByName(hTileIndexDS, pszIndexLayerName); CPLPopErrorHandler(); } } else { printf( "Creating new index file...\n" ); if( pszDriverName == nullptr ) { std::vector<CPLString> aoDrivers = GetOutputDriversFor(index_filename, GDAL_OF_VECTOR); if( aoDrivers.empty() ) { CPLError( CE_Failure, CPLE_AppDefined, "Cannot guess driver for %s", index_filename); exit( 10 ); } else { if( aoDrivers.size() > 1 ) { CPLError( CE_Warning, CPLE_AppDefined, "Several drivers matching %s extension. Using %s", CPLGetExtension(index_filename), aoDrivers[0].c_str() ); } osFormat = aoDrivers[0]; } } else { osFormat = pszDriverName; } if( !EQUAL(osFormat, "ESRI Shapefile") ) nMaxFieldSize = 0; GDALDriverH hDriver = GDALGetDriverByName( osFormat.c_str() ); if( hDriver == nullptr ) { printf( "%s driver not available.\n", osFormat.c_str() ); exit( 1 ); } hTileIndexDS = GDALCreate( hDriver, index_filename, 0, 0, 0, GDT_Unknown, nullptr ); } if( hTileIndexDS != nullptr && hLayer == nullptr ) { OGRSpatialReferenceH hSpatialRef = nullptr; char* pszLayerName = nullptr; if( pszIndexLayerName == nullptr ) { VSIStatBuf sStat; if( EQUAL(osFormat, "ESRI Shapefile") || VSIStat(index_filename, &sStat) == 0 ) { pszLayerName = CPLStrdup(CPLGetBasename(index_filename)); } else { printf( "-lyr_name must be specified.\n" ); exit( 1 ); } } else { pszLayerName = CPLStrdup(pszIndexLayerName); } /* get spatial reference for output file from target SRS (if set) */ /* or from first input file */ if( bSetTargetSRS ) { hSpatialRef = OSRClone( hTargetSRS ); } else { GDALDatasetH hDS = GDALOpen( argv[iArg], GA_ReadOnly ); if( hDS ) { const char* pszWKT = GDALGetProjectionRef(hDS); if (pszWKT != nullptr && pszWKT[0] != '\0') { hSpatialRef = OSRNewSpatialReference(pszWKT); OSRSetAxisMappingStrategy(hSpatialRef, OAMS_TRADITIONAL_GIS_ORDER); } GDALClose(hDS); } } hLayer = GDALDatasetCreateLayer( hTileIndexDS, pszLayerName, hSpatialRef, wkbPolygon, nullptr ); CPLFree(pszLayerName); if( hSpatialRef ) OSRRelease(hSpatialRef); if( hLayer ) { OGRFieldDefnH hFieldDefn = OGR_Fld_Create( tile_index, OFTString ); if( nMaxFieldSize ) OGR_Fld_SetWidth( hFieldDefn, static_cast<int>(nMaxFieldSize)); OGR_L_CreateField( hLayer, hFieldDefn, TRUE ); OGR_Fld_Destroy(hFieldDefn); if( pszSrcSRSName != nullptr ) { hFieldDefn = OGR_Fld_Create( pszSrcSRSName, OFTString ); if( nMaxFieldSize ) OGR_Fld_SetWidth(hFieldDefn, static_cast<int>(nMaxFieldSize)); OGR_L_CreateField( hLayer, hFieldDefn, TRUE ); OGR_Fld_Destroy(hFieldDefn); } } } if( hTileIndexDS == nullptr || hLayer == nullptr ) { fprintf( stderr, "Unable to open/create shapefile `%s'.\n", index_filename ); exit(2); } OGRFeatureDefnH hFDefn = OGR_L_GetLayerDefn(hLayer); const int ti_field = OGR_FD_GetFieldIndex( hFDefn, tile_index ); if( ti_field < 0 ) { fprintf( stderr, "Unable to find field `%s' in file `%s'.\n", tile_index, index_filename ); exit(2); } if( pszSrcSRSName != nullptr ) i_SrcSRSName = OGR_FD_GetFieldIndex( hFDefn, pszSrcSRSName ); // Load in memory existing file names in SHP. int nExistingFiles = static_cast<int>(OGR_L_GetFeatureCount(hLayer, FALSE)); if( nExistingFiles < 0) nExistingFiles = 0; char** existingFilesTab = nullptr; bool alreadyExistingProjectionRefValid = false; char* alreadyExistingProjectionRef = nullptr; if( nExistingFiles > 0 ) { OGRFeatureH hFeature = nullptr; existingFilesTab = static_cast<char **>( CPLMalloc(nExistingFiles * sizeof(char*))); for( int i = 0; i < nExistingFiles; i++ ) { hFeature = OGR_L_GetNextFeature(hLayer); existingFilesTab[i] = CPLStrdup(OGR_F_GetFieldAsString( hFeature, ti_field )); if( i == 0 ) { GDALDatasetH hDS = GDALOpen(existingFilesTab[i], GA_ReadOnly ); if( hDS ) { alreadyExistingProjectionRefValid = true; alreadyExistingProjectionRef = CPLStrdup(GDALGetProjectionRef(hDS)); GDALClose(hDS); } } OGR_F_Destroy( hFeature ); } } if( write_absolute_path ) { current_path = CPLGetCurrentDir(); if (current_path == nullptr) { fprintf( stderr, "This system does not support the CPLGetCurrentDir call. " "The option -write_absolute_path will have no effect\n" ); write_absolute_path = FALSE; } } /* -------------------------------------------------------------------- */ /* loop over GDAL files, processing. */ /* -------------------------------------------------------------------- */ for( ; iArg < argc; iArg++ ) { char *fileNameToWrite = nullptr; VSIStatBuf sStatBuf; // Make sure it is a file before building absolute path name. if( write_absolute_path && CPLIsFilenameRelative( argv[iArg] ) && VSIStat( argv[iArg], &sStatBuf ) == 0 ) { fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path, argv[iArg])); } else { fileNameToWrite = CPLStrdup(argv[iArg]); } // Checks that file is not already in tileindex. { int i = 0; // Used after for. for( ; i < nExistingFiles; i++ ) { if (EQUAL(fileNameToWrite, existingFilesTab[i])) { fprintf(stderr, "File %s is already in tileindex. Skipping it.\n", fileNameToWrite); break; } } if (i != nExistingFiles) { CPLFree(fileNameToWrite); continue; } } GDALDatasetH hDS = GDALOpen( argv[iArg], GA_ReadOnly ); if( hDS == nullptr ) { fprintf( stderr, "Unable to open %s, skipping.\n", argv[iArg] ); CPLFree(fileNameToWrite); continue; } double adfGeoTransform[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; GDALGetGeoTransform( hDS, adfGeoTransform ); if( adfGeoTransform[0] == 0.0 && adfGeoTransform[1] == 1.0 && adfGeoTransform[3] == 0.0 && std::abs(adfGeoTransform[5]) == 1.0 ) { fprintf( stderr, "It appears no georeferencing is available for\n" "`%s', skipping.\n", argv[iArg] ); GDALClose( hDS ); CPLFree(fileNameToWrite); continue; } const char *projectionRef = GDALGetProjectionRef(hDS); // If not set target srs, test that the current file uses same // projection as others. if( !bSetTargetSRS ) { if( alreadyExistingProjectionRefValid ) { int projectionRefNotNull, alreadyExistingProjectionRefNotNull; projectionRefNotNull = projectionRef && projectionRef[0]; alreadyExistingProjectionRefNotNull = alreadyExistingProjectionRef && alreadyExistingProjectionRef[0]; if ((projectionRefNotNull && alreadyExistingProjectionRefNotNull && EQUAL(projectionRef, alreadyExistingProjectionRef) == 0) || (projectionRefNotNull != alreadyExistingProjectionRefNotNull)) { fprintf( stderr, "Warning : %s is not using the same projection system " "as other files in the tileindex.\n" "This may cause problems when using it in MapServer " "for example.\n" "Use -t_srs option to set target projection system " "(not supported by MapServer).\n" "%s\n", argv[iArg], skip_different_projection ? "Skipping this file." : ""); if( skip_different_projection ) { CPLFree(fileNameToWrite); GDALClose( hDS ); continue; } } } else { alreadyExistingProjectionRefValid = true; alreadyExistingProjectionRef = CPLStrdup(projectionRef); } } const int nXSize = GDALGetRasterXSize( hDS ); const int nYSize = GDALGetRasterYSize( hDS ); double adfX[5] = { 0.0, 0.0, 0.0, 0.0, 0.0 }; double adfY[5] = { 0.0, 0.0, 0.0, 0.0, 0.0 }; adfX[0] = adfGeoTransform[0] + 0 * adfGeoTransform[1] + 0 * adfGeoTransform[2]; adfY[0] = adfGeoTransform[3] + 0 * adfGeoTransform[4] + 0 * adfGeoTransform[5]; adfX[1] = adfGeoTransform[0] + nXSize * adfGeoTransform[1] + 0 * adfGeoTransform[2]; adfY[1] = adfGeoTransform[3] + nXSize * adfGeoTransform[4] + 0 * adfGeoTransform[5]; adfX[2] = adfGeoTransform[0] + nXSize * adfGeoTransform[1] + nYSize * adfGeoTransform[2]; adfY[2] = adfGeoTransform[3] + nXSize * adfGeoTransform[4] + nYSize * adfGeoTransform[5]; adfX[3] = adfGeoTransform[0] + 0 * adfGeoTransform[1] + nYSize * adfGeoTransform[2]; adfY[3] = adfGeoTransform[3] + 0 * adfGeoTransform[4] + nYSize * adfGeoTransform[5]; adfX[4] = adfGeoTransform[0] + 0 * adfGeoTransform[1] + 0 * adfGeoTransform[2]; adfY[4] = adfGeoTransform[3] + 0 * adfGeoTransform[4] + 0 * adfGeoTransform[5]; OGRSpatialReferenceH hSourceSRS = nullptr; if( (bSetTargetSRS || i_SrcSRSName >= 0) && projectionRef != nullptr && projectionRef[0] != '\0' ) { hSourceSRS = OSRNewSpatialReference( projectionRef ); OSRSetAxisMappingStrategy(hSourceSRS, OAMS_TRADITIONAL_GIS_ORDER); } // If set target srs, do the forward transformation of all points. if( bSetTargetSRS && projectionRef != nullptr && projectionRef[0] != '\0' ) { OGRCoordinateTransformationH hCT = nullptr; if( hSourceSRS && !OSRIsSame( hSourceSRS, hTargetSRS ) ) { hCT = OCTNewCoordinateTransformation( hSourceSRS, hTargetSRS ); if( hCT == nullptr || !OCTTransform( hCT, 5, adfX, adfY, nullptr ) ) { fprintf( stderr, "Warning : unable to transform points from source " "SRS `%s' to target SRS `%s'\n" "for file `%s' - file skipped\n", projectionRef, pszTargetSRS, fileNameToWrite ); if( hCT ) OCTDestroyCoordinateTransformation( hCT ); if( hSourceSRS ) OSRDestroySpatialReference( hSourceSRS ); continue; } if( hCT ) OCTDestroyCoordinateTransformation( hCT ); } } OGRFeatureH hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) ); OGR_F_SetFieldString( hFeature, ti_field, fileNameToWrite ); if( i_SrcSRSName >= 0 && hSourceSRS != nullptr ) { const char* pszAuthorityCode = OSRGetAuthorityCode(hSourceSRS, nullptr); const char* pszAuthorityName = OSRGetAuthorityName(hSourceSRS, nullptr); if( eSrcSRSFormat == FORMAT_AUTO ) { if( pszAuthorityName != nullptr && pszAuthorityCode != nullptr ) { OGR_F_SetFieldString( hFeature, i_SrcSRSName, CPLSPrintf("%s:%s", pszAuthorityName, pszAuthorityCode) ); } else if( nMaxFieldSize == 0 || strlen(projectionRef) <= nMaxFieldSize ) { OGR_F_SetFieldString(hFeature, i_SrcSRSName, projectionRef); } else { char* pszProj4 = nullptr; if( OSRExportToProj4(hSourceSRS, &pszProj4) == OGRERR_NONE ) { OGR_F_SetFieldString( hFeature, i_SrcSRSName, pszProj4 ); CPLFree(pszProj4); } else { OGR_F_SetFieldString( hFeature, i_SrcSRSName, projectionRef ); } } } else if( eSrcSRSFormat == FORMAT_WKT ) { if( nMaxFieldSize == 0 || strlen(projectionRef) <= nMaxFieldSize ) { OGR_F_SetFieldString( hFeature, i_SrcSRSName, projectionRef ); } else { fprintf(stderr, "Cannot write WKT for file %s as it is too long!\n", fileNameToWrite); } } else if( eSrcSRSFormat == FORMAT_PROJ ) { char* pszProj4 = nullptr; if( OSRExportToProj4(hSourceSRS, &pszProj4) == OGRERR_NONE ) { OGR_F_SetFieldString( hFeature, i_SrcSRSName, pszProj4 ); CPLFree(pszProj4); } } else if( eSrcSRSFormat == FORMAT_EPSG ) { if( pszAuthorityName != nullptr && pszAuthorityCode != nullptr ) OGR_F_SetFieldString( hFeature, i_SrcSRSName, CPLSPrintf("%s:%s", pszAuthorityName, pszAuthorityCode) ); } } if( hSourceSRS ) OSRDestroySpatialReference( hSourceSRS ); OGRGeometryH hPoly = OGR_G_CreateGeometry(wkbPolygon); OGRGeometryH hRing = OGR_G_CreateGeometry(wkbLinearRing); for( int k = 0; k < 5; k++ ) OGR_G_SetPoint_2D(hRing, k, adfX[k], adfY[k]); OGR_G_AddGeometryDirectly( hPoly, hRing ); OGR_F_SetGeometryDirectly( hFeature, hPoly ); if( OGR_L_CreateFeature( hLayer, hFeature ) != OGRERR_NONE ) { printf( "Failed to create feature in shapefile.\n" ); break; } OGR_F_Destroy( hFeature ); CPLFree(fileNameToWrite); GDALClose( hDS ); } CPLFree(current_path); if (nExistingFiles) { for( int i = 0; i < nExistingFiles; i++ ) { CPLFree(existingFilesTab[i]); } CPLFree(existingFilesTab); } CPLFree(alreadyExistingProjectionRef); if ( hTargetSRS ) OSRDestroySpatialReference( hTargetSRS ); GDALClose( hTileIndexDS ); GDALDestroyDriverManager(); OGRCleanupAll(); CSLDestroy(argv); exit( 0 ); }
QgsDataItem *QgsOgrDataItemProvider::createDataItem( const QString &pathIn, QgsDataItem *parentItem ) { QString path( pathIn ); if ( path.isEmpty() ) return nullptr; QgsDebugMsgLevel( "thePath: " + path, 2 ); // zip settings + info QgsSettings settings; QString scanZipSetting = settings.value( QStringLiteral( "qgis/scanZipInBrowser2" ), "basic" ).toString(); QString vsiPrefix = QgsZipItem::vsiPrefix( path ); bool is_vsizip = ( vsiPrefix == QLatin1String( "/vsizip/" ) ); bool is_vsigzip = ( vsiPrefix == QLatin1String( "/vsigzip/" ) ); bool is_vsitar = ( vsiPrefix == QLatin1String( "/vsitar/" ) ); // should we check ext. only? // check if scanItemsInBrowser2 == extension or parent dir in scanItemsFastScanUris // TODO - do this in dir item, but this requires a way to inform which extensions are supported by provider // maybe a callback function or in the provider registry? bool scanExtSetting = false; if ( ( settings.value( QStringLiteral( "qgis/scanItemsInBrowser2" ), "extension" ).toString() == QLatin1String( "extension" ) ) || ( parentItem && settings.value( QStringLiteral( "qgis/scanItemsFastScanUris" ), QStringList() ).toStringList().contains( parentItem->path() ) ) || ( ( is_vsizip || is_vsitar ) && parentItem && parentItem->parent() && settings.value( QStringLiteral( "qgis/scanItemsFastScanUris" ), QStringList() ).toStringList().contains( parentItem->parent()->path() ) ) ) { scanExtSetting = true; } // get suffix, removing .gz if present QString tmpPath = path; //path used for testing, not for layer creation if ( is_vsigzip ) tmpPath.chop( 3 ); QFileInfo info( tmpPath ); QString suffix = info.suffix().toLower(); // extract basename with extension info.setFile( path ); QString name = info.fileName(); // If a .tab exists, then the corresponding .map/.dat is very likely a // side-car file of the .tab if ( suffix == QLatin1String( "map" ) || suffix == QLatin1String( "dat" ) ) { if ( QFileInfo( QDir( info.path() ), info.baseName() + ".tab" ).exists() ) return nullptr; } QgsDebugMsgLevel( "thePath= " + path + " tmpPath= " + tmpPath + " name= " + name + " suffix= " + suffix + " vsiPrefix= " + vsiPrefix, 3 ); QStringList myExtensions = fileExtensions(); QStringList dirExtensions = directoryExtensions(); // allow only normal files, supported directories, or VSIFILE items to continue bool isOgrSupportedDirectory = info.isDir() && dirExtensions.contains( suffix ); if ( !isOgrSupportedDirectory && !info.isFile() && vsiPrefix.isEmpty() ) return nullptr; // skip *.aux.xml files (GDAL auxiliary metadata files), // *.shp.xml files (ESRI metadata) and *.tif.xml files (TIFF metadata) // unless that extension is in the list (*.xml might be though) if ( path.endsWith( QLatin1String( ".aux.xml" ), Qt::CaseInsensitive ) && !myExtensions.contains( QStringLiteral( "aux.xml" ) ) ) return nullptr; if ( path.endsWith( QLatin1String( ".shp.xml" ), Qt::CaseInsensitive ) && !myExtensions.contains( QStringLiteral( "shp.xml" ) ) ) return nullptr; if ( path.endsWith( QLatin1String( ".tif.xml" ), Qt::CaseInsensitive ) && !myExtensions.contains( QStringLiteral( "tif.xml" ) ) ) return nullptr; // skip QGIS style xml files if ( path.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) && QgsStyle::isXmlStyleFile( path ) ) return nullptr; // We have to filter by extensions, otherwise e.g. all Shapefile files are displayed // because OGR drive can open also .dbf, .shx. if ( myExtensions.indexOf( suffix ) < 0 && !dirExtensions.contains( suffix ) ) { bool matches = false; const auto constWildcards = wildcards(); for ( const QString &wildcard : constWildcards ) { QRegExp rx( wildcard, Qt::CaseInsensitive, QRegExp::Wildcard ); if ( rx.exactMatch( info.fileName() ) ) { matches = true; break; } } if ( !matches ) return nullptr; } // .dbf should probably appear if .shp is not present if ( suffix == QLatin1String( "dbf" ) ) { QString pathShp = path.left( path.count() - 4 ) + ".shp"; if ( QFileInfo::exists( pathShp ) ) return nullptr; } // fix vsifile path and name if ( !vsiPrefix.isEmpty() ) { // add vsiPrefix to path if needed if ( !path.startsWith( vsiPrefix ) ) path = vsiPrefix + path; // if this is a /vsigzip/path_to_zip.zip/file_inside_zip remove the full path from the name // no need to change the name I believe #if 0 if ( ( is_vsizip || is_vsitar ) && ( path != vsiPrefix + parentItem->path() ) ) { name = path; name = name.replace( vsiPrefix + parentItem->path() + '/', "" ); } #endif } // Filters out the OGR/GDAL supported formats that can contain multiple layers // and should be treated like a DB: GeoPackage and SQLite // NOTE: this formats are scanned for rasters too and they must // be skipped by "gdal" provider or the rasters will be listed // twice. ogrSupportedDbLayersExtensions must be kept in sync // with the companion variable (same name) in the gdal provider // class // TODO: add more OGR supported multiple layers formats here! static QStringList sOgrSupportedDbLayersExtensions { QStringLiteral( "gpkg" ), QStringLiteral( "sqlite" ), QStringLiteral( "db" ), QStringLiteral( "gdb" ), QStringLiteral( "kml" ) }; static QStringList sOgrSupportedDbDriverNames { QStringLiteral( "GPKG" ), QStringLiteral( "db" ), QStringLiteral( "gdb" ) }; // these extensions are trivial to read, so there's no need to rely on // the extension only scan here -- avoiding it always gives us the correct data type // and sublayer visiblity static QStringList sSkipFastTrackExtensions { QStringLiteral( "xlsx" ), QStringLiteral( "ods" ), QStringLiteral( "csv" ), QStringLiteral( "nc" ) }; // Fast track: return item without testing if: // scanExtSetting or zipfile and scan zip == "Basic scan" // netCDF files can be both raster or vector, so fallback to opening if ( ( scanExtSetting || ( ( is_vsizip || is_vsitar ) && scanZipSetting == QLatin1String( "basic" ) ) ) && !sSkipFastTrackExtensions.contains( suffix ) ) { // if this is a VRT file make sure it is vector VRT to avoid duplicates if ( suffix == QLatin1String( "vrt" ) ) { CPLPushErrorHandler( CPLQuietErrorHandler ); CPLErrorReset(); GDALDriverH hDriver = GDALIdentifyDriver( path.toUtf8().constData(), nullptr ); CPLPopErrorHandler(); if ( !hDriver || GDALGetDriverShortName( hDriver ) == QLatin1String( "VRT" ) ) { QgsDebugMsgLevel( QStringLiteral( "Skipping VRT file because root is not a OGR VRT" ), 2 ); return nullptr; } } // Handle collections // Check if the layer has sublayers by comparing the extension QgsDataItem *item = nullptr; if ( ! sOgrSupportedDbLayersExtensions.contains( suffix ) ) { item = new QgsOgrLayerItem( parentItem, name, path, path, QgsLayerItem::Vector ); } else if ( suffix.compare( QLatin1String( "gpkg" ), Qt::CaseInsensitive ) == 0 ) { item = new QgsGeoPackageCollectionItem( parentItem, name, path ); } else { item = new QgsOgrDataCollectionItem( parentItem, name, path ); } if ( item ) return item; } // Slow track: scan file contents QgsDataItem *item = nullptr; // test that file is valid with OGR if ( OGRGetDriverCount() == 0 ) { OGRRegisterAll(); } // do not print errors, but write to debug CPLPushErrorHandler( CPLQuietErrorHandler ); CPLErrorReset(); gdal::dataset_unique_ptr hDS( GDALOpenEx( path.toUtf8().constData(), GDAL_OF_VECTOR, nullptr, nullptr, nullptr ) ); CPLPopErrorHandler(); if ( ! hDS ) { QgsDebugMsg( QStringLiteral( "GDALOpen error # %1 : %2 on %3" ).arg( CPLGetLastErrorNo() ).arg( CPLGetLastErrorMsg() ).arg( path ) ); return nullptr; } GDALDriverH hDriver = GDALGetDatasetDriver( hDS.get() ); QString driverName = GDALGetDriverShortName( hDriver ); QgsDebugMsgLevel( QStringLiteral( "GDAL Driver : %1" ).arg( driverName ), 2 ); int numLayers = GDALDatasetGetLayerCount( hDS.get() ); // GeoPackage needs a specialized data item, mainly because of raster deletion not // yet implemented in GDAL (2.2.1) if ( driverName == QLatin1String( "GPKG" ) ) { item = new QgsGeoPackageCollectionItem( parentItem, name, path ); } else if ( numLayers > 1 || sOgrSupportedDbDriverNames.contains( driverName ) ) { item = new QgsOgrDataCollectionItem( parentItem, name, path ); } else { item = dataItemForLayer( parentItem, name, path, hDS.get(), 0, false, true ); } return item; }
int main( int argc, char ** argv ) { GDALDatasetH hDataset; GDALRasterBandH hBand; int i, iBand; double adfGeoTransform[6]; GDALDriverH hDriver; char **papszMetadata; int bComputeMinMax = FALSE; if( !GDALBridgeInitialize( "..", stderr ) ) { fprintf( stderr, "Unable to intiailize GDAL bridge.\n" ); exit( 10 ); } if( argc > 1 && strcmp(argv[1],"-mm") == 0 ) { bComputeMinMax = TRUE; argv++; } GDALAllRegister(); hDataset = GDALOpen( argv[1], GA_ReadOnly ); if( hDataset == NULL ) { fprintf( stderr, "GDALOpen failed - %d\n%s\n", CPLGetLastErrorNo(), CPLGetLastErrorMsg() ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Report general info. */ /* -------------------------------------------------------------------- */ hDriver = GDALGetDatasetDriver( hDataset ); printf( "Driver: %s/%s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver ) ); printf( "Size is %d, %d\n", GDALGetRasterXSize( hDataset ), GDALGetRasterYSize( hDataset ) ); /* -------------------------------------------------------------------- */ /* Report projection. */ /* -------------------------------------------------------------------- */ if( GDALGetProjectionRef( hDataset ) != NULL ) { OGRSpatialReferenceH hSRS; char *pszProjection; pszProjection = (char *) GDALGetProjectionRef( hDataset ); hSRS = OSRNewSpatialReference(NULL); if( OSRImportFromWkt( hSRS, &pszProjection ) == CE_None ) { char *pszPrettyWkt = NULL; OSRExportToPrettyWkt( hSRS, &pszPrettyWkt, FALSE ); printf( "Coordinate System is:\n%s\n", pszPrettyWkt ); } else printf( "Coordinate System is `%s'\n", GDALGetProjectionRef( hDataset ) ); OSRDestroySpatialReference( hSRS ); } /* -------------------------------------------------------------------- */ /* Report Geotransform. */ /* -------------------------------------------------------------------- */ if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) { printf( "Origin = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3] ); printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5] ); } /* -------------------------------------------------------------------- */ /* Report GCPs. */ /* -------------------------------------------------------------------- */ if( GDALGetGCPCount( hDataset ) > 0 ) { printf( "GCP Projection = %s\n", GDALGetGCPProjection(hDataset) ); for( i = 0; i < GDALGetGCPCount(hDataset); i++ ) { const GDAL_GCP *psGCP; psGCP = GDALGetGCPs( hDataset ) + i; printf( "GCP[%3d]: Id=%s, Info=%s\n" " (%g,%g) -> (%g,%g,%g)\n", i, psGCP->pszId, psGCP->pszInfo, psGCP->dfGCPPixel, psGCP->dfGCPLine, psGCP->dfGCPX, psGCP->dfGCPY, psGCP->dfGCPZ ); } } /* -------------------------------------------------------------------- */ /* Report metadata. */ /* -------------------------------------------------------------------- */ papszMetadata = GDALGetMetadata( hDataset, NULL ); if( papszMetadata != NULL ) { printf( "Metadata:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } /* -------------------------------------------------------------------- */ /* Report subdatasets. */ /* -------------------------------------------------------------------- */ papszMetadata = GDALGetMetadata( hDataset, "SUBDATASETS" ); if( papszMetadata != NULL ) { printf( "Subdatasets:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } /* -------------------------------------------------------------------- */ /* Report corners. */ /* -------------------------------------------------------------------- */ printf( "Corner Coordinates:\n" ); GDALInfoReportCorner( hDataset, "Upper Left", 0.0, 0.0 ); GDALInfoReportCorner( hDataset, "Lower Left", 0.0, GDALGetRasterYSize(hDataset)); GDALInfoReportCorner( hDataset, "Upper Right", GDALGetRasterXSize(hDataset), 0.0 ); GDALInfoReportCorner( hDataset, "Lower Right", GDALGetRasterXSize(hDataset), GDALGetRasterYSize(hDataset) ); GDALInfoReportCorner( hDataset, "Center", GDALGetRasterXSize(hDataset)/2.0, GDALGetRasterYSize(hDataset)/2.0 ); /* ==================================================================== */ /* Loop over bands. */ /* ==================================================================== */ for( iBand = 0; iBand < GDALGetRasterCount( hDataset ); iBand++ ) { double dfMin, dfMax, adfCMinMax[2], dfNoData; int bGotMin, bGotMax, bGotNodata; int nBlockXSize, nBlockYSize; hBand = GDALGetRasterBand( hDataset, iBand+1 ); GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize ); printf( "Band %d Block=%dx%d Type=%d, ColorInterp=%d\n", iBand+1, nBlockXSize, nBlockYSize, GDALGetRasterDataType(hBand), GDALGetRasterColorInterpretation(hBand) ); dfMin = GDALGetRasterMinimum( hBand, &bGotMin ); dfMax = GDALGetRasterMaximum( hBand, &bGotMax ); printf( " Min=%.3f/%d, Max=%.3f/%d", dfMin, bGotMin, dfMax, bGotMax); if( bComputeMinMax ) { GDALComputeRasterMinMax( hBand, TRUE, adfCMinMax ); printf( ", Computed Min/Max=%.3f,%.3f", adfCMinMax[0], adfCMinMax[1] ); } printf( "\n" ); dfNoData = GDALGetRasterNoDataValue( hBand, &bGotNodata ); if( bGotNodata ) { printf( " NoData Value=%g\n", dfNoData ); } if( GDALGetOverviewCount(hBand) > 0 ) { int iOverview; printf( " Overviews: " ); for( iOverview = 0; iOverview < GDALGetOverviewCount(hBand); iOverview++ ) { GDALRasterBandH hOverview; if( iOverview != 0 ) printf( ", " ); hOverview = GDALGetOverview( hBand, iOverview ); printf( "%dx%d", GDALGetRasterBandXSize( hOverview ), GDALGetRasterBandYSize( hOverview ) ); } printf( "\n" ); } papszMetadata = GDALGetMetadata( hBand, NULL ); if( papszMetadata != NULL ) { printf( "Metadata:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } if( GDALGetRasterColorInterpretation(hBand) == GCI_PaletteIndex ) { GDALColorTableH hTable; int i; hTable = GDALGetRasterColorTable( hBand ); printf( " Color Table (%s with %d entries)\n", GDALGetPaletteInterpretationName( GDALGetPaletteInterpretation( hTable )), GDALGetColorEntryCount( hTable ) ); for( i = 0; i < GDALGetColorEntryCount( hTable ); i++ ) { GDALColorEntry sEntry; GDALGetColorEntryAsRGB( hTable, i, &sEntry ); printf( " %3d: %d,%d,%d,%d\n", i, sEntry.c1, sEntry.c2, sEntry.c3, sEntry.c4 ); } } } GDALClose( hDataset ); exit( 0 ); }
int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len) { VSILFILE* fp = VSIFileFromMemBuffer( "/vsimem/test.tar", reinterpret_cast<GByte*>(const_cast<uint8_t*>(buf)), len, FALSE ); VSIFCloseL(fp); CPLPushErrorHandler(CPLQuietErrorHandler); char** papszArgv = nullptr; CPLString osOutFilename("out"); fp = VSIFOpenL("/vsitar//vsimem/test.tar/cmd.txt", "rb"); if( fp != nullptr ) { const char* pszLine = nullptr; if( (pszLine = CPLReadLineL(fp)) != nullptr ) { osOutFilename = pszLine; osOutFilename = osOutFilename.replaceAll('/', '_'); } int nCandidateLayerNames = 0; while( (pszLine = CPLReadLineL(fp)) != nullptr ) { if( pszLine[0] != '-' ) { nCandidateLayerNames ++; if( nCandidateLayerNames == 10 ) break; } papszArgv = CSLAddString(papszArgv, pszLine); } VSIFCloseL(fp); } char** papszDrivers = CSLAddString(nullptr, "CSV"); GDALDatasetH hSrcDS = GDALOpenEx( "/vsitar//vsimem/test.tar/in", GDAL_OF_VECTOR, papszDrivers, nullptr, nullptr ); CSLDestroy(papszDrivers); if( papszArgv != nullptr && hSrcDS != nullptr ) { OGRLayerH hLayer = GDALDatasetGetLayer(hSrcDS, 0); if( hLayer ) { int nFieldCount = OGR_FD_GetFieldCount( OGR_L_GetLayerDefn(hLayer)); if( nFieldCount > 100 ) { papszArgv = CSLAddString(papszArgv, "-limit"); papszArgv = CSLAddString(papszArgv, "100"); } } GDALVectorTranslateOptions* psOptions = GDALVectorTranslateOptionsNew(papszArgv, nullptr); if( psOptions ) { CPLString osFullOutFilename("/vsimem/" + osOutFilename); GDALDatasetH hOutDS = GDALVectorTranslate( osFullOutFilename.c_str(), nullptr, 1, &hSrcDS, psOptions, nullptr); if( hOutDS ) { GDALDriverH hOutDrv = GDALGetDatasetDriver(hOutDS); GDALClose(hOutDS); // Try re-opening generated file GDALClose( GDALOpenEx(osFullOutFilename, GDAL_OF_VECTOR, nullptr, nullptr, nullptr)); if( hOutDrv ) GDALDeleteDataset(hOutDrv, osFullOutFilename); } GDALVectorTranslateOptionsFree(psOptions); } } CSLDestroy(papszArgv); GDALClose(hSrcDS); VSIRmdirRecursive("/vsimem/"); CPLPopErrorHandler(); return 0; }