double KGDAL2CV::range_cast_inv(const GDALDataType& gdalType, const int& cvDepth, const double& value) { // uint8 -> uint8 if (gdalType == GDT_Byte && cvDepth == CV_8U){ return value; } // uint16 -> uint8 if (gdalType == GDT_Byte && (cvDepth == CV_16U || cvDepth == CV_16S)){ return std::floor(value / 256.f); } // uint32 -> uint8 if (gdalType == GDT_Byte && (cvDepth == CV_32F || cvDepth == CV_32S)){ return std::floor(value / 16777216.f); } // int8 -> uint16 if ((gdalType == GDT_UInt16 || gdalType == GDT_Int16) && cvDepth == CV_8U){ return (value * 256.f); } // int16 -> int16 if ((gdalType == GDT_UInt16 || gdalType == GDT_Int16) && (cvDepth == CV_16U || cvDepth == CV_16S)){ return value; } // float32 -> float32 // float64 -> float64 if ((gdalType == GDT_Float32 || gdalType == GDT_Float64) && (cvDepth == CV_32F || cvDepth == CV_64F)){ return value; } std::cout << GDALGetDataTypeName(gdalType) << std::endl; std::cout << "warning: unknown range cast requested." << std::endl; return (value); }
CPLXMLNode *VRTDerivedRasterBand::SerializeToXML(const char *pszVRTPath) { CPLXMLNode *psTree; psTree = VRTSourcedRasterBand::SerializeToXML( pszVRTPath ); /* -------------------------------------------------------------------- */ /* Set subclass. */ /* -------------------------------------------------------------------- */ CPLCreateXMLNode( CPLCreateXMLNode( psTree, CXT_Attribute, "subClass" ), CXT_Text, "VRTDerivedRasterBand" ); /* ---- Encode DerivedBand-specific fields ---- */ if( pszFuncName != NULL && strlen(pszFuncName) > 0 ) CPLSetXMLValue(psTree, "PixelFunctionType", this->pszFuncName); if( this->eSourceTransferType != GDT_Unknown) CPLSetXMLValue(psTree, "SourceTransferType", GDALGetDataTypeName(this->eSourceTransferType)); return psTree; }
GDALDataset *SAGADataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char **papszParmList ) { if( nXSize <= 0 || nYSize <= 0 ) { CPLError( CE_Failure, CPLE_IllegalArg, "Unable to create grid, both X and Y size must be " "non-negative.\n" ); return NULL; } if( nBands != 1 ) { CPLError( CE_Failure, CPLE_IllegalArg, "SAGA Binary Grid only supports 1 band" ); return NULL; } if( eType != GDT_Byte && eType != GDT_UInt16 && eType != GDT_Int16 && eType != GDT_UInt32 && eType != GDT_Int32 && eType != GDT_Float32 && eType != GDT_Float64 ) { CPLError( CE_Failure, CPLE_AppDefined, "SAGA Binary Grid only supports Byte, UInt16, Int16, " "UInt32, Int32, Float32 and Float64 datatypes. Unable to " "create with type %s.\n", GDALGetDataTypeName( eType ) ); return NULL; } VSILFILE *fp = VSIFOpenL( pszFilename, "w+b" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file '%s' failed.\n", pszFilename ); return NULL; } char abyNoData[8]; double dfNoDataVal = 0.0; const char* pszNoDataValue = CSLFetchNameValue(papszParmList, "NODATA_VALUE"); if (pszNoDataValue) { dfNoDataVal = CPLAtofM(pszNoDataValue); } else { switch (eType) /* GDT_Byte, GDT_UInt16, GDT_Int16, GDT_UInt32 */ { /* GDT_Int32, GDT_Float32, GDT_Float64 */ case (GDT_Byte): { dfNoDataVal = SG_NODATA_GDT_Byte; break; } case (GDT_UInt16): { dfNoDataVal = SG_NODATA_GDT_UInt16; break; } case (GDT_Int16): { dfNoDataVal = SG_NODATA_GDT_Int16; break; } case (GDT_UInt32): { dfNoDataVal = SG_NODATA_GDT_UInt32; break; } case (GDT_Int32): { dfNoDataVal = SG_NODATA_GDT_Int32; break; } default: case (GDT_Float32): { dfNoDataVal = SG_NODATA_GDT_Float32; break; } case (GDT_Float64): { dfNoDataVal = SG_NODATA_GDT_Float64; break; } } } GDALCopyWords(&dfNoDataVal, GDT_Float64, 0, abyNoData, eType, 0, 1); CPLString osHdrFilename = CPLResetExtension( pszFilename, "sgrd" ); CPLErr eErr = WriteHeader( osHdrFilename, eType, nXSize, nYSize, 0.0, 0.0, 1.0, dfNoDataVal, 1.0, false ); if( eErr != CE_None ) { VSIFCloseL( fp ); return NULL; } if (CSLFetchBoolean( papszParmList , "FILL_NODATA", TRUE )) { int nDataTypeSize = GDALGetDataTypeSize(eType) / 8; GByte* pabyNoDataBuf = (GByte*) VSIMalloc2(nDataTypeSize, nXSize); if (pabyNoDataBuf == NULL) { VSIFCloseL( fp ); return NULL; } for( int iCol = 0; iCol < nXSize; iCol++) { memcpy(pabyNoDataBuf + iCol * nDataTypeSize, abyNoData, nDataTypeSize); } for( int iRow = 0; iRow < nYSize; iRow++ ) { if( VSIFWriteL( pabyNoDataBuf, nDataTypeSize, nXSize, fp ) != (unsigned)nXSize ) { VSIFCloseL( fp ); VSIFree(pabyNoDataBuf); CPLError( CE_Failure, CPLE_FileIO, "Unable to write grid cell. Disk full?\n" ); return NULL; } } VSIFree(pabyNoDataBuf); } VSIFCloseL( fp ); return (GDALDataset *)GDALOpen( pszFilename, GA_Update ); }
GDALDataset * WEBPDataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS, int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ) { int nBands = poSrcDS->GetRasterCount(); int nXSize = poSrcDS->GetRasterXSize(); int nYSize = poSrcDS->GetRasterYSize(); /* -------------------------------------------------------------------- */ /* WEBP library initialization */ /* -------------------------------------------------------------------- */ WebPPicture sPicture; if (!WebPPictureInit(&sPicture)) { CPLError(CE_Failure, CPLE_AppDefined, "WebPPictureInit() failed"); return NULL; } /* -------------------------------------------------------------------- */ /* Some some rudimentary checks */ /* -------------------------------------------------------------------- */ if( nXSize > 16383 || nYSize > 16383 ) { CPLError( CE_Failure, CPLE_NotSupported, "WEBP maximum image dimensions are 16383 x 16383."); return NULL; } if( nBands != 3 #if WEBP_ENCODER_ABI_VERSION >= 0x0100 && nBands != 4 #endif ) { CPLError( CE_Failure, CPLE_NotSupported, "WEBP driver doesn't support %d bands. Must be 3 (RGB) " #if WEBP_ENCODER_ABI_VERSION >= 0x0100 "or 4 (RGBA) " #endif "bands.", nBands ); return NULL; } GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType(); if( eDT != GDT_Byte ) { CPLError( (bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported, "WEBP driver doesn't support data type %s. " "Only eight bit byte bands supported.", GDALGetDataTypeName( poSrcDS->GetRasterBand(1)->GetRasterDataType()) ); if (bStrict) return NULL; } /* -------------------------------------------------------------------- */ /* What options has the user selected? */ /* -------------------------------------------------------------------- */ float fQuality = 75.0f; const char* pszQUALITY = CSLFetchNameValue(papszOptions, "QUALITY"); if( pszQUALITY != NULL ) { fQuality = (float) CPLAtof(pszQUALITY); if( fQuality < 0.0f || fQuality > 100.0f ) { CPLError( CE_Failure, CPLE_IllegalArg, "%s=%s is not a legal value.", "QUALITY", pszQUALITY); return NULL; } } WebPPreset nPreset = WEBP_PRESET_DEFAULT; const char* pszPRESET = CSLFetchNameValueDef(papszOptions, "PRESET", "DEFAULT"); if (EQUAL(pszPRESET, "DEFAULT")) nPreset = WEBP_PRESET_DEFAULT; else if (EQUAL(pszPRESET, "PICTURE")) nPreset = WEBP_PRESET_PICTURE; else if (EQUAL(pszPRESET, "PHOTO")) nPreset = WEBP_PRESET_PHOTO; else if (EQUAL(pszPRESET, "PICTURE")) nPreset = WEBP_PRESET_PICTURE; else if (EQUAL(pszPRESET, "DRAWING")) nPreset = WEBP_PRESET_DRAWING; else if (EQUAL(pszPRESET, "ICON")) nPreset = WEBP_PRESET_ICON; else if (EQUAL(pszPRESET, "TEXT")) nPreset = WEBP_PRESET_TEXT; else { CPLError( CE_Failure, CPLE_IllegalArg, "%s=%s is not a legal value.", "PRESET", pszPRESET ); return NULL; } WebPConfig sConfig; if (!WebPConfigInitInternal(&sConfig, nPreset, fQuality, WEBP_ENCODER_ABI_VERSION)) { CPLError(CE_Failure, CPLE_AppDefined, "WebPConfigInit() failed"); return NULL; } #define FETCH_AND_SET_OPTION_INT(name, fieldname, minval, maxval) \ { \ const char* pszVal = CSLFetchNameValue(papszOptions, name); \ if (pszVal != NULL) \ { \ sConfig.fieldname = atoi(pszVal); \ if (sConfig.fieldname < minval || sConfig.fieldname > maxval) \ { \ CPLError( CE_Failure, CPLE_IllegalArg, \ "%s=%s is not a legal value.", name, pszVal ); \ return NULL; \ } \ } \ } FETCH_AND_SET_OPTION_INT("TARGETSIZE", target_size, 0, INT_MAX); const char* pszPSNR = CSLFetchNameValue(papszOptions, "PSNR"); if (pszPSNR) { sConfig.target_PSNR = CPLAtof(pszPSNR); if (sConfig.target_PSNR < 0) { CPLError( CE_Failure, CPLE_IllegalArg, "PSNR=%s is not a legal value.", pszPSNR ); return NULL; } } FETCH_AND_SET_OPTION_INT("METHOD", method, 0, 6); FETCH_AND_SET_OPTION_INT("SEGMENTS", segments, 1, 4); FETCH_AND_SET_OPTION_INT("SNS_STRENGTH", sns_strength, 0, 100); FETCH_AND_SET_OPTION_INT("FILTER_STRENGTH", filter_strength, 0, 100); FETCH_AND_SET_OPTION_INT("FILTER_SHARPNESS", filter_sharpness, 0, 7); FETCH_AND_SET_OPTION_INT("FILTER_TYPE", filter_type, 0, 1); FETCH_AND_SET_OPTION_INT("AUTOFILTER", autofilter, 0, 1); FETCH_AND_SET_OPTION_INT("PASS", pass, 1, 10); FETCH_AND_SET_OPTION_INT("PREPROCESSING", preprocessing, 0, 1); FETCH_AND_SET_OPTION_INT("PARTITIONS", partitions, 0, 3); #if WEBP_ENCODER_ABI_VERSION >= 0x0002 FETCH_AND_SET_OPTION_INT("PARTITION_LIMIT", partition_limit, 0, 100); #endif #if WEBP_ENCODER_ABI_VERSION >= 0x0100 sConfig.lossless = CSLFetchBoolean(papszOptions, "LOSSLESS", FALSE); if (sConfig.lossless) sPicture.use_argb = 1; #endif if (!WebPValidateConfig(&sConfig)) { CPLError(CE_Failure, CPLE_AppDefined, "WebPValidateConfig() failed"); return NULL; } /* -------------------------------------------------------------------- */ /* Allocate memory */ /* -------------------------------------------------------------------- */ GByte *pabyBuffer; pabyBuffer = (GByte *) VSIMalloc( nBands * nXSize * nYSize ); if (pabyBuffer == NULL) { return NULL; } /* -------------------------------------------------------------------- */ /* Create the dataset. */ /* -------------------------------------------------------------------- */ VSILFILE *fpImage; fpImage = VSIFOpenL( pszFilename, "wb" ); if( fpImage == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Unable to create WEBP file %s.\n", pszFilename ); VSIFree(pabyBuffer); return NULL; } WebPUserData sUserData; sUserData.fp = fpImage; sUserData.pfnProgress = pfnProgress ? pfnProgress : GDALDummyProgress; sUserData.pProgressData = pProgressData; /* -------------------------------------------------------------------- */ /* WEBP library settings */ /* -------------------------------------------------------------------- */ sPicture.width = nXSize; sPicture.height = nYSize; sPicture.writer = WEBPDatasetWriter; sPicture.custom_ptr = &sUserData; #if WEBP_ENCODER_ABI_VERSION >= 0x0100 sPicture.progress_hook = WEBPDatasetProgressHook; #endif if (!WebPPictureAlloc(&sPicture)) { CPLError(CE_Failure, CPLE_AppDefined, "WebPPictureAlloc() failed"); VSIFree(pabyBuffer); VSIFCloseL( fpImage ); return NULL; } /* -------------------------------------------------------------------- */ /* Acquire source imagery. */ /* -------------------------------------------------------------------- */ CPLErr eErr = CE_None; eErr = poSrcDS->RasterIO( GF_Read, 0, 0, nXSize, nYSize, pabyBuffer, nXSize, nYSize, GDT_Byte, nBands, NULL, nBands, nBands * nXSize, 1, NULL ); /* -------------------------------------------------------------------- */ /* Import and write to file */ /* -------------------------------------------------------------------- */ #if WEBP_ENCODER_ABI_VERSION >= 0x0100 if (eErr == CE_None && nBands == 4) { if (!WebPPictureImportRGBA(&sPicture, pabyBuffer, nBands * nXSize)) { CPLError(CE_Failure, CPLE_AppDefined, "WebPPictureImportRGBA() failed"); eErr = CE_Failure; } } else #endif if (eErr == CE_None && !WebPPictureImportRGB(&sPicture, pabyBuffer, nBands * nXSize)) { CPLError(CE_Failure, CPLE_AppDefined, "WebPPictureImportRGB() failed"); eErr = CE_Failure; } if (eErr == CE_None && !WebPEncode(&sConfig, &sPicture)) { const char* pszErrorMsg = NULL; #if WEBP_ENCODER_ABI_VERSION >= 0x0100 switch(sPicture.error_code) { case VP8_ENC_ERROR_OUT_OF_MEMORY: pszErrorMsg = "Out of memory"; break; case VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY: pszErrorMsg = "Out of memory while flushing bits"; break; case VP8_ENC_ERROR_NULL_PARAMETER: pszErrorMsg = "A pointer parameter is NULL"; break; case VP8_ENC_ERROR_INVALID_CONFIGURATION: pszErrorMsg = "Configuration is invalid"; break; case VP8_ENC_ERROR_BAD_DIMENSION: pszErrorMsg = "Picture has invalid width/height"; break; case VP8_ENC_ERROR_PARTITION0_OVERFLOW: pszErrorMsg = "Partition is bigger than 512k. Try using less SEGMENTS, or increase PARTITION_LIMIT value"; break; case VP8_ENC_ERROR_PARTITION_OVERFLOW: pszErrorMsg = "Partition is bigger than 16M"; break; case VP8_ENC_ERROR_BAD_WRITE: pszErrorMsg = "Error while flusing bytes"; break; case VP8_ENC_ERROR_FILE_TOO_BIG: pszErrorMsg = "File is bigger than 4G"; break; case VP8_ENC_ERROR_USER_ABORT: pszErrorMsg = "User interrupted"; break; default: break; } #endif if (pszErrorMsg) CPLError(CE_Failure, CPLE_AppDefined, "WebPEncode() failed : %s", pszErrorMsg); else CPLError(CE_Failure, CPLE_AppDefined, "WebPEncode() failed"); eErr = CE_Failure; } /* -------------------------------------------------------------------- */ /* Cleanup and close. */ /* -------------------------------------------------------------------- */ CPLFree( pabyBuffer ); WebPPictureFree(&sPicture); VSIFCloseL( fpImage ); if( eErr != CE_None ) { VSIUnlink( pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Re-open dataset, and copy any auxiliary pam information. */ /* -------------------------------------------------------------------- */ GDALOpenInfo oOpenInfo(pszFilename, GA_ReadOnly); /* If outputing to stdout, we can't reopen it, so we'll return */ /* a fake dataset to make the caller happy */ CPLPushErrorHandler(CPLQuietErrorHandler); WEBPDataset *poDS = (WEBPDataset*) WEBPDataset::Open( &oOpenInfo ); CPLPopErrorHandler(); if( poDS ) { poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT ); return poDS; } return NULL; }
GDALDataset *MEMDataset::Open( GDALOpenInfo * poOpenInfo ) { char **papszOptions; /* -------------------------------------------------------------------- */ /* Do we have the special filename signature for MEM format */ /* description strings? */ /* -------------------------------------------------------------------- */ if( !EQUALN(poOpenInfo->pszFilename,"MEM:::",6) || poOpenInfo->fp != NULL ) return NULL; papszOptions = CSLTokenizeStringComplex(poOpenInfo->pszFilename+6, ",", TRUE, FALSE ); /* -------------------------------------------------------------------- */ /* Verify we have all required fields */ /* -------------------------------------------------------------------- */ if( CSLFetchNameValue( papszOptions, "PIXELS" ) == NULL || CSLFetchNameValue( papszOptions, "LINES" ) == NULL || CSLFetchNameValue( papszOptions, "DATAPOINTER" ) == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Missing required field (one of PIXELS, LINES or DATAPOINTER)\n" "Unable to access in-memory array." ); CSLDestroy( papszOptions ); return NULL; } /* -------------------------------------------------------------------- */ /* Create the new MEMDataset object. */ /* -------------------------------------------------------------------- */ MEMDataset *poDS; poDS = new MEMDataset(); poDS->nRasterXSize = atoi(CSLFetchNameValue(papszOptions,"PIXELS")); poDS->nRasterYSize = atoi(CSLFetchNameValue(papszOptions,"LINES")); poDS->eAccess = GA_Update; /* -------------------------------------------------------------------- */ /* Extract other information. */ /* -------------------------------------------------------------------- */ const char *pszOption; GDALDataType eType; int nBands, nPixelOffset, nLineOffset; size_t nBandOffset; const char *pszDataPointer; GByte *pabyData; pszOption = CSLFetchNameValue(papszOptions,"BANDS"); if( pszOption == NULL ) nBands = 1; else { nBands = atoi(pszOption); } if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize) || !GDALCheckBandCount(nBands, TRUE)) { CSLDestroy( papszOptions ); delete poDS; return NULL; } pszOption = CSLFetchNameValue(papszOptions,"DATATYPE"); if( pszOption == NULL ) eType = GDT_Byte; else { if( atoi(pszOption) > 0 && atoi(pszOption) < GDT_TypeCount ) eType = (GDALDataType) atoi(pszOption); else { int iType; eType = GDT_Unknown; for( iType = 0; iType < GDT_TypeCount; iType++ ) { if( EQUAL(GDALGetDataTypeName((GDALDataType) iType), pszOption) ) { eType = (GDALDataType) iType; break; } } if( eType == GDT_Unknown ) { CPLError( CE_Failure, CPLE_AppDefined, "DATATYPE=%s not recognised.", pszOption ); CSLDestroy( papszOptions ); delete poDS; return NULL; } } } pszOption = CSLFetchNameValue(papszOptions,"PIXELOFFSET"); if( pszOption == NULL ) nPixelOffset = GDALGetDataTypeSize(eType) / 8; else nPixelOffset = atoi(pszOption); pszOption = CSLFetchNameValue(papszOptions,"LINEOFFSET"); if( pszOption == NULL ) nLineOffset = poDS->nRasterXSize * nPixelOffset; else nLineOffset = atoi(pszOption); pszOption = CSLFetchNameValue(papszOptions,"BANDOFFSET"); if( pszOption == NULL ) nBandOffset = nLineOffset * (size_t) poDS->nRasterYSize; else nBandOffset = atoi(pszOption); pszDataPointer = CSLFetchNameValue(papszOptions,"DATAPOINTER"); pabyData = (GByte *) CPLScanPointer( pszDataPointer, strlen(pszDataPointer) ); /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ for( int iBand = 0; iBand < nBands; iBand++ ) { poDS->SetBand( iBand+1, new MEMRasterBand( poDS, iBand+1, pabyData + iBand * nBandOffset, eType, nPixelOffset, nLineOffset, FALSE ) ); } /* -------------------------------------------------------------------- */ /* Try to return a regular handle on the file. */ /* -------------------------------------------------------------------- */ CSLDestroy( papszOptions ); return poDS; }
int main( int argc, char ** argv ) { GDALDatasetH hDataset, hOutDS; int i; const char *pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff"; GDALDriverH hDriver; GDALDataType eOutputType = GDT_Unknown; char **papszCreateOptions = NULL; GDALProgressFunc pfnProgress = GDALTermProgress; int nLUTBins = 256; const char *pszMethod = "minmax"; // double dfStdDevMult = 0.0; double *padfScaleMin = NULL; double *padfScaleMax = NULL; int **papanLUTs = NULL; int iBand; const char *pszConfigFile = NULL; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(argv[0])) exit(1); /* -------------------------------------------------------------------- */ /* Register standard GDAL drivers, and process generic GDAL */ /* command options. */ /* -------------------------------------------------------------------- */ GDALAllRegister(); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Handle command line arguments. */ /* -------------------------------------------------------------------- */ for( i = 1; i < argc; i++ ) { if( EQUAL(argv[i], "--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],"-of") && i < argc-1 ) pszFormat = argv[++i]; else if( EQUAL(argv[i],"-ot") && i < argc-1 ) { int iType; for( iType = 1; iType < GDT_TypeCount; iType++ ) { if( GDALGetDataTypeName((GDALDataType)iType) != NULL && EQUAL(GDALGetDataTypeName((GDALDataType)iType), argv[i+1]) ) { eOutputType = (GDALDataType) iType; } } if( eOutputType == GDT_Unknown ) { printf( "Unknown output pixel type: %s\n", argv[i+1] ); Usage(); GDALDestroyDriverManager(); exit( 2 ); } i++; } else if( EQUALN(argv[i],"-s_nodata",9) ) { // TODO i += 1; } else if( EQUAL(argv[i],"-co") && i < argc-1 ) { papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] ); } else if( EQUALN(argv[i],"-src_scale",10) && i < argc-2) { // TODO i += 2; } else if( EQUALN(argv[i],"-dst_scale",10) && i < argc-2 ) { // TODO i += 2; } else if( EQUAL(argv[i],"-config") && i < argc-1 ) { pszConfigFile = argv[++i]; } else if( EQUAL(argv[i],"-equalize") ) { pszMethod = "equalize"; } else if( EQUAL(argv[i],"-quiet") ) { pfnProgress = GDALDummyProgress; } else if( argv[i][0] == '-' ) { printf( "Option %s incomplete, or not recognised.\n\n", argv[i] ); Usage(); GDALDestroyDriverManager(); exit( 2 ); } else if( pszSource == NULL ) { pszSource = argv[i]; } else if( pszDest == NULL ) { pszDest = argv[i]; } else { printf( "Too many command options.\n\n" ); Usage(); GDALDestroyDriverManager(); exit( 2 ); } } if( pszSource == NULL ) { Usage(); GDALDestroyDriverManager(); exit( 10 ); } /* -------------------------------------------------------------------- */ /* Attempt to open source file. */ /* -------------------------------------------------------------------- */ hDataset = GDALOpenShared( pszSource, GA_ReadOnly ); if( hDataset == NULL ) { fprintf( stderr, "GDALOpen failed - %d\n%s\n", CPLGetLastErrorNo(), CPLGetLastErrorMsg() ); GDALDestroyDriverManager(); exit( 1 ); } int nBandCount = GDALGetRasterCount(hDataset); /* -------------------------------------------------------------------- */ /* Find the output driver. */ /* -------------------------------------------------------------------- */ hDriver = GDALGetDriverByName( pszFormat ); if( hDriver == NULL ) { int iDr; printf( "Output driver `%s' not recognised.\n", pszFormat ); printf( "The following format drivers are configured and support output:\n" ); for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ ) { GDALDriverH hDriver = GDALGetDriver(iDr); if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY, NULL ) != NULL ) { printf( " %s: %s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver ) ); } } printf( "\n" ); Usage(); GDALClose( hDataset ); GDALDestroyDriverManager(); CSLDestroy( argv ); CSLDestroy( papszCreateOptions ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* If histogram equalization is requested, do it now. */ /* -------------------------------------------------------------------- */ if( EQUAL(pszMethod,"equalize") ) { ComputeEqualizationLUTs( hDataset, nLUTBins, &padfScaleMin, &padfScaleMax, &papanLUTs, pfnProgress ); } /* -------------------------------------------------------------------- */ /* If we have a config file, assume it is for input and read */ /* it. */ /* -------------------------------------------------------------------- */ else if( pszConfigFile != NULL ) { char **papszLines = CSLLoad( pszConfigFile ); if( CSLCount(papszLines) == 0 ) exit( 1 ); if( CSLCount(papszLines) != nBandCount ) { fprintf( stderr, "Did not get %d lines in config file as expected.\n", nBandCount ); exit( 1 ); } padfScaleMin = (double *) CPLCalloc(nBandCount,sizeof(double)); padfScaleMax = (double *) CPLCalloc(nBandCount,sizeof(double)); for( iBand = 0; iBand < nBandCount; iBand++ ) { int iLUT; char **papszTokens = CSLTokenizeString( papszLines[iBand] ); if( CSLCount(papszTokens) < 3 || atoi(papszTokens[0]) != iBand+1 ) { fprintf( stderr, "Line %d seems to be corrupt.\n", iBand+1 ); exit( 1 ); } // Process scale min/max padfScaleMin[iBand] = atof(papszTokens[1]); padfScaleMax[iBand] = atof(papszTokens[2]); if( CSLCount(papszTokens) == 3 ) continue; // process lut if( iBand == 0 ) { nLUTBins = CSLCount(papszTokens) - 3; papanLUTs = (int **) CPLCalloc(sizeof(int*),nBandCount); } papanLUTs[iBand] = (int *) CPLCalloc(nLUTBins,sizeof(int)); for( iLUT = 0; iLUT < nLUTBins; iLUT++ ) papanLUTs[iBand][iLUT] = atoi(papszTokens[iLUT+3]); CSLDestroy( papszTokens ); } } /* -------------------------------------------------------------------- */ /* If there is no destination, just report the scaling values */ /* and luts. */ /* -------------------------------------------------------------------- */ if( pszDest == NULL ) { FILE *fpConfig = stdout; if( pszConfigFile ) fpConfig = fopen( pszConfigFile, "w" ); for( iBand = 0; iBand < nBandCount; iBand++ ) { fprintf( fpConfig, "%d:Band ", iBand+1 ); if( padfScaleMin != NULL ) fprintf( fpConfig, "%g:ScaleMin %g:ScaleMax ", padfScaleMin[iBand], padfScaleMax[iBand] ); if( papanLUTs ) { int iLUT; for( iLUT = 0; iLUT < nLUTBins; iLUT++ ) fprintf( fpConfig, "%d ", papanLUTs[iBand][iLUT] ); } fprintf( fpConfig, "\n" ); } if( pszConfigFile ) fclose( fpConfig ); exit( 0 ); } if (padfScaleMin == NULL || padfScaleMax == NULL) { fprintf( stderr, "-equalize or -config filename command line options must be specified.\n"); exit(1); } /* ==================================================================== */ /* Create a virtual dataset. */ /* ==================================================================== */ VRTDataset *poVDS; EnhanceCBInfo *pasEInfo = (EnhanceCBInfo *) CPLCalloc(nBandCount, sizeof(EnhanceCBInfo)); /* -------------------------------------------------------------------- */ /* Make a virtual clone. */ /* -------------------------------------------------------------------- */ poVDS = new VRTDataset( GDALGetRasterXSize(hDataset), GDALGetRasterYSize(hDataset) ); if( GDALGetGCPCount(hDataset) == 0 ) { const char *pszProjection; double adfGeoTransform[6]; pszProjection = GDALGetProjectionRef( hDataset ); if( pszProjection != NULL && strlen(pszProjection) > 0 ) poVDS->SetProjection( pszProjection ); if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) poVDS->SetGeoTransform( adfGeoTransform ); } else { poVDS->SetGCPs( GDALGetGCPCount(hDataset), GDALGetGCPs(hDataset), GDALGetGCPProjection( hDataset ) ); } poVDS->SetMetadata( ((GDALDataset*)hDataset)->GetMetadata() ); for( iBand = 0; iBand < nBandCount; iBand++ ) { VRTSourcedRasterBand *poVRTBand; GDALRasterBand *poSrcBand; GDALDataType eBandType; poSrcBand = ((GDALDataset *) hDataset)->GetRasterBand(iBand+1); /* -------------------------------------------------------------------- */ /* Select output data type to match source. */ /* -------------------------------------------------------------------- */ if( eOutputType == GDT_Unknown ) eBandType = GDT_Byte; else eBandType = eOutputType; /* -------------------------------------------------------------------- */ /* Create this band. */ /* -------------------------------------------------------------------- */ poVDS->AddBand( eBandType, NULL ); poVRTBand = (VRTSourcedRasterBand *) poVDS->GetRasterBand( iBand+1 ); /* -------------------------------------------------------------------- */ /* Create a function based source with info on how to apply the */ /* enhancement. */ /* -------------------------------------------------------------------- */ pasEInfo[iBand].poSrcBand = poSrcBand; pasEInfo[iBand].eWrkType = eBandType; pasEInfo[iBand].dfScaleMin = padfScaleMin[iBand]; pasEInfo[iBand].dfScaleMax = padfScaleMax[iBand]; pasEInfo[iBand].nLUTBins = nLUTBins; if( papanLUTs ) pasEInfo[iBand].panLUT = papanLUTs[iBand]; poVRTBand->AddFuncSource( EnhancerCallback, pasEInfo + iBand ); /* -------------------------------------------------------------------- */ /* copy over some other information of interest. */ /* -------------------------------------------------------------------- */ poVRTBand->CopyCommonInfoFrom( poSrcBand ); } /* -------------------------------------------------------------------- */ /* Write to the output file using CopyCreate(). */ /* -------------------------------------------------------------------- */ hOutDS = GDALCreateCopy( hDriver, pszDest, (GDALDatasetH) poVDS, FALSE, papszCreateOptions, pfnProgress, NULL ); if( hOutDS != NULL ) GDALClose( hOutDS ); GDALClose( (GDALDatasetH) poVDS ); GDALClose( hDataset ); /* -------------------------------------------------------------------- */ /* Cleanup and exit. */ /* -------------------------------------------------------------------- */ GDALDumpOpenDatasets( stderr ); GDALDestroyDriverManager(); CSLDestroy( argv ); CSLDestroy( papszCreateOptions ); exit( 0 ); }
GDALDataset *PAuxDataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char **papszOptions ) { const char *pszInterleave = CSLFetchNameValue( papszOptions, "INTERLEAVE" ); if( pszInterleave == NULL ) pszInterleave = "BAND"; /* -------------------------------------------------------------------- */ /* Verify input options. */ /* -------------------------------------------------------------------- */ if( eType != GDT_Byte && eType != GDT_Float32 && eType != GDT_UInt16 && eType != GDT_Int16 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create PCI .Aux labelled dataset with an illegal\n" "data type (%s).\n", GDALGetDataTypeName(eType) ); return NULL; } /* -------------------------------------------------------------------- */ /* Sum the sizes of the band pixel types. */ /* -------------------------------------------------------------------- */ int nPixelSizeSum = 0; for( int iBand = 0; iBand < nBands; iBand++ ) nPixelSizeSum += (GDALGetDataTypeSize(eType)/8); /* -------------------------------------------------------------------- */ /* Try to create the file. */ /* -------------------------------------------------------------------- */ VSILFILE *fp = VSIFOpenL( pszFilename, "w" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed.\n", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Just write out a couple of bytes to establish the binary */ /* file, and then close it. */ /* -------------------------------------------------------------------- */ CPL_IGNORE_RET_VAL(VSIFWriteL( reinterpret_cast<void *>( const_cast<char *>( "\0\0" ) ), 2, 1, fp )); CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); /* -------------------------------------------------------------------- */ /* Create the aux filename. */ /* -------------------------------------------------------------------- */ char *pszAuxFilename = reinterpret_cast<char *>( CPLMalloc( strlen( pszFilename ) + 5 ) ); strcpy( pszAuxFilename, pszFilename );; for( int i = static_cast<int>(strlen(pszAuxFilename))-1; i > 0; i-- ) { if( pszAuxFilename[i] == '.' ) { pszAuxFilename[i] = '\0'; break; } } strcat( pszAuxFilename, ".aux" ); /* -------------------------------------------------------------------- */ /* Open the file. */ /* -------------------------------------------------------------------- */ fp = VSIFOpenL( pszAuxFilename, "wt" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed.\n", pszAuxFilename ); return NULL; } CPLFree( pszAuxFilename ); /* -------------------------------------------------------------------- */ /* We need to write out the original filename but without any */ /* path components in the AuxilaryTarget line. Do so now. */ /* -------------------------------------------------------------------- */ int iStart = static_cast<int>(strlen(pszFilename))-1; while( iStart > 0 && pszFilename[iStart-1] != '/' && pszFilename[iStart-1] != '\\' ) iStart--; CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "AuxilaryTarget: %s\n", pszFilename + iStart )); /* -------------------------------------------------------------------- */ /* Write out the raw definition for the dataset as a whole. */ /* -------------------------------------------------------------------- */ CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "RawDefinition: %d %d %d\n", nXSize, nYSize, nBands )); /* -------------------------------------------------------------------- */ /* Write out a definition for each band. We always write band */ /* sequential files for now as these are pretty efficiently */ /* handled by GDAL. */ /* -------------------------------------------------------------------- */ vsi_l_offset nImgOffset = 0; for( int iBand = 0; iBand < nBands; iBand++ ) { const char *pszTypeName; int nPixelOffset; int nLineOffset; vsi_l_offset nNextImgOffset; /* -------------------------------------------------------------------- */ /* Establish our file layout based on supplied interleaving. */ /* -------------------------------------------------------------------- */ if( EQUAL(pszInterleave,"LINE") ) { nPixelOffset = GDALGetDataTypeSize(eType)/8; nLineOffset = nXSize * nPixelSizeSum; nNextImgOffset = nImgOffset + nPixelOffset * nXSize; } else if( EQUAL(pszInterleave,"PIXEL") ) { nPixelOffset = nPixelSizeSum; nLineOffset = nXSize * nPixelOffset; nNextImgOffset = nImgOffset + (GDALGetDataTypeSize(eType)/8); } else /* default to band */ { nPixelOffset = GDALGetDataTypeSize(eType)/8; nLineOffset = nXSize * nPixelOffset; nNextImgOffset = nImgOffset + nYSize * (vsi_l_offset) nLineOffset; } /* -------------------------------------------------------------------- */ /* Write out line indicating layout. */ /* -------------------------------------------------------------------- */ if( eType == GDT_Float32 ) pszTypeName = "32R"; else if( eType == GDT_Int16 ) pszTypeName = "16S"; else if( eType == GDT_UInt16 ) pszTypeName = "16U"; else pszTypeName = "8U"; CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "ChanDefinition-%d: %s " CPL_FRMT_GIB " %d %d %s\n", iBand+1, pszTypeName, (GIntBig) nImgOffset, nPixelOffset, nLineOffset, #ifdef CPL_LSB "Swapped" #else "Unswapped" #endif )); nImgOffset = nNextImgOffset; } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); return reinterpret_cast<GDALDataset *>( GDALOpen( pszFilename, GA_Update ) ); }
GDALDataset *GTXDataset::Create( const char * pszFilename, int nXSize, int nYSize, int /* nBands */, GDALDataType eType, char ** /* papszOptions */ ) { if( eType != GDT_Float32 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create gtx file with unsupported data type '%s'.", GDALGetDataTypeName( eType ) ); return NULL; } if( !EQUAL(CPLGetExtension(pszFilename),"gtx") ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create gtx file with extension other than gtx." ); return NULL; } /* -------------------------------------------------------------------- */ /* Try to create the file. */ /* -------------------------------------------------------------------- */ VSILFILE *fp = VSIFOpenL( pszFilename, "wb" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed.\n", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Write out the header with stub georeferencing. */ /* -------------------------------------------------------------------- */ unsigned char header[40] = { '\0' }; double dfYOrigin = 0.0; memcpy( header + 0, &dfYOrigin, 8 ); CPL_MSBPTR64( header + 0 ); double dfXOrigin = 0.0; memcpy( header + 8, &dfXOrigin, 8 ); CPL_MSBPTR64( header + 8 ); double dfYSize = 0.01; memcpy( header + 16, &dfYSize, 8 ); CPL_MSBPTR64( header + 16 ); double dfXSize = 0.01; memcpy( header + 24, &dfXSize, 8 ); CPL_MSBPTR64( header + 24 ); GInt32 nYSize32 = nYSize; memcpy( header + 32, &nYSize32, 4 ); CPL_MSBPTR32( header + 32 ); GInt32 nXSize32 = nXSize; memcpy( header + 36, &nXSize32, 4 ); CPL_MSBPTR32( header + 36 ); CPL_IGNORE_RET_VAL(VSIFWriteL( header, 40, 1, fp )); CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); return reinterpret_cast<GDALDataset *>( GDALOpen( pszFilename, GA_Update ) ); }
static GDALDataset * BSBCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ) { int nBands = poSrcDS->GetRasterCount(); int nXSize = poSrcDS->GetRasterXSize(); int nYSize = poSrcDS->GetRasterYSize(); /* -------------------------------------------------------------------- */ /* Some some rudimentary checks */ /* -------------------------------------------------------------------- */ if( nBands != 1 ) { CPLError( CE_Failure, CPLE_NotSupported, "BSB driver only supports one band images.\n" ); return NULL; } if( poSrcDS->GetRasterBand(1)->GetRasterDataType() != GDT_Byte && bStrict ) { CPLError( CE_Failure, CPLE_NotSupported, "BSB driver doesn't support data type %s. " "Only eight bit bands supported.\n", GDALGetDataTypeName( poSrcDS->GetRasterBand(1)->GetRasterDataType()) ); return NULL; } /* -------------------------------------------------------------------- */ /* Open the output file. */ /* -------------------------------------------------------------------- */ BSBInfo *psBSB; psBSB = BSBCreate( pszFilename, 0, 200, nXSize, nYSize ); if( psBSB == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Prepare initial color table.colortable. */ /* -------------------------------------------------------------------- */ GDALRasterBand *poBand = poSrcDS->GetRasterBand(1); int iColor; unsigned char abyPCT[771]; int nPCTSize; int anRemap[256]; abyPCT[0] = 0; abyPCT[1] = 0; abyPCT[2] = 0; if( poBand->GetColorTable() == NULL ) { /* map greyscale down to 63 grey levels. */ for( iColor = 0; iColor < 256; iColor++ ) { int nOutValue = (int) (iColor / 4.1) + 1; anRemap[iColor] = nOutValue; abyPCT[nOutValue*3 + 0] = (unsigned char) iColor; abyPCT[nOutValue*3 + 1] = (unsigned char) iColor; abyPCT[nOutValue*3 + 2] = (unsigned char) iColor; } nPCTSize = 64; } else { GDALColorTable *poCT = poBand->GetColorTable(); int nColorTableSize = poCT->GetColorEntryCount(); if (nColorTableSize > 255) nColorTableSize = 255; for( iColor = 0; iColor < nColorTableSize; iColor++ ) { GDALColorEntry sEntry; poCT->GetColorEntryAsRGB( iColor, &sEntry ); anRemap[iColor] = iColor + 1; abyPCT[(iColor+1)*3 + 0] = (unsigned char) sEntry.c1; abyPCT[(iColor+1)*3 + 1] = (unsigned char) sEntry.c2; abyPCT[(iColor+1)*3 + 2] = (unsigned char) sEntry.c3; } nPCTSize = nColorTableSize + 1; // Add entries for pixel values which apparently will not occur. for( iColor = nPCTSize; iColor < 256; iColor++ ) anRemap[iColor] = 1; } /* -------------------------------------------------------------------- */ /* Boil out all duplicate entries. */ /* -------------------------------------------------------------------- */ int i; for( i = 1; i < nPCTSize-1; i++ ) { int j; for( j = i+1; j < nPCTSize; j++ ) { if( abyPCT[i*3+0] == abyPCT[j*3+0] && abyPCT[i*3+1] == abyPCT[j*3+1] && abyPCT[i*3+2] == abyPCT[j*3+2] ) { int k; nPCTSize--; abyPCT[j*3+0] = abyPCT[nPCTSize*3+0]; abyPCT[j*3+1] = abyPCT[nPCTSize*3+1]; abyPCT[j*3+2] = abyPCT[nPCTSize*3+2]; for( k = 0; k < 256; k++ ) { // merge matching entries. if( anRemap[k] == j ) anRemap[k] = i; // shift the last PCT entry into the new hole. if( anRemap[k] == nPCTSize ) anRemap[k] = j; } } } } /* -------------------------------------------------------------------- */ /* Boil out all duplicate entries. */ /* -------------------------------------------------------------------- */ if( nPCTSize > 128 ) { CPLError( CE_Warning, CPLE_AppDefined, "Having to merge color table entries to reduce %d real\n" "color table entries down to 127 values.", nPCTSize ); } while( nPCTSize > 128 ) { int nBestRange = 768; int iBestMatch1=-1, iBestMatch2=-1; // Find the closest pair of color table entries. for( i = 1; i < nPCTSize-1; i++ ) { int j; for( j = i+1; j < nPCTSize; j++ ) { int nRange = ABS(abyPCT[i*3+0] - abyPCT[j*3+0]) + ABS(abyPCT[i*3+1] - abyPCT[j*3+1]) + ABS(abyPCT[i*3+2] - abyPCT[j*3+2]); if( nRange < nBestRange ) { iBestMatch1 = i; iBestMatch2 = j; nBestRange = nRange; } } } // Merge the second entry into the first. nPCTSize--; abyPCT[iBestMatch2*3+0] = abyPCT[nPCTSize*3+0]; abyPCT[iBestMatch2*3+1] = abyPCT[nPCTSize*3+1]; abyPCT[iBestMatch2*3+2] = abyPCT[nPCTSize*3+2]; for( i = 0; i < 256; i++ ) { // merge matching entries. if( anRemap[i] == iBestMatch2 ) anRemap[i] = iBestMatch1; // shift the last PCT entry into the new hole. if( anRemap[i] == nPCTSize ) anRemap[i] = iBestMatch2; } } /* -------------------------------------------------------------------- */ /* Write the PCT. */ /* -------------------------------------------------------------------- */ if( !BSBWritePCT( psBSB, nPCTSize, abyPCT ) ) { BSBClose( psBSB ); return NULL; } /* -------------------------------------------------------------------- */ /* Write the GCPs. */ /* -------------------------------------------------------------------- */ double adfGeoTransform[6]; int nGCPCount = poSrcDS->GetGCPCount(); if (nGCPCount) { const char* pszGCPProjection = poSrcDS->GetGCPProjection(); if ( BSBIsSRSOK(pszGCPProjection) ) { const GDAL_GCP * pasGCPList = poSrcDS->GetGCPs(); for( i = 0; i < nGCPCount; i++ ) { VSIFPrintfL( psBSB->fp, "REF/%d,%f,%f,%f,%f\n", i+1, pasGCPList[i].dfGCPPixel, pasGCPList[i].dfGCPLine, pasGCPList[i].dfGCPY, pasGCPList[i].dfGCPX); } } } else if (poSrcDS->GetGeoTransform(adfGeoTransform) == CE_None) { const char* pszProjection = poSrcDS->GetProjectionRef(); if ( BSBIsSRSOK(pszProjection) ) { VSIFPrintfL( psBSB->fp, "REF/%d,%d,%d,%f,%f\n", 1, 0, 0, adfGeoTransform[3] + 0 * adfGeoTransform[4] + 0 * adfGeoTransform[5], adfGeoTransform[0] + 0 * adfGeoTransform[1] + 0 * adfGeoTransform[2]); VSIFPrintfL( psBSB->fp, "REF/%d,%d,%d,%f,%f\n", 2, nXSize, 0, adfGeoTransform[3] + nXSize * adfGeoTransform[4] + 0 * adfGeoTransform[5], adfGeoTransform[0] + nXSize * adfGeoTransform[1] + 0 * adfGeoTransform[2]); VSIFPrintfL( psBSB->fp, "REF/%d,%d,%d,%f,%f\n", 3, nXSize, nYSize, adfGeoTransform[3] + nXSize * adfGeoTransform[4] + nYSize * adfGeoTransform[5], adfGeoTransform[0] + nXSize * adfGeoTransform[1] + nYSize * adfGeoTransform[2]); VSIFPrintfL( psBSB->fp, "REF/%d,%d,%d,%f,%f\n", 4, 0, nYSize, adfGeoTransform[3] + 0 * adfGeoTransform[4] + nYSize * adfGeoTransform[5], adfGeoTransform[0] + 0 * adfGeoTransform[1] + nYSize * adfGeoTransform[2]); } } /* -------------------------------------------------------------------- */ /* Loop over image, copying image data. */ /* -------------------------------------------------------------------- */ GByte *pabyScanline; CPLErr eErr = CE_None; pabyScanline = (GByte *) CPLMalloc( nXSize ); for( int iLine = 0; iLine < nYSize && eErr == CE_None; iLine++ ) { eErr = poBand->RasterIO( GF_Read, 0, iLine, nXSize, 1, pabyScanline, nXSize, 1, GDT_Byte, nBands, nBands * nXSize ); if( eErr == CE_None ) { for( i = 0; i < nXSize; i++ ) pabyScanline[i] = (GByte) anRemap[pabyScanline[i]]; if( !BSBWriteScanline( psBSB, pabyScanline ) ) eErr = CE_Failure; } } CPLFree( pabyScanline ); /* -------------------------------------------------------------------- */ /* cleanup */ /* -------------------------------------------------------------------- */ BSBClose( psBSB ); if( eErr != CE_None ) { VSIUnlink( pszFilename ); return NULL; } else return (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly ); }
GDALDataset* TerragenDataset::Create ( const char* pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char** papszOptions ) { TerragenDataset* poDS = new TerragenDataset(); poDS->eAccess = GA_Update; poDS->m_pszFilename = CPLStrdup(pszFilename); // -------------------------------------------------------------------- // Verify input options. // -------------------------------------------------------------------- const char* pszValue = CSLFetchNameValue( papszOptions,"MINUSERPIXELVALUE"); if( pszValue != NULL ) poDS->m_dLogSpan[0] = atof( pszValue ); pszValue = CSLFetchNameValue( papszOptions,"MAXUSERPIXELVALUE"); if( pszValue != NULL ) poDS->m_dLogSpan[1] = atof( pszValue ); if( poDS->m_dLogSpan[1] <= poDS->m_dLogSpan[0] ) { CPLError( CE_Failure, CPLE_AppDefined, "Inverted, flat, or unspecified span for Terragen file." ); delete poDS; return NULL; } if( eType != GDT_Float32 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create Terragen dataset with a non-float32\n" "data type (%s).\n", GDALGetDataTypeName(eType) ); delete poDS; return NULL; } if( nBands != 1 ) { CPLError( CE_Failure, CPLE_NotSupported, "Terragen driver doesn't support %d bands. Must be 1.\n", nBands ); delete poDS; return NULL; } // -------------------------------------------------------------------- // Try to create the file. // -------------------------------------------------------------------- poDS->m_fp = VSIFOpenL( pszFilename, "wb+" ); if( poDS->m_fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed.\n", pszFilename ); delete poDS; return NULL; } poDS->nRasterXSize = nXSize; poDS->nRasterYSize = nYSize; // Don't bother writing the header here; the first // call to IWriteBlock will do that instead, since // the elevation data's location depends on the // header size. // -------------------------------------------------------------------- // Instance a band. // -------------------------------------------------------------------- poDS->SetBand( 1, new TerragenRasterBand( poDS ) ); //VSIFClose( poDS->m_fp ); //return (GDALDataset *) GDALOpen( pszFilename, GA_Update ); return (GDALDataset *) poDS; }
int main( int argc, char ** argv ) { GDALDriverH hDriver; const char *pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff"; int bFormatExplicitelySet = FALSE; char **papszLayers = NULL; const char *pszBurnAttribute = NULL; double dfIncreaseBurnValue = 0.0; double dfMultiplyBurnValue = 1.0; const char *pszWHERE = NULL, *pszSQL = NULL; GDALDataType eOutputType = GDT_Float64; char **papszCreateOptions = NULL; GUInt32 nXSize = 0, nYSize = 0; double dfXMin = 0.0, dfXMax = 0.0, dfYMin = 0.0, dfYMax = 0.0; int bIsXExtentSet = FALSE, bIsYExtentSet = FALSE; GDALGridAlgorithm eAlgorithm = GGA_InverseDistanceToAPower; void *pOptions = NULL; char *pszOutputSRS = NULL; int bQuiet = FALSE; GDALProgressFunc pfnProgress = GDALTermProgress; int i; OGRGeometry *poSpatialFilter = NULL; int bClipSrc = FALSE; OGRGeometry *poClipSrc = NULL; const char *pszClipSrcDS = NULL; const char *pszClipSrcSQL = NULL; const char *pszClipSrcLayer = NULL; const char *pszClipSrcWhere = NULL; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(argv[0])) exit(1); GDALAllRegister(); OGRRegisterAll(); 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],"--help") ) Usage(); else if( EQUAL(argv[i],"-of") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszFormat = argv[++i]; bFormatExplicitelySet = TRUE; } else if( EQUAL(argv[i],"-q") || EQUAL(argv[i],"-quiet") ) { bQuiet = TRUE; pfnProgress = GDALDummyProgress; } else if( EQUAL(argv[i],"-ot") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); int iType; for( iType = 1; iType < GDT_TypeCount; iType++ ) { if( GDALGetDataTypeName((GDALDataType)iType) != NULL && EQUAL(GDALGetDataTypeName((GDALDataType)iType), argv[i+1]) ) { eOutputType = (GDALDataType) iType; } } if( eOutputType == GDT_Unknown ) { Usage(CPLSPrintf("Unknown output pixel type: %s.", argv[i + 1] )); } i++; } else if( EQUAL(argv[i],"-txe") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); dfXMin = atof(argv[++i]); dfXMax = atof(argv[++i]); bIsXExtentSet = TRUE; } else if( EQUAL(argv[i],"-tye") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); dfYMin = atof(argv[++i]); dfYMax = atof(argv[++i]); bIsYExtentSet = TRUE; } else if( EQUAL(argv[i],"-outsize") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); nXSize = atoi(argv[++i]); nYSize = atoi(argv[++i]); } else if( EQUAL(argv[i],"-co") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] ); } else if( EQUAL(argv[i],"-zfield") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszBurnAttribute = argv[++i]; } else if( EQUAL(argv[i],"-z_increase") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); dfIncreaseBurnValue = atof(argv[++i]); } else if( EQUAL(argv[i],"-z_multiply") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); dfMultiplyBurnValue = atof(argv[++i]); } else if( EQUAL(argv[i],"-where") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszWHERE = argv[++i]; } else if( EQUAL(argv[i],"-l") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); papszLayers = CSLAddString( papszLayers, argv[++i] ); } else if( EQUAL(argv[i],"-sql") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszSQL = argv[++i]; } else if( EQUAL(argv[i],"-spat") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(4); OGRLinearRing oRing; oRing.addPoint( atof(argv[i+1]), atof(argv[i+2]) ); oRing.addPoint( atof(argv[i+1]), atof(argv[i+4]) ); oRing.addPoint( atof(argv[i+3]), atof(argv[i+4]) ); oRing.addPoint( atof(argv[i+3]), atof(argv[i+2]) ); oRing.addPoint( atof(argv[i+1]), atof(argv[i+2]) ); poSpatialFilter = new OGRPolygon(); ((OGRPolygon *) poSpatialFilter)->addRing( &oRing ); i += 4; } else if ( EQUAL(argv[i],"-clipsrc") ) { if (i + 1 >= argc) Usage(CPLSPrintf("%s option requires 1 or 4 arguments", argv[i])); bClipSrc = TRUE; errno = 0; const double unused = strtod( argv[i + 1], NULL ); // XXX: is it a number or not? if ( errno != 0 && argv[i + 2] != NULL && argv[i + 3] != NULL && argv[i + 4] != NULL) { OGRLinearRing oRing; oRing.addPoint( atof(argv[i + 1]), atof(argv[i + 2]) ); oRing.addPoint( atof(argv[i + 1]), atof(argv[i + 4]) ); oRing.addPoint( atof(argv[i + 3]), atof(argv[i + 4]) ); oRing.addPoint( atof(argv[i + 3]), atof(argv[i + 2]) ); oRing.addPoint( atof(argv[i + 1]), atof(argv[i + 2]) ); poClipSrc = new OGRPolygon(); ((OGRPolygon *) poClipSrc)->addRing( &oRing ); i += 4; (void)unused; } else if (EQUALN(argv[i + 1], "POLYGON", 7) || EQUALN(argv[i + 1], "MULTIPOLYGON", 12)) { OGRGeometryFactory::createFromWkt(&argv[i + 1], NULL, &poClipSrc); if ( poClipSrc == NULL ) { Usage("Invalid geometry. " "Must be a valid POLYGON or MULTIPOLYGON WKT."); } i++; } else if (EQUAL(argv[i + 1], "spat_extent") ) { i++; } else { pszClipSrcDS = argv[i + 1]; i++; } } else if ( EQUAL(argv[i], "-clipsrcsql") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszClipSrcSQL = argv[i + 1]; i++; } else if ( EQUAL(argv[i], "-clipsrclayer") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszClipSrcLayer = argv[i + 1]; i++; } else if ( EQUAL(argv[i], "-clipsrcwhere") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); pszClipSrcWhere = argv[i + 1]; i++; } else if( EQUAL(argv[i],"-a_srs") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); OGRSpatialReference oOutputSRS; if( oOutputSRS.SetFromUserInput( argv[i+1] ) != OGRERR_NONE ) { fprintf( stderr, "Failed to process SRS definition: %s\n", argv[i+1] ); GDALDestroyDriverManager(); exit( 1 ); } oOutputSRS.exportToWkt( &pszOutputSRS ); i++; } else if( EQUAL(argv[i],"-a") ) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1); if ( ParseAlgorithmAndOptions( argv[++i], &eAlgorithm, &pOptions ) != CE_None ) { fprintf( stderr, "Failed to process algorithm name and parameters.\n" ); exit( 1 ); } } else if( argv[i][0] == '-' ) { Usage(CPLSPrintf("Unknown option name '%s'", argv[i])); } else if( pszSource == NULL ) { pszSource = argv[i]; } else if( pszDest == NULL ) { pszDest = argv[i]; } else { Usage("Too many command options."); } } if( pszSource == NULL ) { Usage("Source datasource is not specified."); } if( pszDest == NULL ) { Usage("Target dataset is not specified."); } if( pszSQL == NULL && papszLayers == NULL ) { Usage("Neither -sql nor -l are specified."); } if ( bClipSrc && pszClipSrcDS != NULL ) { poClipSrc = LoadGeometry( pszClipSrcDS, pszClipSrcSQL, pszClipSrcLayer, pszClipSrcWhere ); if ( poClipSrc == NULL ) { Usage("Cannot load source clip geometry."); } } else if ( bClipSrc && poClipSrc == NULL && !poSpatialFilter ) { Usage("-clipsrc must be used with -spat option or \n" "a bounding box, WKT string or datasource must be " "specified."); } if ( poSpatialFilter ) { if ( poClipSrc ) { OGRGeometry *poTemp = poSpatialFilter->Intersection( poClipSrc ); if ( poTemp ) { OGRGeometryFactory::destroyGeometry( poSpatialFilter ); poSpatialFilter = poTemp; } OGRGeometryFactory::destroyGeometry( poClipSrc ); poClipSrc = NULL; } } else { if ( poClipSrc ) { poSpatialFilter = poClipSrc; poClipSrc = NULL; } } /* -------------------------------------------------------------------- */ /* Find the output driver. */ /* -------------------------------------------------------------------- */ hDriver = GDALGetDriverByName( pszFormat ); if( hDriver == NULL ) { int iDr; fprintf( stderr, "FAILURE: Output driver `%s' not recognised.\n", pszFormat ); fprintf( stderr, "The following format drivers are configured and support output:\n" ); for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ ) { GDALDriverH hDriver = GDALGetDriver(iDr); if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY, NULL ) != NULL ) { fprintf( stderr, " %s: %s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver ) ); } } printf( "\n" ); Usage(); } /* -------------------------------------------------------------------- */ /* Open input datasource. */ /* -------------------------------------------------------------------- */ OGRDataSourceH hSrcDS; hSrcDS = OGROpen( pszSource, FALSE, NULL ); if( hSrcDS == NULL ) { fprintf( stderr, "Unable to open input datasource \"%s\".\n", pszSource ); fprintf( stderr, "%s\n", CPLGetLastErrorMsg() ); exit( 3 ); } /* -------------------------------------------------------------------- */ /* Create target raster file. */ /* -------------------------------------------------------------------- */ GDALDatasetH hDstDS; int nLayerCount = CSLCount(papszLayers); int nBands = nLayerCount; if ( pszSQL ) nBands++; // FIXME if ( nXSize == 0 ) nXSize = 256; if ( nYSize == 0 ) nYSize = 256; if (!bQuiet && !bFormatExplicitelySet) CheckExtensionConsistency(pszDest, pszFormat); hDstDS = GDALCreate( hDriver, pszDest, nXSize, nYSize, nBands, eOutputType, papszCreateOptions ); if ( hDstDS == NULL ) { fprintf( stderr, "Unable to create target dataset \"%s\".\n", pszDest ); fprintf( stderr, "%s\n", CPLGetLastErrorMsg() ); exit( 3 ); } /* -------------------------------------------------------------------- */ /* If algorithm was not specified assigh default one. */ /* -------------------------------------------------------------------- */ if ( !pOptions ) ParseAlgorithmAndOptions( szAlgNameInvDist, &eAlgorithm, &pOptions ); /* -------------------------------------------------------------------- */ /* Process SQL request. */ /* -------------------------------------------------------------------- */ if( pszSQL != NULL ) { OGRLayerH hLayer; hLayer = OGR_DS_ExecuteSQL( hSrcDS, pszSQL, (OGRGeometryH)poSpatialFilter, NULL ); if( hLayer != NULL ) { // Custom layer will be rasterized in the first band. ProcessLayer( hLayer, hDstDS, poSpatialFilter, nXSize, nYSize, 1, bIsXExtentSet, bIsYExtentSet, dfXMin, dfXMax, dfYMin, dfYMax, pszBurnAttribute, dfIncreaseBurnValue, dfMultiplyBurnValue, eOutputType, eAlgorithm, pOptions, bQuiet, pfnProgress ); } } /* -------------------------------------------------------------------- */ /* Process each layer. */ /* -------------------------------------------------------------------- */ for( i = 0; i < nLayerCount; i++ ) { OGRLayerH hLayer = OGR_DS_GetLayerByName( hSrcDS, papszLayers[i]); if( hLayer == NULL ) { fprintf( stderr, "Unable to find layer \"%s\", skipping.\n", papszLayers[i] ); continue; } if( pszWHERE ) { if( OGR_L_SetAttributeFilter( hLayer, pszWHERE ) != OGRERR_NONE ) break; } if ( poSpatialFilter != NULL ) OGR_L_SetSpatialFilter( hLayer, (OGRGeometryH)poSpatialFilter ); // Fetch the first meaningful SRS definition if ( !pszOutputSRS ) { OGRSpatialReferenceH hSRS = OGR_L_GetSpatialRef( hLayer ); if ( hSRS ) OSRExportToWkt( hSRS, &pszOutputSRS ); } ProcessLayer( hLayer, hDstDS, poSpatialFilter, nXSize, nYSize, i + 1 + nBands - nLayerCount, bIsXExtentSet, bIsYExtentSet, dfXMin, dfXMax, dfYMin, dfYMax, pszBurnAttribute, dfIncreaseBurnValue, dfMultiplyBurnValue, eOutputType, eAlgorithm, pOptions, bQuiet, pfnProgress ); } /* -------------------------------------------------------------------- */ /* Apply geotransformation matrix. */ /* -------------------------------------------------------------------- */ double adfGeoTransform[6]; adfGeoTransform[0] = dfXMin; adfGeoTransform[1] = (dfXMax - dfXMin) / nXSize; adfGeoTransform[2] = 0.0; adfGeoTransform[3] = dfYMin; adfGeoTransform[4] = 0.0; adfGeoTransform[5] = (dfYMax - dfYMin) / nYSize; GDALSetGeoTransform( hDstDS, adfGeoTransform ); /* -------------------------------------------------------------------- */ /* Apply SRS definition if set. */ /* -------------------------------------------------------------------- */ if ( pszOutputSRS ) { GDALSetProjection( hDstDS, pszOutputSRS ); CPLFree( pszOutputSRS ); } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ OGR_DS_Destroy( hSrcDS ); GDALClose( hDstDS ); OGRGeometryFactory::destroyGeometry( poSpatialFilter ); CPLFree( pOptions ); CSLDestroy( papszCreateOptions ); CSLDestroy( argv ); CSLDestroy( papszLayers ); OGRCleanupAll(); GDALDestroyDriverManager(); return 0; }
static CPLErr ProcessLayer( OGRLayerH hSrcLayer, GDALDatasetH hDstDS, OGRGeometry *poClipSrc, GUInt32 nXSize, GUInt32 nYSize, int nBand, int& bIsXExtentSet, int& bIsYExtentSet, double& dfXMin, double& dfXMax, double& dfYMin, double& dfYMax, const char *pszBurnAttribute, const double dfIncreaseBurnValue, const double dfMultiplyBurnValue, GDALDataType eType, GDALGridAlgorithm eAlgorithm, void *pOptions, int bQuiet, GDALProgressFunc pfnProgress ) { /* -------------------------------------------------------------------- */ /* Get field index, and check. */ /* -------------------------------------------------------------------- */ int iBurnField = -1; if ( pszBurnAttribute ) { iBurnField = OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hSrcLayer ), pszBurnAttribute ); if( iBurnField == -1 ) { printf( "Failed to find field %s on layer %s, skipping.\n", pszBurnAttribute, OGR_FD_GetName( OGR_L_GetLayerDefn( hSrcLayer ) ) ); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Collect the geometries from this layer, and build list of */ /* values to be interpolated. */ /* -------------------------------------------------------------------- */ OGRFeature *poFeat; std::vector<double> adfX, adfY, adfZ; OGR_L_ResetReading( hSrcLayer ); while( (poFeat = (OGRFeature *)OGR_L_GetNextFeature( hSrcLayer )) != NULL ) { OGRGeometry *poGeom = poFeat->GetGeometryRef(); double dfBurnValue = 0.0; if ( iBurnField >= 0 ) dfBurnValue = poFeat->GetFieldAsDouble( iBurnField ); ProcessCommonGeometry(poGeom, poClipSrc, iBurnField, dfBurnValue, dfIncreaseBurnValue, dfMultiplyBurnValue, adfX, adfY, adfZ); OGRFeature::DestroyFeature( poFeat ); } if ( adfX.size() == 0 ) { printf( "No point geometry found on layer %s, skipping.\n", OGR_FD_GetName( OGR_L_GetLayerDefn( hSrcLayer ) ) ); return CE_None; } /* -------------------------------------------------------------------- */ /* Compute grid geometry. */ /* -------------------------------------------------------------------- */ if ( !bIsXExtentSet || !bIsYExtentSet ) { OGREnvelope sEnvelope; OGR_L_GetExtent( hSrcLayer, &sEnvelope, TRUE ); if ( !bIsXExtentSet ) { dfXMin = sEnvelope.MinX; dfXMax = sEnvelope.MaxX; bIsXExtentSet = TRUE; } if ( !bIsYExtentSet ) { dfYMin = sEnvelope.MinY; dfYMax = sEnvelope.MaxY; bIsYExtentSet = TRUE; } } /* -------------------------------------------------------------------- */ /* Perform gridding. */ /* -------------------------------------------------------------------- */ const double dfDeltaX = ( dfXMax - dfXMin ) / nXSize; const double dfDeltaY = ( dfYMax - dfYMin ) / nYSize; if ( !bQuiet ) { printf( "Grid data type is \"%s\"\n", GDALGetDataTypeName(eType) ); printf( "Grid size = (%lu %lu).\n", (unsigned long)nXSize, (unsigned long)nYSize ); printf( "Corner coordinates = (%f %f)-(%f %f).\n", dfXMin - dfDeltaX / 2, dfYMax + dfDeltaY / 2, dfXMax + dfDeltaX / 2, dfYMin - dfDeltaY / 2 ); printf( "Grid cell size = (%f %f).\n", dfDeltaX, dfDeltaY ); printf( "Source point count = %lu.\n", (unsigned long)adfX.size() ); PrintAlgorithmAndOptions( eAlgorithm, pOptions ); printf("\n"); } GDALRasterBandH hBand = GDALGetRasterBand( hDstDS, nBand ); if (adfX.size() == 0) { // FIXME: Shoulda' set to nodata value instead GDALFillRaster( hBand, 0.0 , 0.0 ); return CE_None; } GUInt32 nXOffset, nYOffset; int nBlockXSize, nBlockYSize; int nDataTypeSize = GDALGetDataTypeSize(eType) / 8; // Try to grow the work buffer up to 16 MB if it is smaller GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize ); const GUInt32 nDesiredBufferSize = 16*1024*1024; if( (GUInt32)nBlockXSize < nXSize && (GUInt32)nBlockYSize < nYSize && (GUInt32)nBlockXSize < nDesiredBufferSize / (nBlockYSize * nDataTypeSize) ) { int nNewBlockXSize = nDesiredBufferSize / (nBlockYSize * nDataTypeSize); nBlockXSize = (nNewBlockXSize / nBlockXSize) * nBlockXSize; if( (GUInt32)nBlockXSize > nXSize ) nBlockXSize = nXSize; } else if( (GUInt32)nBlockXSize == nXSize && (GUInt32)nBlockYSize < nYSize && (GUInt32)nBlockYSize < nDesiredBufferSize / (nXSize * nDataTypeSize) ) { int nNewBlockYSize = nDesiredBufferSize / (nXSize * nDataTypeSize); nBlockYSize = (nNewBlockYSize / nBlockYSize) * nBlockYSize; if( (GUInt32)nBlockYSize > nYSize ) nBlockYSize = nYSize; } CPLDebug("GDAL_GRID", "Work buffer: %d * %d", nBlockXSize, nBlockYSize); void *pData = VSIMalloc3( nBlockXSize, nBlockYSize, nDataTypeSize ); if( pData == NULL ) { CPLError(CE_Failure, CPLE_OutOfMemory, "Cannot allocate work buffer"); return CE_Failure; } GUInt32 nBlock = 0; GUInt32 nBlockCount = ((nXSize + nBlockXSize - 1) / nBlockXSize) * ((nYSize + nBlockYSize - 1) / nBlockYSize); CPLErr eErr = CE_None; for ( nYOffset = 0; nYOffset < nYSize && eErr == CE_None; nYOffset += nBlockYSize ) { for ( nXOffset = 0; nXOffset < nXSize && eErr == CE_None; nXOffset += nBlockXSize ) { void *pScaledProgress; pScaledProgress = GDALCreateScaledProgress( (double)nBlock / nBlockCount, (double)(nBlock + 1) / nBlockCount, pfnProgress, NULL ); nBlock ++; int nXRequest = nBlockXSize; if (nXOffset + nXRequest > nXSize) nXRequest = nXSize - nXOffset; int nYRequest = nBlockYSize; if (nYOffset + nYRequest > nYSize) nYRequest = nYSize - nYOffset; eErr = GDALGridCreate( eAlgorithm, pOptions, adfX.size(), &(adfX[0]), &(adfY[0]), &(adfZ[0]), dfXMin + dfDeltaX * nXOffset, dfXMin + dfDeltaX * (nXOffset + nXRequest), dfYMin + dfDeltaY * nYOffset, dfYMin + dfDeltaY * (nYOffset + nYRequest), nXRequest, nYRequest, eType, pData, GDALScaledProgress, pScaledProgress ); if( eErr == CE_None ) eErr = GDALRasterIO( hBand, GF_Write, nXOffset, nYOffset, nXRequest, nYRequest, pData, nXRequest, nYRequest, eType, 0, 0 ); GDALDestroyScaledProgress( pScaledProgress ); } } CPLFree( pData ); return eErr; }
bool OsmAnd::HeightmapTileProvider_P::obtainData( const TileId tileId, const ZoomLevel zoom, std::shared_ptr<MapTiledData>& outTiledData, const IQueryController* const queryController) { // Obtain raw data from DB QByteArray data; bool ok = _tileDb.obtainTileData(tileId, zoom, data); if (!ok || data.length() == 0) { // There was no data at all, to avoid further requests, mark this tile as empty outTiledData.reset(); return true; } // We have the data, use GDAL to decode this GeoTIFF const auto tileSize = getTileSize(); bool success = false; QString vmemFilename; vmemFilename.sprintf("/vsimem/heightmapTile@%p", data.data()); VSIFileFromMemBuffer(qPrintable(vmemFilename), reinterpret_cast<GByte*>(data.data()), data.length(), FALSE); auto dataset = reinterpret_cast<GDALDataset*>(GDALOpen(qPrintable(vmemFilename), GA_ReadOnly)); if (dataset != nullptr) { bool bad = false; bad = bad || dataset->GetRasterCount() != 1; bad = bad || dataset->GetRasterXSize() != tileSize; bad = bad || dataset->GetRasterYSize() != tileSize; if (bad) { if (dataset->GetRasterCount() != 1) LogPrintf(LogSeverityLevel::Error, "Height tile %dx%d@%d has %d bands instead of 1", tileId.x, tileId.y, zoom, dataset->GetRasterCount()); if (dataset->GetRasterXSize() != tileSize || dataset->GetRasterYSize() != tileSize) { LogPrintf(LogSeverityLevel::Error, "Height tile %dx%d@%d has %dx%x size instead of %d", tileId.x, tileId.y, zoom, dataset->GetRasterXSize(), dataset->GetRasterYSize(), tileSize); } } else { auto band = dataset->GetRasterBand(1); bad = bad || band->GetColorTable() != nullptr; bad = bad || band->GetRasterDataType() != GDT_Int16; if (bad) { if (band->GetColorTable() != nullptr) LogPrintf(LogSeverityLevel::Error, "Height tile %dx%d@%d has color table", tileId.x, tileId.y, zoom); if (band->GetRasterDataType() != GDT_Int16) LogPrintf(LogSeverityLevel::Error, "Height tile %dx%d@%d has %s data type in band 1", tileId.x, tileId.y, zoom, GDALGetDataTypeName(band->GetRasterDataType())); } else { auto buffer = new float[tileSize*tileSize]; auto res = dataset->RasterIO(GF_Read, 0, 0, tileSize, tileSize, buffer, tileSize, tileSize, GDT_Float32, 1, nullptr, 0, 0, 0); if (res != CE_None) { delete[] buffer; LogPrintf(LogSeverityLevel::Error, "Failed to decode height tile %dx%d@%d: %s", tileId.x, tileId.y, zoom, CPLGetLastErrorMsg()); } else { outTiledData.reset(new ElevationDataTile(buffer, sizeof(float)*tileSize, tileSize, tileId, zoom)); success = true; } } } GDALClose(dataset); } VSIUnlink(qPrintable(vmemFilename)); return success; }
CC_FILE_ERROR RasterGridFilter::loadFile(QString filename, ccHObject& container, bool alwaysDisplayLoadDialog/*=true*/, bool* coordinatesShiftEnabled/*=0*/, CCVector3d* coordinatesShift/*=0*/) { GDALAllRegister(); ccLog::PrintDebug("(GDAL drivers: %i)", GetGDALDriverManager()->GetDriverCount()); GDALDataset* poDataset = static_cast<GDALDataset*>(GDALOpen( qPrintable(filename), GA_ReadOnly )); if( poDataset != NULL ) { ccLog::Print(QString("Raster file: '%1'").arg(filename)); ccLog::Print( "Driver: %s/%s", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); int rasterCount = poDataset->GetRasterCount(); int rasterX = poDataset->GetRasterXSize(); int rasterY = poDataset->GetRasterYSize(); ccLog::Print( "Size is %dx%dx%d", rasterX, rasterY, rasterCount ); ccPointCloud* pc = new ccPointCloud(); if (!pc->reserve(static_cast<unsigned>(rasterX * rasterY))) { delete pc; return CC_FERR_NOT_ENOUGH_MEMORY; } if( poDataset->GetProjectionRef() != NULL ) ccLog::Print( "Projection is `%s'", poDataset->GetProjectionRef() ); double adfGeoTransform[6] = { 0, //top left x 1, //w-e pixel resolution (can be negative) 0, //0 0, //top left y 0, //0 1 //n-s pixel resolution (can be negative) }; if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { ccLog::Print( "Origin = (%.6f,%.6f)", adfGeoTransform[0], adfGeoTransform[3] ); ccLog::Print( "Pixel Size = (%.6f,%.6f)", adfGeoTransform[1], adfGeoTransform[5] ); } if (adfGeoTransform[1] == 0 || adfGeoTransform[5] == 0) { ccLog::Warning("Invalid pixel size! Forcing it to (1,1)"); adfGeoTransform[1] = adfGeoTransform[5] = 1; } CCVector3d origin( adfGeoTransform[0], adfGeoTransform[3], 0.0 ); CCVector3d Pshift(0,0,0); //check for 'big' coordinates { bool shiftAlreadyEnabled = (coordinatesShiftEnabled && *coordinatesShiftEnabled && coordinatesShift); if (shiftAlreadyEnabled) Pshift = *coordinatesShift; bool applyAll = false; if ( sizeof(PointCoordinateType) < 8 && ccCoordinatesShiftManager::Handle(origin,0,alwaysDisplayLoadDialog,shiftAlreadyEnabled,Pshift,0,&applyAll)) { pc->setGlobalShift(Pshift); ccLog::Warning("[RasterFilter::loadFile] Raster has been recentered! Translation: (%.2f,%.2f,%.2f)",Pshift.x,Pshift.y,Pshift.z); //we save coordinates shift information if (applyAll && coordinatesShiftEnabled && coordinatesShift) { *coordinatesShiftEnabled = true; *coordinatesShift = Pshift; } } } //create blank raster 'grid' { double z = 0.0 /*+ Pshift.z*/; for (int j=0; j<rasterY; ++j) { double y = adfGeoTransform[3] + static_cast<double>(j) * adfGeoTransform[5] + Pshift.y; CCVector3 P( 0, static_cast<PointCoordinateType>(y), static_cast<PointCoordinateType>(z)); for (int i=0; i<rasterX; ++i) { double x = adfGeoTransform[0] + static_cast<double>(i) * adfGeoTransform[1] + Pshift.x; P.x = static_cast<PointCoordinateType>(x); pc->addPoint(P); } } QVariant xVar = QVariant::fromValue<int>(rasterX); QVariant yVar = QVariant::fromValue<int>(rasterY); pc->setMetaData("raster_width",xVar); pc->setMetaData("raster_height",yVar); } //fetch raster bands bool zRasterProcessed = false; unsigned zInvalid = 0; double zMinMax[2] = {0, 0}; for (int i=1; i<=rasterCount; ++i) { ccLog::Print( "Reading band #%i", i); GDALRasterBand* poBand = poDataset->GetRasterBand(i); GDALColorInterp colorInterp = poBand->GetColorInterpretation(); GDALDataType bandType = poBand->GetRasterDataType(); int nBlockXSize, nBlockYSize; poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); ccLog::Print( "Block=%dx%d Type=%s, ColorInterp=%s", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName(colorInterp) ); //fetching raster scan-line int nXSize = poBand->GetXSize(); int nYSize = poBand->GetYSize(); assert(nXSize == rasterX); assert(nYSize == rasterY); int bGotMin, bGotMax; double adfMinMax[2] = {0, 0}; adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if (!bGotMin || !bGotMax ) //DGM FIXME: if the file is corrupted (e.g. ASCII ArcGrid with missing rows) this method will enter in a infinite loop! GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); ccLog::Print( "Min=%.3fd, Max=%.3f", adfMinMax[0], adfMinMax[1] ); GDALColorTable* colTable = poBand->GetColorTable(); if( colTable != NULL ) printf( "Band has a color table with %d entries", colTable->GetColorEntryCount() ); if( poBand->GetOverviewCount() > 0 ) printf( "Band has %d overviews", poBand->GetOverviewCount() ); if (colorInterp == GCI_Undefined && !zRasterProcessed/*&& !colTable*/) //probably heights? { zRasterProcessed = true; zMinMax[0] = adfMinMax[0]; zMinMax[1] = adfMinMax[1]; double* scanline = (double*) CPLMalloc(sizeof(double)*nXSize); //double* scanline = new double[nXSize]; memset(scanline,0,sizeof(double)*nXSize); for (int j=0; j<nYSize; ++j) { if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/scanline, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Float64, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None) { delete pc; CPLFree(scanline); GDALClose(poDataset); return CC_FERR_READING; } for (int k=0; k<nXSize; ++k) { double z = static_cast<double>(scanline[k]) + Pshift[2]; unsigned pointIndex = static_cast<unsigned>(k + j * rasterX); if (pointIndex <= pc->size()) { if (z < zMinMax[0] || z > zMinMax[1]) { z = zMinMax[0] - 1.0; ++zInvalid; } const_cast<CCVector3*>(pc->getPoint(pointIndex))->z = static_cast<PointCoordinateType>(z); } } } //update bounding-box pc->invalidateBoundingBox(); if (scanline) CPLFree(scanline); scanline = 0; } else //colors { bool isRGB = false; bool isScalar = false; bool isPalette = false; switch(colorInterp) { case GCI_Undefined: isScalar = true; break; case GCI_PaletteIndex: isPalette = true; break; case GCI_RedBand: case GCI_GreenBand: case GCI_BlueBand: isRGB = true; break; case GCI_AlphaBand: if (adfMinMax[0] != adfMinMax[1]) isScalar = true; else ccLog::Warning(QString("Alpha band ignored as it has a unique value (%1)").arg(adfMinMax[0])); break; default: isScalar = true; break; } if (isRGB || isPalette) { //first check that a palette exists if the band is a palette index if (isPalette && !colTable) { ccLog::Warning(QString("Band is declared as a '%1' but no palette is associated!").arg(GDALGetColorInterpretationName(colorInterp))); isPalette = false; } else { //instantiate memory for RBG colors if necessary if (!pc->hasColors() && !pc->setRGBColor(MAX_COLOR_COMP,MAX_COLOR_COMP,MAX_COLOR_COMP)) { ccLog::Warning(QString("Failed to instantiate memory for storing color band '%1'!").arg(GDALGetColorInterpretationName(colorInterp))); } else { assert(bandType <= GDT_Int32); int* colIndexes = (int*) CPLMalloc(sizeof(int)*nXSize); //double* scanline = new double[nXSize]; memset(colIndexes,0,sizeof(int)*nXSize); for (int j=0; j<nYSize; ++j) { if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/colIndexes, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Int32, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None) { CPLFree(colIndexes); delete pc; return CC_FERR_READING; } for (int k=0; k<nXSize; ++k) { unsigned pointIndex = static_cast<unsigned>(k + j * rasterX); if (pointIndex <= pc->size()) { colorType* C = const_cast<colorType*>(pc->getPointColor(pointIndex)); switch(colorInterp) { case GCI_PaletteIndex: assert(colTable); { GDALColorEntry col; colTable->GetColorEntryAsRGB(colIndexes[k],&col); C[0] = static_cast<colorType>(col.c1 & MAX_COLOR_COMP); C[1] = static_cast<colorType>(col.c2 & MAX_COLOR_COMP); C[2] = static_cast<colorType>(col.c3 & MAX_COLOR_COMP); } break; case GCI_RedBand: C[0] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP); break; case GCI_GreenBand: C[1] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP); break; case GCI_BlueBand: C[2] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP); break; default: assert(false); break; } } } } if (colIndexes) CPLFree(colIndexes); colIndexes = 0; pc->showColors(true); } } } else if (isScalar) { ccScalarField* sf = new ccScalarField(GDALGetColorInterpretationName(colorInterp)); if (!sf->resize(pc->size(),true,NAN_VALUE)) { ccLog::Warning(QString("Failed to instantiate memory for storing '%1' as a scalar field!").arg(sf->getName())); sf->release(); sf = 0; } else { double* colValues = (double*) CPLMalloc(sizeof(double)*nXSize); //double* scanline = new double[nXSize]; memset(colValues,0,sizeof(double)*nXSize); for (int j=0; j<nYSize; ++j) { if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/colValues, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Float64, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None) { CPLFree(colValues); delete pc; return CC_FERR_READING; } for (int k=0; k<nXSize; ++k) { unsigned pointIndex = static_cast<unsigned>(k + j * rasterX); if (pointIndex <= pc->size()) { ScalarType s = static_cast<ScalarType>(colValues[k]); sf->setValue(pointIndex,s); } } } if (colValues) CPLFree(colValues); colValues = 0; sf->computeMinAndMax(); pc->addScalarField(sf); if (pc->getNumberOfScalarFields() == 1) pc->setCurrentDisplayedScalarField(0); pc->showSF(true); } } } } if (pc) { if (!zRasterProcessed) { ccLog::Warning("Raster has no height (Z) information: you can convert one of its scalar fields to Z with 'Edit > Scalar Fields > Set SF as coordinate(s)'"); } else if (zInvalid != 0 && zInvalid < pc->size()) { //shall we remove the points with invalid heights? if (QMessageBox::question(0,"Remove NaN points?","This raster has pixels with invalid heights. Shall we remove them?",QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { CCLib::ReferenceCloud validPoints(pc); unsigned count = pc->size(); bool error = true; if (validPoints.reserve(count-zInvalid)) { for (unsigned i=0; i<count; ++i) { if (pc->getPoint(i)->z >= zMinMax[0]) validPoints.addPointIndex(i); } if (validPoints.size() > 0) { validPoints.resize(validPoints.size()); ccPointCloud* newPC = pc->partialClone(&validPoints); if (newPC) { delete pc; pc = newPC; error = false; } } else { assert(false); } } if (error) { ccLog::Error("Not enough memory to remove the points with invalid heights!"); } } } container.addChild(pc); } GDALClose(poDataset); } else { return CC_FERR_UNKNOWN_FILE; } return CC_FERR_NO_ERROR; }
GDALDataset *NTv2Dataset::Create( const char * pszFilename, int nXSize, int nYSize, CPL_UNUSED int nBands, GDALDataType eType, char ** papszOptions ) { if( eType != GDT_Float32 ) { CPLError(CE_Failure, CPLE_AppDefined, "Attempt to create NTv2 file with unsupported data type '%s'.", GDALGetDataTypeName( eType ) ); return NULL; } /* -------------------------------------------------------------------- */ /* Are we extending an existing file? */ /* -------------------------------------------------------------------- */ VSILFILE *fp; GUInt32 nNumFile = 1; int bAppend = CSLFetchBoolean(papszOptions,"APPEND_SUBDATASET",FALSE); /* -------------------------------------------------------------------- */ /* Try to open or create file. */ /* -------------------------------------------------------------------- */ if( bAppend ) fp = VSIFOpenL( pszFilename, "rb+" ); else fp = VSIFOpenL( pszFilename, "wb" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to open/create file `%s' failed.\n", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Create a file level header if we are creating new. */ /* -------------------------------------------------------------------- */ char achHeader[11*16]; const char *pszValue; if( !bAppend ) { memset( achHeader, 0, sizeof(achHeader) ); memcpy( achHeader + 0*16, "NUM_OREC", 8 ); achHeader[ 0*16 + 8] = 0xb; memcpy( achHeader + 1*16, "NUM_SREC", 8 ); achHeader[ 1*16 + 8] = 0xb; memcpy( achHeader + 2*16, "NUM_FILE", 8 ); achHeader[ 2*16 + 8] = 0x1; memcpy( achHeader + 3*16, "GS_TYPE ", 16 ); pszValue = CSLFetchNameValueDef( papszOptions, "GS_TYPE", "SECONDS"); memcpy( achHeader + 3*16+8, pszValue, MIN(16,strlen(pszValue)) ); memcpy( achHeader + 4*16, "VERSION ", 16 ); pszValue = CSLFetchNameValueDef( papszOptions, "VERSION", "" ); memcpy( achHeader + 4*16+8, pszValue, MIN(16,strlen(pszValue)) ); memcpy( achHeader + 5*16, "SYSTEM_F ", 16 ); pszValue = CSLFetchNameValueDef( papszOptions, "SYSTEM_F", "" ); memcpy( achHeader + 5*16+8, pszValue, MIN(16,strlen(pszValue)) ); memcpy( achHeader + 6*16, "SYSTEM_T ", 16 ); pszValue = CSLFetchNameValueDef( papszOptions, "SYSTEM_T", "" ); memcpy( achHeader + 6*16+8, pszValue, MIN(16,strlen(pszValue)) ); memcpy( achHeader + 7*16, "MAJOR_F ", 8); memcpy( achHeader + 8*16, "MINOR_F ", 8 ); memcpy( achHeader + 9*16, "MAJOR_T ", 8 ); memcpy( achHeader + 10*16, "MINOR_T ", 8 ); VSIFWriteL( achHeader, 1, sizeof(achHeader), fp ); } /* -------------------------------------------------------------------- */ /* Otherwise update the header with an increased subfile count, */ /* and advanced to the last record of the file. */ /* -------------------------------------------------------------------- */ else { VSIFSeekL( fp, 2*16 + 8, SEEK_SET ); VSIFReadL( &nNumFile, 1, 4, fp ); CPL_LSBPTR32( &nNumFile ); nNumFile++; CPL_LSBPTR32( &nNumFile ); VSIFSeekL( fp, 2*16 + 8, SEEK_SET ); VSIFWriteL( &nNumFile, 1, 4, fp ); vsi_l_offset nEnd; VSIFSeekL( fp, 0, SEEK_END ); nEnd = VSIFTellL( fp ); VSIFSeekL( fp, nEnd-16, SEEK_SET ); } /* -------------------------------------------------------------------- */ /* Write the grid header. */ /* -------------------------------------------------------------------- */ memset( achHeader, 0, sizeof(achHeader) ); memcpy( achHeader + 0*16, "SUB_NAME ", 16 ); pszValue = CSLFetchNameValueDef( papszOptions, "SUB_NAME", "" ); memcpy( achHeader + 0*16+8, pszValue, MIN(16,strlen(pszValue)) ); memcpy( achHeader + 1*16, "PARENT ", 16 ); pszValue = CSLFetchNameValueDef( papszOptions, "PARENT", "NONE" ); memcpy( achHeader + 1*16+8, pszValue, MIN(16,strlen(pszValue)) ); memcpy( achHeader + 2*16, "CREATED ", 16 ); pszValue = CSLFetchNameValueDef( papszOptions, "CREATED", "" ); memcpy( achHeader + 2*16+8, pszValue, MIN(16,strlen(pszValue)) ); memcpy( achHeader + 3*16, "UPDATED ", 16 ); pszValue = CSLFetchNameValueDef( papszOptions, "UPDATED", "" ); memcpy( achHeader + 3*16+8, pszValue, MIN(16,strlen(pszValue)) ); double dfValue; memcpy( achHeader + 4*16, "S_LAT ", 8 ); dfValue = 0; CPL_LSBPTR64( &dfValue ); memcpy( achHeader + 4*16 + 8, &dfValue, 8 ); memcpy( achHeader + 5*16, "N_LAT ", 8 ); dfValue = nYSize-1; CPL_LSBPTR64( &dfValue ); memcpy( achHeader + 5*16 + 8, &dfValue, 8 ); memcpy( achHeader + 6*16, "E_LONG ", 8 ); dfValue = -1*(nXSize-1); CPL_LSBPTR64( &dfValue ); memcpy( achHeader + 6*16 + 8, &dfValue, 8 ); memcpy( achHeader + 7*16, "W_LONG ", 8 ); dfValue = 0; CPL_LSBPTR64( &dfValue ); memcpy( achHeader + 7*16 + 8, &dfValue, 8 ); memcpy( achHeader + 8*16, "LAT_INC ", 8 ); dfValue = 1; CPL_LSBPTR64( &dfValue ); memcpy( achHeader + 8*16 + 8, &dfValue, 8 ); memcpy( achHeader + 9*16, "LONG_INC", 8 ); memcpy( achHeader + 9*16 + 8, &dfValue, 8 ); memcpy( achHeader + 10*16, "GS_COUNT", 8 ); GUInt32 nGSCount = nXSize * nYSize; CPL_LSBPTR32( &nGSCount ); memcpy( achHeader + 10*16+8, &nGSCount, 4 ); VSIFWriteL( achHeader, 1, sizeof(achHeader), fp ); /* -------------------------------------------------------------------- */ /* Write zeroed grid data. */ /* -------------------------------------------------------------------- */ int i; memset( achHeader, 0, 16 ); // Use -1 (0x000080bf) as the default error value. memset( achHeader + 10, 0x80, 1 ); memset( achHeader + 11, 0xbf, 1 ); memset( achHeader + 14, 0x80, 1 ); memset( achHeader + 15, 0xbf, 1 ); for( i = 0; i < nXSize * nYSize; i++ ) VSIFWriteL( achHeader, 1, 16, fp ); /* -------------------------------------------------------------------- */ /* Write the end record. */ /* -------------------------------------------------------------------- */ memset( achHeader, 0, 16 ); memcpy( achHeader, "END ", 8 ); VSIFWriteL( achHeader, 1, 16, fp ); VSIFCloseL( fp ); if( nNumFile == 1 ) return (GDALDataset *) GDALOpen( pszFilename, GA_Update ); else { CPLString osSubDSName; osSubDSName.Printf( "NTv2:%d:%s", nNumFile-1, pszFilename ); return (GDALDataset *) GDALOpen( osSubDSName, GA_Update ); } }
GDALRasterizeOptions *GDALRasterizeOptionsNew(char** papszArgv, GDALRasterizeOptionsForBinary* psOptionsForBinary) { GDALRasterizeOptions *psOptions = new GDALRasterizeOptions; psOptions->pszFormat = CPLStrdup("GTiff"); psOptions->pfnProgress = GDALDummyProgress; psOptions->pProgressData = NULL; psOptions->bCreateOutput = FALSE; psOptions->b3D = FALSE; psOptions->bInverse = FALSE; memset(&(psOptions->sEnvelop), 0, sizeof(psOptions->sEnvelop)); psOptions->papszCreationOptions = NULL; psOptions->papszLayers = NULL; psOptions->pszSQL = NULL; psOptions->pszDialect = NULL; psOptions->pszBurnAttribute = NULL; psOptions->pszWHERE = NULL; psOptions->papszRasterizeOptions = NULL; psOptions->dfXRes = 0; psOptions->dfYRes = 0; psOptions->bCreateOutput = FALSE; psOptions->eOutputType = GDT_Float64; psOptions->bNoDataSet = FALSE; psOptions->dfNoData = 0; psOptions->bGotBounds = FALSE; psOptions->nXSize = 0; psOptions->nYSize = 0; psOptions->hSRS = NULL; psOptions->bTargetAlignedPixels = FALSE; /* -------------------------------------------------------------------- */ /* Handle command line arguments. */ /* -------------------------------------------------------------------- */ int argc = CSLCount(papszArgv); for( int i = 0; i < argc; i++ ) { if( EQUAL(papszArgv[i],"-of") && i < argc-1 ) { ++i; CPLFree(psOptions->pszFormat); psOptions->pszFormat = CPLStrdup(papszArgv[i]); psOptions->bCreateOutput = TRUE; if( psOptionsForBinary ) { psOptionsForBinary->bFormatExplicitlySet = TRUE; } } else if( EQUAL(papszArgv[i],"-q") || EQUAL(papszArgv[i],"-quiet") ) { if( psOptionsForBinary ) psOptionsForBinary->bQuiet = TRUE; } else if( EQUAL(papszArgv[i],"-a") && i < argc-1 ) { CPLFree(psOptions->pszBurnAttribute); psOptions->pszBurnAttribute = CPLStrdup(papszArgv[++i]); } else if( EQUAL(papszArgv[i],"-b") && i < argc-1 ) { if (strchr(papszArgv[i+1], ' ')) { char** papszTokens = CSLTokenizeString( papszArgv[i+1] ); char** papszIter = papszTokens; while(papszIter && *papszIter) { psOptions->anBandList.push_back(atoi(*papszIter)); papszIter ++; } CSLDestroy(papszTokens); i += 1; } else { while(i < argc-1 && ArgIsNumeric(papszArgv[i+1])) { psOptions->anBandList.push_back(atoi(papszArgv[i+1])); i += 1; } } } else if( EQUAL(papszArgv[i],"-3d") ) { psOptions->b3D = TRUE; psOptions->papszRasterizeOptions = CSLSetNameValue( psOptions->papszRasterizeOptions, "BURN_VALUE_FROM", "Z"); } else if( EQUAL(papszArgv[i],"-add") ) { psOptions->papszRasterizeOptions = CSLSetNameValue( psOptions->papszRasterizeOptions, "MERGE_ALG", "ADD"); } else if( EQUAL(papszArgv[i],"-chunkysize") && i < argc-1 ) { psOptions->papszRasterizeOptions = CSLSetNameValue( psOptions->papszRasterizeOptions, "CHUNKYSIZE", papszArgv[++i] ); } else if( EQUAL(papszArgv[i],"-i") ) { psOptions->bInverse = TRUE; } else if( EQUAL(papszArgv[i],"-at") ) { psOptions->papszRasterizeOptions = CSLSetNameValue( psOptions->papszRasterizeOptions, "ALL_TOUCHED", "TRUE" ); } else if( EQUAL(papszArgv[i],"-burn") && i < argc-1 ) { if (strchr(papszArgv[i+1], ' ')) { char** papszTokens = CSLTokenizeString( papszArgv[i+1] ); char** papszIter = papszTokens; while(papszIter && *papszIter) { psOptions->adfBurnValues.push_back(CPLAtof(*papszIter)); papszIter ++; } CSLDestroy(papszTokens); i += 1; } else { while(i < argc-1 && ArgIsNumeric(papszArgv[i+1])) { psOptions->adfBurnValues.push_back(CPLAtof(papszArgv[i+1])); i += 1; } } } else if( EQUAL(papszArgv[i],"-where") && i < argc-1 ) { CPLFree(psOptions->pszWHERE); psOptions->pszWHERE = CPLStrdup(papszArgv[++i]); } else if( EQUAL(papszArgv[i],"-l") && i < argc-1 ) { psOptions->papszLayers = CSLAddString( psOptions->papszLayers, papszArgv[++i] ); } else if( EQUAL(papszArgv[i],"-sql") && i < argc-1 ) { CPLFree(psOptions->pszSQL); psOptions->pszSQL = CPLStrdup(papszArgv[++i]); } else if( EQUAL(papszArgv[i],"-dialect") && i < argc-1 ) { CPLFree(psOptions->pszDialect); psOptions->pszDialect = CPLStrdup(papszArgv[++i]); } else if( EQUAL(papszArgv[i],"-init") && i < argc - 1 ) { if (strchr(papszArgv[i+1], ' ')) { char** papszTokens = CSLTokenizeString( papszArgv[i+1] ); char** papszIter = papszTokens; while(papszIter && *papszIter) { psOptions->adfInitVals.push_back(CPLAtof(*papszIter)); papszIter ++; } CSLDestroy(papszTokens); i += 1; } else { while(i < argc-1 && ArgIsNumeric(papszArgv[i+1])) { psOptions->adfInitVals.push_back(CPLAtof(papszArgv[i+1])); i += 1; } } psOptions->bCreateOutput = TRUE; } else if( EQUAL(papszArgv[i],"-a_nodata") && i < argc - 1 ) { psOptions->dfNoData = CPLAtof(papszArgv[i+1]); psOptions->bNoDataSet = TRUE; i += 1; psOptions->bCreateOutput = TRUE; } else if( EQUAL(papszArgv[i],"-a_srs") && i < argc-1 ) { OSRDestroySpatialReference(psOptions->hSRS); psOptions->hSRS = OSRNewSpatialReference( NULL ); if( OSRSetFromUserInput(psOptions->hSRS, papszArgv[i+1]) != OGRERR_NONE ) { CPLError(CE_Failure, CPLE_AppDefined, "Failed to process SRS definition: %s", papszArgv[i+1] ); GDALRasterizeOptionsFree(psOptions); return NULL; } i++; psOptions->bCreateOutput = TRUE; } else if( EQUAL(papszArgv[i],"-te") && i < argc - 4 ) { psOptions->sEnvelop.MinX = CPLAtof(papszArgv[++i]); psOptions->sEnvelop.MinY = CPLAtof(papszArgv[++i]); psOptions->sEnvelop.MaxX = CPLAtof(papszArgv[++i]); psOptions->sEnvelop.MaxY = CPLAtof(papszArgv[++i]); psOptions->bGotBounds = TRUE; psOptions->bCreateOutput = TRUE; } else if( EQUAL(papszArgv[i],"-a_ullr") && i < argc - 4 ) { psOptions->sEnvelop.MinX = CPLAtof(papszArgv[++i]); psOptions->sEnvelop.MaxY = CPLAtof(papszArgv[++i]); psOptions->sEnvelop.MaxX = CPLAtof(papszArgv[++i]); psOptions->sEnvelop.MinY = CPLAtof(papszArgv[++i]); psOptions->bGotBounds = TRUE; psOptions->bCreateOutput = TRUE; } else if( EQUAL(papszArgv[i],"-co") && i < argc-1 ) { psOptions->papszCreationOptions = CSLAddString( psOptions->papszCreationOptions, papszArgv[++i] ); psOptions->bCreateOutput = TRUE; } else if( EQUAL(papszArgv[i],"-ot") && i < argc-1 ) { int iType; for( iType = 1; iType < GDT_TypeCount; iType++ ) { if( GDALGetDataTypeName((GDALDataType)iType) != NULL && EQUAL(GDALGetDataTypeName((GDALDataType)iType), papszArgv[i+1]) ) { psOptions->eOutputType = (GDALDataType) iType; } } if( psOptions->eOutputType == GDT_Unknown ) { CPLError(CE_Failure, CPLE_AppDefined, "Unknown output pixel type: %s", papszArgv[i+1] ); GDALRasterizeOptionsFree(psOptions); return NULL; } i++; psOptions->bCreateOutput = TRUE; } else if( (EQUAL(papszArgv[i],"-ts") || EQUAL(papszArgv[i],"-outsize")) && i < argc-2 ) { psOptions->nXSize = atoi(papszArgv[++i]); psOptions->nYSize = atoi(papszArgv[++i]); if (psOptions->nXSize <= 0 || psOptions->nYSize <= 0) { CPLError(CE_Failure, CPLE_AppDefined, "Wrong value for -outsize parameter."); GDALRasterizeOptionsFree(psOptions); return NULL; } psOptions->bCreateOutput = TRUE; } else if( EQUAL(papszArgv[i],"-tr") && i < argc-2 ) { psOptions->dfXRes = CPLAtof(papszArgv[++i]); psOptions->dfYRes = fabs(CPLAtof(papszArgv[++i])); if( psOptions->dfXRes == 0 || psOptions->dfYRes == 0 ) { CPLError(CE_Failure, CPLE_AppDefined, "Wrong value for -tr parameter."); GDALRasterizeOptionsFree(psOptions); return NULL; } psOptions->bCreateOutput = TRUE; } else if( EQUAL(papszArgv[i],"-tap") ) { psOptions->bTargetAlignedPixels = TRUE; psOptions->bCreateOutput = TRUE; } else if( papszArgv[i][0] == '-' ) { CPLError(CE_Failure, CPLE_NotSupported, "Unknown option name '%s'", papszArgv[i]); GDALRasterizeOptionsFree(psOptions); return NULL; } else if( psOptionsForBinary && psOptionsForBinary->pszSource == NULL ) { psOptionsForBinary->pszSource = CPLStrdup(papszArgv[i]); } else if( psOptionsForBinary && psOptionsForBinary->pszDest == NULL ) { psOptionsForBinary->pszDest = CPLStrdup(papszArgv[i]); } else { CPLError(CE_Failure, CPLE_NotSupported, "Too many command options '%s'", papszArgv[i]); GDALRasterizeOptionsFree(psOptions); return NULL; } } if( psOptions->adfBurnValues.size() == 0 && psOptions->pszBurnAttribute == NULL && !(psOptions->b3D) ) { if( psOptionsForBinary == NULL ) psOptions->adfBurnValues.push_back(255); else { CPLError(CE_Failure, CPLE_NotSupported, "At least one of -3d, -burn or -a required." ); GDALRasterizeOptionsFree(psOptions); return NULL; } } if( psOptions->bCreateOutput ) { if( psOptions->dfXRes == 0 && psOptions->dfYRes == 0 && psOptions->nXSize == 0 && psOptions->nYSize == 0 ) { CPLError(CE_Failure, CPLE_NotSupported, "'-tr xres yres' or '-ts xsize ysize' is required." ); GDALRasterizeOptionsFree(psOptions); return NULL; } if (psOptions->bTargetAlignedPixels && psOptions->dfXRes == 0 && psOptions->dfYRes == 0) { CPLError(CE_Failure, CPLE_NotSupported, "-tap option cannot be used without using -tr."); GDALRasterizeOptionsFree(psOptions); return NULL;; } if( psOptions->anBandList.size() != 0 ) { CPLError(CE_Failure, CPLE_NotSupported, "-b option cannot be used when creating a GDAL dataset." ); GDALRasterizeOptionsFree(psOptions); return NULL; } int nBandCount = 1; if (psOptions->adfBurnValues.size() != 0) nBandCount = static_cast<int>(psOptions->adfBurnValues.size()); if ((int)psOptions->adfInitVals.size() > nBandCount) nBandCount = static_cast<int>(psOptions->adfInitVals.size()); if (psOptions->adfInitVals.size() == 1) { for(int i=1;i<=nBandCount - 1;i++) psOptions->adfInitVals.push_back( psOptions->adfInitVals[0] ); } int i; for(i=1;i<=nBandCount;i++) psOptions->anBandList.push_back( i ); } else { if( psOptions->anBandList.size() == 0 ) psOptions->anBandList.push_back( 1 ); } if( psOptions->pszDialect != NULL && psOptions->pszWHERE != NULL && psOptions->pszSQL == NULL ) { CPLError( CE_Warning, CPLE_AppDefined, "-dialect is ignored with -where. Use -sql instead" ); } if( psOptionsForBinary ) { psOptionsForBinary->bCreateOutput = psOptions->bCreateOutput; psOptionsForBinary->pszFormat = CPLStrdup(psOptions->pszFormat); } return psOptions; }
static GDALDataset * GMTCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, int bStrict, CPL_UNUSED char ** papszOptions, CPL_UNUSED GDALProgressFunc pfnProgress, CPL_UNUSED void * pProgressData ) { /* -------------------------------------------------------------------- */ /* Figure out general characteristics. */ /* -------------------------------------------------------------------- */ nc_type nc_datatype; GDALRasterBand *poBand; int nXSize, nYSize; CPLMutexHolderD(&hNCMutex); if( poSrcDS->GetRasterCount() != 1 ) { CPLError( CE_Failure, CPLE_AppDefined, "Currently GMT export only supports 1 band datasets." ); return NULL; } poBand = poSrcDS->GetRasterBand(1); nXSize = poSrcDS->GetRasterXSize(); nYSize = poSrcDS->GetRasterYSize(); if( poBand->GetRasterDataType() == GDT_Int16 ) nc_datatype = NC_SHORT; else if( poBand->GetRasterDataType() == GDT_Int32 ) nc_datatype = NC_INT; else if( poBand->GetRasterDataType() == GDT_Float32 ) nc_datatype = NC_FLOAT; else if( poBand->GetRasterDataType() == GDT_Float64 ) nc_datatype = NC_DOUBLE; else if( bStrict ) { CPLError( CE_Failure, CPLE_AppDefined, "Band data type %s not supported in GMT, giving up.", GDALGetDataTypeName( poBand->GetRasterDataType() ) ); return NULL; } else if( poBand->GetRasterDataType() == GDT_Byte ) nc_datatype = NC_SHORT; else if( poBand->GetRasterDataType() == GDT_UInt16 ) nc_datatype = NC_INT; else if( poBand->GetRasterDataType() == GDT_UInt32 ) nc_datatype = NC_INT; else nc_datatype = NC_FLOAT; /* -------------------------------------------------------------------- */ /* Establish bounds from geotransform. */ /* -------------------------------------------------------------------- */ double adfGeoTransform[6]; double dfXMax, dfYMin; poSrcDS->GetGeoTransform( adfGeoTransform ); if( adfGeoTransform[2] != 0.0 || adfGeoTransform[4] != 0.0 ) { CPLError( bStrict ? CE_Failure : CE_Warning, CPLE_AppDefined, "Geotransform has rotational coefficients not supported in GMT." ); if( bStrict ) return NULL; } dfXMax = adfGeoTransform[0] + adfGeoTransform[1] * nXSize; dfYMin = adfGeoTransform[3] + adfGeoTransform[5] * nYSize; /* -------------------------------------------------------------------- */ /* Create base file. */ /* -------------------------------------------------------------------- */ int cdfid, err; err = nc_create (pszFilename, NC_CLOBBER,&cdfid); if( err != NC_NOERR ) { CPLError( CE_Failure, CPLE_AppDefined, "nc_create(%s): %s", pszFilename, nc_strerror( err ) ); return NULL; } /* -------------------------------------------------------------------- */ /* Define the dimensions and so forth. */ /* -------------------------------------------------------------------- */ int side_dim, xysize_dim, dims[1]; int x_range_id, y_range_id, z_range_id, inc_id, nm_id, z_id; nc_def_dim(cdfid, "side", 2, &side_dim); nc_def_dim(cdfid, "xysize", (int) (nXSize * nYSize), &xysize_dim); dims[0] = side_dim; nc_def_var (cdfid, "x_range", NC_DOUBLE, 1, dims, &x_range_id); nc_def_var (cdfid, "y_range", NC_DOUBLE, 1, dims, &y_range_id); nc_def_var (cdfid, "z_range", NC_DOUBLE, 1, dims, &z_range_id); nc_def_var (cdfid, "spacing", NC_DOUBLE, 1, dims, &inc_id); nc_def_var (cdfid, "dimension", NC_LONG, 1, dims, &nm_id); dims[0] = xysize_dim; nc_def_var (cdfid, "z", nc_datatype, 1, dims, &z_id); /* -------------------------------------------------------------------- */ /* Assign attributes. */ /* -------------------------------------------------------------------- */ double default_scale = 1.0; double default_offset = 0.0; int default_node_offset = 1; // pixel is area nc_put_att_text (cdfid, x_range_id, "units", 7, "meters"); nc_put_att_text (cdfid, y_range_id, "units", 7, "meters"); nc_put_att_text (cdfid, z_range_id, "units", 7, "meters"); nc_put_att_double (cdfid, z_id, "scale_factor", NC_DOUBLE, 1, &default_scale ); nc_put_att_double (cdfid, z_id, "add_offset", NC_DOUBLE, 1, &default_offset ); nc_put_att_int (cdfid, z_id, "node_offset", NC_LONG, 1, &default_node_offset ); nc_put_att_text (cdfid, NC_GLOBAL, "title", 1, ""); nc_put_att_text (cdfid, NC_GLOBAL, "source", 1, ""); /* leave define mode */ nc_enddef (cdfid); /* -------------------------------------------------------------------- */ /* Get raster min/max. */ /* -------------------------------------------------------------------- */ double adfMinMax[2]; GDALComputeRasterMinMax( (GDALRasterBandH) poBand, FALSE, adfMinMax ); /* -------------------------------------------------------------------- */ /* Set range variables. */ /* -------------------------------------------------------------------- */ size_t start[2], edge[2]; double dummy[2]; int nm[2]; start[0] = 0; edge[0] = 2; dummy[0] = adfGeoTransform[0]; dummy[1] = dfXMax; nc_put_vara_double(cdfid, x_range_id, start, edge, dummy); dummy[0] = dfYMin; dummy[1] = adfGeoTransform[3]; nc_put_vara_double(cdfid, y_range_id, start, edge, dummy); dummy[0] = adfGeoTransform[1]; dummy[1] = -adfGeoTransform[5]; nc_put_vara_double(cdfid, inc_id, start, edge, dummy); nm[0] = nXSize; nm[1] = nYSize; nc_put_vara_int(cdfid, nm_id, start, edge, nm); nc_put_vara_double(cdfid, z_range_id, start, edge, adfMinMax); /* -------------------------------------------------------------------- */ /* Write out the image one scanline at a time. */ /* -------------------------------------------------------------------- */ double *padfData; int iLine; padfData = (double *) CPLMalloc( sizeof(double) * nXSize ); edge[0] = nXSize; for( iLine = 0; iLine < nYSize; iLine++ ) { start[0] = iLine * nXSize; poBand->RasterIO( GF_Read, 0, iLine, nXSize, 1, padfData, nXSize, 1, GDT_Float64, 0, 0, NULL ); err = nc_put_vara_double( cdfid, z_id, start, edge, padfData ); if( err != NC_NOERR ) { CPLError( CE_Failure, CPLE_AppDefined, "nc_put_vara_double(%s): %s", pszFilename, nc_strerror( err ) ); nc_close (cdfid); return( NULL ); } } CPLFree( padfData ); /* -------------------------------------------------------------------- */ /* Close file, and reopen. */ /* -------------------------------------------------------------------- */ nc_close (cdfid); /* -------------------------------------------------------------------- */ /* Re-open dataset, and copy any auxiliary pam information. */ /* -------------------------------------------------------------------- */ GDALPamDataset *poDS = (GDALPamDataset *) GDALOpen( pszFilename, GA_ReadOnly ); if( poDS ) poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT ); return poDS; }
GDALDataset *BTDataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, CPL_UNUSED char ** papszOptions ) { /* -------------------------------------------------------------------- */ /* Verify input options. */ /* -------------------------------------------------------------------- */ if( eType != GDT_Int16 && eType != GDT_Int32 && eType != GDT_Float32 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create .bt dataset with an illegal " "data type (%s), only Int16, Int32 and Float32 supported.", GDALGetDataTypeName(eType) ); return NULL; } if( nBands != 1 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create .bt dataset with %d bands, only 1 supported", nBands ); return NULL; } /* -------------------------------------------------------------------- */ /* Try to create the file. */ /* -------------------------------------------------------------------- */ VSILFILE *fp = VSIFOpenL( pszFilename, "wb" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed.", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Setup base header. */ /* -------------------------------------------------------------------- */ unsigned char abyHeader[256] = {}; memcpy( abyHeader, "binterr1.3", 10 ); GInt32 nTemp = CPL_LSBWORD32( nXSize ); memcpy( abyHeader+10, &nTemp, 4 ); nTemp = CPL_LSBWORD32( nYSize ); memcpy( abyHeader+14, &nTemp, 4 ); GInt16 nShortTemp = static_cast<GInt16>( CPL_LSBWORD16( (GInt16)(GDALGetDataTypeSize( eType ) / 8 )) ); memcpy( abyHeader + 18, &nShortTemp, 2 ); if( eType == GDT_Float32 ) abyHeader[20] = 1; else abyHeader[20] = 0; nShortTemp = CPL_LSBWORD16( 1 ); /* meters */ memcpy( abyHeader + 22, &nShortTemp, 2 ); nShortTemp = CPL_LSBWORD16( 0 ); /* not utm */ memcpy( abyHeader + 24, &nShortTemp, 2 ); nShortTemp = CPL_LSBWORD16( -2 ); /* datum unknown */ memcpy( abyHeader + 26, &nShortTemp, 2 ); /* -------------------------------------------------------------------- */ /* Set dummy extents. */ /* -------------------------------------------------------------------- */ double dfLeft = 0.0; double dfRight = nXSize; double dfTop = nYSize; double dfBottom = 0.0; memcpy( abyHeader + 28, &dfLeft, 8 ); memcpy( abyHeader + 36, &dfRight, 8 ); memcpy( abyHeader + 44, &dfBottom, 8 ); memcpy( abyHeader + 52, &dfTop, 8 ); CPL_LSBPTR64( abyHeader + 28 ); CPL_LSBPTR64( abyHeader + 36 ); CPL_LSBPTR64( abyHeader + 44 ); CPL_LSBPTR64( abyHeader + 52 ); /* -------------------------------------------------------------------- */ /* Set dummy scale. */ /* -------------------------------------------------------------------- */ float fScale = 1.0; memcpy( abyHeader + 62, &fScale, 4 ); CPL_LSBPTR32( abyHeader + 62 ); /* -------------------------------------------------------------------- */ /* Write to disk. */ /* -------------------------------------------------------------------- */ if( VSIFWriteL( (void *) abyHeader, 256, 1, fp ) != 1 || VSIFSeekL( fp, (GDALGetDataTypeSize(eType)/8) * nXSize * (vsi_l_offset)nYSize - 1, SEEK_CUR ) != 0 || VSIFWriteL( abyHeader+255, 1, 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to extent file to its full size, out of disk space?" ); CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); VSIUnlink( pszFilename ); return NULL; } if( VSIFCloseL( fp ) != 0 ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to extent file to its full size, out of disk space?" ); VSIUnlink( pszFilename ); return NULL; } return (GDALDataset *) GDALOpen( pszFilename, GA_Update ); }
void generateTexture(string fname, GLuint& tex, int bandnum) { if(bandnum <= 0 ) { bandnum = 1; } GDALDataset *poDataset; GDALAllRegister(); poDataset= (GDALDataset*) GDALOpen(fname.c_str(),GA_ReadOnly); if(poDataset == NULL) { cout << "OUCH!" << endl; //exit(0); return; } cout << "Data size: " << GDALGetRasterXSize(poDataset) << " " << GDALGetRasterYSize(poDataset) << endl; GDALRasterBand *poBand; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; double adfMinMax[2]; int bands = poDataset->GetRasterCount(); bandnum = bandnum % bands + 1; if(bandnum > bands) { bandnum = 1; } poBand = poDataset->GetRasterBand( bandnum ); poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName( poBand->GetColorInterpretation()) ); float max = adfMinMax[0] = poBand->GetMinimum( &bGotMin ); float min = adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); int width = poBand->GetXSize(); int height = poBand->GetYSize(); float *pafScanline; std::cout << "Before allocation" << adfMinMax[0] << " " << adfMinMax[1] << endl; min = adfMinMax[0]; max = adfMinMax[1]; int dsize = 256; pafScanline = (float *) CPLMalloc(sizeof(float)*512*512); vector<vector<float>> out = vector<vector<float>>(height,vector<float> (width,0)); //vector<vector<unsigned char>> texs = vector<vector<unsigned char>>(height,vector<unsigned char> (width,0)); unsigned char texs[512*512]; poBand->RasterIO(GF_Read,0,0,width,height,pafScanline,512,512,GDT_Float32,0,0); float no = poBand->GetNoDataValue(); cout << "After allocation" << endl; for(int i = 0; i < 512; i++) { for(int j = 0; j < 512; j++) { //cout << i << j << endl << pafS; if(pafScanline[i*width+j] != no) { // set tex val texs[i*512+j] = (unsigned char)(255*((pafScanline[i*512+j] - min)/(max-min))); //if((int)texs[i*width] < 0) //cout << (int)texs[i*512 +j] << " " << pafScanline[i*512+j] << " " << no << " " << fname << " " << min << " " << max << endl; } else { // Set zero val texs[i*512+j] = 0; //cout << (int)texs[i*512 +j] << fname << endl; } //texs[i*512+j] = 255; //ut[i][j] = pafScanline[i*width+j]; } } CPLFree(pafScanline); //exit(0); // Create a texture glGenTextures(1,&tex); glBindTexture(GL_TEXTURE_2D,tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 512,512, 0, GL_RED, GL_UNSIGNED_BYTE,texs); GDALClose( (GDALDatasetH) poDataset); return; }
static int ProxyMain( int argc, char ** argv ) { // GDALDatasetH hDataset, hOutDS; // int i; // int nRasterXSize, nRasterYSize; // const char *pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff"; // GDALDriverH hDriver; // int *panBandList = NULL; /* negative value of panBandList[i] means mask band of ABS(panBandList[i]) */ // int nBandCount = 0, bDefBands = TRUE; // double adfGeoTransform[6]; // GDALDataType eOutputType = GDT_Unknown; // int nOXSize = 0, nOYSize = 0; // char *pszOXSize=NULL, *pszOYSize=NULL; // char **papszCreateOptions = NULL; // int anSrcWin[4], bStrict = FALSE; // const char *pszProjection; // int bScale = FALSE, bHaveScaleSrc = FALSE, bUnscale=FALSE; // double dfScaleSrcMin=0.0, dfScaleSrcMax=255.0; // double dfScaleDstMin=0.0, dfScaleDstMax=255.0; // double dfULX, dfULY, dfLRX, dfLRY; // char **papszMetadataOptions = NULL; // char *pszOutputSRS = NULL; // int bQuiet = FALSE, bGotBounds = FALSE; // GDALProgressFunc pfnProgress = GDALTermProgress; // int nGCPCount = 0; // GDAL_GCP *pasGCPs = NULL; // int iSrcFileArg = -1, iDstFileArg = -1; // int bCopySubDatasets = FALSE; // double adfULLR[4] = { 0,0,0,0 }; // int bSetNoData = FALSE; // int bUnsetNoData = FALSE; // double dfNoDataReal = 0.0; // int nRGBExpand = 0; // int bParsedMaskArgument = FALSE; // int eMaskMode = MASK_AUTO; // int nMaskBand = 0; /* negative value means mask band of ABS(nMaskBand) */ // int bStats = FALSE, bApproxStats = FALSE; // GDALDatasetH hDataset, hOutDS; GDALDataset *hDataset = NULL; GDALDataset *hOutDS = NULL; int i; int nRasterXSize, nRasterYSize; const char *pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff"; // GDALDriverH hDriver; GDALDriver *hDriver; GDALDataType eOutputType = GDT_Unknown; char **papszCreateOptions = NULL; int bStrict = FALSE; int bQuiet = FALSE; GDALProgressFunc pfnProgress = GDALTermProgress; int iSrcFileArg = -1, iDstFileArg = -1; int bSetNoData = FALSE; int bUnsetNoData = FALSE; double dfNoDataReal = 0.0; GDALRasterBand *inBand = NULL; GDALRasterBand *outBand = NULL; GByte *srcBuffer; double adfGeoTransform[6]; int nRasterCount; int bReplaceIds = FALSE; const char *pszReplaceFilename = NULL; const char *pszReplaceFieldFrom = NULL; const char *pszReplaceFieldTo = NULL; std::map<GByte,GByte> mReplaceTable; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(argv[0])) exit(1); /* Must process GDAL_SKIP before GDALAllRegister(), but we can't call */ /* GDALGeneralCmdLineProcessor before it needs the drivers to be registered */ /* for the --format or --formats options */ for( i = 1; i < argc; i++ ) { if( EQUAL(argv[i],"--config") && i + 2 < argc && EQUAL(argv[i + 1], "GDAL_SKIP") ) { CPLSetConfigOption( argv[i+1], argv[i+2] ); i += 2; } } /* -------------------------------------------------------------------- */ /* Register standard GDAL drivers, and process generic GDAL */ /* command options. */ /* -------------------------------------------------------------------- */ GDALAllRegister(); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Handle command line arguments. */ /* -------------------------------------------------------------------- */ for( i = 1; i < argc; i++ ) { if( EQUAL(argv[i],"-of") && i < argc-1 ) pszFormat = argv[++i]; else if( EQUAL(argv[i],"-q") || EQUAL(argv[i],"-quiet") ) { bQuiet = TRUE; pfnProgress = GDALDummyProgress; } else if( EQUAL(argv[i],"-ot") && i < argc-1 ) { int iType; for( iType = 1; iType < GDT_TypeCount; iType++ ) { if( GDALGetDataTypeName((GDALDataType)iType) != NULL && EQUAL(GDALGetDataTypeName((GDALDataType)iType), argv[i+1]) ) { eOutputType = (GDALDataType) iType; } } if( eOutputType == GDT_Unknown ) { printf( "Unknown output pixel type: %s\n", argv[i+1] ); Usage(); GDALDestroyDriverManager(); exit( 2 ); } i++; } else if( EQUAL(argv[i],"-not_strict") ) bStrict = FALSE; else if( EQUAL(argv[i],"-strict") ) bStrict = TRUE; else if( EQUAL(argv[i],"-a_nodata") && i < argc - 1 ) { if (EQUAL(argv[i+1], "none")) { bUnsetNoData = TRUE; } else { bSetNoData = TRUE; dfNoDataReal = CPLAtofM(argv[i+1]); } i += 1; } else if( EQUAL(argv[i],"-co") && i < argc-1 ) { papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] ); } else if( EQUAL(argv[i],"-replace_ids") && i < argc-3 ) { bReplaceIds = TRUE; pszReplaceFilename = (argv[++i]); pszReplaceFieldFrom = (argv[++i]); pszReplaceFieldTo = (argv[++i]); } else if( argv[i][0] == '-' ) { printf( "Option %s incomplete, or not recognised.\n\n", argv[i] ); Usage(); GDALDestroyDriverManager(); exit( 2 ); } else if( pszSource == NULL ) { iSrcFileArg = i; pszSource = argv[i]; } else if( pszDest == NULL ) { pszDest = argv[i]; iDstFileArg = i; } else { printf( "Too many command options.\n\n" ); Usage(); GDALDestroyDriverManager(); exit( 2 ); } } if( pszDest == NULL ) { Usage(); GDALDestroyDriverManager(); exit( 10 ); } if ( strcmp(pszSource, pszDest) == 0) { fprintf(stderr, "Source and destination datasets must be different.\n"); GDALDestroyDriverManager(); exit( 1 ); } if( bReplaceIds ) { if ( ! pszReplaceFilename | ! pszReplaceFieldFrom | ! pszReplaceFieldTo ) Usage(); // FILE * ifile; // if ( (ifile = fopen(pszReplaceFilename, "r")) == NULL ) // { // fprintf( stderr, "Replace file %s cannot be read!\n\n", pszReplaceFilename ); // Usage(); // } // else // fclose( ifile ); mReplaceTable = InitReplaceTable(pszReplaceFilename, pszReplaceFieldFrom, pszReplaceFieldTo); printf("TMP ET size: %d\n",(int)mReplaceTable.size()); } /* -------------------------------------------------------------------- */ /* Attempt to open source file. */ /* -------------------------------------------------------------------- */ // hDataset = GDALOpenShared( pszSource, GA_ReadOnly ); hDataset = (GDALDataset *) GDALOpen(pszSource, GA_ReadOnly ); if( hDataset == NULL ) { fprintf( stderr, "GDALOpen failed - %d\n%s\n", CPLGetLastErrorNo(), CPLGetLastErrorMsg() ); GDALDestroyDriverManager(); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Collect some information from the source file. */ /* -------------------------------------------------------------------- */ // nRasterXSize = GDALGetRasterXSize( hDataset ); // nRasterYSize = GDALGetRasterYSize( hDataset ); nRasterXSize = hDataset->GetRasterXSize(); nRasterYSize = hDataset->GetRasterYSize(); if( !bQuiet ) printf( "Input file size is %d, %d\n", nRasterXSize, nRasterYSize ); /* -------------------------------------------------------------------- */ /* Find the output driver. */ /* -------------------------------------------------------------------- */ hDriver = GetGDALDriverManager()->GetDriverByName( pszFormat ); if( hDriver == NULL ) { int iDr; printf( "Output driver `%s' not recognised.\n", pszFormat ); printf( "The following format drivers are configured and support output:\n" ); for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ ) { GDALDriverH hDriver = GDALGetDriver(iDr); if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY, NULL ) != NULL ) { printf( " %s: %s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver ) ); } } printf( "\n" ); Usage(); GDALClose( (GDALDatasetH) hDataset ); GDALDestroyDriverManager(); CSLDestroy( argv ); CSLDestroy( papszCreateOptions ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Create Dataset and copy info */ /* -------------------------------------------------------------------- */ nRasterCount = hDataset->GetRasterCount(); printf("creating\n"); hOutDS = hDriver->Create( pszDest, nRasterXSize, nRasterYSize, nRasterCount, GDT_Byte, papszCreateOptions); printf("created\n"); if( hOutDS != NULL ) { hDataset->GetGeoTransform( adfGeoTransform); hOutDS->SetGeoTransform( adfGeoTransform ); hOutDS->SetProjection( hDataset->GetProjectionRef() ); /* ==================================================================== */ /* Process all bands. */ /* ==================================================================== */ // if (0) for( i = 1; i < nRasterCount+1; i++ ) { inBand = hDataset->GetRasterBand( i ); // hOutDS->AddBand(GDT_Byte); outBand = hOutDS->GetRasterBand( i ); CopyBandInfo( inBand, outBand, 0, 1, 1 ); nRasterXSize = inBand->GetXSize( ); nRasterYSize = inBand->GetYSize( ); GByte old_value, new_value; // char tmp_value[255]; // const char *tmp_value2; std::map<GByte,GByte>::iterator it; //tmp int nXBlocks, nYBlocks, nXBlockSize, nYBlockSize; int iXBlock, iYBlock; inBand->GetBlockSize( &nXBlockSize, &nYBlockSize ); // nXBlockSize = nXBlockSize / 4; // nYBlockSize = nYBlockSize / 4; nXBlocks = (inBand->GetXSize() + nXBlockSize - 1) / nXBlockSize; nYBlocks = (inBand->GetYSize() + nYBlockSize - 1) / nYBlockSize; printf("blocks: %d %d %d %d\n",nXBlockSize,nYBlockSize,nXBlocks,nYBlocks); printf("TMP ET creating raster %d x %d\n",nRasterXSize, nRasterYSize); // srcBuffer = new GByte[nRasterXSize * nRasterYSize]; // printf("reading\n"); // inBand->RasterIO( GF_Read, 0, 0, nRasterXSize, nRasterYSize, // srcBuffer, nRasterXSize, nRasterYSize, GDT_Byte, // 0, 0 ); // srcBuffer = (GByte *) CPLMalloc(sizeof(GByte)*nRasterXSize * nRasterYSize); srcBuffer = (GByte *) CPLMalloc(nXBlockSize * nYBlockSize); for( iYBlock = 0; iYBlock < nYBlocks; iYBlock++ ) { // if(iYBlock%1000 == 0) // printf("iXBlock: %d iYBlock: %d\n",iXBlock,iYBlock); if(iYBlock%1000 == 0) printf("iYBlock: %d / %d\n",iYBlock,nYBlocks); for( iXBlock = 0; iXBlock < nXBlocks; iXBlock++ ) { int nXValid, nYValid; // inBand->ReadBlock( iXBlock, iYBlock, srcBuffer ); inBand->RasterIO( GF_Read, iXBlock, iYBlock, nXBlockSize, nYBlockSize, srcBuffer, nXBlockSize, nYBlockSize, GDT_Byte, 0, 0 ); // Compute the portion of the block that is valid // for partial edge blocks. if( (iXBlock+1) * nXBlockSize > inBand->GetXSize() ) nXValid = inBand->GetXSize() - iXBlock * nXBlockSize; else nXValid = nXBlockSize; if( (iYBlock+1) * nYBlockSize > inBand->GetYSize() ) nYValid = inBand->GetYSize() - iYBlock * nYBlockSize; else nYValid = nYBlockSize; // printf("iXBlock: %d iYBlock: %d read, nXValid: %d nYValid: %d\n",iXBlock,iYBlock,nXValid, nYValid); // if(0) if ( pszReplaceFilename ) { for( int iY = 0; iY < nYValid; iY++ ) { for( int iX = 0; iX < nXValid; iX++ ) { // panHistogram[pabyData[iX + iY * nXBlockSize]] += 1; old_value = new_value = srcBuffer[iX + iY * nXBlockSize]; // sprintf(tmp_value,"%d",old_value); it = mReplaceTable.find(old_value); if ( it != mReplaceTable.end() ) new_value = it->second; if ( old_value != new_value ) { srcBuffer[iX + iY * nXBlockSize] = new_value; // printf("old_value %d new_value %d final %d\n",old_value,new_value, srcBuffer[iX + iY * nXBlockSize]); } // tmp_value2 = CSVGetField( pszReplaceFilename,pszReplaceFieldFrom, // tmp_value, CC_Integer, pszReplaceFieldTo); // if( tmp_value2 != NULL ) // { // new_value = atoi(tmp_value2); // } // new_value = old_value +1; // } } } // printf("writing\n"); // outBand->WriteBlock( iXBlock, iYBlock, srcBuffer ); outBand->RasterIO( GF_Write, iXBlock, iYBlock, nXBlockSize, nYBlockSize, srcBuffer, nXBlockSize, nYBlockSize, GDT_Byte, 0, 0 ); // printf("wrote\n"); } } CPLFree(srcBuffer); printf("read\n"); printf("mod\n"); // if ( pszReplaceFilename ) // { // GByte old_value, new_value; // // char tmp_value[255]; // // const char *tmp_value2; // std::map<GByte,GByte>::iterator it; // for ( int j=0; j<nRasterXSize*nRasterYSize; j++ ) // { // old_value = new_value = srcBuffer[j]; // // sprintf(tmp_value,"%d",old_value); // it = mReplaceTable.find(old_value); // if ( it != mReplaceTable.end() ) new_value = it->second; // // tmp_value2 = CSVGetField( pszReplaceFilename,pszReplaceFieldFrom, // // tmp_value, CC_Integer, pszReplaceFieldTo); // // if( tmp_value2 != NULL ) // // { // // new_value = atoi(tmp_value2); // // } // // new_value = old_value +1; // if ( old_value != new_value ) srcBuffer[j] = new_value; // // printf("old_value %d new_value %d final %d\n",old_value,new_value, srcBuffer[j]); // } // printf("writing\n"); // outBand->RasterIO( GF_Write, 0, 0, nRasterXSize, nRasterYSize, // srcBuffer, nRasterXSize, nRasterYSize, GDT_Byte, // 0, 0 ); // printf("wrote\n"); // delete [] srcBuffer; // } } } if( hOutDS != NULL ) GDALClose( (GDALDatasetH) hOutDS ); if( hDataset != NULL ) GDALClose( (GDALDatasetH) hDataset ); GDALDumpOpenDatasets( stderr ); // GDALDestroyDriverManager(); CSLDestroy( argv ); CSLDestroy( papszCreateOptions ); return hOutDS == NULL; }
void readFrames( int argc, char* argv[] ) { pfs::DOMIO pfsio; bool verbose = false; // Parse command line parameters static struct option cmdLineOptions[] = { { "help", no_argument, NULL, 'h' }, { "verbose", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char optstring[] = "hv"; pfs::FrameFileIterator it( argc, argv, "rb", NULL, NULL, optstring, cmdLineOptions ); int optionIndex = 0; while( 1 ) { int c = getopt_long (argc, argv, optstring, cmdLineOptions, &optionIndex); if( c == -1 ) break; switch( c ) { case 'h': printHelp(); throw QuietException(); case 'v': verbose = true; break; case '?': throw QuietException(); case ':': throw QuietException(); } } GDALAllRegister(); GDALDataset *poDataset; GDALRasterBand *poBand; double adfGeoTransform[6]; size_t nBlockXSize, nBlockYSize, nBands; int bGotMin, bGotMax; double adfMinMax[2]; float *pafScanline; while( true ) { pfs::FrameFile ff = it.getNextFrameFile(); if( ff.fh == NULL ) break; // No more frames it.closeFrameFile( ff ); VERBOSE_STR << "reading file '" << ff.fileName << "'" << std::endl; if( !( poDataset = (GDALDataset *) GDALOpen( ff.fileName, GA_ReadOnly ) ) ) { std::cerr << "input does not seem to be in a format supported by GDAL" << std::endl; throw QuietException(); } VERBOSE_STR << "GDAL driver: " << poDataset->GetDriver()->GetDescription() << " / " << poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) << std::endl; nBlockXSize = poDataset->GetRasterXSize(); nBlockYSize = poDataset->GetRasterYSize(); nBands = poDataset->GetRasterCount(); VERBOSE_STR << "Data size " << nBlockXSize << "x" << nBlockYSize << "x" << nBands << std::endl; if( poDataset->GetProjectionRef() ) { VERBOSE_STR << "Projection " << poDataset->GetProjectionRef() << std::endl; } if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { VERBOSE_STR << "Origin = (" << adfGeoTransform[0] << ", " << adfGeoTransform[3] << ")" << std::endl; VERBOSE_STR << "Pixel Size = (" << adfGeoTransform[1] << ", " << adfGeoTransform[5] << ")" << std::endl; } if( nBlockXSize==0 || nBlockYSize==0 || ( SIZE_MAX / nBlockYSize < nBlockXSize ) || ( SIZE_MAX / (nBlockXSize * nBlockYSize ) < 4 ) ) { std::cerr << "input data has invalid size" << std::endl; throw QuietException(); } if( !(pafScanline = (float *) CPLMalloc( sizeof(float) * nBlockXSize ) ) ) { std::cerr << "not enough memory" << std::endl; throw QuietException(); } pfs::Frame *frame = pfsio.createFrame( nBlockXSize, nBlockYSize ); pfs::Channel *C[nBands]; char channel_name[32]; frame->getTags()->setString( "X-GDAL_DRIVER_SHORTNAME", poDataset->GetDriver()->GetDescription() ); frame->getTags()->setString( "X-GDAL_DRIVER_LONGNAME", poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); frame->getTags()->setString( "X-PROJECTION", poDataset->GetProjectionRef() ); if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { frame->getTags()->setString( "X-ORIGIN_X", stringify(adfGeoTransform[0]).c_str() ); frame->getTags()->setString( "X-ORIGIN_Y", stringify(adfGeoTransform[3]).c_str() ); frame->getTags()->setString( "X-PIXEL_WIDTH", stringify(adfGeoTransform[1]).c_str() ); frame->getTags()->setString( "X-PIXEL_HEIGHT", stringify(adfGeoTransform[5]).c_str() ); } for ( size_t band = 1; band <= nBands; band++) { size_t nBandXSize, nBandYSize; VERBOSE_STR << "Band " << band << ": " << std::endl; snprintf( channel_name, 32, "X-GDAL%zu", band ); C[band - 1] = frame->createChannel( channel_name ); poBand = poDataset->GetRasterBand( band ); nBandXSize = poBand->GetXSize(); nBandYSize = poBand->GetYSize(); VERBOSE_STR << " " << nBandXSize << "x" << nBandYSize << std::endl; if( nBandXSize != (int)nBlockXSize || nBandYSize != (int)nBlockYSize ) { std::cerr << "data in band " << band << " has different size" << std::endl; throw QuietException(); } VERBOSE_STR << " Type " << GDALGetDataTypeName( poBand->GetRasterDataType() ) << ", " << "Color Interpretation " << GDALGetColorInterpretationName( poBand->GetColorInterpretation() ) << std::endl; adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) { GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); } VERBOSE_STR << " Min " << adfMinMax[0] << ", Max " << adfMinMax[1] << std::endl; C[band - 1]->getTags()->setString( "X-TYPE", GDALGetDataTypeName( poBand->GetRasterDataType() ) ); C[band - 1]->getTags()->setString( "X-COLOR_INTERPRETATION", GDALGetColorInterpretationName( poBand->GetColorInterpretation() ) ); C[band - 1]->getTags()->setString( "X-MIN", stringify(adfMinMax[0]).c_str() ); C[band - 1]->getTags()->setString( "X-MAX", stringify(adfMinMax[1]).c_str() ); for( size_t y = 0; y < nBlockYSize; y++ ) { if( poBand->RasterIO( GF_Read, 0, y, nBlockXSize, 1, pafScanline, nBlockXSize, 1, GDT_Float32, 0, 0) != CE_None ) { std::cerr << "input error" << std::endl; throw QuietException(); } memcpy( C[band - 1]->getRawData() + y * nBlockXSize, pafScanline, nBlockXSize * sizeof(float) ); } } CPLFree( pafScanline ); GDALClose( poDataset ); const char *fileNameTag = strcmp( "-", ff.fileName )==0 ? "stdin" : ff.fileName; frame->getTags()->setString( "FILE_NAME", fileNameTag ); pfsio.writeFrame( frame, stdout ); pfsio.freeFrame( frame ); } }
/* TODO: check if georeference is the same as for BLX files, WGS84 */ static GDALDataset * BLXCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ) { // -------------------------------------------------------------------- // Some rudimentary checks // -------------------------------------------------------------------- const int nBands = poSrcDS->GetRasterCount(); if( nBands != 1 ) { CPLError( CE_Failure, CPLE_NotSupported, "BLX driver doesn't support %d bands. Must be 1 (grey) ", nBands ); return NULL; } if( poSrcDS->GetRasterBand(1)->GetRasterDataType() != GDT_Int16 && bStrict ) { CPLError( CE_Failure, CPLE_NotSupported, "BLX driver doesn't support data type %s. " "Only 16 bit byte bands supported.\n", GDALGetDataTypeName( poSrcDS->GetRasterBand(1)->GetRasterDataType()) ); return NULL; } const int nXSize = poSrcDS->GetRasterXSize(); const int nYSize = poSrcDS->GetRasterYSize(); if( (nXSize % 128 != 0) || (nYSize % 128 != 0) ) { CPLError( CE_Failure, CPLE_NotSupported, "BLX driver doesn't support dimensions that are not a multiple of 128.\n"); return NULL; } // -------------------------------------------------------------------- // What options has the user selected? // -------------------------------------------------------------------- int zscale = 1; if( CSLFetchNameValue(papszOptions,"ZSCALE") != NULL ) { zscale = atoi(CSLFetchNameValue(papszOptions,"ZSCALE")); if( zscale < 1 ) { CPLError( CE_Failure, CPLE_IllegalArg, "ZSCALE=%s is not a legal value in the range >= 1.", CSLFetchNameValue(papszOptions,"ZSCALE") ); return NULL; } } int fillundef = 1; if( CSLFetchNameValue(papszOptions,"FILLUNDEF") != NULL && EQUAL(CSLFetchNameValue(papszOptions,"FILLUNDEF"),"NO") ) fillundef = 0; int fillundefval = 0; if( CSLFetchNameValue(papszOptions,"FILLUNDEFVAL") != NULL ) { fillundefval = atoi(CSLFetchNameValue(papszOptions,"FILLUNDEFVAL")); if( (fillundefval < -32768) || (fillundefval > 32767) ) { CPLError( CE_Failure, CPLE_IllegalArg, "FILLUNDEFVAL=%s is not a legal value in the range -32768, 32767.", CSLFetchNameValue(papszOptions,"FILLUNDEFVAL") ); return NULL; } } int endian = LITTLEENDIAN; if( CSLFetchNameValue(papszOptions,"BIGENDIAN") != NULL && !EQUAL(CSLFetchNameValue(papszOptions,"BIGENDIAN"),"NO") ) endian = BIGENDIAN; // -------------------------------------------------------------------- // Create the dataset. // -------------------------------------------------------------------- // Create a BLX context blxcontext_t *ctx = blx_create_context(); // Setup BLX parameters ctx->cell_rows = nYSize / ctx->cell_ysize; ctx->cell_cols = nXSize / ctx->cell_xsize; ctx->zscale = zscale; ctx->fillundef = fillundef; ctx->fillundefval = fillundefval; ctx->endian = endian; if(blxopen(ctx, pszFilename, "wb")) { CPLError( CE_Failure, CPLE_OpenFailed, "Unable to create blx file %s.\n", pszFilename ); blx_free_context(ctx); return NULL; } // -------------------------------------------------------------------- // Loop over image, copying image data. // -------------------------------------------------------------------- GInt16 *pabyTile = (GInt16 *) VSI_MALLOC_VERBOSE( sizeof(GInt16)*ctx->cell_xsize*ctx->cell_ysize ); if (pabyTile == NULL) { blxclose(ctx); blx_free_context(ctx); return NULL; } CPLErr eErr=CE_None; if( !pfnProgress( 0.0, NULL, pProgressData ) ) eErr = CE_Failure; for(int i=0; (i < ctx->cell_rows) && (eErr == CE_None); i++) for(int j=0; j < ctx->cell_cols; j++) { blxdata *celldata; GDALRasterBand * poBand = poSrcDS->GetRasterBand( 1 ); eErr = poBand->RasterIO( GF_Read, j*ctx->cell_xsize, i*ctx->cell_ysize, ctx->cell_xsize, ctx->cell_ysize, pabyTile, ctx->cell_xsize, ctx->cell_ysize, GDT_Int16, 0, 0, NULL ); if(eErr >= CE_Failure) break; celldata = pabyTile; if (blx_writecell(ctx, celldata, i, j) != 0) { eErr = CE_Failure; break; } if ( ! pfnProgress( 1.0 * (i * ctx->cell_cols + j) / (ctx->cell_rows * ctx->cell_cols), NULL, pProgressData )) { eErr = CE_Failure; break; } } pfnProgress( 1.0, NULL, pProgressData ); CPLFree( pabyTile ); double adfGeoTransform[6]; if( poSrcDS->GetGeoTransform( adfGeoTransform ) == CE_None ) { ctx->lon = adfGeoTransform[0]; ctx->lat = adfGeoTransform[3]; ctx->pixelsize_lon = adfGeoTransform[1]; ctx->pixelsize_lat = adfGeoTransform[5]; } blxclose(ctx); blx_free_context(ctx); if (eErr == CE_None) return reinterpret_cast<GDALDataset *>( GDALOpen( pszFilename, GA_ReadOnly ) ); return NULL; }
std::tuple<boost::shared_ptr<Map_Matrix<DataFormat> >, std::string, GeoTransform> read_in_map(fs::path file_path, GDALDataType data_type, const bool doCategorise) throw(std::runtime_error) { std::string projection; GeoTransform transformation; GDALDriver driver; //Check that the file name is valid if (!(fs::is_regular_file(file_path))) { throw std::runtime_error("Input file is not a regular file"); } // Get GDAL to open the file - code is based on the tutorial at http://www.gdal.org/gdal_tutorial.html GDALDataset *poDataset; GDALAllRegister(); //This registers all availble raster file formats for use with this utility. How neat is that. We can input any GDAL supported rater file format. //Open the Raster by calling GDALOpen. http://www.gdal.org/gdal_8h.html#a6836f0f810396c5e45622c8ef94624d4 //char pszfilename[] = file_path.c_str(); //Set this to the file name, as GDALOpen requires the standard C char pointer as function parameter. poDataset = (GDALDataset *) GDALOpen (file_path.string().c_str(), GA_ReadOnly); if (poDataset == NULL) { throw std::runtime_error("Unable to open file"); } // Print some general information about the raster double adfGeoTransform[6]; //An array of doubles that will be used to save information about the raster - where the origin is, what the raster pizel size is. printf( "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); printf( "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() ); if( poDataset->GetProjectionRef() != NULL ) { printf( "Projection is `%s'\n", poDataset->GetProjectionRef() ); projection = poDataset->GetProjectionRef(); } if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { printf( "Origin = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3] ); printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5] ); transformation.x_origin = adfGeoTransform[0]; transformation.pixel_width = adfGeoTransform[1]; transformation.x_line_space = adfGeoTransform[2]; transformation.y_origin = adfGeoTransform[3]; transformation.pixel_height = adfGeoTransform[4]; transformation.y_line_space = adfGeoTransform[5]; } /// Some raster file formats allow many layers of data (called a 'band', with each having the same pixel size and origin location and spatial extent). We will get the data for the first layer into a Boost Array. //Get the data from the first band, // TODO implement method with input to specify what band. GDALRasterBand *poBand; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; double adfMinMax[2]; poBand = poDataset->GetRasterBand( 1 ); poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName( poBand->GetColorInterpretation()) ); adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1] ); if( poBand->GetOverviewCount() > 0 ) printf( "Band has %d overviews.\n", poBand->GetOverviewCount() ); if( poBand->GetColorTable() != NULL ) printf( "Band has a color table with %d entries.\n", poBand->GetColorTable()->GetColorEntryCount() ); DataFormat * pafScanline; int nXSize = poBand->GetXSize(); int nYSize = poBand->GetYSize(); boost::shared_ptr<Map_Matrix<DataFormat> > in_map(new Map_Matrix<DataFormat>(nYSize, nXSize)); //get a c array of this size and read into this. //pafScanline = new DataFormat[nXSize]; //for (int i = 0; i < nYSize; i++) //rows //{ // poBand->RasterIO(GF_Read, 0, i, nXSize, 1, // pafScanline, nXSize, 1, data_type, // 0, 0); // for (int j = 0; j < nXSize; j++) //cols // { // in_map->Get(i, j) = pafScanline[j]; // } //} //get a c array of this size and read into this. pafScanline = new DataFormat[nXSize * nYSize]; //pafScanline = (float *) CPLMalloc(sizeof(float)*nXSize); poBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, pafScanline, nXSize, nYSize, data_type, 0, 0 ); //Copy into Map_Matrix. int pafIterator = 0; // Note: Map Matrixes indexes are in opposite order to C arrays. e.g. map matrix is indexed by (row, Col) which is (y, x) and c matrices are done by (x, y) which is (Col, Row) //for (int i = 0; i < nXSize; i++) //{ // for(int j = 0; j < nYSize; j++) // { // in_map->Get(j, i) = pafScanline[pafIterator]; // pafIterator++; // } //} for (int i = 0; i < nYSize; i++) //rows { for (int j = 0; j < nXSize; j++) //cols { in_map->Get(i, j) = pafScanline[pafIterator]; pafIterator++; } } //free the c array storage delete pafScanline; int pbsuccess; // can be used with get no data value in_map->SetNoDataValue(poBand->GetNoDataValue(&pbsuccess)); //This creates a list (map?) listing all the unique values contained in the raster. if (doCategorise) in_map->updateCategories(); //Close GDAL, freeing the memory GDAL is using GDALClose( (GDALDatasetH)poDataset); return (std::make_tuple(in_map, projection, transformation)); }
GDALDataset * GIFDataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS, int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ) { int nBands = poSrcDS->GetRasterCount(); int nXSize = poSrcDS->GetRasterXSize(); int nYSize = poSrcDS->GetRasterYSize(); int bInterlace = FALSE; /* -------------------------------------------------------------------- */ /* Check for interlaced option. */ /* -------------------------------------------------------------------- */ bInterlace = CSLFetchBoolean(papszOptions, "INTERLACING", FALSE); /* -------------------------------------------------------------------- */ /* Some some rudimentary checks */ /* -------------------------------------------------------------------- */ if( nBands != 1 ) { CPLError( CE_Failure, CPLE_NotSupported, "GIF driver only supports one band images.\n" ); return NULL; } if (nXSize > 65535 || nYSize > 65535) { CPLError( CE_Failure, CPLE_NotSupported, "GIF driver only supports datasets up to 65535x65535 size.\n" ); return NULL; } if( poSrcDS->GetRasterBand(1)->GetRasterDataType() != GDT_Byte && bStrict ) { CPLError( CE_Failure, CPLE_NotSupported, "GIF driver doesn't support data type %s. " "Only eight bit bands supported.\n", GDALGetDataTypeName( poSrcDS->GetRasterBand(1)->GetRasterDataType()) ); return NULL; } /* -------------------------------------------------------------------- */ /* Open the output file. */ /* -------------------------------------------------------------------- */ GifFileType *hGifFile; VSILFILE *fp; fp = VSIFOpenL( pszFilename, "wb" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to create %s:\n%s", pszFilename, VSIStrerror( errno ) ); return NULL; } #if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5 int nError; hGifFile = EGifOpen( fp, VSIGIFWriteFunc, &nError ); #else hGifFile = EGifOpen( fp, VSIGIFWriteFunc ); #endif if( hGifFile == NULL ) { VSIFCloseL( fp ); CPLError( CE_Failure, CPLE_OpenFailed, "EGifOpenFilename(%s) failed. Does file already exist?", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Prepare colortable. */ /* -------------------------------------------------------------------- */ GDALRasterBand *poBand = poSrcDS->GetRasterBand(1); ColorMapObject *psGifCT; int iColor; if( poBand->GetColorTable() == NULL ) { psGifCT = GifMakeMapObject( 256, NULL ); for( iColor = 0; iColor < 256; iColor++ ) { psGifCT->Colors[iColor].Red = (GifByteType) iColor; psGifCT->Colors[iColor].Green = (GifByteType) iColor; psGifCT->Colors[iColor].Blue = (GifByteType) iColor; } } else { GDALColorTable *poCT = poBand->GetColorTable(); int nFullCount = 1; while( nFullCount < poCT->GetColorEntryCount() ) nFullCount = nFullCount * 2; psGifCT = GifMakeMapObject( nFullCount, NULL ); for( iColor = 0; iColor < poCT->GetColorEntryCount(); iColor++ ) { GDALColorEntry sEntry; poCT->GetColorEntryAsRGB( iColor, &sEntry ); psGifCT->Colors[iColor].Red = (GifByteType) sEntry.c1; psGifCT->Colors[iColor].Green = (GifByteType) sEntry.c2; psGifCT->Colors[iColor].Blue = (GifByteType) sEntry.c3; } for( ; iColor < nFullCount; iColor++ ) { psGifCT->Colors[iColor].Red = 0; psGifCT->Colors[iColor].Green = 0; psGifCT->Colors[iColor].Blue = 0; } } /* -------------------------------------------------------------------- */ /* Setup parameters. */ /* -------------------------------------------------------------------- */ if (EGifPutScreenDesc(hGifFile, nXSize, nYSize, psGifCT->ColorCount, 255, psGifCT) == GIF_ERROR) { GifFreeMapObject(psGifCT); GDALPrintGifError(hGifFile, "Error writing gif file."); GIFAbstractDataset::myEGifCloseFile(hGifFile); VSIFCloseL( fp ); return NULL; } GifFreeMapObject(psGifCT); psGifCT = NULL; /* Support for transparency */ int bNoDataValue; double noDataValue = poBand->GetNoDataValue(&bNoDataValue); if (bNoDataValue && noDataValue >= 0 && noDataValue <= 255) { unsigned char extensionData[4]; extensionData[0] = 1; /* Transparent Color Flag */ extensionData[1] = 0; extensionData[2] = 0; extensionData[3] = (unsigned char)noDataValue; EGifPutExtension(hGifFile, 0xf9, 4, extensionData); } if (EGifPutImageDesc(hGifFile, 0, 0, nXSize, nYSize, bInterlace, NULL) == GIF_ERROR ) { GDALPrintGifError(hGifFile, "Error writing gif file."); GIFAbstractDataset::myEGifCloseFile(hGifFile); VSIFCloseL( fp ); return NULL; } /* -------------------------------------------------------------------- */ /* Loop over image, copying image data. */ /* -------------------------------------------------------------------- */ CPLErr eErr; GDALPamDataset *poDS; GByte *pabyScanline; pabyScanline = (GByte *) CPLMalloc( nXSize ); if( !pfnProgress( 0.0, NULL, pProgressData ) ) eErr = CE_Failure; if( !bInterlace ) { for( int iLine = 0; iLine < nYSize; iLine++ ) { eErr = poBand->RasterIO( GF_Read, 0, iLine, nXSize, 1, pabyScanline, nXSize, 1, GDT_Byte, nBands, nBands * nXSize ); if( eErr != CE_None || EGifPutLine( hGifFile, pabyScanline, nXSize ) == GIF_ERROR ) { CPLError( CE_Failure, CPLE_AppDefined, "Error writing gif file." ); goto error; } if( !pfnProgress( (iLine + 1) * 1.0 / nYSize, NULL, pProgressData ) ) { goto error; } } } else { int i, j; int nLinesRead = 0; int nLinesToRead = 0; for ( i = 0; i < 4; i++) { for (j = InterlacedOffset[i]; j < nYSize; j += InterlacedJumps[i]) { nLinesToRead ++; } } /* Need to perform 4 passes on the images: */ for ( i = 0; i < 4; i++) { for (j = InterlacedOffset[i]; j < nYSize; j += InterlacedJumps[i]) { eErr= poBand->RasterIO( GF_Read, 0, j, nXSize, 1, pabyScanline, nXSize, 1, GDT_Byte, 1, nXSize ); if (eErr != CE_None || EGifPutLine(hGifFile, pabyScanline, nXSize) == GIF_ERROR) { CPLError( CE_Failure, CPLE_AppDefined, "Error writing gif file." ); goto error; } nLinesRead ++; if( !pfnProgress( nLinesRead * 1.0 / nYSize, NULL, pProgressData ) ) { goto error; } } } } CPLFree( pabyScanline ); pabyScanline = NULL; /* -------------------------------------------------------------------- */ /* cleanup */ /* -------------------------------------------------------------------- */ if (GIFAbstractDataset::myEGifCloseFile(hGifFile) == GIF_ERROR) { CPLError( CE_Failure, CPLE_AppDefined, "EGifCloseFile() failed.\n" ); hGifFile = NULL; goto error; } hGifFile = NULL; VSIFCloseL( fp ); fp = NULL; /* -------------------------------------------------------------------- */ /* Do we need a world file? */ /* -------------------------------------------------------------------- */ if( CSLFetchBoolean( papszOptions, "WORLDFILE", FALSE ) ) { double adfGeoTransform[6]; if( poSrcDS->GetGeoTransform( adfGeoTransform ) == CE_None ) GDALWriteWorldFile( pszFilename, "wld", adfGeoTransform ); } /* -------------------------------------------------------------------- */ /* Re-open dataset, and copy any auxilary pam information. */ /* -------------------------------------------------------------------- */ /* If outputing to stdout, we can't reopen it, so we'll return */ /* a fake dataset to make the caller happy */ CPLPushErrorHandler(CPLQuietErrorHandler); poDS = (GDALPamDataset*) GDALOpen(pszFilename, GA_ReadOnly); CPLPopErrorHandler(); if (poDS) { poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT ); return poDS; } else { CPLErrorReset(); GIFDataset* poGIF_DS = new GIFDataset(); poGIF_DS->nRasterXSize = nXSize; poGIF_DS->nRasterYSize = nYSize; for(int i=0;i<nBands;i++) poGIF_DS->SetBand( i+1, new GIFRasterBand( poGIF_DS, i+1, NULL, 0 ) ); return poGIF_DS; } error: if (hGifFile) GIFAbstractDataset::myEGifCloseFile(hGifFile); if (fp) VSIFCloseL( fp ); if (pabyScanline) CPLFree( pabyScanline ); return NULL; }
GDALDataset *ARGDataset::CreateCopy( const char *pszFilename, GDALDataset *poSrcDS, int /* bStrict */ , char ** /* papszOptions */ , GDALProgressFunc /* pfnProgress */ , void * /*pProgressData */ ) { const int nBands = poSrcDS->GetRasterCount(); if( nBands != 1 ) { CPLError( CE_Failure, CPLE_NotSupported, "ARG driver doesn't support %d bands. Must be 1 band.", nBands ); return nullptr; } CPLString pszDataType; int nPixelOffset = 0; GDALDataType eType = poSrcDS->GetRasterBand(1)->GetRasterDataType(); if( eType == GDT_Unknown || eType == GDT_CInt16 || eType == GDT_CInt32 || eType == GDT_CFloat32 || eType == GDT_CFloat64 ) { CPLError( CE_Failure, CPLE_NotSupported, "ARG driver doesn't support data type %s.", GDALGetDataTypeName(eType) ); return nullptr; } else if (eType == GDT_Int16) { pszDataType = "int16"; nPixelOffset = 2; } else if (eType == GDT_Int32) { pszDataType = "int32"; nPixelOffset = 4; } else if (eType == GDT_Byte) { pszDataType = "uint8"; nPixelOffset = 1; } else if (eType == GDT_UInt16) { pszDataType = "uint16"; nPixelOffset = 2; } else if (eType == GDT_UInt32) { pszDataType = "uint32"; nPixelOffset = 4; } else if (eType == GDT_Float32) { pszDataType = "float32"; nPixelOffset = 4; } else if (eType == GDT_Float64) { pszDataType = "float64"; nPixelOffset = 8; } double adfTransform[6]; poSrcDS->GetGeoTransform( adfTransform ); const char *pszWKT = poSrcDS->GetProjectionRef(); OGRSpatialReference oSRS; OGRErr nErr = oSRS.importFromWkt(pszWKT); if (nErr != OGRERR_NONE) { CPLError( CE_Failure, CPLE_NotSupported, "Cannot import spatial reference WKT from source dataset."); return nullptr; } int nSrs = 0; if (oSRS.GetAuthorityCode("PROJCS") != nullptr) { nSrs = atoi(oSRS.GetAuthorityCode("PROJCS")); } else if (oSRS.GetAuthorityCode("GEOGCS") != nullptr) { nSrs = atoi(oSRS.GetAuthorityCode("GEOGCS")); } else { // could not determine projected or geographic code // default to EPSG:3857 if no code could be found nSrs = 3857; } /********************************************************************/ /* Create JSON companion file. */ /********************************************************************/ const CPLString osJSONFilename = GetJsonFilename(pszFilename); json_object *poJSONObject = json_object_new_object(); char **pszTokens = poSrcDS->GetMetadata(); const char *pszLayer = CSLFetchNameValue(pszTokens, "LAYER"); if ( pszLayer == nullptr) { // Set the layer json_object_object_add(poJSONObject, "layer", json_object_new_string( CPLGetBasename(osJSONFilename) )); } else { // Set the layer json_object_object_add(poJSONObject, "layer", json_object_new_string( pszLayer )); } // Set the type json_object_object_add(poJSONObject, "type", json_object_new_string("arg")); // Set the datatype json_object_object_add(poJSONObject, "datatype", json_object_new_string(pszDataType)); const int nXSize = poSrcDS->GetRasterXSize(); const int nYSize = poSrcDS->GetRasterYSize(); // Set the number of rows json_object_object_add(poJSONObject, "rows", json_object_new_int(nYSize)); // Set the number of columns json_object_object_add(poJSONObject, "cols", json_object_new_int(nXSize)); // Set the xmin json_object_object_add(poJSONObject, "xmin", json_object_new_double(adfTransform[0])); // Set the ymax json_object_object_add(poJSONObject, "ymax", json_object_new_double(adfTransform[3])); // Set the cellwidth json_object_object_add(poJSONObject, "cellwidth", json_object_new_double(adfTransform[1])); // Set the cellheight json_object_object_add(poJSONObject, "cellheight", json_object_new_double(-adfTransform[5])); // Set the xmax json_object_object_add(poJSONObject, "xmax", json_object_new_double(adfTransform[0] + nXSize * adfTransform[1])); // Set the ymin json_object_object_add(poJSONObject, "ymin", json_object_new_double(adfTransform[3] + nYSize * adfTransform[5])); // Set the xskew json_object_object_add(poJSONObject, "xskew", json_object_new_double(adfTransform[2])); // Set the yskew json_object_object_add(poJSONObject, "yskew", json_object_new_double(adfTransform[4])); if (nSrs > 0) { // Set the epsg json_object_object_add(poJSONObject, "epsg", json_object_new_int(nSrs)); } if (json_object_to_file(const_cast<char *>(osJSONFilename.c_str()), poJSONObject) < 0) { CPLError( CE_Failure, CPLE_NotSupported, "ARG driver can't write companion file."); json_object_put(poJSONObject); poJSONObject = nullptr; return nullptr; } json_object_put(poJSONObject); poJSONObject = nullptr; VSILFILE *fpImage = VSIFOpenL(pszFilename, "wb"); if (fpImage == nullptr) { CPLError( CE_Failure, CPLE_NotSupported, "ARG driver can't create data file %s.", pszFilename); // remove JSON file VSIUnlink( osJSONFilename.c_str() ); return nullptr; } // only 1 raster band GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( 1 ); #ifdef CPL_LSB bool bNative = false; #else bool bNative = true; #endif RawRasterBand *poDstBand = new RawRasterBand( fpImage, 0, nPixelOffset, nPixelOffset * nXSize, eType, bNative, nXSize, nYSize, RawRasterBand::OwnFP::NO); int nXBlockSize, nYBlockSize; poSrcBand->GetBlockSize(&nXBlockSize, &nYBlockSize); void *pabyData = CPLMalloc(nXBlockSize * nPixelOffset); // convert any blocks into scanlines for (int nYBlock = 0; nYBlock * nYBlockSize < nYSize; nYBlock++) { for (int nYScanline = 0; nYScanline < nYBlockSize; nYScanline++) { if ((nYScanline+1) + nYBlock * nYBlockSize > poSrcBand->GetYSize() ) { continue; } for (int nXBlock = 0; nXBlock * nXBlockSize < nXSize; nXBlock++) { int nXValid; if( (nXBlock+1) * nXBlockSize > poSrcBand->GetXSize() ) nXValid = poSrcBand->GetXSize() - nXBlock * nXBlockSize; else nXValid = nXBlockSize; CPLErr eErr = poSrcBand->RasterIO(GF_Read, nXBlock * nXBlockSize, nYBlock * nYBlockSize + nYScanline, nXValid, 1, pabyData, nXBlockSize, 1, eType, 0, 0, nullptr); if (eErr != CE_None) { CPLError(CE_Failure, CPLE_AppDefined, "Error reading."); CPLFree( pabyData ); delete poDstBand; VSIFCloseL( fpImage ); return nullptr; } eErr = poDstBand->RasterIO(GF_Write, nXBlock * nXBlockSize, nYBlock * nYBlockSize + nYScanline, nXValid, 1, pabyData, nXBlockSize, 1, eType, 0, 0, nullptr); if (eErr != CE_None) { CPLError(CE_Failure, CPLE_AppDefined, "Error writing."); CPLFree( pabyData ); delete poDstBand; VSIFCloseL( fpImage ); return nullptr; } } } } CPLFree( pabyData ); delete poDstBand; VSIFCloseL( fpImage ); return reinterpret_cast<GDALDataset *>( GDALOpen( pszFilename, GA_ReadOnly ) ); }
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 ); }
// static function H5::H5File *KEADataset::CreateLL( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char ** papszParmList ) { GDALDriverH hDriver = GDALGetDriverByName( "KEA" ); if( ( hDriver == NULL ) || !GDALValidateCreationOptions( hDriver, papszParmList ) ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed. Invalid creation option(s)\n", pszFilename); return NULL; } // process any creation options in papszParmList // default value unsigned int nimageblockSize = kealib::KEA_IMAGE_CHUNK_SIZE; // see if they have provided a different value const char *pszValue = CSLFetchNameValue( papszParmList, "IMAGEBLOCKSIZE" ); if( pszValue != NULL ) nimageblockSize = (unsigned int) atol( pszValue ); unsigned int nattblockSize = kealib::KEA_ATT_CHUNK_SIZE; pszValue = CSLFetchNameValue( papszParmList, "ATTBLOCKSIZE" ); if( pszValue != NULL ) nattblockSize = (unsigned int) atol( pszValue ); unsigned int nmdcElmts = kealib::KEA_MDC_NELMTS; pszValue = CSLFetchNameValue( papszParmList, "MDC_NELMTS" ); if( pszValue != NULL ) nmdcElmts = (unsigned int) atol( pszValue ); hsize_t nrdccNElmts = kealib::KEA_RDCC_NELMTS; pszValue = CSLFetchNameValue( papszParmList, "RDCC_NELMTS" ); if( pszValue != NULL ) nrdccNElmts = (unsigned int) atol( pszValue ); hsize_t nrdccNBytes = kealib::KEA_RDCC_NBYTES; pszValue = CSLFetchNameValue( papszParmList, "RDCC_NBYTES" ); if( pszValue != NULL ) nrdccNBytes = (unsigned int) atol( pszValue ); double nrdccW0 = kealib::KEA_RDCC_W0; pszValue = CSLFetchNameValue( papszParmList, "RDCC_W0" ); if( pszValue != NULL ) nrdccW0 = CPLAtof( pszValue ); hsize_t nsieveBuf = kealib::KEA_SIEVE_BUF; pszValue = CSLFetchNameValue( papszParmList, "SIEVE_BUF" ); if( pszValue != NULL ) nsieveBuf = (unsigned int) atol( pszValue ); hsize_t nmetaBlockSize = kealib::KEA_META_BLOCKSIZE; pszValue = CSLFetchNameValue( papszParmList, "META_BLOCKSIZE" ); if( pszValue != NULL ) nmetaBlockSize = (unsigned int) atol( pszValue ); unsigned int ndeflate = kealib::KEA_DEFLATE; pszValue = CSLFetchNameValue( papszParmList, "DEFLATE" ); if( pszValue != NULL ) ndeflate = (unsigned int) atol( pszValue ); kealib::KEADataType keaDataType = GDAL_to_KEA_Type( eType ); if( nBands > 0 && keaDataType == kealib::kea_undefined ) { CPLError( CE_Failure, CPLE_NotSupported, "Data type %s not supported in KEA", GDALGetDataTypeName(eType) ); return NULL; } try { // now create it H5::H5File *keaImgH5File = kealib::KEAImageIO::createKEAImage( pszFilename, keaDataType, nXSize, nYSize, nBands, NULL, NULL, nimageblockSize, nattblockSize, nmdcElmts, nrdccNElmts, nrdccNBytes, nrdccW0, nsieveBuf, nmetaBlockSize, ndeflate ); return keaImgH5File; } catch (kealib::KEAIOException &e) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed. Error: %s\n", pszFilename, e.what() ); return NULL; } }
GDALDataset *GS7BGDataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, CPL_UNUSED char **papszParmList ) { if( nXSize <= 0 || nYSize <= 0 ) { CPLError( CE_Failure, CPLE_IllegalArg, "Unable to create grid, both X and Y size must be " "non-negative.\n" ); return NULL; } if( eType != GDT_Byte && eType != GDT_Float32 && eType != GDT_UInt16 && eType != GDT_Int16 && eType != GDT_Float64) { CPLError( CE_Failure, CPLE_AppDefined, "GS7BG Grid only supports Byte, Int16, " "Uint16, Float32, and Float64 datatypes. Unable to create with " "type %s.\n", GDALGetDataTypeName( eType ) ); return NULL; } if (nBands > 1) { CPLError( CE_Failure, CPLE_NotSupported, "Unable to create copy, " "format only supports one raster band.\n" ); return NULL; } VSILFILE *fp = VSIFOpenL( pszFilename, "w+b" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file '%s' failed.\n", pszFilename ); return NULL; } CPLErr eErr = WriteHeader( fp, nXSize, nYSize, 0.0, nXSize, 0.0, nYSize, 0.0, 0.0 ); if( eErr != CE_None ) { VSIFCloseL( fp ); return NULL; } double dfVal = dfDefaultNoDataValue; CPL_LSBPTR64( &dfVal ); for( int iRow = 0; iRow < nYSize; iRow++ ) { for( int iCol=0; iCol<nXSize; iCol++ ) { if( VSIFWriteL( (void *)&dfVal, sizeof(double), 1, fp ) != 1 ) { VSIFCloseL( fp ); CPLError( CE_Failure, CPLE_FileIO, "Unable to write grid cell. Disk full?\n" ); return NULL; } } } VSIFCloseL( fp ); return (GDALDataset *)GDALOpen( pszFilename, GA_Update ); }
CPLErr VRTKernelFilteredSource:: FilterData( int nXSize, int nYSize, GDALDataType eType, GByte *pabySrcData, GByte *pabyDstData ) { /* -------------------------------------------------------------------- */ /* Validate data type. */ /* -------------------------------------------------------------------- */ if( eType != GDT_Float32 ) { CPLError( CE_Failure, CPLE_AppDefined, "Unsupported data type (%s) in VRTKernelFilteredSource::FilterData()", GDALGetDataTypeName( eType ) ); return CE_Failure; } CPLAssert( nExtraEdgePixels*2 + 1 == nKernelSize || (nKernelSize == 0 && nExtraEdgePixels == 0) ); /* -------------------------------------------------------------------- */ /* Float32 case. */ /* -------------------------------------------------------------------- */ if( eType == GDT_Float32 ) { int iX, iY; int bHasNoData; float fNoData = (float) poRasterBand->GetNoDataValue(&bHasNoData); for( iY = 0; iY < nYSize; iY++ ) { for( iX = 0; iX < nXSize; iX++ ) { int iYY, iKern = 0; double dfSum = 0.0, dfKernSum = 0.0; float fResult; int iIndex = (iY+nKernelSize/2 ) * (nXSize+2*nExtraEdgePixels) + iX + nKernelSize/2; float fCenter = ((float *)pabySrcData)[iIndex]; // Check if center srcpixel is NoData if(!bHasNoData || fCenter != fNoData) { for( iYY = 0; iYY < nKernelSize; iYY++ ) { int i; float *pafData = ((float *)pabySrcData) + (iY+iYY) * (nXSize+2*nExtraEdgePixels) + iX; for( i = 0; i < nKernelSize; i++, pafData++, iKern++ ) { if(!bHasNoData || *pafData != fNoData) { dfSum += *pafData * padfKernelCoefs[iKern]; dfKernSum += padfKernelCoefs[iKern]; } } } if( bNormalized ) { if( dfKernSum != 0.0 ) fResult = (float) (dfSum / dfKernSum); else fResult = 0.0; } else fResult = (float) dfSum; ((float *) pabyDstData)[iX + iY * nXSize] = fResult; } else ((float *) pabyDstData)[iX + iY * nXSize] = fNoData; } } } return CE_None; }
GDALDataset *IntergraphDataset::Create( const char *pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char **papszOptions ) { int nDeviceResolution = 1; const char *pszValue; const char *pszCompression = NULL; pszValue = CSLFetchNameValue(papszOptions, "RESOLUTION"); if( pszValue != NULL ) nDeviceResolution = -atoi( pszValue ); char *pszExtension = CPLStrlwr(CPLStrdup(CPLGetExtension(pszFilename))); if ( EQUAL( pszExtension, "rle" ) ) pszCompression = INGR_GetFormatName(RunLengthEncoded); CPLFree(pszExtension); if( eType != GDT_Byte && eType != GDT_Int16 && eType != GDT_Int32 && eType != GDT_UInt16 && eType != GDT_UInt32 && eType != GDT_Float32&& eType != GDT_Float64 ) { CPLError( CE_Failure, CPLE_AppDefined, "Data type not supported (%s)", GDALGetDataTypeName( eType ) ); return NULL; } // -------------------------------------------------------------------- // Fill headers with minimun information // -------------------------------------------------------------------- INGR_HeaderOne hHdr1; INGR_HeaderTwoA hHdr2; INGR_ColorTable256 hCTab; int i; memset(&hHdr1, 0, SIZEOF_HDR1); memset(&hHdr2, 0, SIZEOF_HDR2_A); memset(&hCTab, 0, SIZEOF_CTAB); hHdr1.HeaderType.Version = INGR_HEADER_VERSION; hHdr1.HeaderType.Type = INGR_HEADER_TYPE; hHdr1.HeaderType.Is2Dor3D = INGR_HEADER_2D; hHdr1.DataTypeCode = (uint16) INGR_GetFormat( eType, (pszCompression!=NULL)?pszCompression:"None" ); hHdr1.WordsToFollow = ( ( SIZEOF_HDR1 * 3 ) / 2 ) - 2; hHdr1.ApplicationType = GenericRasterImageFile; hHdr1.XViewOrigin = 0.0; hHdr1.YViewOrigin = 0.0; hHdr1.ZViewOrigin = 0.0; hHdr1.XViewExtent = 0.0; hHdr1.YViewExtent = 0.0; hHdr1.ZViewExtent = 0.0; for( i = 0; i < 15; i++ ) hHdr1.TransformationMatrix[i] = 0.0; hHdr1.TransformationMatrix[15] = 1.0; hHdr1.PixelsPerLine = nXSize; hHdr1.NumberOfLines = nYSize; hHdr1.DeviceResolution = nDeviceResolution; hHdr1.ScanlineOrientation = UpperLeftHorizontal; hHdr1.ScannableFlag = NoLineHeader; hHdr1.RotationAngle = 0.0; hHdr1.SkewAngle = 0.0; hHdr1.DataTypeModifier = 0; hHdr1.DesignFileName[0] = '\0'; hHdr1.DataBaseFileName[0] = '\0'; hHdr1.ParentGridFileName[0] = '\0'; hHdr1.FileDescription[0] = '\0'; hHdr1.Minimum = INGR_SetMinMax( eType, 0.0 ); hHdr1.Maximum = INGR_SetMinMax( eType, 0.0 ); hHdr1.GridFileVersion = 3; hHdr1.Reserved[0] = 0; hHdr1.Reserved[1] = 0; hHdr1.Reserved[2] = 0; hHdr2.Gain = 0; hHdr2.OffsetThreshold = 0; hHdr2.View1 = 0; hHdr2.View2 = 0; hHdr2.ViewNumber = 0; hHdr2.Reserved2 = 0; hHdr2.Reserved3 = 0; hHdr2.AspectRatio = nXSize / nYSize; hHdr2.CatenatedFilePointer = 0; hHdr2.ColorTableType = NoColorTable; hHdr2.NumberOfCTEntries = 0; hHdr2.Reserved8 = 0; for( i = 0; i < 110; i++ ) hHdr2.Reserved[i] = 0; hHdr2.ApplicationPacketLength = 0; hHdr2.ApplicationPacketPointer = 0; // -------------------------------------------------------------------- // RGB Composite assumption // -------------------------------------------------------------------- if( eType == GDT_Byte && nBands == 3 ) { hHdr1.DataTypeCode = Uncompressed24bit; } // -------------------------------------------------------------------- // Create output file with minimum header info // -------------------------------------------------------------------- VSILFILE *fp = VSIFOpenL( pszFilename, "wb+" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file %s' failed.\n", pszFilename ); return NULL; } GByte abyBuf[MAX(SIZEOF_HDR1,SIZEOF_CTAB)]; INGR_HeaderOneMemToDisk( &hHdr1, abyBuf ); VSIFWriteL( abyBuf, 1, SIZEOF_HDR1, fp ); INGR_HeaderTwoAMemToDisk( &hHdr2, abyBuf ); VSIFWriteL( abyBuf, 1, SIZEOF_HDR2_A, fp ); unsigned int n = 0; for( i = 0; i < 256; i++ ) { STRC2BUF( abyBuf, n, hCTab.Entry[i].v_red ); STRC2BUF( abyBuf, n, hCTab.Entry[i].v_green ); STRC2BUF( abyBuf, n, hCTab.Entry[i].v_blue ); } VSIFWriteL( abyBuf, 1, SIZEOF_CTAB, fp ); VSIFCloseL( fp ); // -------------------------------------------------------------------- // Returns a new IntergraphDataset from the created file // -------------------------------------------------------------------- return ( IntergraphDataset * ) GDALOpen( pszFilename, GA_Update ); }