void* CUtils::mallocData(GDALRasterBandH hBand, void * pdata, int count) { switch(GDALGetRasterDataType(hBand)) { case GDT_Float32: pdata = CPLMalloc(sizeof(float)*count); break; case GDT_Int32: pdata = CPLMalloc(sizeof(int)*count); break; case GDT_UInt32: pdata = CPLMalloc(sizeof(unsigned int)*count); break; case GDT_Int16: pdata = CPLMalloc(sizeof(short int)*count); break; case GDT_UInt16: pdata = CPLMalloc(sizeof(unsigned short int)*count); break; case GDT_Byte: pdata = CPLMalloc(sizeof(unsigned char)*count); break; case GDT_CInt16: pdata = CPLMalloc(sizeof(int)*count); break; //UNKNOWN default: pdata = NULL; } return pdata; }
void TestQgsGdalUtils::testCreateSingleBandTiffDataset() { QString filename = QDir::tempPath() + "/qgis_test_single_band_raster.tif"; QFile::remove( filename ); QVERIFY( !QFile::exists( filename ) ); gdal::dataset_unique_ptr ds1 = QgsGdalUtils::createSingleBandTiffDataset( filename, GDT_Float32, QgsRectangle( 1, 1, 21, 11 ), 40, 20, QgsCoordinateReferenceSystem( "EPSG:4326" ) ); QVERIFY( ds1 ); QCOMPARE( GDALGetRasterCount( ds1.get() ), 1 ); QCOMPARE( GDALGetRasterXSize( ds1.get() ), 40 ); QCOMPARE( GDALGetRasterYSize( ds1.get() ), 20 ); QCOMPARE( GDALGetProjectionRef( ds1.get() ), EPSG_4326_WKT ); double geoTransform[6]; double geoTransformExpected[] = { 1, 0.5, 0, 11, 0, -0.5 }; QCOMPARE( GDALGetGeoTransform( ds1.get(), geoTransform ), CE_None ); QVERIFY( memcmp( geoTransform, geoTransformExpected, sizeof( double ) * 6 ) == 0 ); QCOMPARE( GDALGetRasterDataType( GDALGetRasterBand( ds1.get(), 1 ) ), GDT_Float32 ); ds1.reset(); // makes sure the file is fully written QVERIFY( QFile::exists( filename ) ); std::unique_ptr<QgsRasterLayer> layer( new QgsRasterLayer( filename, "test", "gdal" ) ); QVERIFY( layer->isValid() ); QCOMPARE( layer->extent(), QgsRectangle( 1, 1, 21, 11 ) ); QCOMPARE( layer->width(), 40 ); QCOMPARE( layer->height(), 20 ); layer.reset(); // let's clean up before removing the file QFile::remove( filename ); }
float CUtils::getDataAsFloat(GDALRasterBandH hBand, const void * pdata, int index) { float * pFloat = NULL; int * pInt = NULL; unsigned int * pUInt = NULL; short int * pShort = NULL; unsigned short int * pUShort = NULL; unsigned char * pByte = NULL; float v = 0; TRANSFER_CINT16 tr = {0}; switch((int)GDALGetRasterDataType(hBand)) { case GDT_Float32: pFloat = (float*)pdata; v = pFloat[index]; return v; case GDT_Int32: pInt = (int*)pdata; v = (float)pInt[index]; return v; case GDT_UInt32: pUInt = (unsigned int*)pdata; v = (float)pUInt[index]; return v; case GDT_Int16: pShort = (short int*)pdata; v = (float)pShort[index]; return v; case GDT_UInt16: pUShort = (unsigned short int*)pdata; v = (float)pUShort[index]; return v; case GDT_Byte: pByte = (unsigned char*)pdata; v = (float)pByte[index]; return v; case GDT_CInt16: pInt = (int*)pdata; tr.data = pInt[index]; return (float)tr.sdata[0]; //UNKNOWN default: return 0; } return 0; }
void CUtils::setData(float v, GDALRasterBandH hBand, const void * pdata, int index) { float * pFloat = NULL; int * pInt = NULL; unsigned int * pUInt = NULL; short int * pShort = NULL; unsigned short int * pUShort = NULL; unsigned char * pByte = NULL; TRANSFER_CINT16 tr = {0}; switch((int)GDALGetRasterDataType(hBand)) { case GDT_Float32: pFloat = (float*)pdata; pFloat[index] = v; break; case GDT_Int32: pInt = (int*)pdata; pInt[index] = (int)v; break; case GDT_UInt32: pUInt = (unsigned int*)pdata; pUInt[index] = (unsigned int)v; break; case GDT_Int16: pShort = (short int*)pdata; pShort[index] = (short int)v; break; case GDT_UInt16: pUShort = (unsigned short int*)pdata; pUShort[index] = (unsigned short int)v; break; case GDT_Byte: pByte = (unsigned char*)pdata; pByte[index] = (unsigned char)v; break; case GDT_CInt16: pInt = (int*)pdata; tr.sdata[0] = (short)v; pInt[index] = tr.data; break; //UNKNOWN //default:; } }
static Read * read_new( const char *filename, VipsImage *out ) { Read *read; int64_t w, h; read = VIPS_NEW( out, Read ); memset( read, 0, sizeof( *read ) ); g_signal_connect( out, "close", G_CALLBACK( read_destroy_cb ), read ); GDALAllRegister(); read->hDataset = GDALOpen( filename, GA_ReadOnly ); if( read->hDataset == NULL ) { vips_error( "gdal2vips", "%s", _( "unsupported gdal format" ) ); return( NULL ); } vips_image_pipelinev( out, VIPS_DEMAND_STYLE_SMALLTILE, NULL ); w = GDALGetRasterXSize (read->hDataset); h = GDALGetRasterYSize (read->hDataset); GDALRasterBandH hBand; hBand = GDALGetRasterBand( read->hDataset, 1 ); if( hBand == NULL ) { vips_error( "gdal2vips", "%s", _( "can not open raster band" ) ); return( NULL ); } GDALGetBlockSize( hBand, &read->tile_width, &read->tile_height ); read->data_type = GDALGetRasterDataType( hBand ); // int vipsFormat = VIPS_FORMAT_UCHAR; // switch( dataType ) { // case GDT_Byte: vipsFormat = VIPS_FORMAT_UCHAR; break; // case GDT_UInt16: vipsFormat = VIPS_FORMAT_USHORT; break; // } vips_image_init_fields( out, w, h, 3, VIPS_FORMAT_UCHAR, VIPS_CODING_NONE, VIPS_INTERPRETATION_RGB, 1.0, 1.0 ); return( read ); }
void CUtils::getComplexDataAsDouble(GDALRasterBandH hBand, const void * pdata, int index, double * pReal, double * pImaginary) { int * pInt = NULL; TRANSFER_CINT16 tr = {0}; *pReal = 0 ; *pImaginary = 0; if(GDALGetRasterDataType(hBand) == GDT_CInt16) { pInt = (int*)pdata; tr.data = pInt[index]; *pReal = (double)tr.sdata[0]; *pImaginary = (double)tr.sdata[1]; } }
void TestQgsGdalUtils::testCreateSingleBandMemoryDataset() { gdal::dataset_unique_ptr ds1 = QgsGdalUtils::createSingleBandMemoryDataset( GDT_Float32, QgsRectangle( 1, 1, 21, 11 ), 40, 20, QgsCoordinateReferenceSystem( "EPSG:4326" ) ); QVERIFY( ds1 ); QCOMPARE( GDALGetRasterCount( ds1.get() ), 1 ); QCOMPARE( GDALGetRasterXSize( ds1.get() ), 40 ); QCOMPARE( GDALGetRasterYSize( ds1.get() ), 20 ); QCOMPARE( GDALGetProjectionRef( ds1.get() ), EPSG_4326_WKT ); double geoTransform[6]; double geoTransformExpected[] = { 1, 0.5, 0, 11, 0, -0.5 }; QCOMPARE( GDALGetGeoTransform( ds1.get(), geoTransform ), CE_None ); QVERIFY( memcmp( geoTransform, geoTransformExpected, sizeof( double ) * 6 ) == 0 ); QCOMPARE( GDALGetRasterDataType( GDALGetRasterBand( ds1.get(), 1 ) ), GDT_Float32 ); }
void object::test<6>() { // Index of test file being tested const std::size_t fileIdx = 1; std::string file(data_ + SEP); file += grids_.at(fileIdx).file_; GDALDatasetH ds = GDALOpen(file.c_str(), GA_ReadOnly); ensure("Can't open dataset: " + file, nullptr != ds); GDALRasterBandH band = GDALGetRasterBand(ds, grids_.at(fileIdx).band_); ensure("Can't get raster band", nullptr != band); const double noData = GDALGetRasterNoDataValue(band, nullptr); ensure_equals("Grid NODATA value wrong or missing", noData, -99999); ensure_equals("Data type is not GDT_Float32", GDALGetRasterDataType(band), GDT_Float32); GDALClose(ds); }
CPLErr CPL_STDCALL GDALFillNodata( GDALRasterBandH hTargetBand, GDALRasterBandH hMaskBand, double dfMaxSearchDist, CPL_UNUSED int bDeprecatedOption, int nSmoothingIterations, char **papszOptions, GDALProgressFunc pfnProgress, void * pProgressArg ) { VALIDATE_POINTER1( hTargetBand, "GDALFillNodata", CE_Failure ); const int nXSize = GDALGetRasterBandXSize(hTargetBand); const int nYSize = GDALGetRasterBandYSize(hTargetBand); if( dfMaxSearchDist == 0.0 ) dfMaxSearchDist = std::max(nXSize, nYSize) + 1; const int nMaxSearchDist = static_cast<int>(floor(dfMaxSearchDist)); // Special "x" pixel values identifying pixels as special. GDALDataType eType = GDT_UInt16; GUInt32 nNoDataVal = 65535; if( nXSize > 65533 || nYSize > 65533 ) { eType = GDT_UInt32; nNoDataVal = 4000002; } if( hMaskBand == nullptr ) hMaskBand = GDALGetMaskBand( hTargetBand ); // If there are smoothing iterations, reserve 10% of the progress for them. const double dfProgressRatio = nSmoothingIterations > 0 ? 0.9 : 1.0; const char* pszNoData = CSLFetchNameValue(papszOptions, "NODATA"); bool bHasNoData = false; float fNoData = 0.0f; if( pszNoData ) { bHasNoData = true; fNoData = static_cast<float>(CPLAtof(pszNoData)); } /* -------------------------------------------------------------------- */ /* Initialize progress counter. */ /* -------------------------------------------------------------------- */ if( pfnProgress == nullptr ) pfnProgress = GDALDummyProgress; if( !pfnProgress( 0.0, "Filling...", pProgressArg ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); return CE_Failure; } /* -------------------------------------------------------------------- */ /* Determine format driver for temp work files. */ /* -------------------------------------------------------------------- */ CPLString osTmpFileDriver = CSLFetchNameValueDef( papszOptions, "TEMP_FILE_DRIVER", "GTiff"); GDALDriverH hDriver = GDALGetDriverByName(osTmpFileDriver.c_str()); if( hDriver == nullptr ) { CPLError(CE_Failure, CPLE_AppDefined, "Given driver is not registered"); return CE_Failure; } if( GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATE, nullptr) == nullptr ) { CPLError(CE_Failure, CPLE_AppDefined, "Given driver is incapable of creating temp work files"); return CE_Failure; } char **papszWorkFileOptions = nullptr; if( osTmpFileDriver == "GTiff" ) { papszWorkFileOptions = CSLSetNameValue( papszWorkFileOptions, "COMPRESS", "LZW"); papszWorkFileOptions = CSLSetNameValue( papszWorkFileOptions, "BIGTIFF", "IF_SAFER"); } /* -------------------------------------------------------------------- */ /* Create a work file to hold the Y "last value" indices. */ /* -------------------------------------------------------------------- */ const CPLString osTmpFile = CPLGenerateTempFilename(""); const CPLString osYTmpFile = osTmpFile + "fill_y_work.tif"; GDALDatasetH hYDS = GDALCreate( hDriver, osYTmpFile, nXSize, nYSize, 1, eType, papszWorkFileOptions ); if( hYDS == nullptr ) { CPLError( CE_Failure, CPLE_AppDefined, "Could not create Y index work file. Check driver capabilities."); return CE_Failure; } GDALRasterBandH hYBand = GDALGetRasterBand( hYDS, 1 ); /* -------------------------------------------------------------------- */ /* Create a work file to hold the pixel value associated with */ /* the "last xy value" pixel. */ /* -------------------------------------------------------------------- */ const CPLString osValTmpFile = osTmpFile + "fill_val_work.tif"; GDALDatasetH hValDS = GDALCreate( hDriver, osValTmpFile, nXSize, nYSize, 1, GDALGetRasterDataType( hTargetBand ), papszWorkFileOptions ); if( hValDS == nullptr ) { CPLError(CE_Failure, CPLE_AppDefined, "Could not create XY value work file. Check driver capabilities."); return CE_Failure; } GDALRasterBandH hValBand = GDALGetRasterBand( hValDS, 1 ); /* -------------------------------------------------------------------- */ /* Create a mask file to make it clear what pixels can be filtered */ /* on the filtering pass. */ /* -------------------------------------------------------------------- */ const CPLString osFiltMaskTmpFile = osTmpFile + "fill_filtmask_work.tif"; GDALDatasetH hFiltMaskDS = GDALCreate( hDriver, osFiltMaskTmpFile, nXSize, nYSize, 1, GDT_Byte, papszWorkFileOptions ); if( hFiltMaskDS == nullptr ) { CPLError(CE_Failure, CPLE_AppDefined, "Could not create mask work file. Check driver capabilities."); return CE_Failure; } GDALRasterBandH hFiltMaskBand = GDALGetRasterBand( hFiltMaskDS, 1 ); /* -------------------------------------------------------------------- */ /* Allocate buffers for last scanline and this scanline. */ /* -------------------------------------------------------------------- */ GUInt32 *panLastY = static_cast<GUInt32 *>(VSI_CALLOC_VERBOSE(nXSize, sizeof(GUInt32))); GUInt32 *panThisY = static_cast<GUInt32 *>(VSI_CALLOC_VERBOSE(nXSize, sizeof(GUInt32))); GUInt32 *panTopDownY = static_cast<GUInt32 *>(VSI_CALLOC_VERBOSE(nXSize, sizeof(GUInt32))); float *pafLastValue = static_cast<float *>(VSI_CALLOC_VERBOSE(nXSize, sizeof(float))); float *pafThisValue = static_cast<float *>(VSI_CALLOC_VERBOSE(nXSize, sizeof(float))); float *pafTopDownValue = static_cast<float *>(VSI_CALLOC_VERBOSE(nXSize, sizeof(float))); float *pafScanline = static_cast<float *>(VSI_CALLOC_VERBOSE(nXSize, sizeof(float))); GByte *pabyMask = static_cast<GByte *>(VSI_CALLOC_VERBOSE(nXSize, 1)); GByte *pabyFiltMask = static_cast<GByte *>(VSI_CALLOC_VERBOSE(nXSize, 1)); CPLErr eErr = CE_None; if( panLastY == nullptr || panThisY == nullptr || panTopDownY == nullptr || pafLastValue == nullptr || pafThisValue == nullptr || pafTopDownValue == nullptr || pafScanline == nullptr || pabyMask == nullptr || pabyFiltMask == nullptr ) { eErr = CE_Failure; goto end; } for( int iX = 0; iX < nXSize; iX++ ) { panLastY[iX] = nNoDataVal; } /* ==================================================================== */ /* Make first pass from top to bottom collecting the "last */ /* known value" for each column and writing it out to the work */ /* files. */ /* ==================================================================== */ for( int iY = 0; iY < nYSize && eErr == CE_None; iY++ ) { /* -------------------------------------------------------------------- */ /* Read data and mask for this line. */ /* -------------------------------------------------------------------- */ eErr = GDALRasterIO( hMaskBand, GF_Read, 0, iY, nXSize, 1, pabyMask, nXSize, 1, GDT_Byte, 0, 0 ); if( eErr != CE_None ) break; eErr = GDALRasterIO( hTargetBand, GF_Read, 0, iY, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) break; /* -------------------------------------------------------------------- */ /* Figure out the most recent pixel for each column. */ /* -------------------------------------------------------------------- */ for( int iX = 0; iX < nXSize; iX++ ) { if( pabyMask[iX] ) { pafThisValue[iX] = pafScanline[iX]; panThisY[iX] = iY; } else if( iY <= dfMaxSearchDist + panLastY[iX] ) { pafThisValue[iX] = pafLastValue[iX]; panThisY[iX] = panLastY[iX]; } else { panThisY[iX] = nNoDataVal; } } /* -------------------------------------------------------------------- */ /* Write out best index/value to working files. */ /* -------------------------------------------------------------------- */ eErr = GDALRasterIO( hYBand, GF_Write, 0, iY, nXSize, 1, panThisY, nXSize, 1, GDT_UInt32, 0, 0 ); if( eErr != CE_None ) break; eErr = GDALRasterIO( hValBand, GF_Write, 0, iY, nXSize, 1, pafThisValue, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) break; /* -------------------------------------------------------------------- */ /* Flip this/last buffers. */ /* -------------------------------------------------------------------- */ std::swap(pafThisValue, pafLastValue); std::swap(panThisY, panLastY); /* -------------------------------------------------------------------- */ /* report progress. */ /* -------------------------------------------------------------------- */ if( eErr == CE_None && !pfnProgress( dfProgressRatio * (0.5*(iY+1) / static_cast<double>(nYSize)), "Filling...", pProgressArg ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); eErr = CE_Failure; } } for( int iX = 0; iX < nXSize; iX++ ) { panLastY[iX] = nNoDataVal; } /* ==================================================================== */ /* Now we will do collect similar this/last information from */ /* bottom to top and use it in combination with the top to */ /* bottom search info to interpolate. */ /* ==================================================================== */ for( int iY = nYSize-1; iY >= 0 && eErr == CE_None; iY-- ) { eErr = GDALRasterIO( hMaskBand, GF_Read, 0, iY, nXSize, 1, pabyMask, nXSize, 1, GDT_Byte, 0, 0 ); if( eErr != CE_None ) break; eErr = GDALRasterIO( hTargetBand, GF_Read, 0, iY, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) break; /* -------------------------------------------------------------------- */ /* Figure out the most recent pixel for each column. */ /* -------------------------------------------------------------------- */ for( int iX = 0; iX < nXSize; iX++ ) { if( pabyMask[iX] ) { pafThisValue[iX] = pafScanline[iX]; panThisY[iX] = iY; } else if( panLastY[iX] - iY <= dfMaxSearchDist ) { pafThisValue[iX] = pafLastValue[iX]; panThisY[iX] = panLastY[iX]; } else { panThisY[iX] = nNoDataVal; } } /* -------------------------------------------------------------------- */ /* Load the last y and corresponding value from the top down pass. */ /* -------------------------------------------------------------------- */ eErr = GDALRasterIO( hYBand, GF_Read, 0, iY, nXSize, 1, panTopDownY, nXSize, 1, GDT_UInt32, 0, 0 ); if( eErr != CE_None ) break; eErr = GDALRasterIO( hValBand, GF_Read, 0, iY, nXSize, 1, pafTopDownValue, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) break; /* -------------------------------------------------------------------- */ /* Attempt to interpolate any pixels that are nodata. */ /* -------------------------------------------------------------------- */ memset( pabyFiltMask, 0, nXSize ); for( int iX = 0; iX < nXSize; iX++ ) { int nThisMaxSearchDist = nMaxSearchDist; // If this was a valid target - no change. if( pabyMask[iX] ) continue; // Quadrants 0:topleft, 1:bottomleft, 2:topright, 3:bottomright double adfQuadDist[4] = {}; float fQuadValue[4] = {}; for( int iQuad = 0; iQuad < 4; iQuad++ ) { adfQuadDist[iQuad] = dfMaxSearchDist + 1.0; fQuadValue[iQuad] = 0.0; } // Step left and right by one pixel searching for the closest // target value for each quadrant. for( int iStep = 0; iStep <= nThisMaxSearchDist; iStep++ ) { const int iLeftX = std::max(0, iX - iStep); const int iRightX = std::min(nXSize - 1, iX + iStep); // Top left includes current line. QUAD_CHECK(adfQuadDist[0], fQuadValue[0], iLeftX, panTopDownY[iLeftX], iX, iY, pafTopDownValue[iLeftX], nNoDataVal ); // Bottom left. QUAD_CHECK(adfQuadDist[1], fQuadValue[1], iLeftX, panLastY[iLeftX], iX, iY, pafLastValue[iLeftX], nNoDataVal ); // Top right and bottom right do no include center pixel. if( iStep == 0 ) continue; // Top right includes current line. QUAD_CHECK(adfQuadDist[2], fQuadValue[2], iRightX, panTopDownY[iRightX], iX, iY, pafTopDownValue[iRightX], nNoDataVal ); // Bottom right. QUAD_CHECK(adfQuadDist[3], fQuadValue[3], iRightX, panLastY[iRightX], iX, iY, pafLastValue[iRightX], nNoDataVal ); // Every four steps, recompute maximum distance. if( (iStep & 0x3) == 0 ) nThisMaxSearchDist = static_cast<int>(floor( std::max(std::max(adfQuadDist[0], adfQuadDist[1]), std::max(adfQuadDist[2], adfQuadDist[3])))); } double dfWeightSum = 0.0; double dfValueSum = 0.0; bool bHasSrcValues = false; for( int iQuad = 0; iQuad < 4; iQuad++ ) { if( adfQuadDist[iQuad] <= dfMaxSearchDist ) { const double dfWeight = 1.0 / adfQuadDist[iQuad]; bHasSrcValues = dfWeight != 0; if( !bHasNoData || fQuadValue[iQuad] != fNoData ) { dfWeightSum += dfWeight; dfValueSum += fQuadValue[iQuad] * dfWeight; } } } if( bHasSrcValues ) { pabyMask[iX] = 255; pabyFiltMask[iX] = 255; if( dfWeightSum > 0.0 ) pafScanline[iX] = static_cast<float>(dfValueSum / dfWeightSum); else pafScanline[iX] = fNoData; } } /* -------------------------------------------------------------------- */ /* Write out the updated data and mask information. */ /* -------------------------------------------------------------------- */ eErr = GDALRasterIO( hTargetBand, GF_Write, 0, iY, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) break; eErr = GDALRasterIO( hFiltMaskBand, GF_Write, 0, iY, nXSize, 1, pabyFiltMask, nXSize, 1, GDT_Byte, 0, 0 ); if( eErr != CE_None ) break; /* -------------------------------------------------------------------- */ /* Flip this/last buffers. */ /* -------------------------------------------------------------------- */ std::swap(pafThisValue, pafLastValue); std::swap(panThisY, panLastY); /* -------------------------------------------------------------------- */ /* report progress. */ /* -------------------------------------------------------------------- */ if( eErr == CE_None && !pfnProgress( dfProgressRatio*(0.5+0.5*(nYSize-iY) / static_cast<double>(nYSize)), "Filling...", pProgressArg) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); eErr = CE_Failure; } } /* ==================================================================== */ /* Now we will do iterative average filters over the */ /* interpolated values to smooth things out and make linear */ /* artifacts less obvious. */ /* ==================================================================== */ if( eErr == CE_None && nSmoothingIterations > 0 ) { // Force masks to be to flushed and recomputed. GDALFlushRasterCache( hMaskBand ); void *pScaledProgress = GDALCreateScaledProgress( dfProgressRatio, 1.0, pfnProgress, nullptr ); eErr = GDALMultiFilter( hTargetBand, hMaskBand, hFiltMaskBand, nSmoothingIterations, GDALScaledProgress, pScaledProgress ); GDALDestroyScaledProgress( pScaledProgress ); } /* -------------------------------------------------------------------- */ /* Close and clean up temporary files. Free working buffers */ /* -------------------------------------------------------------------- */ end: CPLFree(panLastY); CPLFree(panThisY); CPLFree(panTopDownY); CPLFree(pafLastValue); CPLFree(pafThisValue); CPLFree(pafTopDownValue); CPLFree(pafScanline); CPLFree(pabyMask); CPLFree(pabyFiltMask); GDALClose( hYDS ); GDALClose( hValDS ); GDALClose( hFiltMaskDS ); CSLDestroy(papszWorkFileOptions); GDALDeleteDataset( hDriver, osYTmpFile ); GDALDeleteDataset( hDriver, osValTmpFile ); GDALDeleteDataset( hDriver, osFiltMaskTmpFile ); return eErr; }
bool CUtils::isFloat32DataType(GDALDatasetH hDataset) { return ( GDALGetRasterDataType( GDALGetRasterBand(hDataset, 1) ) == GDT_Float32 ); }
CPLErr CPL_STDCALL GDALFillNodata( GDALRasterBandH hTargetBand, GDALRasterBandH hMaskBand, double dfMaxSearchDist, CPL_UNUSED int bDeprecatedOption, int nSmoothingIterations, CPL_UNUSED char **papszOptions, GDALProgressFunc pfnProgress, void * pProgressArg ) { VALIDATE_POINTER1( hTargetBand, "GDALFillNodata", CE_Failure ); int nXSize = GDALGetRasterBandXSize( hTargetBand ); int nYSize = GDALGetRasterBandYSize( hTargetBand ); CPLErr eErr = CE_None; // Special "x" pixel values identifying pixels as special. GUInt32 nNoDataVal; GDALDataType eType; if( dfMaxSearchDist == 0.0 ) dfMaxSearchDist = MAX(nXSize,nYSize) + 1; int nMaxSearchDist = (int) floor(dfMaxSearchDist); if( nXSize > 65533 || nYSize > 65533 ) { eType = GDT_UInt32; nNoDataVal = 4000002; } else { eType = GDT_UInt16; nNoDataVal = 65535; } if( hMaskBand == NULL ) hMaskBand = GDALGetMaskBand( hTargetBand ); /* If there are smoothing iterations, reserve 10% of the progress for them */ double dfProgressRatio = (nSmoothingIterations > 0) ? 0.9 : 1.0; /* -------------------------------------------------------------------- */ /* Initialize progress counter. */ /* -------------------------------------------------------------------- */ if( pfnProgress == NULL ) pfnProgress = GDALDummyProgress; if( !pfnProgress( 0.0, "Filling...", pProgressArg ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); return CE_Failure; } /* -------------------------------------------------------------------- */ /* Create a work file to hold the Y "last value" indices. */ /* -------------------------------------------------------------------- */ GDALDriverH hDriver = GDALGetDriverByName( "GTiff" ); if (hDriver == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "GDALFillNodata needs GTiff driver"); return CE_Failure; } GDALDatasetH hYDS; GDALRasterBandH hYBand; static const char *apszOptions[] = { "COMPRESS=LZW", "BIGTIFF=IF_SAFER", NULL }; CPLString osTmpFile = CPLGenerateTempFilename(""); CPLString osYTmpFile = osTmpFile + "fill_y_work.tif"; hYDS = GDALCreate( hDriver, osYTmpFile, nXSize, nYSize, 1, eType, (char **) apszOptions ); if( hYDS == NULL ) return CE_Failure; hYBand = GDALGetRasterBand( hYDS, 1 ); /* -------------------------------------------------------------------- */ /* Create a work file to hold the pixel value associated with */ /* the "last xy value" pixel. */ /* -------------------------------------------------------------------- */ GDALDatasetH hValDS; GDALRasterBandH hValBand; CPLString osValTmpFile = osTmpFile + "fill_val_work.tif"; hValDS = GDALCreate( hDriver, osValTmpFile, nXSize, nYSize, 1, GDALGetRasterDataType( hTargetBand ), (char **) apszOptions ); if( hValDS == NULL ) return CE_Failure; hValBand = GDALGetRasterBand( hValDS, 1 ); /* -------------------------------------------------------------------- */ /* Create a mask file to make it clear what pixels can be filtered */ /* on the filtering pass. */ /* -------------------------------------------------------------------- */ GDALDatasetH hFiltMaskDS; GDALRasterBandH hFiltMaskBand; CPLString osFiltMaskTmpFile = osTmpFile + "fill_filtmask_work.tif"; hFiltMaskDS = GDALCreate( hDriver, osFiltMaskTmpFile, nXSize, nYSize, 1, GDT_Byte, (char **) apszOptions ); if( hFiltMaskDS == NULL ) return CE_Failure; hFiltMaskBand = GDALGetRasterBand( hFiltMaskDS, 1 ); /* -------------------------------------------------------------------- */ /* Allocate buffers for last scanline and this scanline. */ /* -------------------------------------------------------------------- */ GUInt32 *panLastY, *panThisY, *panTopDownY; float *pafLastValue, *pafThisValue, *pafScanline, *pafTopDownValue; GByte *pabyMask, *pabyFiltMask; int iX; int iY; panLastY = (GUInt32 *) VSICalloc(nXSize,sizeof(GUInt32)); panThisY = (GUInt32 *) VSICalloc(nXSize,sizeof(GUInt32)); panTopDownY = (GUInt32 *) VSICalloc(nXSize,sizeof(GUInt32)); pafLastValue = (float *) VSICalloc(nXSize,sizeof(float)); pafThisValue = (float *) VSICalloc(nXSize,sizeof(float)); pafTopDownValue = (float *) VSICalloc(nXSize,sizeof(float)); pafScanline = (float *) VSICalloc(nXSize,sizeof(float)); pabyMask = (GByte *) VSICalloc(nXSize,1); pabyFiltMask = (GByte *) VSICalloc(nXSize,1); if (panLastY == NULL || panThisY == NULL || panTopDownY == NULL || pafLastValue == NULL || pafThisValue == NULL || pafTopDownValue == NULL || pafScanline == NULL || pabyMask == NULL || pabyFiltMask == NULL) { CPLError(CE_Failure, CPLE_OutOfMemory, "Could not allocate enough memory for temporary buffers"); eErr = CE_Failure; goto end; } for( iX = 0; iX < nXSize; iX++ ) { panLastY[iX] = nNoDataVal; } /* ==================================================================== */ /* Make first pass from top to bottom collecting the "last */ /* known value" for each column and writing it out to the work */ /* files. */ /* ==================================================================== */ for( iY = 0; iY < nYSize && eErr == CE_None; iY++ ) { /* -------------------------------------------------------------------- */ /* Read data and mask for this line. */ /* -------------------------------------------------------------------- */ eErr = GDALRasterIO( hMaskBand, GF_Read, 0, iY, nXSize, 1, pabyMask, nXSize, 1, GDT_Byte, 0, 0 ); if( eErr != CE_None ) break; eErr = GDALRasterIO( hTargetBand, GF_Read, 0, iY, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) break; /* -------------------------------------------------------------------- */ /* Figure out the most recent pixel for each column. */ /* -------------------------------------------------------------------- */ for( iX = 0; iX < nXSize; iX++ ) { if( pabyMask[iX] ) { pafThisValue[iX] = pafScanline[iX]; panThisY[iX] = iY; } else if( iY <= dfMaxSearchDist + panLastY[iX] ) { pafThisValue[iX] = pafLastValue[iX]; panThisY[iX] = panLastY[iX]; } else { panThisY[iX] = nNoDataVal; } } /* -------------------------------------------------------------------- */ /* Write out best index/value to working files. */ /* -------------------------------------------------------------------- */ eErr = GDALRasterIO( hYBand, GF_Write, 0, iY, nXSize, 1, panThisY, nXSize, 1, GDT_UInt32, 0, 0 ); if( eErr != CE_None ) break; eErr = GDALRasterIO( hValBand, GF_Write, 0, iY, nXSize, 1, pafThisValue, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) break; /* -------------------------------------------------------------------- */ /* Flip this/last buffers. */ /* -------------------------------------------------------------------- */ { float *pafTmp = pafThisValue; pafThisValue = pafLastValue; pafLastValue = pafTmp; GUInt32 *panTmp = panThisY; panThisY = panLastY; panLastY = panTmp; } /* -------------------------------------------------------------------- */ /* report progress. */ /* -------------------------------------------------------------------- */ if( eErr == CE_None && !pfnProgress( dfProgressRatio * (0.5*(iY+1) / (double)nYSize), "Filling...", pProgressArg ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); eErr = CE_Failure; } } /* ==================================================================== */ /* Now we will do collect similar this/last information from */ /* bottom to top and use it in combination with the top to */ /* bottom search info to interpolate. */ /* ==================================================================== */ for( iY = nYSize-1; iY >= 0 && eErr == CE_None; iY-- ) { eErr = GDALRasterIO( hMaskBand, GF_Read, 0, iY, nXSize, 1, pabyMask, nXSize, 1, GDT_Byte, 0, 0 ); if( eErr != CE_None ) break; eErr = GDALRasterIO( hTargetBand, GF_Read, 0, iY, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) break; /* -------------------------------------------------------------------- */ /* Figure out the most recent pixel for each column. */ /* -------------------------------------------------------------------- */ for( iX = 0; iX < nXSize; iX++ ) { if( pabyMask[iX] ) { pafThisValue[iX] = pafScanline[iX]; panThisY[iX] = iY; } else if( panLastY[iX] - iY <= dfMaxSearchDist ) { pafThisValue[iX] = pafLastValue[iX]; panThisY[iX] = panLastY[iX]; } else { panThisY[iX] = nNoDataVal; } } /* -------------------------------------------------------------------- */ /* Load the last y and corresponding value from the top down pass. */ /* -------------------------------------------------------------------- */ eErr = GDALRasterIO( hYBand, GF_Read, 0, iY, nXSize, 1, panTopDownY, nXSize, 1, GDT_UInt32, 0, 0 ); if( eErr != CE_None ) break; eErr = GDALRasterIO( hValBand, GF_Read, 0, iY, nXSize, 1, pafTopDownValue, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) break; /* -------------------------------------------------------------------- */ /* Attempt to interpolate any pixels that are nodata. */ /* -------------------------------------------------------------------- */ memset( pabyFiltMask, 0, nXSize ); for( iX = 0; iX < nXSize; iX++ ) { int iStep, iQuad; int nThisMaxSearchDist = nMaxSearchDist; // If this was a valid target - no change. if( pabyMask[iX] ) continue; // Quadrants 0:topleft, 1:bottomleft, 2:topright, 3:bottomright double adfQuadDist[4]; double adfQuadValue[4]; for( iQuad = 0; iQuad < 4; iQuad++ ) { adfQuadDist[iQuad] = dfMaxSearchDist + 1.0; adfQuadValue[iQuad] = 0.0; } // Step left and right by one pixel searching for the closest // target value for each quadrant. for( iStep = 0; iStep < nThisMaxSearchDist; iStep++ ) { int iLeftX = MAX(0,iX - iStep); int iRightX = MIN(nXSize-1,iX + iStep); // top left includes current line QUAD_CHECK(adfQuadDist[0],adfQuadValue[0], iLeftX, panTopDownY[iLeftX], iX, iY, pafTopDownValue[iLeftX] ); // bottom left QUAD_CHECK(adfQuadDist[1],adfQuadValue[1], iLeftX, panLastY[iLeftX], iX, iY, pafLastValue[iLeftX] ); // top right and bottom right do no include center pixel. if( iStep == 0 ) continue; // top right includes current line QUAD_CHECK(adfQuadDist[2],adfQuadValue[2], iRightX, panTopDownY[iRightX], iX, iY, pafTopDownValue[iRightX] ); // bottom right QUAD_CHECK(adfQuadDist[3],adfQuadValue[3], iRightX, panLastY[iRightX], iX, iY, pafLastValue[iRightX] ); // every four steps, recompute maximum distance. if( (iStep & 0x3) == 0 ) nThisMaxSearchDist = (int) floor( MAX(MAX(adfQuadDist[0],adfQuadDist[1]), MAX(adfQuadDist[2],adfQuadDist[3])) ); } double dfWeightSum = 0.0; double dfValueSum = 0.0; for( iQuad = 0; iQuad < 4; iQuad++ ) { if( adfQuadDist[iQuad] <= dfMaxSearchDist ) { double dfWeight = 1.0 / adfQuadDist[iQuad]; dfWeightSum += dfWeight; dfValueSum += adfQuadValue[iQuad] * dfWeight; } } if( dfWeightSum > 0.0 ) { pabyMask[iX] = 255; pabyFiltMask[iX] = 255; pafScanline[iX] = (float) (dfValueSum / dfWeightSum); } } /* -------------------------------------------------------------------- */ /* Write out the updated data and mask information. */ /* -------------------------------------------------------------------- */ eErr = GDALRasterIO( hTargetBand, GF_Write, 0, iY, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) break; eErr = GDALRasterIO( hFiltMaskBand, GF_Write, 0, iY, nXSize, 1, pabyFiltMask, nXSize, 1, GDT_Byte, 0, 0 ); if( eErr != CE_None ) break; /* -------------------------------------------------------------------- */ /* Flip this/last buffers. */ /* -------------------------------------------------------------------- */ { float *pafTmp = pafThisValue; pafThisValue = pafLastValue; pafLastValue = pafTmp; GUInt32 *panTmp = panThisY; panThisY = panLastY; panLastY = panTmp; } /* -------------------------------------------------------------------- */ /* report progress. */ /* -------------------------------------------------------------------- */ if( eErr == CE_None && !pfnProgress( dfProgressRatio*(0.5+0.5*(nYSize-iY) / (double)nYSize), "Filling...", pProgressArg ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); eErr = CE_Failure; } } /* ==================================================================== */ /* Now we will do iterative average filters over the */ /* interpolated values to smooth things out and make linear */ /* artifacts less obvious. */ /* ==================================================================== */ if( eErr == CE_None && nSmoothingIterations > 0 ) { // force masks to be to flushed and recomputed. GDALFlushRasterCache( hMaskBand ); void *pScaledProgress; pScaledProgress = GDALCreateScaledProgress( dfProgressRatio, 1.0, pfnProgress, NULL ); eErr = GDALMultiFilter( hTargetBand, hMaskBand, hFiltMaskBand, nSmoothingIterations, GDALScaledProgress, pScaledProgress ); GDALDestroyScaledProgress( pScaledProgress ); } /* -------------------------------------------------------------------- */ /* Close and clean up temporary files. Free working buffers */ /* -------------------------------------------------------------------- */ end: CPLFree(panLastY); CPLFree(panThisY); CPLFree(panTopDownY); CPLFree(pafLastValue); CPLFree(pafThisValue); CPLFree(pafTopDownValue); CPLFree(pafScanline); CPLFree(pabyMask); CPLFree(pabyFiltMask); GDALClose( hYDS ); GDALClose( hValDS ); GDALClose( hFiltMaskDS ); GDALDeleteDataset( hDriver, osYTmpFile ); GDALDeleteDataset( hDriver, osValTmpFile ); GDALDeleteDataset( hDriver, osFiltMaskTmpFile ); return eErr; }
void CUtils::setRasterBlock(GDALRasterBandH hBand, int rows, int cols, void* pBlockValues) { GDALRasterIO(hBand, GF_Write, 0, 0, cols, rows, pBlockValues, cols, rows, GDALGetRasterDataType(hBand), 0, 0); }
int main( int argc, const char* argv[] ) { GDALDriverH hDriver; double adfGeoTransform[6]; GDALDatasetH in_Dataset; GDALDatasetH mask_Dataset; GDALDatasetH out_Dataset; GDALRasterBandH mask_band; char *mask_scan_line, *data_scan_line; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; int bands; int xsize; double adfMinMax[2]; GDALAllRegister(); if ( argc != 2) { printf("Usage: %s <file to add mask to> \n", argv[0]); printf("This utility adds a nodata mask to a file, were the datadata value is \"0\"\n"); printf("contact/blame [email protected] for questions/problems.\n"); return 0; } /* open datasets..*/ in_Dataset = GDAL_open( argv[1]); /* add mask.. */ GDALCreateDatasetMaskBand( in_Dataset, 0); /* Basic info on source dataset..*/ GDALGetBlockSize(GDALGetRasterBand( in_Dataset, 1 ) , &nBlockXSize, &nBlockYSize ); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(GDALGetRasterDataType( GDALGetRasterBand( in_Dataset, 1 ))), GDALGetColorInterpretationName( GDALGetRasterColorInterpretation(GDALGetRasterBand( in_Dataset, 1 )))); /* Loop though bands, wiping values with mask values of 0.. */ xsize = GDALGetRasterXSize( in_Dataset ); mask_scan_line = (char *) CPLMalloc(sizeof(char)*xsize); data_scan_line = (char *) CPLMalloc(sizeof(char)*xsize); for (bands=1; bands <= GDALGetRasterCount( in_Dataset ); bands ++ ) { int x; GDALRasterBandH data_band, out_band; int y_index = 0; printf("INFO: Doing band %d of %d\n", bands,GDALGetRasterCount( in_Dataset ) ); data_band = GDALGetRasterBand( in_Dataset, bands); mask_band = GDALGetMaskBand(data_band); for (y_index = 0; y_index <GDALGetRasterYSize( in_Dataset ); y_index ++ ) { /* Read data..*/ GDALRasterIO( data_band, GF_Read, 0, y_index, xsize , 1, data_scan_line, xsize , 1, GDT_Byte, 0, 0 ); for(x=0; x < xsize; x++) { /* if mask is set to 0, then mask off...*/ /* lame nodata handleing, but such is life.. */ if ( data_scan_line[x] == 0 ) mask_scan_line[x]=0; else mask_scan_line[x]=255; } /* now write out band..*/ GDALRasterIO( mask_band, GF_Write, 0, y_index, xsize , 1, mask_scan_line, xsize , 1, GDT_Byte, 0, 0 ); } } GDALClose(in_Dataset); }
void convert(const input_arguments& args) { // determine the subdataset pattern name using the first available file if(args.verbose) std::cout << "\tlooking for the names of subdatasets (or variables)... " << std::flush; std::vector<std::string> band_names = modis2scidb::extract_subdatasets_pattern_names(args.source_file_name); if(args.verbose) std::cout << "OK!" << std::endl; // check if band numbers are in the valid range if(args.verbose) std::cout << "\tchecking the range for choosed band numbers... " << std::flush; std::size_t num_bands = args.bands.size(); for(std::size_t i = 0; i != num_bands; ++i) if(args.bands[i] >= band_names.size()) throw modis2scidb::invalid_arg_value() << modis2scidb::error_description("band number is invalid!"); if(args.verbose) std::cout << "OK!" << std::endl; // let's buffer each subdataset if(args.verbose) std::cout << "\tbuffering data... " << std::flush; std::vector<boost::shared_array<unsigned char> > data_buffers; std::vector<unsigned char*> aux_data_buffers; std::vector<std::size_t> band_datatype_size; int64_t ncols = 0; int64_t nrows = 0; for(std::size_t i = 0; i != num_bands; ++i) { if(args.verbose) std::cout << "\n\t\tband #" << args.bands[i] << "... " << std::flush; boost::format subdataset(band_names[args.bands[i]]); subdataset.bind_arg(1, args.source_file_name); GDALDatasetH dataset = GDALOpen(subdataset.str().c_str(), GA_ReadOnly); if(dataset == 0) { boost::format err_msg("could not open subdataset: '%1%', for input hdf file: '%2%'!"); throw modis2scidb::gdal_error() << modis2scidb::error_description((err_msg % subdataset.str() % args.source_file_name).str()); } GDALRasterBandH band = GDALGetRasterBand(dataset, 1); if(band == 0) { GDALClose(dataset); boost::format err_msg("could not access band: %1%!"); throw modis2scidb::gdal_error() << modis2scidb::error_description((err_msg % args.bands[i]).str()); } if(i == 0) { ncols = GDALGetRasterBandXSize(band); nrows = GDALGetRasterBandYSize(band); } else { if((GDALGetRasterBandXSize(band) != ncols) || (GDALGetRasterBandYSize(band) != nrows)) { GDALClose(dataset); throw modis2scidb::gdal_error() << modis2scidb::error_description("selected bands must have the same dimension (rows and cols)!"); } } GDALDataType pixel_type = GDALGetRasterDataType(band); std::size_t pixel_size = modis2scidb::num_bytes(pixel_type); band_datatype_size.push_back(pixel_size); boost::shared_array<unsigned char> buffer(new unsigned char[ncols * nrows * pixel_size]); data_buffers.push_back(buffer); aux_data_buffers.push_back(buffer.get()); CPLErr result = GDALRasterIO(band, GF_Read, 0, 0, static_cast<int>(ncols), static_cast<int>(nrows), buffer.get(), static_cast<int>(ncols), static_cast<int>(nrows), pixel_type, 0, 0); if(result == CE_Failure) { GDALClose(dataset); boost::format err_msg("could not read subdataset: '%1%', for input hdf file: '%2%'!"); throw modis2scidb::gdal_error() << modis2scidb::error_description((err_msg % subdataset.str() % args.source_file_name).str()); } GDALClose(dataset); if(args.verbose) std::cout << "OK!" << std::flush; } if(args.verbose) std::cout << "\n\tOK!" << std::endl; // lets write the output to a SciDB binary file if(args.verbose) std::cout << "\tsaving data... " << std::flush; boost::filesystem::path input_file(args.source_file_name); FILE* f = fopen(args.target_file_name.c_str(), "wb"); if(f == 0) { boost::format err_msg("could not open output file: '%1%', for write! check if path exists."); throw modis2scidb::gdal_error() << modis2scidb::error_description((err_msg % args.target_file_name).str()); } for(int32_t i = 0; i != nrows; ++i) { int32_t gi = args.row_offset + i; for(int32_t j = 0; j != ncols; ++j) { int32_t gj = args.column_offset + j; fwrite(&gj, sizeof(unsigned char), sizeof(int32_t), f); fwrite(&gi, sizeof(unsigned char), sizeof(int32_t), f); if(args.time_point >= 0) fwrite(&args.time_point, sizeof(unsigned char), sizeof(int16_t), f); for(std::size_t b = 0; b != num_bands; ++b) { unsigned char* buffer = aux_data_buffers[b]; fwrite(buffer, sizeof(unsigned char), band_datatype_size[b], f); aux_data_buffers[b] = buffer + band_datatype_size[b]; } } } fclose(f); }
int main(void) { GDALAllRegister(); /*Open a file*/ GDALDatasetH hDataset; hDataset = GDALOpen( "./dem.tif", GA_ReadOnly ); if( hDataset == NULL ) printf("The dataset is NULL!\n"); /*Getting Dasetset Information*/ GDALDriverH hDriver; double adfGeoTransform[6]; hDriver = GDALGetDatasetDriver( hDataset ); printf( "Driver: %s/%s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver )); printf("Size is %dx%dx%d\n", GDALGetRasterXSize( hDataset ), GDALGetRasterYSize( hDataset ), GDALGetRasterCount( hDataset )); if( GDALGetProjectionRef( hDataset ) != NULL ) printf("Projection is '%s'\n", GDALGetProjectionRef( hDataset ) ); if (GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) { printf("Origin = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3]); printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[5]); } /*Fetching a Raster Band*/ GDALRasterBandH hBand; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; double adfMinMax[2]; hBand = GDALGetRasterBand( hDataset, 1); GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(GDALGetRasterDataType(hBand)), GDALGetColorInterpretationName( GDALGetRasterColorInterpretation(hBand)) ); adfMinMax[0] = GDALGetRasterMinimum( hBand, &bGotMin ); adfMinMax[1] = GDALGetRasterMaximum( hBand, &bGotMax ); if( !(bGotMin && bGotMax) ) { GDALComputeRasterMinMax( hBand, TRUE, adfMinMax ); } printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1]); if(GDALGetOverviewCount(hBand) > 0) printf( "Band has %d overviews.\n", GDALGetOverviewCount(hBand)); if( GDALGetRasterColorTable( hBand ) != NULL) printf( "Band has a color table with %d entries.\n", GDALGetColorEntryCount( GDALGetRasterColorTable( hBand))); /*Reading Raster Data*/ float *pafScanline; int nXSize = GDALGetRasterBandXSize( hBand ); pafScanline = (float *)CPLMalloc(sizeof(float)*nXSize); GDALRasterIO(hBand, GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0); CPLFree(pafScanline); return 0; }
HRESULT CImage::Open(char* pszPathName,UINT uMode) { Close(); m_pszPathName=new char[strlen(pszPathName)+1]; strcpy(m_pszPathName,pszPathName); if(strcmp(m_pszPathName+strlen(m_pszPathName)-3,"txt")==0) { char szPath[512]; memset(szPath,0,512*sizeof(char)); int nPos=-1; int i=strlen(m_pszPathName)-1; for(;i>=0;i--) { if(m_pszPathName[i]=='\\'||m_pszPathName[i]=='/') { nPos=i; break; } } for(i=0;i<=nPos;i++) { szPath[i]=m_pszPathName[i]; } FILE* fp=fopen(m_pszPathName,"rt"); if(fp==NULL) { return S_FALSE; } BOOL bGeoCoded=FALSE; char szBuffer[1024]; char szTag[100],szEqualMark[10],szValue[512]; while(!feof(fp)) { memset(szBuffer, 0 ,sizeof(char)*1024); memset(szTag, 0 ,sizeof(char)*100); memset(szEqualMark, 0 ,sizeof(char)*10); memset(szValue, 0 ,sizeof(char)*512); fgets(szBuffer,1023,fp); sscanf(szBuffer,"%s%s%s",szTag,szEqualMark,szValue); int nLength=strlen(szValue); if(nLength>0) { if(szValue[nLength-1]==';') { szValue[nLength-1]='\0'; } } // Parse the satellite ID from the GC report file. [Wei.Zuo,4/15/2009] if(strcmp(szTag,"satelliteID")==0) { if(strcmp(szValue,"\"HJ1A\"")==0) m_nSatelliteID = 1; else if(strcmp(szValue,"\"HJ1B\"")==0) m_nSatelliteID = 2; else m_nSatelliteID = 0; } else if(strcmp(szTag,"sensorID")==0) { if(strcmp(szValue,"\"CCD\"")==0) { m_nSensorType=SENSOR_CCD; m_nBPB=1; m_datatype=ConvertDataType2GDALDataType(Pixel_Byte); } else if(strcmp(szValue,"\"HSI\"")==0) { m_nSensorType=SENSOR_HSI; m_nBPB=2; m_datatype=ConvertDataType2GDALDataType(Pixel_Int16); } else if(strcmp(szValue,"\"IRS\"")==0) { m_nSensorType=SENSOR_IRS; m_nBPB=2; m_datatype=ConvertDataType2GDALDataType(Pixel_Int16); } // Add sensor CCD1 and CCD2. [Wei.Zuo,4/15/2009] else if(strcmp(szValue,"\"CCD1\"")==0) { m_nSensorType=SENSOR_CCD1; m_nBPB=1; m_datatype=ConvertDataType2GDALDataType(Pixel_Byte); } else if(strcmp(szValue,"\"CCD2\"")==0) { m_nSensorType=SENSOR_CCD2; m_nBPB=1; m_datatype=ConvertDataType2GDALDataType(Pixel_Byte); } // Later will add sensor SAR. [Wei.Zuo,4/15/2009] } else if(strcmp(szTag,"ImgNum")==0) { m_nImgNum=atoi(szValue); m_nBandNum=m_nImgNum; } else if(strcmp(szTag,"Bands")==0) { m_nBandNum=atoi(szValue); } else if(strcmp(szTag,"processedImageWidth")==0) { m_nCols=atoi(szValue); } else if(strcmp(szTag,"processedImageHeight")==0) { m_nRows=atoi(szValue); } //������Ϣ else if(strcmp(szTag,"pixelSpacing")==0) { m_CellSize=atof(szValue); bGeoCoded=TRUE; } else if(strcmp(szTag,"productLowerLeftX")==0) { m_LBX=atof(szValue); } else if(strcmp(szTag,"productLowerLeftY")==0) { m_LBY=atof(szValue); } else if(strcmp(szTag,"productLowerRightX")==0) { } else if(strcmp(szTag,"productLowerRightY")==0) { } else if(strcmp(szTag,"productUpperRightX")==0) { m_RTX=atof(szValue); } else if(strcmp(szTag,"productUpperRightY")==0) { m_RTY=atof(szValue); } else if(strcmp(szTag,"productUpperLeftX")==0) { } else if(strcmp(szTag,"productUpperLeftY")==0) { } } if(m_nBandNum<=0||m_nImgNum<=0) { fclose(fp); return S_FALSE; } if(bGeoCoded==FALSE) { m_LBX=0; m_LBY=0; m_RTX=m_nCols; m_RTY=m_nRows; m_CellSize=1.0; } m_fpRaws=new FILE*[m_nImgNum]; memset(m_fpRaws,0,sizeof(FILE*)*m_nImgNum); for(i=0;i<m_nImgNum;i++) { char szStdTag[100]; sprintf(szStdTag,"outputdata%d",i); fseek(fp,0,SEEK_SET); while(!feof(fp)) { fgets(szBuffer,1023,fp); sscanf(szBuffer,"%s%s%s",szTag,szEqualMark,szValue); if(strcmp(szTag,szStdTag)==0) { char szName[512]; memset(szName,0,512*sizeof(char)); int nPos=-1; int k=strlen(szValue)-1; for(;k>=0;k--) { if(szValue[k]=='\\'||szValue[k]=='/') { nPos=k; break; } } for(k=nPos+1;k<((int)(strlen(szValue)));k++) { if(szValue[k]=='\"') { break; } szName[k-nPos-1]=szValue[k]; } char szRawPathName[512]; strcpy(szRawPathName,szPath); strcat(szRawPathName,szName); if(m_nSensorType==SENSOR_IRS&&i==3&&m_nRows==4500&&m_nCols==4500) { char szRawPathNameTemp[512]; sprintf(szRawPathNameTemp,"%s_resample.raw",szRawPathName); FILE* fpSrc=fopen(szRawPathName,"rb"); FILE* fpDst=fopen(szRawPathNameTemp,"wb"); if(fpSrc==NULL||fpDst==NULL) { Close(); fclose(fpSrc); fclose(fpDst); return S_FALSE; } BYTE* pSrcBuffer=new BYTE[m_nCols/2*m_nBPB]; BYTE* pDstBuffer=new BYTE[m_nCols*m_nBPB]; int m=0,n=0; for(m=0;m<m_nRows/2;m++) { fread(pSrcBuffer,m_nBPB,m_nCols/2,fpSrc); for(n=0;n<m_nCols/2;n++) { memcpy(pDstBuffer+(n*2+0)*m_nBPB,pSrcBuffer+n*m_nBPB,m_nBPB); memcpy(pDstBuffer+(n*2+1)*m_nBPB,pSrcBuffer+n*m_nBPB,m_nBPB); } fwrite(pDstBuffer,m_nBPB,m_nCols,fpDst); fwrite(pDstBuffer,m_nBPB,m_nCols,fpDst); } fclose(fpSrc); fclose(fpDst); delete [] pSrcBuffer; delete [] pDstBuffer; strcpy(szRawPathName,szRawPathNameTemp); } m_fpRaws[i]=fopen(szRawPathName,"rb"); if(m_fpRaws[i]==NULL) { Close(); fclose(fp); return S_FALSE; } } } } fclose(fp); } else { GDALAllRegister(); m_pGdalImage=(GDALDataset*)GDALOpen(m_pszPathName,GA_ReadOnly); if(m_pGdalImage==NULL) { return S_FALSE; } //��ȡӰ��ߴ���Ϣ m_nCols=GDALGetRasterXSize(m_pGdalImage); m_nRows=GDALGetRasterYSize(m_pGdalImage); m_nBandNum=GDALGetRasterCount(m_pGdalImage); if(m_nBandNum<=0) { return S_FALSE; } m_datatype=GDALGetRasterDataType(GDALGetRasterBand(m_pGdalImage,1)); m_nBPB=GDALGetDataTypeSize(m_datatype)/8; for(int i=2;i<=m_nBandNum;i++) { if(GDALGetRasterDataType(GDALGetRasterBand(m_pGdalImage,i))!=m_datatype) { GDALClose(m_pGdalImage); COutput::OutputFileOpenFailed(m_pszPathName); return S_FALSE; } } //��ȡ������Ϣ double grdTransform[6]; memset(grdTransform,0,sizeof(double)*6); CPLErr error=m_pGdalImage->GetGeoTransform(grdTransform); if(error==CE_None) { double X0,Y0,X2,Y2; X0=grdTransform[0]; Y0=grdTransform[3]; X2=grdTransform[0]+m_nCols*grdTransform[1]+m_nRows*grdTransform[2]; Y2=grdTransform[3]+m_nCols*grdTransform[4]+m_nRows*grdTransform[5]; m_LBX=__min(X0,X2); m_LBY=__min(Y0,Y2); m_RTX=__max(X0,X2); m_RTY=__max(Y0,Y2); m_CellSize=fabs(grdTransform[1]); } else { m_LBX=0; m_LBY=0; m_RTX=m_nCols; m_RTY=m_nRows; m_CellSize=1.0; } } //��ʼ�������� m_nCacheRow=m_CacheSize/(m_nCols*m_nBandNum*m_nBPB); if(m_nCacheRow<=0) { if(m_pCache) { delete [] m_pCache; } m_pCache=NULL; BOOL bMemEnough=FALSE; int nRow=24000; while(bMemEnough==FALSE&&nRow>1) { try { m_nCacheRow=nRow; m_CacheSize=m_nCols*m_nBandNum*m_nBPB*m_nCacheRow; m_pCache=new BYTE[m_CacheSize]; bMemEnough=TRUE; } catch(...) { nRow=nRow/2; if(nRow<=0) { nRow=1; } } } if(m_pCache==NULL) { try { m_pCache=new BYTE[m_nCols*m_nBandNum*m_nBPB*1]; m_CacheSize=m_nCols*m_nBandNum*m_nBPB*1; m_nCacheRow=1; } catch(...) { COutput::OutputMemoryError(); Close(); return S_FALSE; } } } if((uMode&modeAqlut)==modeAqlut) { //here pHistogram mast write as follows CHistogram* pHistogram=new CHistogram[m_nBandNum]; for(int i=0;i<m_nBandNum;i++) { pHistogram[i].StatHistogram(this,i); } m_pHistogram=pHistogram; pHistogram=NULL; } return S_OK; }
static void DumpBand( GDALDatasetH hBaseDS, GDALRasterBandH hSrcOver, const char *pszName ) { /* -------------------------------------------------------------------- */ /* Get base ds info. */ /* -------------------------------------------------------------------- */ double adfGeoTransform[6]; bool bHaveGT = GDALGetGeoTransform( hBaseDS, adfGeoTransform ) == CE_None; int nOrigXSize = GDALGetRasterXSize( hBaseDS ); int nOrigYSize = GDALGetRasterYSize( hBaseDS ); /* -------------------------------------------------------------------- */ /* Create matching output file. */ /* -------------------------------------------------------------------- */ int nXSize = GDALGetRasterBandXSize( hSrcOver ); int nYSize = GDALGetRasterBandYSize( hSrcOver ); GDALDataType eDT = GDALGetRasterDataType( hSrcOver ); GDALDriverH hDriver = GDALGetDriverByName( "GTiff" ); GDALDatasetH hDstDS = GDALCreate( hDriver, pszName, nXSize, nYSize, 1, eDT, NULL ); if( hDstDS == NULL ) exit( 1 ); /* -------------------------------------------------------------------- */ /* Apply corresponding georeferencing, scaled to size. */ /* -------------------------------------------------------------------- */ if( bHaveGT ) { double adfOvGeoTransform[6]; memcpy( adfOvGeoTransform, adfGeoTransform, sizeof(double) * 6 ); adfOvGeoTransform[1] *= (nOrigXSize / (double) nXSize); adfOvGeoTransform[2] *= (nOrigXSize / (double) nXSize); adfOvGeoTransform[4] *= (nOrigYSize / (double) nYSize); adfOvGeoTransform[5] *= (nOrigYSize / (double) nYSize); GDALSetGeoTransform( hDstDS, adfOvGeoTransform ); GDALSetProjection( hDstDS, GDALGetProjectionRef( hBaseDS ) ); } /* -------------------------------------------------------------------- */ /* Copy over all the image data. */ /* -------------------------------------------------------------------- */ void *pData = CPLMalloc(64 * nXSize); for( int iLine = 0; iLine < nYSize; iLine++ ) { GDALRasterIO( hSrcOver, GF_Read, 0, iLine, nXSize, 1, pData, nXSize, 1, eDT, 0, 0 ); GDALRasterIO( GDALGetRasterBand( hDstDS, 1 ), GF_Write, 0, iLine, nXSize, 1, pData, nXSize, 1, eDT, 0, 0 ); } CPLFree( pData ); GDALClose( hDstDS ); }
SVImage init(int xLow, int xHigh, int yLow, int yHigh, const char *filepath){ GDALDatasetH hDataset; // Register drivers GDALAllRegister(); // open the given file as Read Only hDataset = GDALOpen(filepath, GA_ReadOnly ); // if opening failed if( hDataset == NULL ) { fprintf(stderr, "Unable to open file."); exit(EXIT_FAILURE); } /* Declare some variables to be used later */ int *xBlockSize = malloc(sizeof(int)); int *yBlockSize = malloc(sizeof(int)); int xOutputSize; int yOutputSize; int numXBlocks; int numYBlocks; int origWidth; int origHeight; int origBandCount; /*Get some information on the image*/ origWidth = GDALGetRasterXSize( hDataset ); // Get raster pixel width origHeight = GDALGetRasterYSize( hDataset ); // Get raster pixel height origBandCount = GDALGetRasterCount( hDataset ); // Get number of raster bands in the image GDALRasterBandH hBand = GDALGetRasterBand( hDataset, 1 ); // Get raster band with id 1 GDALGetBlockSize( hBand, xBlockSize, yBlockSize); // Fetch the block size for this band /*TODO make sure scale is set somewhere*/ /*Store some information on what the output should have*/ xOutputSize = ((*xBlockSize) / scale); // get the new x block size yOutputSize = ((*yBlockSize) / scale); // get the new y block size numXBlocks = origWidth/(*xBlockSize); // Get x block count numYBlocks = origHeight/(*yBlockSize); // Get y block count int bandCount; if (origBandCount >= 3) // Just a guess, limit bands to RGB? { bandCount = 3; } else // Otherwise image is probably grayscale, one band? { bandCount = 1; } /*TODO edit this or remove it since we aren't using focusing on openGL*/ /* *int format; *if (bandCount == 3) *{ * format = GL_RGBA; *} *else *{ * format = GL_LUMINANCE_ALPHA; *} */ int usedBlocks; int usedXBlocks; int usedYBlocks; /* *This is odd, xHigh and yHigh are *passed as parameters but changed here *TODO see if we can remove parameters or just use this */ if ((xHigh < 0) || (xHigh < xLow)) { xHigh = numXBlocks; } if ((yHigh < 0)|| (yHigh < yLow)) { yHigh = numYBlocks; } usedXBlocks = (xHigh - xLow); // This is probably the part of the image that should be displayed on screen usedYBlocks = (yHigh - yLow); // Y part on screen? usedBlocks = (usedXBlocks * usedYBlocks); // Total blocks on screen? SVImage svip = { .Width = xOutputSize*usedXBlocks, .Height = yOutputSize*usedYBlocks, .BytesPerPixel = 1, .Data = (CPLMalloc((sizeof(char) * xOutputSize * yOutputSize * usedBlocks * (bandCount+1)))) // Data = xOutputSize * yOutputSize = pixels/block * usedBlocks = totalpixels }; free(xBlockSize); free(yBlockSize); return svip; } /* Uses stochastic sampling to fill the data section of an SVImage struct. */ void sample(params *in) //TODO handle 32 bit representations { /*Set variables from the params struct*/ SVImage* out = in->target; int xLow = in->xLow; int xHigh = in->xHigh; int yLow = in->yLow; int yHigh = in->yHigh; const char *file = in->file; GDALDatasetH hDataset; GDALRasterBandH hBand; /*Register drivers*/ GDALAllRegister(); //TODO Dynamically calculate sample count? int avgSampleCount = 25; //Open GDAL File //------------------------------------------------ hDataset = GDALOpen(file, GA_ReadOnly ); if( hDataset == NULL ) { fprintf(stderr, "Unable to open file.\n"); exit(EXIT_FAILURE); } //GDAL FILE INFO //--------------------------------------------- GDALDriverH hDriver; hDriver = GDALGetDatasetDriver( hDataset ); // Get driver for this file double adfGeoTransform[6]; //Print GDAL Driver printf( "Driver: %s/%s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver ) ); //Get original raster size int origWidth = GDALGetRasterXSize( hDataset ); int origHeight = GDALGetRasterYSize( hDataset ); printf("width = %i\n", origWidth); printf("height = %i\n", origHeight); //Get Raster band count int origBandCount = GDALGetRasterCount( hDataset ); printf("origBandCount = %i\n", origBandCount); int bandCount; if (origBandCount >= 3) { bandCount = 3; } else { bandCount = 1; } //Target output Width and Height float stride = (scale * scale); stride /= (avgSampleCount); //the greatest number of pixels that can be skipped in a single iteration int maxStride = ((int)stride) + 1; //Load band 1 hBand = GDALGetRasterBand( hDataset, 1 ); if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) { printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5] ); } else { fprintf(stderr, "Failed to get pixel size\n"); } int* xBlockSize = malloc(sizeof(int)); int* yBlockSize = malloc(sizeof(int)); //get block size GDALGetBlockSize( hBand, xBlockSize, yBlockSize); printf("xBlockSize = %i\n", *xBlockSize); printf("yBlockSize = %i\n", *yBlockSize); int xOutputSize = ((*xBlockSize) / scale); int yOutputSize = ((*yBlockSize) / scale); printf("X Output Size%i\n", xOutputSize); int numXBlocks = origWidth/(*xBlockSize); int numYBlocks = origHeight/(*yBlockSize); printf("numXBlocks = %i\n", numXBlocks); printf("numYBlocks = %i\n", numYBlocks); if ((xHigh < 0) || (xHigh < xLow)) { xHigh = numXBlocks; } if ((yHigh < 0)|| (yHigh < yLow)) { yHigh = numYBlocks; } int usedXBlocks = (xHigh - xLow); int usedYBlocks = (yHigh - yLow); int usedBlocks = (usedXBlocks * usedYBlocks); unsigned char* output = CPLMalloc((sizeof(char) * xOutputSize* yOutputSize *usedBlocks * (bandCount+1))); // Allocate space for the output float* vals = calloc( xOutputSize* yOutputSize *usedBlocks * (bandCount+1), sizeof(float)); //stores pixel values unsigned long* valsPerIndex = calloc( xOutputSize* yOutputSize * usedBlocks * (bandCount+1), sizeof(unsigned long)); //stores number of pixel values per output index unsigned long rseed = 0; unsigned long rowIndex = 0; //the index of the row to which we will output our value unsigned long colIndex = 0; //the index of the column to which we will output our value unsigned long outIndex = 0; unsigned long sampledIndex = 0; //One dimensional representation of column/row index //iterate through each pixel, jump to the last pixel we sampled. long long i = 0; int outputXOffset = 0; int outputYOffset = 0; int outputIndexOffset = 0; if (GDALGetRasterDataType(hBand) == GDT_Int16) { short* data = (short *) CPLMalloc(sizeof(unsigned short) * (*xBlockSize)*(*yBlockSize)); //TODO: GDAL Raster can be 16 bit pixel representation int band; for (band = 1; band <= bandCount; band++){ hBand = GDALGetRasterBand( hDataset, band ); int yBlock, xBlock; for(yBlock = yLow; yBlock < yHigh; yBlock++){ for(xBlock = xLow; xBlock < xHigh; xBlock++){ if(GDALReadBlock(hBand,xBlock,yBlock, data) != CE_None) { fprintf(stderr, "Read block failed\n"); exit(EXIT_FAILURE); } for(i = 0 ; i < ((*xBlockSize)*(*yBlockSize)-1) ; i += rseed){ rseed = (214013 * rseed + 2531011); // Magic numbers. rseed %= maxStride; sampledIndex = i; i = (maxStride ==1) ? (i+1) : i; rowIndex = (sampledIndex/(xOutputSize*scale* scale)) + ((yBlock - yLow)* yOutputSize); colIndex = ((sampledIndex % (xOutputSize * scale))/scale) + ((xBlock - xLow) * xOutputSize); outIndex = ((rowIndex * (xOutputSize * usedXBlocks ) + colIndex) * (bandCount+1) ) + (band -1); vals[outIndex] += (*(data + sampledIndex)); vals[outIndex] += 118.450588 + ((*(data + sampledIndex))/128); if (vals[outIndex]/valsPerIndex[outIndex] < 0) { vals[outIndex] =0; }else if (vals[outIndex]/valsPerIndex[outIndex] > 255){ vals[outIndex] = 255; } } } } } } else { unsigned char* data = (unsigned char *) CPLMalloc(sizeof(char) * (*xBlockSize)*(*yBlockSize)); int band; for (band = 1; band <= bandCount; band++) { hBand = GDALGetRasterBand( hDataset, band ); int yBlock, xBlock; outputYOffset = 0; for(yBlock = yLow; yBlock < yHigh; yBlock++){ outputYOffset = ((yBlock - yLow) * yOutputSize * xOutputSize * usedXBlocks * (bandCount + 1)); outputXOffset = 0; for(xBlock = xLow; xBlock < xHigh; xBlock++){ outputXOffset = ((xBlock - xLow) * xOutputSize * (bandCount + 1)); if(GDALReadBlock(hBand,xBlock,yBlock, data) != CE_None) { fprintf(stderr, "Read block failed\n"); exit(EXIT_FAILURE); } for(i = 0 ; i < ((*xBlockSize)*(*yBlockSize)) ; i += rseed){ rseed = (214013 * rseed + 2531011); rseed %= maxStride; sampledIndex = i; i = (maxStride ==1) ? (i+1) : i; rowIndex = (sampledIndex/(xOutputSize*scale* scale)) + ((yBlock - yLow)* yOutputSize); colIndex = ((sampledIndex % (xOutputSize * scale))/scale) + ((xBlock - xLow) * xOutputSize); outIndex = ((rowIndex * (xOutputSize * usedXBlocks ) + colIndex) * (bandCount+1) ) + (band -1); vals[outIndex] += (*(data + sampledIndex)); valsPerIndex[outIndex] +=1; } outputIndexOffset = (outputYOffset + outputXOffset); int j; for (j = 0; j<yOutputSize; j++){ i = outputIndexOffset; int k = (i + (xOutputSize * (bandCount+1))); for (i = 0; i<k;i++){ int x = (i+(j*(xOutputSize * (bandCount + 1) * (usedXBlocks)))); if(((x+1)%4==0&&bandCount==3)||((x+1)%2==0&&bandCount==1)){ output[x] = (unsigned char) 1; //Sets the alpha to opaque }else{ output[x] = (unsigned char) (vals[x]/valsPerIndex[x]); //calculate final output by averaging each color value } } } out->Data = output; } } } } printf("sampling complete\n"); GDALClose(hDataset); }
int main( int argc, char ** argv ) { /* Check that we are running against at least GDAL 1.4 (probably older in fact !) */ /* Note to developers : if we use newer API, please change the requirement */ if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400) { fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, " "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME); exit(1); } /* -------------------------------------------------------------------- */ /* Generic arg processing. */ /* -------------------------------------------------------------------- */ GDALAllRegister(); GDALSetCacheMax( 100000000 ); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Parse arguments. */ /* -------------------------------------------------------------------- */ int i; const char *pszOutFile = NULL; const char *pszInFile = NULL; int nMaxNonBlack = 2; int nNearDist = 15; int bNearWhite = FALSE; int bSetAlpha = FALSE; int bSetMask = FALSE; const char* pszDriverName = "HFA"; int bFormatExplicitelySet = FALSE; char** papszCreationOptions = NULL; int bQuiet = FALSE; Colors oColors; 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], "-o") && i < argc-1 ) pszOutFile = argv[++i]; else if( EQUAL(argv[i], "-of") && i < argc-1 ) { pszDriverName = argv[++i]; bFormatExplicitelySet = TRUE; } else if( EQUAL(argv[i], "-white") ) { bNearWhite = TRUE; } /***** -color c1,c2,c3...cn *****/ else if( EQUAL(argv[i], "-color") && i < argc-1 ) { Color oColor; /***** tokenize the arg on , *****/ char **papszTokens; papszTokens = CSLTokenizeString2( argv[++i], ",", 0 ); /***** loop over the tokens *****/ int iToken; for( iToken = 0; papszTokens && papszTokens[iToken]; iToken++ ) { /***** ensure the token is an int and add it to the color *****/ if ( IsInt( papszTokens[iToken] ) ) oColor.push_back( atoi( papszTokens[iToken] ) ); else { CPLError(CE_Failure, CPLE_AppDefined, "Colors must be valid integers." ); CSLDestroy( papszTokens ); exit(1); } } CSLDestroy( papszTokens ); /***** check if the number of bands is consistant *****/ if ( oColors.size() > 0 && oColors.front().size() != oColor.size() ) { CPLError(CE_Failure, CPLE_AppDefined, "ERROR: all -color args must have the same number of values.\n" ); exit(1); } /***** add the color to the colors *****/ oColors.push_back( oColor ); } else if( EQUAL(argv[i], "-nb") && i < argc-1 ) nMaxNonBlack = atoi(argv[++i]); else if( EQUAL(argv[i], "-near") && i < argc-1 ) nNearDist = atoi(argv[++i]); else if( EQUAL(argv[i], "-setalpha") ) bSetAlpha = TRUE; else if( EQUAL(argv[i], "-setmask") ) bSetMask = TRUE; else if( EQUAL(argv[i], "-q") || EQUAL(argv[i], "-quiet") ) bQuiet = TRUE; else if( EQUAL(argv[i], "-co") && i < argc-1 ) papszCreationOptions = CSLAddString(papszCreationOptions, argv[++i]); else if( argv[i][0] == '-' ) Usage(); else if( pszInFile == NULL ) pszInFile = argv[i]; else Usage(); } if( pszInFile == NULL ) Usage(); if( pszOutFile == NULL ) pszOutFile = pszInFile; /* -------------------------------------------------------------------- */ /* Open input file. */ /* -------------------------------------------------------------------- */ GDALDatasetH hInDS, hOutDS = NULL; int nXSize, nYSize, nBands; if( pszOutFile == pszInFile ) hInDS = hOutDS = GDALOpen( pszInFile, GA_Update ); else hInDS = GDALOpen( pszInFile, GA_ReadOnly ); if( hInDS == NULL ) exit( 1 ); nXSize = GDALGetRasterXSize( hInDS ); nYSize = GDALGetRasterYSize( hInDS ); nBands = GDALGetRasterCount( hInDS ); int nDstBands = nBands; if( hOutDS != NULL && papszCreationOptions != NULL) { CPLError(CE_Warning, CPLE_AppDefined, "Warning: creation options are ignored when writing to an existing file."); } /* -------------------------------------------------------------------- */ /* Do we need to create output file? */ /* -------------------------------------------------------------------- */ if( hOutDS == NULL ) { GDALDriverH hDriver = GDALGetDriverByName( pszDriverName ); if (hDriver == NULL) exit(1); if (!bQuiet && !bFormatExplicitelySet) CheckExtensionConsistency(pszOutFile, pszDriverName); if (bSetAlpha) { /***** fixme there should be a way to preserve alpha band data not in the collar *****/ if (nBands == 4) nBands --; else nDstBands ++; } if (bSetMask) { if (nBands == 4) nDstBands = nBands = 3; } hOutDS = GDALCreate( hDriver, pszOutFile, nXSize, nYSize, nDstBands, GDT_Byte, papszCreationOptions ); if( hOutDS == NULL ) exit( 1 ); double adfGeoTransform[6]; if( GDALGetGeoTransform( hInDS, adfGeoTransform ) == CE_None ) { GDALSetGeoTransform( hOutDS, adfGeoTransform ); GDALSetProjection( hOutDS, GDALGetProjectionRef( hInDS ) ); } } else { if (bSetAlpha) { if (nBands != 4 && (nBands < 2 || GDALGetRasterColorInterpretation(GDALGetRasterBand(hOutDS, nBands)) != GCI_AlphaBand)) { CPLError(CE_Failure, CPLE_AppDefined, "Last band is not an alpha band."); exit(1); } nBands --; } if (bSetMask) { if (nBands == 4) nDstBands = nBands = 3; } } /***** set a color if there are no colors set? *****/ if ( oColors.size() == 0) { Color oColor; /***** loop over the bands to get the right number of values *****/ int iBand; for (iBand = 0; iBand < nBands ; iBand++) { /***** black or white? *****/ if (bNearWhite) oColor.push_back(255); else oColor.push_back(0); } /***** add the color to the colors *****/ oColors.push_back(oColor); } /***** does the number of bands match the number of color values? *****/ if ( (int)oColors.front().size() != nBands ) { CPLError( CE_Failure, CPLE_AppDefined, "-color args must have the same number of values as the non alpha input band count.\n" ); exit(1); } /***** check the input and output datasets are the same size *****/ if (GDALGetRasterXSize(hOutDS) != nXSize || GDALGetRasterYSize(hOutDS) != nYSize) { CPLError(CE_Failure, CPLE_AppDefined, "The dimensions of the output dataset don't match " "the dimensions of the input dataset."); exit(1); } int iBand; for( iBand = 0; iBand < nBands; iBand++ ) { GDALRasterBandH hBand = GDALGetRasterBand(hInDS, iBand+1); if (GDALGetRasterDataType(hBand) != GDT_Byte) { CPLError(CE_Warning, CPLE_AppDefined, "Band %d is not of type GDT_Byte. It can lead to unexpected results.", iBand+1); } if (GDALGetRasterColorTable(hBand) != NULL) { CPLError(CE_Warning, CPLE_AppDefined, "Band %d has a color table, which is ignored by nearblack. " "It can lead to unexpected results.", iBand+1); } } GDALRasterBandH hMaskBand = NULL; if (bSetMask) { /***** if there isn't already a mask band on the output file create one *****/ if ( GMF_PER_DATASET != GDALGetMaskFlags( GDALGetRasterBand(hOutDS, 1) ) ) { if ( CE_None != GDALCreateDatasetMaskBand(hOutDS, GMF_PER_DATASET) ) { CPLError(CE_Failure, CPLE_AppDefined, "Failed to create mask band on output DS"); bSetMask = FALSE; } } if (bSetMask) { hMaskBand = GDALGetMaskBand(GDALGetRasterBand(hOutDS, 1)); } } /* -------------------------------------------------------------------- */ /* Allocate a line buffer. */ /* -------------------------------------------------------------------- */ GByte *pabyLine; GByte *pabyMask=NULL; int *panLastLineCounts; pabyLine = (GByte *) CPLMalloc(nXSize * nDstBands); if (bSetMask) pabyMask = (GByte *) CPLMalloc(nXSize); panLastLineCounts = (int *) CPLCalloc(sizeof(int),nXSize); /* -------------------------------------------------------------------- */ /* Processing data one line at a time. */ /* -------------------------------------------------------------------- */ int iLine; for( iLine = 0; iLine < nYSize; iLine++ ) { CPLErr eErr; eErr = GDALDatasetRasterIO( hInDS, GF_Read, 0, iLine, nXSize, 1, pabyLine, nXSize, 1, GDT_Byte, nBands, NULL, nDstBands, nXSize * nDstBands, 1 ); if( eErr != CE_None ) break; if (bSetAlpha) { int iCol; for(iCol = 0; iCol < nXSize; iCol ++) { pabyLine[iCol * nDstBands + nDstBands - 1] = 255; } } if (bSetMask) { int iCol; for(iCol = 0; iCol < nXSize; iCol ++) { pabyMask[iCol] = 255; } } ProcessLine( pabyLine, pabyMask, 0, nXSize-1, nBands, nDstBands, nNearDist, nMaxNonBlack, bNearWhite, &oColors, panLastLineCounts, TRUE, // bDoHorizontalCheck TRUE, // bDoVerticalCheck FALSE // bBottomUp ); ProcessLine( pabyLine, pabyMask, nXSize-1, 0, nBands, nDstBands, nNearDist, nMaxNonBlack, bNearWhite, &oColors, panLastLineCounts, TRUE, // bDoHorizontalCheck FALSE, // bDoVerticalCheck FALSE // bBottomUp ); eErr = GDALDatasetRasterIO( hOutDS, GF_Write, 0, iLine, nXSize, 1, pabyLine, nXSize, 1, GDT_Byte, nDstBands, NULL, nDstBands, nXSize * nDstBands, 1 ); if( eErr != CE_None ) break; /***** write out the mask band line *****/ if (bSetMask) { eErr = GDALRasterIO ( hMaskBand, GF_Write, 0, iLine, nXSize, 1, pabyMask, nXSize, 1, GDT_Byte, 0, 0 ); if( eErr != CE_None ) { CPLError(CE_Warning, CPLE_AppDefined, "ERROR writeing out line to mask band."); break; } } if (!bQuiet) GDALTermProgress( 0.5 * ((iLine+1) / (double) nYSize), NULL, NULL ); } /* -------------------------------------------------------------------- */ /* Now process from the bottom back up .*/ /* -------------------------------------------------------------------- */ memset( panLastLineCounts, 0, sizeof(int) * nXSize); for( iLine = nYSize-1; iLine >= 0; iLine-- ) { CPLErr eErr; eErr = GDALDatasetRasterIO( hOutDS, GF_Read, 0, iLine, nXSize, 1, pabyLine, nXSize, 1, GDT_Byte, nDstBands, NULL, nDstBands, nXSize * nDstBands, 1 ); if( eErr != CE_None ) break; /***** read the mask band line back in *****/ if (bSetMask) { eErr = GDALRasterIO ( hMaskBand, GF_Read, 0, iLine, nXSize, 1, pabyMask, nXSize, 1, GDT_Byte, 0, 0 ); if( eErr != CE_None ) break; } ProcessLine( pabyLine, pabyMask, 0, nXSize-1, nBands, nDstBands, nNearDist, nMaxNonBlack, bNearWhite, &oColors, panLastLineCounts, TRUE, // bDoHorizontalCheck TRUE, // bDoVerticalCheck TRUE // bBottomUp ); ProcessLine( pabyLine, pabyMask, nXSize-1, 0, nBands, nDstBands, nNearDist, nMaxNonBlack, bNearWhite, &oColors, panLastLineCounts, TRUE, // bDoHorizontalCheck FALSE, // bDoVerticalCheck TRUE // bBottomUp ); eErr = GDALDatasetRasterIO( hOutDS, GF_Write, 0, iLine, nXSize, 1, pabyLine, nXSize, 1, GDT_Byte, nDstBands, NULL, nDstBands, nXSize * nDstBands, 1 ); if( eErr != CE_None ) break; /***** write out the mask band line *****/ if (bSetMask) { eErr = GDALRasterIO ( hMaskBand, GF_Write, 0, iLine, nXSize, 1, pabyMask, nXSize, 1, GDT_Byte, 0, 0 ); if( eErr != CE_None ) break; } if (!bQuiet) GDALTermProgress( 0.5 + 0.5 * (nYSize-iLine) / (double) nYSize, NULL, NULL ); } CPLFree(pabyLine); if (bSetMask) CPLFree(pabyMask); CPLFree( panLastLineCounts ); GDALClose( hOutDS ); if( hInDS != hOutDS ) GDALClose( hInDS ); GDALDumpOpenDatasets( stderr ); CSLDestroy( argv ); CSLDestroy( papszCreationOptions ); GDALDestroyDriverManager(); return 0; }
void stochastic_sample(GDALImage *image, int avg_sample_count, LevelOfDetail *lod) { float *vals; unsigned long seed, row_index, col_index, out_index, sample_index, *vals_per_index, current_index; long long i; int maxStride; double stride; int xBlockLow, xBlockHigh, yBlockLow, yBlockHigh; // get block range to display svGetVisibleTiles(&xBlockLow, &xBlockHigh, &yBlockLow, &yBlockHigh); /*if(xBlockHigh < 0 || xBlockHigh < xBlockLow)*/ xBlockHigh = image->num_blocks.x; /*if(yBlockHigh < 0 || yBlockHigh < yBlockLow)*/ yBlockHigh = image->num_blocks.y; #ifdef DEBUG printf("xLow: %i \nxHigh: %i\nyLow: %i\nyHigh: %i\n", xBlockLow, xBlockHigh, yBlockLow, yBlockHigh); #endif // Calculate stride for reading stride = (scale * scale) / avg_sample_count; maxStride = ((int)stride) + 1; // Set bounds that we will should read // Possibly change these to band_count + 1 vals = calloc(image->output_size.x * image->output_size.y * (image->band_count+1), sizeof(float)); vals_per_index = calloc(image->output_size.x * image->output_size.y * (image->band_count+1), sizeof(long)); seed = row_index = col_index = out_index = sample_index = i = 0; if(GDALGetRasterDataType(image->current_band) == GDT_Int16) { puts("GDT_Int16"); } else { GByte* data = (GByte *) CPLMalloc(sizeof(char) * image->block_size.x * image->block_size.y); int band; for (band = 1; band <= image->band_count; band++){ image->current_band = GDALGetRasterBand( image->dataset, band ); int yBlock, xBlock; for(yBlock = yBlockLow; yBlock < yBlockHigh; yBlock++) { for(xBlock = xBlockLow; xBlock < xBlockHigh; xBlock++) { if(lod->data[(yBlock * image->num_blocks.x) + xBlock]->Sampled == 0) { if(GDALReadBlock(image->current_band,xBlock,yBlock, data) == CE_Failure) { continue; } //Testing for(i=0 ; i < image->block_size.x * image->block_size.y ; i += seed){ seed = (214013 * seed + 2531011); seed %= maxStride; row_index = i/(image->output_size.x * scale * scale); col_index = (i % (image->output_size.x * scale))/scale; out_index = row_index * image->output_size.x + col_index; vals[out_index] += *(data + i); vals_per_index[out_index] +=1; } current_index = yBlock * image->num_blocks.x + xBlock; for (i=0; i< ( image->output_size.x* image->output_size.y* (image->band_count+1)); i+=4){ //output[i] = (unsigned char) (vals[i]/valsPerIndex[i]); //calculate final output by averaging each color value lod->data[current_index]->Data[i+ (band-1)] = (vals[((i/4))]/vals_per_index[((i/4))]); if(band ==1){ lod->data[current_index]->Data[i+3] = 255; } } //clear vals for the next block memset(vals, 0, image->output_size.x * image->output_size.y * (image->band_count + 1) * sizeof(float)); memset(vals_per_index, 0, image->output_size.x * image->output_size.y * (image->band_count + 1) * sizeof(float)); lod->data[current_index]->Width = image->output_size.x; lod->data[current_index]->Height = image->output_size.y; lod->data[current_index]->Format = GL_RGBA; lod->data[current_index]->BytesPerPixel = 1; if(band == image->band_count){ lod->data[current_index]->Sampled = 1; } } } } } } GDALClose(image->dataset); puts("Done Sampling"); }
int CPL_STDCALL GDALChecksumImage( GDALRasterBandH hBand, int nXOff, int nYOff, int nXSize, int nYSize ) { VALIDATE_POINTER1( hBand, "GDALChecksumImage", 0 ); const static int anPrimes[11] = { 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 }; int iLine, i, nChecksum = 0, iPrime = 0, nCount; GDALDataType eDataType = GDALGetRasterDataType( hBand ); int bComplex = GDALDataTypeIsComplex( eDataType ); if (eDataType == GDT_Float32 || eDataType == GDT_Float64 || eDataType == GDT_CFloat32 || eDataType == GDT_CFloat64) { double* padfLineData; GDALDataType eDstDataType = (bComplex) ? GDT_CFloat64 : GDT_Float64; padfLineData = (double *) VSIMalloc2(nXSize, sizeof(double) * 2); if (padfLineData == NULL) { CPLError( CE_Failure, CPLE_OutOfMemory, "VSIMalloc2(): Out of memory in GDALChecksumImage. " "Checksum value couldn't be computed\n"); return 0; } for( iLine = nYOff; iLine < nYOff + nYSize; iLine++ ) { if (GDALRasterIO( hBand, GF_Read, nXOff, iLine, nXSize, 1, padfLineData, nXSize, 1, eDstDataType, 0, 0 ) != CE_None) { CPLError( CE_Failure, CPLE_FileIO, "Checksum value couldn't be computed due to I/O read error.\n"); break; } nCount = (bComplex) ? nXSize * 2 : nXSize; for( i = 0; i < nCount; i++ ) { double dfVal = padfLineData[i]; int nVal; if (CPLIsNan(dfVal) || CPLIsInf(dfVal)) { /* Most compilers seem to cast NaN or Inf to 0x80000000. */ /* but VC7 is an exception. So we force the result */ /* of such a cast */ nVal = 0x80000000; } else { /* Standard behaviour of GDALCopyWords when converting */ /* from floating point to Int32 */ dfVal += 0.5; if( dfVal < -2147483647.0 ) nVal = -2147483647; else if( dfVal > 2147483647 ) nVal = 2147483647; else nVal = (GInt32) floor(dfVal); } nChecksum += (nVal % anPrimes[iPrime++]); if( iPrime > 10 ) iPrime = 0; nChecksum &= 0xffff; } } CPLFree(padfLineData); } else { int *panLineData; GDALDataType eDstDataType = (bComplex) ? GDT_CInt32 : GDT_Int32; panLineData = (GInt32 *) VSIMalloc2(nXSize, sizeof(GInt32) * 2); if (panLineData == NULL) { CPLError( CE_Failure, CPLE_OutOfMemory, "VSIMalloc2(): Out of memory in GDALChecksumImage. " "Checksum value couldn't be computed\n"); return 0; } for( iLine = nYOff; iLine < nYOff + nYSize; iLine++ ) { if (GDALRasterIO( hBand, GF_Read, nXOff, iLine, nXSize, 1, panLineData, nXSize, 1, eDstDataType, 0, 0 ) != CE_None) { CPLError( CE_Failure, CPLE_FileIO, "Checksum value couldn't be computed due to I/O read error.\n"); break; } nCount = (bComplex) ? nXSize * 2 : nXSize; for( i = 0; i < nCount; i++ ) { nChecksum += (panLineData[i] % anPrimes[iPrime++]); if( iPrime > 10 ) iPrime = 0; nChecksum &= 0xffff; } } CPLFree( panLineData ); } return nChecksum; }
ral_grid_handle RAL_CALL ral_grid_create_using_GDAL(GDALDatasetH dataset, int band, ral_rectangle clip_region, double cell_size) { GDALRasterBandH hBand; GDALDataType datatype; int M, N, gd_datatype; int W, H; /* size of the full GDAL raster */ int north_up, east_up, i0, j0, i1, j1, w, h; /* the clip region (P) */ int ws, hs; /* the size of the buffer into which to rasterIO to */ CPLErr err; ral_grid *gd_s = NULL, *gd_t = NULL; double t[6] = {0,1,0,0,0,1}; /* the geotransformation P -> G */ double tx[6]; /* the inverse geotransformation G -> P */ ral_rectangle GDAL; /* boundaries of the GDAL raster */ ral_point p0, p1, p2, p3; /* locations of corners of clip region: top left, top right, bottom right, bottom left, i.e, 0,0 W',0 W',H' 0,H' */ CPLPushErrorHandler(ral_cpl_error); GDALGetGeoTransform(dataset, t); north_up = (t[2] == 0) AND (t[4] == 0); east_up = (t[1] == 0) AND (t[5] == 0); /*fprintf(stderr, "\nt is\n%f %f %f\n%f %f %f\n", t[0],t[1],t[2],t[3],t[4],t[5]);*/ W = GDALGetRasterXSize(dataset); H = GDALGetRasterYSize(dataset); /*fprintf(stderr, "cell size is %f, raster size is %i %i\n", cell_size, W, H);*/ /* test all corners to find the min & max xg and yg */ { double x, y; P2G(0, 0, t, GDAL.min.x, GDAL.min.y); GDAL.max.x = GDAL.min.x; GDAL.max.y = GDAL.min.y; P2G(0, H, t, x, y); GDAL.min.x = MIN(x, GDAL.min.x); GDAL.min.y = MIN(y, GDAL.min.y); GDAL.max.x = MAX(x, GDAL.max.x); GDAL.max.y = MAX(y, GDAL.max.y); P2G(W, H, t, x, y); GDAL.min.x = MIN(x, GDAL.min.x); GDAL.min.y = MIN(y, GDAL.min.y); GDAL.max.x = MAX(x, GDAL.max.x); GDAL.max.y = MAX(y, GDAL.max.y); P2G(W, 0, t, x, y); GDAL.min.x = MIN(x, GDAL.min.x); GDAL.min.y = MIN(y, GDAL.min.y); GDAL.max.x = MAX(x, GDAL.max.x); GDAL.max.y = MAX(y, GDAL.max.y); } /*fprintf(stderr, "clip region is %f %f %f %f\n", clip_region.min.x, clip_region.min.y, clip_region.max.x, clip_region.max.y); fprintf(stderr, "GDAL raster is %f %f %f %f\n", GDAL.min.x, GDAL.min.y, GDAL.max.x, GDAL.max.y);*/ clip_region.min.x = MAX(clip_region.min.x, GDAL.min.x); clip_region.min.y = MAX(clip_region.min.y, GDAL.min.y); clip_region.max.x = MIN(clip_region.max.x, GDAL.max.x); clip_region.max.y = MIN(clip_region.max.y, GDAL.max.y); /*fprintf(stderr, "visible region is %f %f %f %f\n", clip_region.min.x, clip_region.min.y, clip_region.max.x, clip_region.max.y);*/ RAL_CHECK((clip_region.min.x < clip_region.max.x) AND (clip_region.min.y < clip_region.max.y)); /* the inverse transformation, from georeferenced space to pixel space */ { double tmp = t[2]*t[4] - t[1]*t[5]; tx[0] = (t[0]*t[5] - t[2]*t[3])/tmp; tx[1] = -t[5]/tmp; tx[2] = t[2]/tmp; tx[3] = (t[1]*t[3] - t[0]*t[4])/tmp; tx[4] = t[4]/tmp; tx[5] = -t[1]/tmp; } /* the clip region in pixel space */ /* test all corners to find the min & max xp and yp (j0..j1, i0..i1) */ { int i, j; G2P(clip_region.min.x, clip_region.min.y, tx, j0, i0); j1 = j0; i1 = i0; G2P(clip_region.min.x, clip_region.max.y, tx, j, i); j0 = MIN(j, j0); i0 = MIN(i, i0); j1 = MAX(j, j1); i1 = MAX(i, i1); G2P(clip_region.max.x, clip_region.max.y, tx, j, i); j0 = MIN(j, j0); i0 = MIN(i, i0); j1 = MAX(j, j1); i1 = MAX(i, i1); G2P(clip_region.max.x, clip_region.min.y, tx, j, i); j0 = MIN(j, j0); i0 = MIN(i, i0); j1 = MAX(j, j1); i1 = MAX(i, i1); j0 = MAX(j0, 0); j0 = MIN(j0, W-1); j1 = MAX(j1, 0); j1 = MIN(j1, W-1); i0 = MAX(i0, 0); i0 = MIN(i0, H-1); i1 = MAX(i1, 0); i1 = MIN(i1, H-1); } w = j1 - j0 + 1; h = i1 - i0 + 1; /*fprintf(stderr, "visible region in raster is %i %i %i %i\n", j0, i0, j1, i1);*/ RAL_CHECK(w > 0 AND h > 0); /* the corners of the raster clip */ P2G(j0, i0, t, p0.x, p0.y); P2G(j1+1, i0, t, p1.x, p1.y); P2G(j1+1, i1+1, t, p2.x, p2.y); P2G(j0, i1+1, t, p3.x, p3.y); /*fprintf(stderr, "source corners: (%f,%f %f,%f %f,%f %f,%f)\n", p0.x, p0.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);*/ /* the width and height of the resized raster clip */ /* the resized clip has the same corner coordinates as the clip */ ws = round(sqrt((p1.x-p0.x)*(p1.x-p0.x)+(p1.y-p0.y)*(p1.y-p0.y))/cell_size); hs = round(sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y))/cell_size); /*fprintf(stderr, "clipped source size is %i, %i\n", ws, hs);*/ hBand = GDALGetRasterBand(dataset, band); RAL_CHECK(hBand); switch (GDALGetRasterDataType(hBand)) { case GDT_Byte: case GDT_UInt16: case GDT_Int16: case GDT_UInt32: case GDT_Int32: gd_datatype = RAL_INTEGER_GRID; switch (sizeof(RAL_INTEGER)) { /* hmm.. this breaks if INTEGER is unsigned */ case 1: datatype = GDT_Byte; break; case 2: datatype = GDT_Int16; break; case 4: datatype = GDT_Int32; break; default: RAL_CHECKM(0, ral_msg("Strange sizeof(INTEGER): %i",sizeof(RAL_INTEGER))); } break; case GDT_Float32: case GDT_Float64: gd_datatype = RAL_REAL_GRID; switch (sizeof(RAL_REAL)) { case 4: datatype = GDT_Float32; break; case 8: datatype = GDT_Float64; break; default: RAL_CHECKM(0, ral_msg("Strange sizeof(REAL): %i", sizeof(RAL_REAL))); } break; default: RAL_CHECKM(0, "complex data type not supported"); } /* size of the grid in display */ M = ceil(fabs(clip_region.max.y - clip_region.min.y)/cell_size); N = ceil(fabs(clip_region.max.x - clip_region.min.x)/cell_size); /*fprintf(stderr, "display size is %i, %i\n", N, M);*/ RAL_CHECK(gd_s = ral_grid_create(gd_datatype, hs, ws)); RAL_CHECK(gd_t = ral_grid_create(gd_datatype, M, N)); ral_grid_set_bounds_csnx(gd_t, cell_size, clip_region.min.x, clip_region.max.y); err = GDALRasterIO(hBand, GF_Read, j0, i0, w, h, gd_s->data, ws, hs, datatype, 0, 0); RAL_CHECK(err == CE_None); { int success; double nodata_value = GDALGetRasterNoDataValue(hBand, &success); if (success) { RAL_CHECK(ral_grid_set_real_nodata_value(gd_t, nodata_value)); RAL_CHECK(ral_grid_set_all_nodata(gd_t)); } else { RAL_CHECK(ral_grid_set_real_nodata_value(gd_t, -9999)); /* change this! */ RAL_CHECK(ral_grid_set_all_nodata(gd_t)); } } /* from source to target */ { /* b = from p0 to p1 */ double bx = p1.x - p0.x; double by = p1.y - p0.y; double b = east_up ? 0 : bx/by; double b2 = east_up ? 1 : sqrt(1+1/b/b); /*fprintf(stderr, "b = %f %f (%f)\n", bx, by, b);*/ /* c = from p0 to p3 */ double cx = p3.x - p0.x; double cy = p3.y - p0.y; double c = north_up ? 0 : cx/cy; double c2 = north_up ? 1 : sqrt(1+1/c/c); /*fprintf(stderr, "c = %f %f (%f)\n", cx, cy, c);*/ ral_cell cs, ct; switch (gd_t->datatype) { case RAL_REAL_GRID: RAL_FOR(ct, gd_t) { /* p = the location of the center of the target pixel in georeferenced coordinates */ double px = clip_region.min.x + cell_size*(ct.j+0.5); double py = clip_region.max.y - cell_size*(ct.i+0.5); /* vector a = from p0 to p */ double ax = px - p0.x; double ay = py - p0.y; /* x = the vector from p0 to the beginning of y */ double x = east_up ? ay : (north_up ? ax : (ax-c*ay)/(1-c/b)); if (!east_up AND !north_up AND (x/b > 0)) continue; /* the length */ x = fabs(x)*b2; /* y = length of the parallel to c vector from b to p */ double y = east_up ? ax : (north_up ? ay : (ax-b*ay)/(1-b/c)); if (!east_up AND !north_up AND (y/c < 0)) continue; /* the length */ y = fabs(y)*c2; ral_cell cs; /* the coordinates in the clipped raster */ cs.j = floor(x/cell_size); cs.i = floor(y/cell_size); if (RAL_GRID_CELL_IN(gd_s, cs)) RAL_REAL_GRID_CELL(gd_t, ct) = RAL_REAL_GRID_CELL(gd_s, cs); } break; case RAL_INTEGER_GRID: RAL_FOR(ct, gd_t) { /* p = the location of the center of the target pixel in georeferenced coordinates */ double px = clip_region.min.x + cell_size*(ct.j+0.5); double py = clip_region.max.y - cell_size*(ct.i+0.5); /* vector a = from p0 to p */ double ax = px - p0.x; double ay = py - p0.y; /* x = the vector from p0 to the beginning of y */ double x = east_up ? ay : (north_up ? ax : (ax-c*ay)/(1-c/b)); if (!east_up AND !north_up AND (x/b > 0)) continue; /* the length */ x = fabs(x)*b2; /* y = length of the parallel to c vector from b to p */ double y = east_up ? ax : (north_up ? ay : (ax-b*ay)/(1-b/c)); if (!east_up AND !north_up AND (y/c < 0)) continue; /* the length */ y = fabs(y)*c2; ral_cell cs; /* the coordinates in the clipped raster */ cs.j = floor(x/cell_size); cs.i = floor(y/cell_size); /* if ((cs.i == 0 AND cs.j == 0) OR (cs.i == hs-1 AND cs.j == 0) OR (cs.i == 0 AND cs.j == ws-1) OR (cs.i == hs-1 AND cs.j == ws-1) OR (ct.i == 0 AND ct.j == 0) OR (ct.i == M-1 AND ct.j == N-1)) { fprintf(stderr, "p = %f %f\n", px, py); fprintf(stderr, "a = %f %f\n", ax, ay); fprintf(stderr, "x = %f\n", x); fprintf(stderr, "y = %f\n", y); fprintf(stderr, "copy %i, %i -> %i, %i\n", cs.j, cs.i, ct.j, ct.i); } */ if (RAL_GRID_CELL_IN(gd_s, cs)) { RAL_INTEGER_GRID_CELL(gd_t, ct) = RAL_INTEGER_GRID_CELL(gd_s, cs); } } }
bool QgsAlignRaster::createAndWarp( const Item& raster ) { GDALDriverH hDriver = GDALGetDriverByName( "GTiff" ); if ( !hDriver ) { mErrorMessage = QString( "GDALGetDriverByName(GTiff) failed." ); return false; } // Open the source file. GDALDatasetH hSrcDS = GDALOpen( raster.inputFilename.toLocal8Bit().constData(), GA_ReadOnly ); if ( !hSrcDS ) { mErrorMessage = QObject::tr( "Unable to open input file: " ) + raster.inputFilename; return false; } // Create output with same datatype as first input band. int bandCount = GDALGetRasterCount( hSrcDS ); GDALDataType eDT = GDALGetRasterDataType( GDALGetRasterBand( hSrcDS, 1 ) ); // Create the output file. GDALDatasetH hDstDS; hDstDS = GDALCreate( hDriver, raster.outputFilename.toLocal8Bit().constData(), mXSize, mYSize, bandCount, eDT, NULL ); if ( !hDstDS ) { GDALClose( hSrcDS ); mErrorMessage = QObject::tr( "Unable to create output file: " ) + raster.outputFilename; return false; } // Write out the projection definition. GDALSetProjection( hDstDS, mCrsWkt.toAscii().constData() ); GDALSetGeoTransform( hDstDS, ( double* )mGeoTransform ); // Copy the color table, if required. GDALColorTableH hCT = GDALGetRasterColorTable( GDALGetRasterBand( hSrcDS, 1 ) ); if ( hCT != NULL ) GDALSetRasterColorTable( GDALGetRasterBand( hDstDS, 1 ), hCT ); // ----------------------------------------------------------------------- // Setup warp options. GDALWarpOptions* psWarpOptions = GDALCreateWarpOptions(); psWarpOptions->hSrcDS = hSrcDS; psWarpOptions->hDstDS = hDstDS; psWarpOptions->nBandCount = GDALGetRasterCount( hSrcDS ); psWarpOptions->panSrcBands = ( int * ) CPLMalloc( sizeof( int ) * psWarpOptions->nBandCount ); psWarpOptions->panDstBands = ( int * ) CPLMalloc( sizeof( int ) * psWarpOptions->nBandCount ); for ( int i = 0; i < psWarpOptions->nBandCount; ++i ) { psWarpOptions->panSrcBands[i] = i + 1; psWarpOptions->panDstBands[i] = i + 1; } psWarpOptions->eResampleAlg = ( GDALResampleAlg ) raster.resampleMethod; // our progress function psWarpOptions->pfnProgress = _progress; psWarpOptions->pProgressArg = this; // Establish reprojection transformer. psWarpOptions->pTransformerArg = GDALCreateGenImgProjTransformer( hSrcDS, GDALGetProjectionRef( hSrcDS ), hDstDS, GDALGetProjectionRef( hDstDS ), FALSE, 0.0, 1 ); psWarpOptions->pfnTransformer = GDALGenImgProjTransform; double rescaleArg[2]; if ( raster.rescaleValues ) { rescaleArg[0] = raster.srcCellSizeInDestCRS; // source cell size rescaleArg[1] = mCellSizeX * mCellSizeY; // destination cell size psWarpOptions->pfnPreWarpChunkProcessor = rescalePreWarpChunkProcessor; psWarpOptions->pfnPostWarpChunkProcessor = rescalePostWarpChunkProcessor; psWarpOptions->pPreWarpProcessorArg = rescaleArg; psWarpOptions->pPostWarpProcessorArg = rescaleArg; // force use of float32 data type as that is what our pre/post-processor uses psWarpOptions->eWorkingDataType = GDT_Float32; } // Initialize and execute the warp operation. GDALWarpOperation oOperation; oOperation.Initialize( psWarpOptions ); oOperation.ChunkAndWarpImage( 0, 0, mXSize, mYSize ); GDALDestroyGenImgProjTransformer( psWarpOptions->pTransformerArg ); GDALDestroyWarpOptions( psWarpOptions ); GDALClose( hDstDS ); GDALClose( hSrcDS ); return true; }
int main (int argc, const char *argv[]) { GDALDriverH hDriver; double adfGeoTransform[6]; GDALDatasetH in_Dataset; GDALDatasetH out_Dataset; double *data_scan_line; char *out_scan_line; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; int bands; int xsize; double lower_fiddle, upper_fiddle; double adfMinMax[2]; /* These are hard coded for now - need to figure out a better way to handle this.. */ double palette_in[256] = { 0.0, 1.00011, 1.9999649999999998, 3.000075, 3.9999299999999995, 5.00004, 5.999895, 7.000005, 8.000115, 8.99997, 10.00008, 10.999935, 12.000044999999998, 12.9999, 14.00001, 15.00012, 15.999975, 17.000085000000002, 17.99994, 19.00005, 19.999905000000002, 21.000014999999998, 22.000125, 22.99998, 24.000089999999997, 24.999945, 26.000055, 26.99991, 28.00002, 28.999875000000003, 29.999985, 31.000094999999998, 31.99995, 33.00006, 33.999915, 35.000024999999994, 35.99988, 36.999990000000004, 38.0001, 38.999955, 40.000065, 40.99992, 42.000029999999995, 42.999885, 43.999995000000006, 45.000105, 45.99996, 47.00007, 47.999925000000005, 49.000035, 49.99989, 51.0, 52.00011, 52.999965, 54.000075, 54.99993, 56.00004, 56.999895, 58.000004999999994, 59.000115, 59.99997, 61.000080000000004, 61.999935, 63.000045, 63.9999, 65.00001, 66.00012, 66.999975, 68.000085, 68.99994, 70.00004999999999, 70.999905, 72.000015, 73.000125, 73.99998000000001, 75.00009, 75.999945, 77.00005499999999, 77.99991, 79.00002, 79.99987499999999, 80.99998500000001, 82.000095, 82.99995, 84.00005999999999, 84.999915, 86.00002500000001, 86.99987999999999, 87.99999000000001, 89.0001, 89.999955, 91.00006499999999, 91.99992, 93.00003, 93.99988499999999, 94.999995, 96.000105, 96.99996, 98.00007, 98.999925, 100.000035, 100.99989, 102.0, 103.00011, 103.999965, 105.000075, 105.99993, 107.00004, 107.999895, 109.000005, 110.00011500000001, 110.99997, 112.00008, 112.99993500000001, 114.000045, 114.9999, 116.00000999999999, 117.00012, 117.999975, 119.000085, 119.99994, 121.00005, 121.999905, 123.00001499999999, 124.000125, 124.99998000000001, 126.00009, 126.999945, 128.000055, 128.99991, 130.00002, 130.999875, 131.99998499999998, 133.000095, 133.99995, 135.00006, 135.999915, 137.00002500000002, 137.99988, 138.99999, 140.00009999999997, 140.999955, 142.000065, 142.99991999999997, 144.00003, 144.999885, 145.99999499999998, 147.000105, 147.99996000000002, 149.00007, 149.999925, 151.00003500000003, 151.99989, 153.0, 154.00010999999998, 154.999965, 156.000075, 156.99992999999998, 158.00004, 158.999895, 160.000005, 161.000115, 161.99997000000002, 163.00008, 163.999935, 165.000045, 165.9999, 167.00001, 168.00011999999998, 168.999975, 170.000085, 170.99993999999998, 172.00005000000002, 172.999905, 174.000015, 175.000125, 175.99998000000002, 177.00009, 177.999945, 179.00005499999997, 179.99991, 181.00002, 181.999875, 182.999985, 184.00009500000002, 184.99994999999998, 186.00006, 186.99991500000002, 188.000025, 188.99988, 189.99999, 191.0001, 191.999955, 193.00006499999998, 193.99992, 195.00003, 195.99988499999998, 196.999995, 198.00010500000002, 198.99996, 200.00007, 200.99992500000002, 202.000035, 202.99989, 204.0, 205.00011, 205.999965, 207.00007499999998, 207.99993, 209.00004, 209.99989499999998, 211.00000500000002, 212.000115, 212.99997, 214.00008, 214.999935, 216.000045, 216.9999, 218.00001, 219.00012, 219.999975, 221.00008499999998, 221.99994, 223.00005000000002, 223.99990499999998, 225.00001500000002, 226.000125, 226.99998, 228.00009, 228.999945, 230.000055, 230.99991, 232.00001999999998, 232.999875, 233.999985, 235.000095, 235.99995, 237.00006, 237.999915, 239.000025, 239.99988, 240.99999, 242.0001, 242.999955, 244.000065, 244.99992, 246.00002999999998, 246.999885, 247.999995, 249.000105, 249.99996000000002, 251.00007, 251.999925, 253.000035, 253.99989, 255.0 }; double palette_out[256] = { 0.0, 0.042075, 0.08415, 0.126225, 0.169065, 0.21216, 0.255765, 0.29988, 0.345015, 0.390915, 0.437835, 0.48602999999999996, 0.5352450000000001, 0.58599, 0.63801, 0.69156, 0.7468950000000001, 0.804015, 0.8629199999999999, 0.9238649999999999, 0.98685, 1.05213, 1.119705, 1.18983, 1.26225, 1.337475, 1.415505, 1.49634, 1.580235, 1.6674449999999998, 1.75746, 1.851045, 1.9482, 2.04867, 2.152965, 2.2608300000000003, 2.3727750000000003, 2.4885450000000002, 2.6083950000000002, 2.73258, 2.8611000000000004, 2.993955, 3.1313999999999997, 3.27369, 3.42057, 3.572295, 3.72912, 3.891045, 4.05807, 4.23045, 4.408440000000001, 4.591785, 4.780995, 4.975815, 5.1765, 5.38305, 5.595975, 5.8150200000000005, 6.040185, 6.27198, 6.510405, 6.755205, 7.007145, 7.265715, 7.53117, 7.8040199999999995, 8.084010000000001, 8.37114, 8.66592, 8.968095, 9.27792, 9.59565, 9.92103, 10.25457, 10.596015, 10.945875, 11.30415, 11.670585, 12.04569, 12.429465, 12.82191, 13.223279999999999, 13.63383, 14.053305, 14.48196, 14.919794999999999, 15.36732, 15.82428, 16.29093, 16.767270000000003, 17.253555, 17.749785, 18.256215, 18.925845, 19.456245000000003, 19.99863, 20.552745, 21.11859, 21.696165, 22.285725, 22.887014999999998, 23.500035, 24.125295, 24.762285, 25.411260000000002, 26.071965, 26.74491, 27.42984, 28.12701, 28.835910000000002, 29.55705, 30.29043, 31.035795, 31.7934, 32.56299, 33.345075, 34.139145, 34.94571, 35.764514999999996, 36.595305, 37.438845, 38.294625, 39.162645, 40.04316, 40.935915, 41.84142, 42.759165, 43.68966, 44.632394999999995, 45.58788, 46.55586, 47.536335, 48.529560000000004, 49.535535, 50.554005000000004, 51.58497, 52.62894, 53.68566, 54.75513, 55.837095, 56.932064999999994, 58.040040000000005, 59.160765, 60.294239999999995, 61.44072, 62.59995000000001, 63.772439999999996, 64.95768000000001, 66.15592500000001, 67.36743, 68.591685, 69.82919999999999, 71.07972, 72.343245, 73.620285, 74.910075, 76.21337999999999, 77.52968999999999, 78.85926, 80.20209, 81.55843499999999, 82.927785, 84.31065, 85.66419, 87.10264500000001, 88.611225, 90.18712500000001, 91.82779500000001, 93.52992, 95.291205, 97.108845, 98.979525, 100.90095, 102.87006, 104.884305, 106.94037, 109.03596, 111.16827, 113.33424000000001, 115.531065, 117.756195, 120.00657, 122.27964, 124.572345, 126.88213499999999, 129.20595, 131.54124, 133.8852, 136.23477, 138.58714500000002, 140.939775, 143.289855, 145.63458, 147.97089, 150.296235, 152.60781, 154.902555, 157.17817499999998, 159.431355, 161.65929, 163.859685, 166.02948, 168.165615, 170.26554, 172.32645, 174.34554, 176.320005, 178.24704, 180.292905, 182.130945, 183.953685, 185.76138, 187.554285, 189.33291, 191.09751, 192.84834, 194.58591, 196.310475, 198.02229, 199.72161, 201.4092, 203.084805, 204.74944499999998, 206.402865, 208.04557499999999, 209.67808499999998, 211.30065, 212.913525, 214.516965, 216.11148, 217.69758000000002, 219.27501, 220.84479, 222.406665, 223.9614, 225.50924999999998, 227.05047000000002, 228.585315, 230.114295, 231.63766500000003, 233.15568000000002, 234.66885000000002, 236.17743, 237.681675, 239.18184, 240.67869, 242.172225, 243.66295499999998, 245.15088, 246.636765, 248.12061000000003, 249.602925, 251.083965, 252.56424, 254.04375, 255.0 }; GDALAllRegister (); /* ussage.. */ if (argc != 3) ussage (); /* Set cache to something reasonable.. - 1/2 gig */ CPLSetConfigOption ("GDAL_CACHEMAX", "512"); /* open datasets.. */ in_Dataset = GDAL_open_read (argv[1]); out_Dataset = make_me_a_sandwitch (&in_Dataset, argv[2]); /* Basic info on source dataset.. */ GDALGetBlockSize (GDALGetRasterBand (in_Dataset, 1), &nBlockXSize, &nBlockYSize); printf ("Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName (GDALGetRasterDataType (GDALGetRasterBand (in_Dataset, 1))), GDALGetColorInterpretationName (GDALGetRasterColorInterpretation (GDALGetRasterBand (in_Dataset, 1)))); /* Loop though bands, scaling the data.. */ xsize = GDALGetRasterXSize (in_Dataset); data_scan_line = (double *) CPLMalloc (sizeof (double) * xsize); out_scan_line = (char *) CPLMalloc (sizeof (char) * xsize); for (bands = 1; bands <= GDALGetRasterCount (in_Dataset); bands++) { int x; double min = 9999999.0, max = 0.0; /* probibly a better way to set these.. */ double dmin, dmax, middle; GDALRasterBandH data_band, out_band; int y_index = 0; data_band = GDALGetRasterBand (in_Dataset, bands); out_band = GDALGetRasterBand (out_Dataset, bands); /* Set nodata for that band */ GDALSetRasterNoDataValue (out_band, 0.0); /*Find Min,Max, required for scaling */ for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++) { /* Read data.. */ GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1, data_scan_line, xsize, 1, GDT_Float64, 0, 0); for (x = 0; x < xsize; x++) { if (data_scan_line[x] < MAX_MODIS && data_scan_line[x] > MIN_VALUE) { if (data_scan_line[x] > max) max = data_scan_line[x]; else if (data_scan_line[x] < min) min = data_scan_line[x]; } } } dmax = (double) max; dmin = (double) min; printf ("Info: For Band %d -> Min=%g,Max=%g\n", bands, dmin, dmax); for (y_index = 0; y_index < GDALGetRasterYSize (in_Dataset); y_index++) { double scaled; /* Read data.. */ GDALRasterIO (data_band, GF_Read, 0, y_index, xsize, 1, data_scan_line, xsize, 1, GDT_Float64, 0, 0); /* scale each .. */ for (x = 0; x < xsize; x++) { out_scan_line[x] = scale (palette_in, palette_out, data_scan_line[x], dmin, dmax); } /* now write out band.. */ GDALRasterIO (out_band, GF_Write, 0, y_index, xsize, 1, out_scan_line, xsize, 1, GDT_Byte, 0, 0); } } /* close file, and we are done. */ GDALClose (out_Dataset); }
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 ); }
void CUtils::setRasterLine(GDALRasterBandH hBand, int current_row, int cols, void* pLineValues) { GDALRasterIO(hBand, GF_Write, 0, current_row, cols, 1, pLineValues, cols, 1, GDALGetRasterDataType(hBand), 0, 0); }
void CUtils::setRasterValue(GDALRasterBandH hBand, int current_row, int current_col, void* pValue) { GDALRasterIO(hBand, GF_Write, current_col, current_row, 1, 1, pValue, 1, 1, GDALGetRasterDataType(hBand), 0, 0); }
int main(int argc, char* argv[]) { fprintf(stderr, "TASSELED CAP TRANSFORMATION\nVersion %s.%s. Free software. GNU General Public License, version 3\n", PROG_VERSION, DATE_VERSION); fprintf(stderr, "Copyright (C) 2016 Igor Garkusha.\nUkraine, Dnipro\n\n"); if(argc!=5) { fputs("Input parameters not found!\n", stderr); printHelp(); fputs("\n", stderr); return 1; } GDALDatasetH pSrcDataset = NULL; GDALDatasetH pDstDataset = NULL; GDALRasterBandH pSrcBand = NULL; GDALRasterBandH pDstBand = NULL; GDALDriverH pDriver = NULL; GDALAllRegister(); bool flagNoData = (atoi(argv[argc-1]) == 1)?true:false; int sensorIndexFlag = OLI; if( strcmp(argv[argc-2], "oli") == 0) sensorIndexFlag = OLI; else if( strcmp(argv[argc-2], "etm") == 0) sensorIndexFlag = ETM; else if( strcmp(argv[argc-2], "tm4") == 0) sensorIndexFlag = TM4; else if( strcmp(argv[argc-2], "tm5") == 0) sensorIndexFlag = TM5; else //if( strcmp(argv[argc-2], "msi10") == 0) sensorIndexFlag = S2AMSI10; //else if( strcmp(argv[argc-2], "msi") == 0) sensorIndexFlag = S2AMSI; pSrcDataset = GDALOpen( argv[1], GA_ReadOnly ); int bands = 0; if(pSrcDataset!=NULL) { if(CUtils::isFloat32DataType(pSrcDataset)) { bands = GDALGetRasterCount(pSrcDataset); if( ((bands == 6)||(bands == 4)) ) { pSrcBand = GDALGetRasterBand(pSrcDataset, 1); if(pSrcBand != NULL) { int cols = GDALGetRasterBandXSize(pSrcBand); int rows = GDALGetRasterBandYSize(pSrcBand); float NoDataValue = 0; pDriver = GDALGetDriverByName("GTiff"); char **papszOptions = NULL; pDstDataset = GDALCreate(pDriver, argv[2], cols, rows, COUNT_OUT_BANDS, GDT_Float32, papszOptions); double adfGeoTransform[6]={0}; GDALGetGeoTransform(pSrcDataset, adfGeoTransform ); const char *szProjection = GDALGetProjectionRef(pSrcDataset); GDALSetGeoTransform(pDstDataset, adfGeoTransform ); GDALSetProjection(pDstDataset, szProjection ); pDstBand = GDALGetRasterBand(pDstDataset, 1); float *pSrcLine = NULL; float *pDstLine = NULL; pSrcLine = (float*)CPLMalloc(sizeof(GDALGetRasterDataType(pSrcBand))*cols); pDstLine = (float*)CPLMalloc(sizeof(GDALGetRasterDataType(pDstBand))*cols); if(flagNoData == false) { for(int resultBandNumber=1; resultBandNumber <= COUNT_OUT_BANDS; resultBandNumber++) { fprintf(stderr, "Processing for band %d...\n", resultBandNumber); pDstBand = GDALGetRasterBand(pDstDataset, resultBandNumber); int pr = CUtils::progress_ln_ex(stderr, 0, 0, START_PROGRESS); for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) pDstLine[j] = 0; for(int currentBandNumber=1; currentBandNumber <= bands; currentBandNumber++) { pSrcBand = GDALGetRasterBand(pSrcDataset, currentBandNumber); GDALRasterIO(pSrcBand, GF_Read, 0, i, cols, 1, pSrcLine, cols, 1, GDALGetRasterDataType(pSrcBand), 0, 0 ); for(int j=0; j<cols; j++) pDstLine[j] += getTasseledCapValue(pSrcLine[j], sensorIndexFlag, resultBandNumber, currentBandNumber); } if(sensorIndexFlag == TM5) for(int j=0; j<cols; j++) pDstLine[j] += TM5_TCCoeff[resultBandNumber][6]; GDALRasterIO(pDstBand, GF_Write, 0, i, cols, 1, pDstLine, cols, 1, GDT_Float32, 0, 0 ); pr = CUtils::progress_ln_ex(stderr, i, rows, pr); } CUtils::progress_ln_ex(stderr, 0, 0, END_PROGRESS); } } else // WITH NODATA VALUE - pixel(1,1) { for(int resultBandNumber=1; resultBandNumber <= COUNT_OUT_BANDS; resultBandNumber++) { fprintf(stderr, "Processing for band %d...\n", resultBandNumber); pDstBand = GDALGetRasterBand(pDstDataset, resultBandNumber); int pr = CUtils::progress_ln_ex(stderr, 0, 0, START_PROGRESS); for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) pDstLine[j] = 0; for(int currentBandNumber=1; currentBandNumber <= bands; currentBandNumber++) { pSrcBand = GDALGetRasterBand(pSrcDataset, currentBandNumber); NoDataValue = CUtils::getFloatNoDataValueAsBackground(pSrcBand); GDALRasterIO(pSrcBand, GF_Read, 0, i, cols, 1, pSrcLine, cols, 1, GDALGetRasterDataType(pSrcBand), 0, 0 ); for(int j=0; j<cols; j++) { if(NoDataValue == pSrcLine[j]) pDstLine[j] = NoDataValue; else pDstLine[j] += getTasseledCapValue(pSrcLine[j], sensorIndexFlag, resultBandNumber, currentBandNumber); } } if(sensorIndexFlag == TM5) { for(int j=0; j<cols; j++) if(NoDataValue != pDstLine[j]) pDstLine[j] += TM5_TCCoeff[resultBandNumber][6]; } GDALRasterIO(pDstBand, GF_Write, 0, i, cols, 1, pDstLine, cols, 1, GDT_Float32, 0, 0 ); pr = CUtils::progress_ln_ex(stderr, i, rows, pr); } CUtils::progress_ln_ex(stderr, 0, 0, END_PROGRESS); } } CPLFree(pSrcLine); pSrcLine = NULL; CPLFree(pDstLine); pDstLine = NULL; if(flagNoData) CUtils::calculateFloatGeoTIFFStatistics(pDstDataset, -1, true); else CUtils::calculateFloatGeoTIFFStatistics(pDstDataset, -1, false); fputs("Output band:\n\tband1: Brightness, band2: Greenness (Vegetation), band3: Wetness, band4: Haze\n\n", stderr); fputs("\nEnd Processing.\n\n", stderr); } } else { fputs("\nERROR: Source Band Number is Invalid!!!\n", stderr); fprintf(stderr, "Source Bands Number: %d!\n\n", bands); printHelp(); } } if(pSrcDataset!=NULL) { GDALClose(pSrcDataset); } if(pDstDataset!=NULL) { GDALClose(pDstDataset); } } return 0; }
int main( int argc, char ** argv ) { GDALDatasetH hDataset; GDALRasterBandH hBand; int i, iBand; double adfGeoTransform[6]; GDALDriverH hDriver; char **papszMetadata; int bComputeMinMax = FALSE; if( !GDALBridgeInitialize( "..", stderr ) ) { fprintf( stderr, "Unable to intiailize GDAL bridge.\n" ); exit( 10 ); } if( argc > 1 && strcmp(argv[1],"-mm") == 0 ) { bComputeMinMax = TRUE; argv++; } GDALAllRegister(); hDataset = GDALOpen( argv[1], GA_ReadOnly ); if( hDataset == NULL ) { fprintf( stderr, "GDALOpen failed - %d\n%s\n", CPLGetLastErrorNo(), CPLGetLastErrorMsg() ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Report general info. */ /* -------------------------------------------------------------------- */ hDriver = GDALGetDatasetDriver( hDataset ); printf( "Driver: %s/%s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver ) ); printf( "Size is %d, %d\n", GDALGetRasterXSize( hDataset ), GDALGetRasterYSize( hDataset ) ); /* -------------------------------------------------------------------- */ /* Report projection. */ /* -------------------------------------------------------------------- */ if( GDALGetProjectionRef( hDataset ) != NULL ) { OGRSpatialReferenceH hSRS; char *pszProjection; pszProjection = (char *) GDALGetProjectionRef( hDataset ); hSRS = OSRNewSpatialReference(NULL); if( OSRImportFromWkt( hSRS, &pszProjection ) == CE_None ) { char *pszPrettyWkt = NULL; OSRExportToPrettyWkt( hSRS, &pszPrettyWkt, FALSE ); printf( "Coordinate System is:\n%s\n", pszPrettyWkt ); } else printf( "Coordinate System is `%s'\n", GDALGetProjectionRef( hDataset ) ); OSRDestroySpatialReference( hSRS ); } /* -------------------------------------------------------------------- */ /* Report Geotransform. */ /* -------------------------------------------------------------------- */ if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ) { printf( "Origin = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3] ); printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5] ); } /* -------------------------------------------------------------------- */ /* Report GCPs. */ /* -------------------------------------------------------------------- */ if( GDALGetGCPCount( hDataset ) > 0 ) { printf( "GCP Projection = %s\n", GDALGetGCPProjection(hDataset) ); for( i = 0; i < GDALGetGCPCount(hDataset); i++ ) { const GDAL_GCP *psGCP; psGCP = GDALGetGCPs( hDataset ) + i; printf( "GCP[%3d]: Id=%s, Info=%s\n" " (%g,%g) -> (%g,%g,%g)\n", i, psGCP->pszId, psGCP->pszInfo, psGCP->dfGCPPixel, psGCP->dfGCPLine, psGCP->dfGCPX, psGCP->dfGCPY, psGCP->dfGCPZ ); } } /* -------------------------------------------------------------------- */ /* Report metadata. */ /* -------------------------------------------------------------------- */ papszMetadata = GDALGetMetadata( hDataset, NULL ); if( papszMetadata != NULL ) { printf( "Metadata:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } /* -------------------------------------------------------------------- */ /* Report subdatasets. */ /* -------------------------------------------------------------------- */ papszMetadata = GDALGetMetadata( hDataset, "SUBDATASETS" ); if( papszMetadata != NULL ) { printf( "Subdatasets:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } /* -------------------------------------------------------------------- */ /* Report corners. */ /* -------------------------------------------------------------------- */ printf( "Corner Coordinates:\n" ); GDALInfoReportCorner( hDataset, "Upper Left", 0.0, 0.0 ); GDALInfoReportCorner( hDataset, "Lower Left", 0.0, GDALGetRasterYSize(hDataset)); GDALInfoReportCorner( hDataset, "Upper Right", GDALGetRasterXSize(hDataset), 0.0 ); GDALInfoReportCorner( hDataset, "Lower Right", GDALGetRasterXSize(hDataset), GDALGetRasterYSize(hDataset) ); GDALInfoReportCorner( hDataset, "Center", GDALGetRasterXSize(hDataset)/2.0, GDALGetRasterYSize(hDataset)/2.0 ); /* ==================================================================== */ /* Loop over bands. */ /* ==================================================================== */ for( iBand = 0; iBand < GDALGetRasterCount( hDataset ); iBand++ ) { double dfMin, dfMax, adfCMinMax[2], dfNoData; int bGotMin, bGotMax, bGotNodata; int nBlockXSize, nBlockYSize; hBand = GDALGetRasterBand( hDataset, iBand+1 ); GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize ); printf( "Band %d Block=%dx%d Type=%d, ColorInterp=%d\n", iBand+1, nBlockXSize, nBlockYSize, GDALGetRasterDataType(hBand), GDALGetRasterColorInterpretation(hBand) ); dfMin = GDALGetRasterMinimum( hBand, &bGotMin ); dfMax = GDALGetRasterMaximum( hBand, &bGotMax ); printf( " Min=%.3f/%d, Max=%.3f/%d", dfMin, bGotMin, dfMax, bGotMax); if( bComputeMinMax ) { GDALComputeRasterMinMax( hBand, TRUE, adfCMinMax ); printf( ", Computed Min/Max=%.3f,%.3f", adfCMinMax[0], adfCMinMax[1] ); } printf( "\n" ); dfNoData = GDALGetRasterNoDataValue( hBand, &bGotNodata ); if( bGotNodata ) { printf( " NoData Value=%g\n", dfNoData ); } if( GDALGetOverviewCount(hBand) > 0 ) { int iOverview; printf( " Overviews: " ); for( iOverview = 0; iOverview < GDALGetOverviewCount(hBand); iOverview++ ) { GDALRasterBandH hOverview; if( iOverview != 0 ) printf( ", " ); hOverview = GDALGetOverview( hBand, iOverview ); printf( "%dx%d", GDALGetRasterBandXSize( hOverview ), GDALGetRasterBandYSize( hOverview ) ); } printf( "\n" ); } papszMetadata = GDALGetMetadata( hBand, NULL ); if( papszMetadata != NULL ) { printf( "Metadata:\n" ); for( i = 0; papszMetadata[i] != NULL; i++ ) { printf( " %s\n", papszMetadata[i] ); } } if( GDALGetRasterColorInterpretation(hBand) == GCI_PaletteIndex ) { GDALColorTableH hTable; int i; hTable = GDALGetRasterColorTable( hBand ); printf( " Color Table (%s with %d entries)\n", GDALGetPaletteInterpretationName( GDALGetPaletteInterpretation( hTable )), GDALGetColorEntryCount( hTable ) ); for( i = 0; i < GDALGetColorEntryCount( hTable ); i++ ) { GDALColorEntry sEntry; GDALGetColorEntryAsRGB( hTable, i, &sEntry ); printf( " %3d: %d,%d,%d,%d\n", i, sEntry.c1, sEntry.c2, sEntry.c3, sEntry.c4 ); } } } GDALClose( hDataset ); exit( 0 ); }
bool toprsGadlReader::open() { if(isOpen()) { close(); } std::string driverNameTmp; if (theSubDatasets.size() == 0) { // Note: Cannot feed GDALOpen a NULL string! if (theImageFile.size()) { theDataset = GDALOpen(theImageFile.c_str(), GA_ReadOnly); if( theDataset == 0 ) { return false; } } else { return false; } // Check if it is nitf data for deciding whether or not open each sub-dataset //This will be removed eventually when toprs can handle 2GB nitf file. GDALDriverH driverTmp = GDALGetDatasetDriver(theDataset); bool isNtif = false; if (driverTmp != 0) { driverNameTmp = std::string(GDALGetDriverShortName(driverTmp)); std::transform(driverNameTmp.begin(), driverNameTmp.end(), driverNameTmp.begin(), [&](char ch){return toupper(ch);}); if (driverNameTmp == "NITF") { isNtif = true; } } // Check for sub data sets... char** papszMetadata = GDALGetMetadata( theDataset, "SUBDATASETS" ); if( CSLCount(papszMetadata) > 0 ) { theSubDatasets.clear(); for( int i = 0; papszMetadata[i] != 0; ++i ) { std::string os = papszMetadata[i]; if (os.find("_NAME=") != std::string::npos) { //Sub sets have already been set. Open each sub-dataset really slow down the process //specially for hdf data which sometimes has over 100 sub-datasets. Since following code //only for ntif cloud checking, so only open each sub-dataset here if the dataset is //nitf. This will be removed eventually when toprs can handle 2GB nitf file. //Otherwise open a sub-dataset when setCurrentEntry() gets called. if (isNtif) { GDALDatasetH subDataset = GDALOpen(filterSubDatasetsString(os).c_str(), GA_ReadOnly); if ( subDataset != 0 ) { // "Worldview ingest should ignore subimages when NITF_ICAT=CLOUD" // Hack: Ignore NITF subimages marked as cloud layers. std::string nitfIcatTag( GDALGetMetadataItem( subDataset, "NITF_ICAT", "" ) ); if ( nitfIcatTag.find("CLOUD") == std::string::npos ) { theSubDatasets.push_back(filterSubDatasetsString(os)); } } GDALClose(subDataset); } else { theSubDatasets.push_back(filterSubDatasetsString(os)); } } } //--- // Have multiple entries. We're going to default to open the first // entry like cidcadrg. //--- close(); theDataset = GDALOpen(theSubDatasets[theEntryNumberToRender].c_str(), GA_ReadOnly); if (theDataset == 0) { return false; } } // End of has subsets block. } // End of "if (theSubdatasets.size() == 0)" else { // Sub sets have already been set. theDataset = GDALOpen(theSubDatasets[theEntryNumberToRender].c_str(), GA_ReadOnly); if (theDataset == 0) { return false; } } // Set the driver. theDriver = GDALGetDatasetDriver( theDataset ); if(!theDriver) return false; theGdtType = GDT_Byte; theOutputGdtType = GDT_Byte; if(getNumberOfInputBands() < 1 ) { if(CSLCount(GDALGetMetadata(theDataset, "SUBDATASETS"))) { std::cout << "torsGdalReader::open WARNING:" << "\nHas multiple sub datasets and need to set the data before" << " we can get to the bands" << std::endl; } close(); std::cout << "torsGdalReader::open WARNING:" << "\nNo band data present in torsGdalReader::open" << std::endl; return false; } toprs_int32 i = 0; GDALRasterBandH bBand = GDALGetRasterBand( theDataset, 1 ); theGdtType = GDALGetRasterDataType(bBand); char** papszMetadata = GDALGetMetadata( bBand, NULL ); if (CSLCount(papszMetadata) > 0) { for(int i = 0; papszMetadata[i] != NULL; i++ ) { std::string metaStr = papszMetadata[i]; if (metaStr.find("AREA_OR_POINT") != std::string::npos) { //std::string pixel_is_point_or_area = metaStr.split("=")[1]; //pixel_is_point_or_area.downcase(); //if (pixel_is_point_or_area.contains("area")) // thePixelType = TOPRS_PIXEL_IS_AREA; break; } } } if(!isIndexed(1)) { for(i = 0; i < GDALGetRasterCount(theDataset); ++i) { if(theGdtType != GDALGetRasterDataType(GDALGetRasterBand( theDataset,i+1 ))) { std::cout << "torsGdalReader::open WARNING" << "\nWe currently do not support different scalar type bands." << std::endl; close(); return false; } } } theOutputGdtType = theGdtType; switch(theGdtType) { case GDT_CInt16: { // theOutputGdtType = GDT_Int16; theIsComplexFlag = true; break; } case GDT_CInt32: { // theOutputGdtType = GDT_Int32; theIsComplexFlag = true; break; } case GDT_CFloat32: { // theOutputGdtType = GDT_Float32; theIsComplexFlag = true; break; } case GDT_CFloat64: { // theOutputGdtType = GDT_Float64; theIsComplexFlag = true; break; } default: { theIsComplexFlag = false; break; } } if((std::string(GDALGetDriverShortName( theDriver )) == "PNG")&& (getNumberOfInputBands() == 4)) { theAlphaChannelFlag = true; } populateLut(); computeMinMax(); completeOpen(); theTile = toprsImgFactory::instance()->create(this); theSingleBandTile = toprsImgFactory::instance()->create(getInputScalarType(), 1); if ( m_preservePaletteIndexesFlag ) { theTile->setIndexedFlag(true); theSingleBandTile->setIndexedFlag(true); } theTile->initialize(); theSingleBandTile->initialize(); theGdalBuffer.resize(0); if(theIsComplexFlag) { theGdalBuffer.resize(theSingleBandTile->getSizePerBandInBytes()*2); } theImageBound = toprsIRect(0 ,0 ,GDALGetRasterXSize(theDataset)-1 ,GDALGetRasterYSize(theDataset)-1); int xSize=0, ySize=0; GDALGetBlockSize(GDALGetRasterBand( theDataset, 1 ), &xSize, &ySize); if (driverNameTmp.find("JPIP")!= std::string::npos || driverNameTmp.find("JP2")!= std::string::npos) { m_isBlocked = ((xSize > 1)&&(ySize > 1)); } else { m_isBlocked = false; } //if(m_isBlocked) //{ // setRlevelCache(); //} return true; }