/*! \file io.cpp With a little bit of a elaboration, should you feel it necessary. */ int printRasterInfo(const char* pszFilename) { /** An enum type. * The documentation block cannot be put after the enum! */ GDALDataset *poDataset; GDALAllRegister(); poDataset = (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly ); if( poDataset == NULL ) { std::cout << "Dataset " << pszFilename << " could not be opened." << std::endl; return -1; } else { std::cout << "Dataset: " << pszFilename << std::endl; double adfGeoTransform[6]; std::cout << " Driver: " << poDataset->GetDriver()->GetDescription() << "/" << poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) << std::endl; std::cout << " Size: " << poDataset->GetRasterXSize() << "x" << poDataset->GetRasterYSize() << "x" << poDataset->GetRasterCount() << std::endl; if( poDataset->GetProjectionRef() != NULL ) std::cout << " Projection: " << poDataset->GetProjectionRef() << std::endl; if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { std::cout << " Origin: (" << adfGeoTransform[0] << ", " << adfGeoTransform[3] << ")" << std::endl; std::cout << " Pixel Size: (" << adfGeoTransform[1] << ", " << adfGeoTransform[5] << std::endl; } } return 0; }
Raster* import_raster(string raster_filename, int band_number) { GDALAllRegister(); GDALDataset* poDataset = (GDALDataset *) GDALOpen( raster_filename.c_str(), GA_ReadOnly ); if( poDataset == NULL ) { cerr << "Error: Could not open raster data file" << endl; exit(1); } fprintf(stderr, "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); fprintf(stderr, "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() ); if( poDataset->GetProjectionRef() != NULL ) cerr << "Projection is `" << poDataset->GetProjectionRef() << "'" << endl;; GDALRasterBand* poBand = poDataset->GetRasterBand( band_number ); int nBlockXSize, nBlockYSize; poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); fprintf(stderr, "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName( poBand->GetColorInterpretation()) ); Raster* raster = extract_raster_attributes( poDataset ); raster->band = poBand; return raster; }
int main() { GDALDataset *poDataset; GDALAllRegister(); poDataset = (GDALDataset *) GDALOpen( "GE01.tif", GA_ReadOnly ); printf("Working! \n"); if( poDataset != NULL ){ //Get Dataset Information double adfGeoTransform[6]; printf( "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); printf( "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() ); if( poDataset->GetProjectionRef() != NULL ) printf( "Projection is `%s'\n", poDataset->GetProjectionRef() ); if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ){ printf( "Origin = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3] ); printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5] ); } //Fetch Raster Band GDALRasterBand *poBand; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; double adfMinMax[2]; poBand = poDataset->GetRasterBand( 1 ); poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName( poBand->GetColorInterpretation()) ); adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1] ); if( poBand->GetOverviewCount() > 0 ) printf( "Band has %d overviews.\n", poBand->GetOverviewCount() ); if( poBand->GetColorTable() != NULL ) printf( "Band has a color table with %d entries.\n", poBand->GetColorTable()->GetColorEntryCount() ); //Close Dataset GDALClose(poDataset); //Exit return 0; } }
/* changed to return proj4 string 20060212 RSB */ SEXP RGDAL_GetProjectionRef(SEXP sDataset) { OGRSpatialReference oSRS; char *pszSRS_WKT = NULL; SEXP ans; GDALDataset *pDataset = getGDALDatasetPtr(sDataset); installErrorHandler(); pszSRS_WKT = (char*) pDataset->GetProjectionRef(); uninstallErrorHandlerAndTriggerError(); installErrorHandler(); oSRS.importFromWkt( &pszSRS_WKT ); oSRS.exportToProj4( &pszSRS_WKT ); uninstallErrorHandlerAndTriggerError(); PROTECT(ans = NEW_CHARACTER(1)); SET_STRING_ELT(ans, 0, COPY_TO_USER_STRING(pszSRS_WKT)); installErrorHandler(); CPLFree( pszSRS_WKT ); uninstallErrorHandlerAndTriggerError(); UNPROTECT(1); return(ans); }
void SmallpatchSieveFilter::SieveFilter(const char* Src_path, const char* Dst_Path, int SizeThresthod, int Connectedness) { GDALAllRegister(); CPLSetConfigOption("GDAL_FILENAME_IS_UTF8","NO"); GDALDriver* poDriver = GetGDALDriverManager()->GetDriverByName("GTIFF"); if (poDriver == NULL) { cout << "不能创建指定类型的文件:" << endl; } GDALDataset* poSrc = (GDALDataset*)GDALOpen(Src_path,GA_ReadOnly); int NewBandXsize = poSrc->GetRasterXSize(); int NewBandYsize = poSrc->GetRasterYSize(); GDALDataType Type = poSrc->GetRasterBand(1)->GetRasterDataType(); GDALDataset* poDstDS = poDriver->Create(Dst_Path, NewBandXsize, NewBandYsize, 1, Type, NULL); double GeoTrans[6] = { 0 }; poSrc->GetGeoTransform(GeoTrans); poDstDS->SetGeoTransform(GeoTrans); poDstDS->SetProjection(poSrc->GetProjectionRef()); GDALRasterBandH HImgBand = (GDALRasterBandH)poSrc->GetRasterBand(1); GDALRasterBandH HPDstDSBand = (GDALRasterBandH)poDstDS->GetRasterBand(1); GDALSetRasterColorTable(HPDstDSBand, GDALGetRasterColorTable(HImgBand)); GDALSieveFilter(HImgBand, NULL, HPDstDSBand, SizeThresthod, Connectedness, NULL, NULL, NULL); GDALClose((GDALDatasetH)poDstDS); };
/** *@brief tif图片投影转换 *@param tifPath [in] tif图片路径 *@param toWkt [in] 目标点的wkt字符串 *@param outPath [in] 转换后文件路径 *@return */ void GdalProjection::TifProjectionTransformation(const char *tifPath, const char *toWkt,const char *outPath) { GDALDataset *poDataset = gbase.OpenDatasetR(tifPath); const char *fromWkt = poDataset->GetProjectionRef(); //double *adfGeoTransform = (double *)CPLMalloc(sizeof(double) * 6); //int x = poDataset->GetRasterXSize(); //int y = poDataset->GetRasterYSize(); int bands = poDataset->GetRasterCount(); double adfGeoTransform[6]; GDALDataType gdt = poDataset->GetRasterBand(1)->GetRasterDataType(); void *hTransformArg; //cout<<fromWkt; hTransformArg = GDALCreateGenImgProjTransformer(poDataset,fromWkt,NULL,toWkt,FALSE,0,1); //cout<<toWkt<<endl; int nPixels = 0,nLines = 0; CPLErr eErr; eErr = GDALSuggestedWarpOutput(poDataset,GDALGenImgProjTransform,hTransformArg, adfGeoTransform,&nPixels,&nLines); //cout<<nPixels<<" : "<<nLines<<endl; //创建转换后的投影和坐标系的空图像 CreateTiff(outPath,gdt,toWkt,adfGeoTransform,nPixels,nLines,bands); ////重投影 TifReProjection(tifPath,outPath); }
int Raster<T>::ReadAsInt32(const char* filename) { GDALDataset *poDataset = (GDALDataset *) GDALOpen( filename, GA_ReadOnly ); if( poDataset == NULL ) { cerr << "Open file: " << filename << " failed.\n"; return -1; } GDALRasterBand *poBand= poDataset->GetRasterBand(1); m_nCols = poBand->GetXSize(); m_nRows = poBand->GetYSize(); m_nAll = m_nRows * m_nCols; m_noDataValue = poBand->GetNoDataValue(); double adfGeoTransform[6]; poDataset->GetGeoTransform(adfGeoTransform); m_dx = adfGeoTransform[1]; m_dy = -adfGeoTransform[5]; m_xMin = adfGeoTransform[0]; m_yMax = adfGeoTransform[3]; m_proj = poDataset->GetProjectionRef(); if (m_data != NULL) CPLFree(m_data); m_dType = GDT_Int32; m_data = (T*) CPLMalloc(sizeof(int)*m_nAll); poBand->RasterIO(GF_Read, 0, 0, m_nCols, m_nRows, m_data, m_nCols, m_nRows, m_dType, 0, 0); GDALClose(poDataset); return 0; }
void RasterImageLayer::loadFile() { GDALDataset *ds = static_cast<GDALDataset*>(GDALOpen(m_filename.toLocal8Bit(), GA_ReadOnly)); if (ds == nullptr) { qWarning() << "Error opening file:" << m_filename; } else { projection().setGeogCS(new OGRSpatialReference(ds->GetProjectionRef())); projection().setProjCS(new OGRSpatialReference(ds->GetProjectionRef())); projection().setDomain({-180., -90., 360., 180.}); std::vector<double> geoTransform(6); int xsize = ds->GetRasterXSize(); int ysize = ds->GetRasterYSize(); ds->GetGeoTransform(geoTransform.data()); vertData.resize(4); vertData[0] = QVector2D(geoTransform[0], geoTransform[3]); vertData[1] = QVector2D(geoTransform[0] + geoTransform[2] * ysize, geoTransform[3] + geoTransform[5] * ysize); vertData[2] = QVector2D(geoTransform[0] + geoTransform[1] * xsize + geoTransform[2] * ysize, geoTransform[3] + geoTransform[4] * xsize + geoTransform[5] * ysize); vertData[3] = QVector2D(geoTransform[0] + geoTransform[1] * xsize, geoTransform[3] + geoTransform[4] * xsize); texData = {{0., 0.}, {0., 1.}, {1., 1.}, {1., 0.}}; int numBands = ds->GetRasterCount(); qDebug() << "Bands:" << numBands; imData = QImage(xsize, ysize, QImage::QImage::Format_RGBA8888); imData.fill(QColor(255, 255, 255, 255)); // Bands start at 1 for (int i = 1; i <= numBands; ++i) { GDALRasterBand *band = ds->GetRasterBand(i); switch(band->GetColorInterpretation()) { case GCI_RedBand: band->RasterIO(GF_Read, 0, 0, xsize, ysize, imData.bits(), xsize, ysize, GDT_Byte, 4, 0); break; case GCI_GreenBand: band->RasterIO(GF_Read, 0, 0, xsize, ysize, imData.bits() + 1, xsize, ysize, GDT_Byte, 4, 0); break; case GCI_BlueBand: band->RasterIO(GF_Read, 0, 0, xsize, ysize, imData.bits() + 2, xsize, ysize, GDT_Byte, 4, 0); break; default: qWarning() << "Unhandled color interpretation:" << band->GetColorInterpretation(); } } GDALClose(ds); newFile = true; } }
int main(int argc, char** argv ) { float xright,ybottom,x,y; if (argc > 1) { // Now getting information for this dataset cout << "File Inputed: " << argv[1] << endl; // Lets open a Tif GDALDataset *poDataset; // Register all gdal drivers -- load every possible driver gdal has GDALAllRegister(); // lets load a "dataset" which is gdal terminology for your data poDataset = (GDALDataset*) GDALOpen(argv[1], GA_ReadOnly); // Get width and height of this dataset int width = GDALGetRasterXSize(poDataset); int height = GDALGetRasterYSize(poDataset); cout << "Data size: " << width << " " << height << endl; // Get projection information of this dataset string proj; proj = string(poDataset->GetProjectionRef()); cout << "Projection: " << proj << endl; // get geo transform for this dataset double adfGeoTransform[6]; if ( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { printf( "Origin = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3] ); printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5] ); x = adfGeoTransform[0]; y = adfGeoTransform[3]; xright = x + adfGeoTransform[1] * width; ybottom = y + adfGeoTransform[5] * height; cout << "East: " << x << " West: " << xright << " North: " << y << " South: " << ybottom << endl; cout << "Pixel Size(x y): " << adfGeoTransform[1] << " " << adfGeoTransform[5] << endl; } else { return 1; } } return 0; }
/** *@brief 点对点的转换 *@param tifPath [in] tif图片路径 *@param toWkt [in] 目标点的wkt字符串 *@param x [in] x点经度 *@param y [in] y点纬度 *@return 转换后的经纬度坐标 */ double *GdalProjection::PointToPoint(const char *tifPath,const char *toWkt,int x,int y) { GDALDataset *poDataset = gbase.OpenDatasetR(tifPath); const char *fromWkt = poDataset->GetProjectionRef(); double *adfGeoTransform = (double *)CPLMalloc(sizeof(double) * 6); poDataset->GetGeoTransform(adfGeoTransform); double nx = gbase.GetLonOfPoint(adfGeoTransform,x,y); double ny = gbase.GetLatOfPoint(adfGeoTransform,x,y); double *ptop = PointToPoint(fromWkt,toWkt,nx,ny); GDALClose(poDataset); CPLFree(adfGeoTransform); return ptop; }
void saveGDAL(const std::string &filename, const std::string &template_name, int xoffset, int yoffset){ GDALDataset *fintempl = (GDALDataset*)GDALOpen(template_name.c_str(), GA_ReadOnly); assert(fintempl!=NULL); //TODO: Error handle GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName("GTiff"); assert(poDriver!=NULL); //TODO: Error handle GDALDataset *fout = poDriver->Create(filename.c_str(), viewWidth(), viewHeight(), 1, myGDALType(), NULL); assert(fout!=NULL); //TODO: Error handle GDALRasterBand *oband = fout->GetRasterBand(1); oband->SetNoDataValue(no_data); //The geotransform maps each grid cell to a point in an affine-transformed //projection of the actual terrain. The geostransform is specified as follows: // Xgeo = GT(0) + Xpixel*GT(1) + Yline*GT(2) // Ygeo = GT(3) + Xpixel*GT(4) + Yline*GT(5) //In case of north up images, the GT(2) and GT(4) coefficients are zero, and //the GT(1) is pixel width, and GT(5) is pixel height. The (GT(0),GT(3)) //position is the top left corner of the top left pixel of the raster. double geotrans[6]; fintempl->GetGeoTransform(geotrans); //We shift the top-left pixel of hte image eastward to the appropriate //coordinate geotrans[0] += xoffset*geotrans[1]; //We shift the top-left pixel of the image southward to the appropriate //coordinate geotrans[3] += yoffset*geotrans[5]; #ifdef DEBUG std::cerr<<"Filename: "<<std::setw(20)<<filename<<" Xoffset: "<<std::setw(6)<<xoffset<<" Yoffset: "<<std::setw(6)<<yoffset<<" Geotrans0: "<<std::setw(10)<<std::setprecision(10)<<std::fixed<<geotrans[0]<<" Geotrans3: "<<std::setw(10)<<std::setprecision(10)<<std::fixed<<geotrans[3]<< std::endl; #endif fout->SetGeoTransform(geotrans); const char* projection_string=fintempl->GetProjectionRef(); fout->SetProjection(projection_string); GDALClose(fintempl); for(int y=0;y<view_height;y++) oband->RasterIO(GF_Write, 0, y, viewWidth(), 1, data[y].data(), viewWidth(), 1, myGDALType(), 0, 0); GDALClose(fout); }
/** *@brief 数组对数组的转换 *@param tifPath [in] tif图片路径 *@param toWkt [in] 目标点的wkt字符串 *@param x [in] 经度数组 *@param y [in] 纬度数组 *@param nCount [in] 数组大小 *@return 转换后的经纬度坐标 */ vector<double *> GdalProjection::ArrayToArray(const char *tifPath,const char *toWkt,int *x,int *y,int nCount) { vector<double *> ve; GDALDataset *poDataset = gbase.OpenDatasetR(tifPath); const char *fromWkt = poDataset->GetProjectionRef(); double *adfGeoTransform = (double *)CPLMalloc(sizeof(double) * 6); poDataset->GetGeoTransform(adfGeoTransform); double *nx = (double *)CPLMalloc(sizeof(double) * nCount); double *ny = (double *)CPLMalloc(sizeof(double) * nCount); for (int i = 0; i < nCount; i++) { nx[i] = gbase.GetLonOfPoint(adfGeoTransform,x[i],y[i]); ny[i] = gbase.GetLatOfPoint(adfGeoTransform,x[i],y[i]); } free(x); free(y); ve = ArrayToArray(fromWkt,toWkt,nx,ny,nCount); return ve; }
//virtual method that will be executed void executeAlgorithm(AlgorithmData& data, AlgorithmContext& context) { //****define algorithm here**** //open native message block std::string nativeHdr="\n*************************NATIVE_OUTPUT*************************\n"; std::cout<<nativeHdr<<std::endl; //open image files // input/output directory names specified in configuration file Dataset* input = data.getInputDataset("imagesIn"); Dataset* output = data.getOutputDataset("imagesOut"); //get keyspace elements (files in directory by dimension) Keyspace keyspace = data.getKeyspace(); std::vector<DataKeyElement> names = keyspace.getKeyspaceDimension(DataKeyDimension("NAME")).getElements(); //... iterate through keys and do work ... for ( std::vector<DataKeyElement>::iterator n=names.begin(); n != names.end(); n++ ) { //print dimension name to stdout std::cout<<*n<<std::endl; //get multispectral data DataKey skyKey = *n; DataFile* skyFile = input->getDataFile(skyKey); //unique name for an in-memory GDAL file std::string inputFileName = skyKey.toName("__")+"_input"; //get gdal dataset GDALMemoryFile inputMemFile(inputFileName, *skyFile); GDALDataset * skyDataset = inputMemFile.getGDALDataset(); //get gdal bands GDALRasterBand * blueBand = skyDataset->GetRasterBand(1); GDALRasterBand * greenBand = skyDataset->GetRasterBand(2); GDALRasterBand * redBand = skyDataset->GetRasterBand(3); GDALRasterBand * nirBand = skyDataset->GetRasterBand(4); //create memory buffers to hold bands int nXSize = redBand->GetXSize(); int nYSize = redBand->GetYSize(); uint16_t * bufferBlue = (uint16_t *) CPLMalloc(sizeof(uint16_t)*nXSize*nYSize); uint16_t * bufferGreen = (uint16_t *) CPLMalloc(sizeof(uint16_t)*nXSize*nYSize); uint16_t * bufferRed = (uint16_t *) CPLMalloc(sizeof(uint16_t)*nXSize*nYSize); uint16_t * bufferNIR = (uint16_t *) CPLMalloc(sizeof(uint16_t)*nXSize*nYSize); //output uint16_t * bufferClass = (uint16_t *) CPLMalloc(sizeof(uint16_t)*nXSize*nYSize); //gdal read bands into buffer blueBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, bufferBlue, nXSize , nYSize, GDT_UInt16, 0, 0 ); greenBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, bufferGreen, nXSize , nYSize, GDT_UInt16, 0, 0 ); redBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, bufferRed, nXSize , nYSize, GDT_UInt16, 0, 0 ); nirBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, bufferNIR, nXSize , nYSize, GDT_UInt16, 0, 0 ); //classify pixels for (int i=0 ; i < nXSize*nYSize ; i++ ) { //unclassified uint16_t pixelClass = 0; if (bufferBlue[i]>0 && bufferGreen[i]>0 && bufferRed[i]>0 && bufferNIR[i]>0 ) { //ground pixelClass = 1; //classify pixels double ndvi = ((double)bufferNIR[i]-(double)bufferRed[i])/((double)bufferNIR[i]+(double)bufferRed[i]); double water = ((double)bufferBlue[i]-(double)bufferRed[i])/(double)(bufferRed[i]+(double)bufferBlue[i]); if ( ndvi>0.1 ) { //vegetation pixelClass = 128; } else if (water > 0.1 ) { //water pixelClass = 256; } } //write to buffer bufferClass[i]=pixelClass; } // create in memory storage for GDAL output file std::string outputFileName = skyKey.toName("__")+"_output"; GDALMemoryFile outMemFile(outputFileName); // create the output dataset GDALDataset* outDataset = newGDALDataset( outMemFile.getPath(), "Gtiff", nXSize, nYSize, 1, // 1 band GDT_UInt16 ); outMemFile.setGDALDataset(outDataset); // Write results into a band GDALRasterBand * gBand = outDataset->GetRasterBand(1); gBand->RasterIO( GF_Write, 0, 0, nXSize, nYSize, bufferClass, nXSize, nYSize, GDT_UInt16,0,0 ); // copy metadata double adfGeoTransform[6]; const char * projection = skyDataset->GetProjectionRef(); outDataset->SetProjection(projection); skyDataset->GetGeoTransform( adfGeoTransform ); outDataset->SetGeoTransform( adfGeoTransform ); // close the files inputMemFile.close(); outMemFile.close(); // output file in the output folder DataKey outKey = DataKey(*n); DataFile* fileData = outMemFile.toDataFile("image/tif"); output->addDataFile(outKey, fileData); //close message block std::cout<<nativeHdr<<std::endl; //free buffers CPLFree(bufferBlue); CPLFree(bufferGreen); CPLFree(bufferRed); CPLFree(bufferNIR); CPLFree(bufferClass); } }
static int ProxyMain( int argc, char ** argv ) { // GDALDatasetH hDataset, hOutDS; // int i; // int nRasterXSize, nRasterYSize; // const char *pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff"; // GDALDriverH hDriver; // int *panBandList = NULL; /* negative value of panBandList[i] means mask band of ABS(panBandList[i]) */ // int nBandCount = 0, bDefBands = TRUE; // double adfGeoTransform[6]; // GDALDataType eOutputType = GDT_Unknown; // int nOXSize = 0, nOYSize = 0; // char *pszOXSize=NULL, *pszOYSize=NULL; // char **papszCreateOptions = NULL; // int anSrcWin[4], bStrict = FALSE; // const char *pszProjection; // int bScale = FALSE, bHaveScaleSrc = FALSE, bUnscale=FALSE; // double dfScaleSrcMin=0.0, dfScaleSrcMax=255.0; // double dfScaleDstMin=0.0, dfScaleDstMax=255.0; // double dfULX, dfULY, dfLRX, dfLRY; // char **papszMetadataOptions = NULL; // char *pszOutputSRS = NULL; // int bQuiet = FALSE, bGotBounds = FALSE; // GDALProgressFunc pfnProgress = GDALTermProgress; // int nGCPCount = 0; // GDAL_GCP *pasGCPs = NULL; // int iSrcFileArg = -1, iDstFileArg = -1; // int bCopySubDatasets = FALSE; // double adfULLR[4] = { 0,0,0,0 }; // int bSetNoData = FALSE; // int bUnsetNoData = FALSE; // double dfNoDataReal = 0.0; // int nRGBExpand = 0; // int bParsedMaskArgument = FALSE; // int eMaskMode = MASK_AUTO; // int nMaskBand = 0; /* negative value means mask band of ABS(nMaskBand) */ // int bStats = FALSE, bApproxStats = FALSE; // GDALDatasetH hDataset, hOutDS; GDALDataset *hDataset = NULL; GDALDataset *hOutDS = NULL; int i; int nRasterXSize, nRasterYSize; const char *pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff"; // GDALDriverH hDriver; GDALDriver *hDriver; GDALDataType eOutputType = GDT_Unknown; char **papszCreateOptions = NULL; int bStrict = FALSE; int bQuiet = FALSE; GDALProgressFunc pfnProgress = GDALTermProgress; int iSrcFileArg = -1, iDstFileArg = -1; int bSetNoData = FALSE; int bUnsetNoData = FALSE; double dfNoDataReal = 0.0; GDALRasterBand *inBand = NULL; GDALRasterBand *outBand = NULL; GByte *srcBuffer; double adfGeoTransform[6]; int nRasterCount; int bReplaceIds = FALSE; const char *pszReplaceFilename = NULL; const char *pszReplaceFieldFrom = NULL; const char *pszReplaceFieldTo = NULL; std::map<GByte,GByte> mReplaceTable; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(argv[0])) exit(1); /* Must process GDAL_SKIP before GDALAllRegister(), but we can't call */ /* GDALGeneralCmdLineProcessor before it needs the drivers to be registered */ /* for the --format or --formats options */ for( i = 1; i < argc; i++ ) { if( EQUAL(argv[i],"--config") && i + 2 < argc && EQUAL(argv[i + 1], "GDAL_SKIP") ) { CPLSetConfigOption( argv[i+1], argv[i+2] ); i += 2; } } /* -------------------------------------------------------------------- */ /* Register standard GDAL drivers, and process generic GDAL */ /* command options. */ /* -------------------------------------------------------------------- */ GDALAllRegister(); argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 ); if( argc < 1 ) exit( -argc ); /* -------------------------------------------------------------------- */ /* Handle command line arguments. */ /* -------------------------------------------------------------------- */ for( i = 1; i < argc; i++ ) { if( EQUAL(argv[i],"-of") && i < argc-1 ) pszFormat = argv[++i]; else if( EQUAL(argv[i],"-q") || EQUAL(argv[i],"-quiet") ) { bQuiet = TRUE; pfnProgress = GDALDummyProgress; } else if( EQUAL(argv[i],"-ot") && i < argc-1 ) { int iType; for( iType = 1; iType < GDT_TypeCount; iType++ ) { if( GDALGetDataTypeName((GDALDataType)iType) != NULL && EQUAL(GDALGetDataTypeName((GDALDataType)iType), argv[i+1]) ) { eOutputType = (GDALDataType) iType; } } if( eOutputType == GDT_Unknown ) { printf( "Unknown output pixel type: %s\n", argv[i+1] ); Usage(); GDALDestroyDriverManager(); exit( 2 ); } i++; } else if( EQUAL(argv[i],"-not_strict") ) bStrict = FALSE; else if( EQUAL(argv[i],"-strict") ) bStrict = TRUE; else if( EQUAL(argv[i],"-a_nodata") && i < argc - 1 ) { if (EQUAL(argv[i+1], "none")) { bUnsetNoData = TRUE; } else { bSetNoData = TRUE; dfNoDataReal = CPLAtofM(argv[i+1]); } i += 1; } else if( EQUAL(argv[i],"-co") && i < argc-1 ) { papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] ); } else if( EQUAL(argv[i],"-replace_ids") && i < argc-3 ) { bReplaceIds = TRUE; pszReplaceFilename = (argv[++i]); pszReplaceFieldFrom = (argv[++i]); pszReplaceFieldTo = (argv[++i]); } else if( argv[i][0] == '-' ) { printf( "Option %s incomplete, or not recognised.\n\n", argv[i] ); Usage(); GDALDestroyDriverManager(); exit( 2 ); } else if( pszSource == NULL ) { iSrcFileArg = i; pszSource = argv[i]; } else if( pszDest == NULL ) { pszDest = argv[i]; iDstFileArg = i; } else { printf( "Too many command options.\n\n" ); Usage(); GDALDestroyDriverManager(); exit( 2 ); } } if( pszDest == NULL ) { Usage(); GDALDestroyDriverManager(); exit( 10 ); } if ( strcmp(pszSource, pszDest) == 0) { fprintf(stderr, "Source and destination datasets must be different.\n"); GDALDestroyDriverManager(); exit( 1 ); } if( bReplaceIds ) { if ( ! pszReplaceFilename | ! pszReplaceFieldFrom | ! pszReplaceFieldTo ) Usage(); // FILE * ifile; // if ( (ifile = fopen(pszReplaceFilename, "r")) == NULL ) // { // fprintf( stderr, "Replace file %s cannot be read!\n\n", pszReplaceFilename ); // Usage(); // } // else // fclose( ifile ); mReplaceTable = InitReplaceTable(pszReplaceFilename, pszReplaceFieldFrom, pszReplaceFieldTo); printf("TMP ET size: %d\n",(int)mReplaceTable.size()); } /* -------------------------------------------------------------------- */ /* Attempt to open source file. */ /* -------------------------------------------------------------------- */ // hDataset = GDALOpenShared( pszSource, GA_ReadOnly ); hDataset = (GDALDataset *) GDALOpen(pszSource, GA_ReadOnly ); if( hDataset == NULL ) { fprintf( stderr, "GDALOpen failed - %d\n%s\n", CPLGetLastErrorNo(), CPLGetLastErrorMsg() ); GDALDestroyDriverManager(); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Collect some information from the source file. */ /* -------------------------------------------------------------------- */ // nRasterXSize = GDALGetRasterXSize( hDataset ); // nRasterYSize = GDALGetRasterYSize( hDataset ); nRasterXSize = hDataset->GetRasterXSize(); nRasterYSize = hDataset->GetRasterYSize(); if( !bQuiet ) printf( "Input file size is %d, %d\n", nRasterXSize, nRasterYSize ); /* -------------------------------------------------------------------- */ /* Find the output driver. */ /* -------------------------------------------------------------------- */ hDriver = GetGDALDriverManager()->GetDriverByName( pszFormat ); if( hDriver == NULL ) { int iDr; printf( "Output driver `%s' not recognised.\n", pszFormat ); printf( "The following format drivers are configured and support output:\n" ); for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ ) { GDALDriverH hDriver = GDALGetDriver(iDr); if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY, NULL ) != NULL ) { printf( " %s: %s\n", GDALGetDriverShortName( hDriver ), GDALGetDriverLongName( hDriver ) ); } } printf( "\n" ); Usage(); GDALClose( (GDALDatasetH) hDataset ); GDALDestroyDriverManager(); CSLDestroy( argv ); CSLDestroy( papszCreateOptions ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Create Dataset and copy info */ /* -------------------------------------------------------------------- */ nRasterCount = hDataset->GetRasterCount(); printf("creating\n"); hOutDS = hDriver->Create( pszDest, nRasterXSize, nRasterYSize, nRasterCount, GDT_Byte, papszCreateOptions); printf("created\n"); if( hOutDS != NULL ) { hDataset->GetGeoTransform( adfGeoTransform); hOutDS->SetGeoTransform( adfGeoTransform ); hOutDS->SetProjection( hDataset->GetProjectionRef() ); /* ==================================================================== */ /* Process all bands. */ /* ==================================================================== */ // if (0) for( i = 1; i < nRasterCount+1; i++ ) { inBand = hDataset->GetRasterBand( i ); // hOutDS->AddBand(GDT_Byte); outBand = hOutDS->GetRasterBand( i ); CopyBandInfo( inBand, outBand, 0, 1, 1 ); nRasterXSize = inBand->GetXSize( ); nRasterYSize = inBand->GetYSize( ); GByte old_value, new_value; // char tmp_value[255]; // const char *tmp_value2; std::map<GByte,GByte>::iterator it; //tmp int nXBlocks, nYBlocks, nXBlockSize, nYBlockSize; int iXBlock, iYBlock; inBand->GetBlockSize( &nXBlockSize, &nYBlockSize ); // nXBlockSize = nXBlockSize / 4; // nYBlockSize = nYBlockSize / 4; nXBlocks = (inBand->GetXSize() + nXBlockSize - 1) / nXBlockSize; nYBlocks = (inBand->GetYSize() + nYBlockSize - 1) / nYBlockSize; printf("blocks: %d %d %d %d\n",nXBlockSize,nYBlockSize,nXBlocks,nYBlocks); printf("TMP ET creating raster %d x %d\n",nRasterXSize, nRasterYSize); // srcBuffer = new GByte[nRasterXSize * nRasterYSize]; // printf("reading\n"); // inBand->RasterIO( GF_Read, 0, 0, nRasterXSize, nRasterYSize, // srcBuffer, nRasterXSize, nRasterYSize, GDT_Byte, // 0, 0 ); // srcBuffer = (GByte *) CPLMalloc(sizeof(GByte)*nRasterXSize * nRasterYSize); srcBuffer = (GByte *) CPLMalloc(nXBlockSize * nYBlockSize); for( iYBlock = 0; iYBlock < nYBlocks; iYBlock++ ) { // if(iYBlock%1000 == 0) // printf("iXBlock: %d iYBlock: %d\n",iXBlock,iYBlock); if(iYBlock%1000 == 0) printf("iYBlock: %d / %d\n",iYBlock,nYBlocks); for( iXBlock = 0; iXBlock < nXBlocks; iXBlock++ ) { int nXValid, nYValid; // inBand->ReadBlock( iXBlock, iYBlock, srcBuffer ); inBand->RasterIO( GF_Read, iXBlock, iYBlock, nXBlockSize, nYBlockSize, srcBuffer, nXBlockSize, nYBlockSize, GDT_Byte, 0, 0 ); // Compute the portion of the block that is valid // for partial edge blocks. if( (iXBlock+1) * nXBlockSize > inBand->GetXSize() ) nXValid = inBand->GetXSize() - iXBlock * nXBlockSize; else nXValid = nXBlockSize; if( (iYBlock+1) * nYBlockSize > inBand->GetYSize() ) nYValid = inBand->GetYSize() - iYBlock * nYBlockSize; else nYValid = nYBlockSize; // printf("iXBlock: %d iYBlock: %d read, nXValid: %d nYValid: %d\n",iXBlock,iYBlock,nXValid, nYValid); // if(0) if ( pszReplaceFilename ) { for( int iY = 0; iY < nYValid; iY++ ) { for( int iX = 0; iX < nXValid; iX++ ) { // panHistogram[pabyData[iX + iY * nXBlockSize]] += 1; old_value = new_value = srcBuffer[iX + iY * nXBlockSize]; // sprintf(tmp_value,"%d",old_value); it = mReplaceTable.find(old_value); if ( it != mReplaceTable.end() ) new_value = it->second; if ( old_value != new_value ) { srcBuffer[iX + iY * nXBlockSize] = new_value; // printf("old_value %d new_value %d final %d\n",old_value,new_value, srcBuffer[iX + iY * nXBlockSize]); } // tmp_value2 = CSVGetField( pszReplaceFilename,pszReplaceFieldFrom, // tmp_value, CC_Integer, pszReplaceFieldTo); // if( tmp_value2 != NULL ) // { // new_value = atoi(tmp_value2); // } // new_value = old_value +1; // } } } // printf("writing\n"); // outBand->WriteBlock( iXBlock, iYBlock, srcBuffer ); outBand->RasterIO( GF_Write, iXBlock, iYBlock, nXBlockSize, nYBlockSize, srcBuffer, nXBlockSize, nYBlockSize, GDT_Byte, 0, 0 ); // printf("wrote\n"); } } CPLFree(srcBuffer); printf("read\n"); printf("mod\n"); // if ( pszReplaceFilename ) // { // GByte old_value, new_value; // // char tmp_value[255]; // // const char *tmp_value2; // std::map<GByte,GByte>::iterator it; // for ( int j=0; j<nRasterXSize*nRasterYSize; j++ ) // { // old_value = new_value = srcBuffer[j]; // // sprintf(tmp_value,"%d",old_value); // it = mReplaceTable.find(old_value); // if ( it != mReplaceTable.end() ) new_value = it->second; // // tmp_value2 = CSVGetField( pszReplaceFilename,pszReplaceFieldFrom, // // tmp_value, CC_Integer, pszReplaceFieldTo); // // if( tmp_value2 != NULL ) // // { // // new_value = atoi(tmp_value2); // // } // // new_value = old_value +1; // if ( old_value != new_value ) srcBuffer[j] = new_value; // // printf("old_value %d new_value %d final %d\n",old_value,new_value, srcBuffer[j]); // } // printf("writing\n"); // outBand->RasterIO( GF_Write, 0, 0, nRasterXSize, nRasterYSize, // srcBuffer, nRasterXSize, nRasterYSize, GDT_Byte, // 0, 0 ); // printf("wrote\n"); // delete [] srcBuffer; // } } } if( hOutDS != NULL ) GDALClose( (GDALDatasetH) hOutDS ); if( hDataset != NULL ) GDALClose( (GDALDatasetH) hDataset ); GDALDumpOpenDatasets( stderr ); // GDALDestroyDriverManager(); CSLDestroy( argv ); CSLDestroy( papszCreateOptions ); return hOutDS == NULL; }
GDALDataset *DTEDDataset::Open( GDALOpenInfo * poOpenInfo ) { int i; DTEDInfo *psDTED; if (!Identify(poOpenInfo) || poOpenInfo->fpL == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Try opening the dataset. */ /* -------------------------------------------------------------------- */ VSILFILE* fp = poOpenInfo->fpL; poOpenInfo->fpL = NULL; psDTED = DTEDOpenEx( fp, poOpenInfo->pszFilename, (poOpenInfo->eAccess == GA_Update) ? "rb+" : "rb", TRUE ); if( psDTED == NULL ) return( NULL ); /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ DTEDDataset *poDS; poDS = new DTEDDataset(); poDS->SetFileName(poOpenInfo->pszFilename); poDS->eAccess = poOpenInfo->eAccess; poDS->psDTED = psDTED; /* -------------------------------------------------------------------- */ /* Capture some information from the file that is of interest. */ /* -------------------------------------------------------------------- */ poDS->nRasterXSize = psDTED->nXSize; poDS->nRasterYSize = psDTED->nYSize; if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize)) { delete poDS; return NULL; } /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ poDS->nBands = 1; for( i = 0; i < poDS->nBands; i++ ) poDS->SetBand( i+1, new DTEDRasterBand( poDS, i+1 ) ); /* -------------------------------------------------------------------- */ /* Collect any metadata available. */ /* -------------------------------------------------------------------- */ char *pszValue; pszValue = DTEDGetMetadata( psDTED, DTEDMD_VERTACCURACY_UHL ); poDS->SetMetadataItem( "DTED_VerticalAccuracy_UHL", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_VERTACCURACY_ACC ); poDS->SetMetadataItem( "DTED_VerticalAccuracy_ACC", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_SECURITYCODE_UHL ); poDS->SetMetadataItem( "DTED_SecurityCode_UHL", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_SECURITYCODE_DSI ); poDS->SetMetadataItem( "DTED_SecurityCode_DSI", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_UNIQUEREF_UHL ); poDS->SetMetadataItem( "DTED_UniqueRef_UHL", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_UNIQUEREF_DSI ); poDS->SetMetadataItem( "DTED_UniqueRef_DSI", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_DATA_EDITION ); poDS->SetMetadataItem( "DTED_DataEdition", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_MATCHMERGE_VERSION ); poDS->SetMetadataItem( "DTED_MatchMergeVersion", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_MAINT_DATE ); poDS->SetMetadataItem( "DTED_MaintenanceDate", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_MATCHMERGE_DATE ); poDS->SetMetadataItem( "DTED_MatchMergeDate", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_MAINT_DESCRIPTION ); poDS->SetMetadataItem( "DTED_MaintenanceDescription", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_PRODUCER ); poDS->SetMetadataItem( "DTED_Producer", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_VERTDATUM ); poDS->SetMetadataItem( "DTED_VerticalDatum", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_HORIZDATUM ); poDS->SetMetadataItem( "DTED_HorizontalDatum", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_DIGITIZING_SYS ); poDS->SetMetadataItem( "DTED_DigitizingSystem", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_COMPILATION_DATE ); poDS->SetMetadataItem( "DTED_CompilationDate", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_HORIZACCURACY ); poDS->SetMetadataItem( "DTED_HorizontalAccuracy", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_REL_HORIZACCURACY ); poDS->SetMetadataItem( "DTED_RelHorizontalAccuracy", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_REL_VERTACCURACY ); poDS->SetMetadataItem( "DTED_RelVerticalAccuracy", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_ORIGINLAT ); poDS->SetMetadataItem( "DTED_OriginLatitude", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_ORIGINLONG ); poDS->SetMetadataItem( "DTED_OriginLongitude", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_NIMA_DESIGNATOR ); poDS->SetMetadataItem( "DTED_NimaDesignator", pszValue ); CPLFree( pszValue ); pszValue = DTEDGetMetadata( psDTED, DTEDMD_PARTIALCELL_DSI ); poDS->SetMetadataItem( "DTED_PartialCellIndicator", pszValue ); CPLFree( pszValue ); poDS->SetMetadataItem( GDALMD_AREA_OR_POINT, GDALMD_AOP_POINT ); /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); poDS->TryLoadXML( poOpenInfo->GetSiblingFiles() ); // if no SR in xml, try aux const char* pszPrj = poDS->GDALPamDataset::GetProjectionRef(); if( !pszPrj || strlen(pszPrj) == 0 ) { int bTryAux = TRUE; if( poOpenInfo->GetSiblingFiles() != NULL && CSLFindString(poOpenInfo->GetSiblingFiles(), CPLResetExtension(CPLGetFilename(poOpenInfo->pszFilename), "aux")) < 0 && CSLFindString(poOpenInfo->GetSiblingFiles(), CPLSPrintf("%s.aux", CPLGetFilename(poOpenInfo->pszFilename))) < 0 ) bTryAux = FALSE; if( bTryAux ) { GDALDataset* poAuxDS = GDALFindAssociatedAuxFile( poOpenInfo->pszFilename, GA_ReadOnly, poDS ); if( poAuxDS ) { pszPrj = poAuxDS->GetProjectionRef(); if( pszPrj && strlen(pszPrj) > 0 ) { CPLFree( poDS->pszProjection ); poDS->pszProjection = CPLStrdup(pszPrj); } GDALClose( poAuxDS ); } } } /* -------------------------------------------------------------------- */ /* Support overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename, poOpenInfo->GetSiblingFiles() ); return( poDS ); }
GDALDataset *TSXDataset::Open( GDALOpenInfo *poOpenInfo ) { /* -------------------------------------------------------------------- */ /* Is this a TerraSAR-X product file? */ /* -------------------------------------------------------------------- */ if (!TSXDataset::Identify( poOpenInfo )) { return NULL; /* nope */ } /* -------------------------------------------------------------------- */ /* Confirm the requested access is supported. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->eAccess == GA_Update ) { CPLError( CE_Failure, CPLE_NotSupported, "The TSX driver does not support update access to existing" " datasets.\n" ); return NULL; } CPLString osFilename; if( poOpenInfo->bIsDirectory ) { osFilename = CPLFormCIFilename( poOpenInfo->pszFilename, CPLGetFilename( poOpenInfo->pszFilename ), "xml" ); } else osFilename = poOpenInfo->pszFilename; /* Ingest the XML */ CPLXMLNode *psData = CPLParseXMLFile( osFilename ); if (psData == NULL) return NULL; /* find the product components */ CPLXMLNode *psComponents = CPLGetXMLNode( psData, "=level1Product.productComponents" ); if (psComponents == NULL) { CPLError( CE_Failure, CPLE_OpenFailed, "Unable to find <productComponents> tag in file.\n" ); CPLDestroyXMLNode(psData); return NULL; } /* find the product info tag */ CPLXMLNode *psProductInfo = CPLGetXMLNode( psData, "=level1Product.productInfo" ); if (psProductInfo == NULL) { CPLError( CE_Failure, CPLE_OpenFailed, "Unable to find <productInfo> tag in file.\n" ); CPLDestroyXMLNode(psData); return NULL; } /* -------------------------------------------------------------------- */ /* Create the dataset. */ /* -------------------------------------------------------------------- */ TSXDataset *poDS = new TSXDataset(); /* -------------------------------------------------------------------- */ /* Read in product info. */ /* -------------------------------------------------------------------- */ poDS->SetMetadataItem( "SCENE_CENTRE_TIME", CPLGetXMLValue( psProductInfo, "sceneInfo.sceneCenterCoord.azimuthTimeUTC", "unknown" ) ); poDS->SetMetadataItem( "OPERATIONAL_MODE", CPLGetXMLValue( psProductInfo, "generationInfo.groundOperationsType", "unknown" ) ); poDS->SetMetadataItem( "ORBIT_CYCLE", CPLGetXMLValue( psProductInfo, "missionInfo.orbitCycle", "unknown" ) ); poDS->SetMetadataItem( "ABSOLUTE_ORBIT", CPLGetXMLValue( psProductInfo, "missionInfo.absOrbit", "unknown" ) ); poDS->SetMetadataItem( "ORBIT_DIRECTION", CPLGetXMLValue( psProductInfo, "missionInfo.orbitDirection", "unknown" ) ); poDS->SetMetadataItem( "IMAGING_MODE", CPLGetXMLValue( psProductInfo, "acquisitionInfo.imagingMode", "unknown" ) ); poDS->SetMetadataItem( "PRODUCT_VARIANT", CPLGetXMLValue( psProductInfo, "productVariantInfo.productVariant", "unknown" ) ); char *pszDataType = CPLStrdup( CPLGetXMLValue( psProductInfo, "imageDataInfo.imageDataType", "unknown" ) ); poDS->SetMetadataItem( "IMAGE_TYPE", pszDataType ); /* Get raster information */ int nRows = atoi( CPLGetXMLValue( psProductInfo, "imageDataInfo.imageRaster.numberOfRows", "" ) ); int nCols = atoi( CPLGetXMLValue( psProductInfo, "imageDataInfo.imageRaster.numberOfColumns", "" ) ); poDS->nRasterXSize = nCols; poDS->nRasterYSize = nRows; poDS->SetMetadataItem( "ROW_SPACING", CPLGetXMLValue( psProductInfo, "imageDataInfo.imageRaster.rowSpacing", "unknown" ) ); poDS->SetMetadataItem( "COL_SPACING", CPLGetXMLValue( psProductInfo, "imageDataInfo.imageRaster.columnSpacing", "unknown" ) ); poDS->SetMetadataItem( "COL_SPACING_UNITS", CPLGetXMLValue( psProductInfo, "imageDataInfo.imageRaster.columnSpacing.units", "unknown" ) ); /* Get equivalent number of looks */ poDS->SetMetadataItem( "AZIMUTH_LOOKS", CPLGetXMLValue( psProductInfo, "imageDataInfo.imageRaster.azimuthLooks", "unknown" ) ); poDS->SetMetadataItem( "RANGE_LOOKS", CPLGetXMLValue( psProductInfo, "imageDataInfo.imageRaster.rangeLooks", "unknown" ) ); const char *pszProductVariant = CPLGetXMLValue( psProductInfo, "productVariantInfo.productVariant", "unknown" ); poDS->SetMetadataItem( "PRODUCT_VARIANT", pszProductVariant ); /* Determine what product variant this is */ if (STARTS_WITH_CI(pszProductVariant, "SSC")) poDS->nProduct = eSSC; else if (STARTS_WITH_CI(pszProductVariant, "MGD")) poDS->nProduct = eMGD; else if (STARTS_WITH_CI(pszProductVariant, "EEC")) poDS->nProduct = eEEC; else if (STARTS_WITH_CI(pszProductVariant, "GEC")) poDS->nProduct = eGEC; else poDS->nProduct = eUnknown; /* Start reading in the product components */ char *pszGeorefFile = NULL; CPLErr geoTransformErr=CE_Failure; for ( CPLXMLNode *psComponent = psComponents->psChild; psComponent != NULL; psComponent = psComponent->psNext) { const char *pszType = NULL; const char *pszPath = CPLFormFilename( CPLGetDirname( osFilename ), GetFilePath(psComponent, &pszType), "" ); const char *pszPolLayer = CPLGetXMLValue(psComponent, "polLayer", " "); if ( !STARTS_WITH_CI(pszType, " ") ) { if (STARTS_WITH_CI(pszType, "MAPPING_GRID") ) { /* the mapping grid... save as a metadata item this path */ poDS->SetMetadataItem( "MAPPING_GRID", pszPath ); } else if (STARTS_WITH_CI(pszType, "GEOREF")) { /* save the path to the georef data for later use */ CPLFree( pszGeorefFile ); pszGeorefFile = CPLStrdup( pszPath ); } } else if( !STARTS_WITH_CI(pszPolLayer, " ") && STARTS_WITH_CI(psComponent->pszValue, "imageData") ) { /* determine the polarization of this band */ ePolarization ePol; if ( STARTS_WITH_CI(pszPolLayer, "HH") ) { ePol = HH; } else if ( STARTS_WITH_CI(pszPolLayer, "HV") ) { ePol = HV; } else if ( STARTS_WITH_CI(pszPolLayer, "VH") ) { ePol = VH; } else { ePol = VV; } GDALDataType eDataType = STARTS_WITH_CI(pszDataType, "COMPLEX") ? GDT_CInt16 : GDT_UInt16; /* try opening the file that represents that band */ GDALDataset *poBandData = reinterpret_cast<GDALDataset *>( GDALOpen( pszPath, GA_ReadOnly ) ); if ( poBandData != NULL ) { TSXRasterBand *poBand = new TSXRasterBand( poDS, eDataType, ePol, poBandData ); poDS->SetBand( poDS->GetRasterCount() + 1, poBand ); //copy georeferencing info from the band //need error checking?? //it will just save the info from the last band CPLFree( poDS->pszProjection ); poDS->pszProjection = CPLStrdup(poBandData->GetProjectionRef()); geoTransformErr = poBandData->GetGeoTransform(poDS->adfGeoTransform); } } } //now check if there is a geotransform if ( strcmp(poDS->pszProjection, "") && geoTransformErr==CE_None) { poDS->bHaveGeoTransform = TRUE; } else { poDS->bHaveGeoTransform = FALSE; CPLFree( poDS->pszProjection ); poDS->pszProjection = CPLStrdup(""); poDS->adfGeoTransform[0] = 0.0; poDS->adfGeoTransform[1] = 1.0; poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[3] = 0.0; poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = 1.0; } CPLFree(pszDataType); /* -------------------------------------------------------------------- */ /* Check and set matrix representation. */ /* -------------------------------------------------------------------- */ if (poDS->GetRasterCount() == 4) { poDS->SetMetadataItem( "MATRIX_REPRESENTATION", "SCATTERING" ); } /* -------------------------------------------------------------------- */ /* Read the four corners and centre GCPs in */ /* -------------------------------------------------------------------- */ CPLXMLNode *psSceneInfo = CPLGetXMLNode( psData, "=level1Product.productInfo.sceneInfo" ); if (psSceneInfo != NULL) { /* extract the GCPs from the provided file */ bool success = false; if (pszGeorefFile != NULL) success = poDS->getGCPsFromGEOREF_XML(pszGeorefFile); //if the gcp's cannot be extracted from the georef file, try to get the corner coordinates //for now just SSC because the others don't have refColumn and refRow if (!success && poDS->nProduct == eSSC) { int nGCP = 0; double dfAvgHeight = CPLAtof(CPLGetXMLValue(psSceneInfo, "sceneAverageHeight", "0.0")); //count and allocate gcps - there should be five - 4 corners and a centre poDS->nGCPCount = 0; CPLXMLNode *psNode = psSceneInfo->psChild; for ( ; psNode != NULL; psNode = psNode->psNext ) { if (!EQUAL(psNode->pszValue, "sceneCenterCoord") && !EQUAL(psNode->pszValue, "sceneCornerCoord")) continue; poDS->nGCPCount++; } if (poDS->nGCPCount > 0) { poDS->pasGCPList = (GDAL_GCP *)CPLCalloc(sizeof(GDAL_GCP), poDS->nGCPCount); /* iterate over GCPs */ for (psNode = psSceneInfo->psChild; psNode != NULL; psNode = psNode->psNext ) { GDAL_GCP *psGCP = poDS->pasGCPList + nGCP; if (!EQUAL(psNode->pszValue, "sceneCenterCoord") && !EQUAL(psNode->pszValue, "sceneCornerCoord")) continue; psGCP->dfGCPPixel = CPLAtof(CPLGetXMLValue(psNode, "refColumn", "0.0")); psGCP->dfGCPLine = CPLAtof(CPLGetXMLValue(psNode, "refRow", "0.0")); psGCP->dfGCPX = CPLAtof(CPLGetXMLValue(psNode, "lon", "0.0")); psGCP->dfGCPY = CPLAtof(CPLGetXMLValue(psNode, "lat", "0.0")); psGCP->dfGCPZ = dfAvgHeight; psGCP->pszId = CPLStrdup( CPLSPrintf( "%d", nGCP ) ); psGCP->pszInfo = CPLStrdup(""); nGCP++; } //set the projection string - the fields are lat/long - seems to be WGS84 datum OGRSpatialReference osr; osr.SetWellKnownGeogCS( "WGS84" ); CPLFree(poDS->pszGCPProjection); osr.exportToWkt( &(poDS->pszGCPProjection) ); } } //gcps override geotransform - does it make sense to have both?? if (poDS->nGCPCount>0) { poDS->bHaveGeoTransform = FALSE; CPLFree( poDS->pszProjection ); poDS->pszProjection = CPLStrdup(""); poDS->adfGeoTransform[0] = 0.0; poDS->adfGeoTransform[1] = 1.0; poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[3] = 0.0; poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = 1.0; } } else { CPLError(CE_Warning, CPLE_AppDefined, "Unable to find sceneInfo tag in XML document. " "Proceeding with caution."); } CPLFree(pszGeorefFile); /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); poDS->TryLoadXML(); /* -------------------------------------------------------------------- */ /* Check for overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename ); CPLDestroyXMLNode(psData); return poDS; }
CC_FILE_ERROR RasterGridFilter::loadFile(QString filename, ccHObject& container, bool alwaysDisplayLoadDialog/*=true*/, bool* coordinatesShiftEnabled/*=0*/, CCVector3d* coordinatesShift/*=0*/) { GDALAllRegister(); ccLog::PrintDebug("(GDAL drivers: %i)", GetGDALDriverManager()->GetDriverCount()); GDALDataset* poDataset = static_cast<GDALDataset*>(GDALOpen( qPrintable(filename), GA_ReadOnly )); if( poDataset != NULL ) { ccLog::Print(QString("Raster file: '%1'").arg(filename)); ccLog::Print( "Driver: %s/%s", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); int rasterCount = poDataset->GetRasterCount(); int rasterX = poDataset->GetRasterXSize(); int rasterY = poDataset->GetRasterYSize(); ccLog::Print( "Size is %dx%dx%d", rasterX, rasterY, rasterCount ); ccPointCloud* pc = new ccPointCloud(); if (!pc->reserve(static_cast<unsigned>(rasterX * rasterY))) { delete pc; return CC_FERR_NOT_ENOUGH_MEMORY; } if( poDataset->GetProjectionRef() != NULL ) ccLog::Print( "Projection is `%s'", poDataset->GetProjectionRef() ); double adfGeoTransform[6] = { 0, //top left x 1, //w-e pixel resolution (can be negative) 0, //0 0, //top left y 0, //0 1 //n-s pixel resolution (can be negative) }; if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { ccLog::Print( "Origin = (%.6f,%.6f)", adfGeoTransform[0], adfGeoTransform[3] ); ccLog::Print( "Pixel Size = (%.6f,%.6f)", adfGeoTransform[1], adfGeoTransform[5] ); } if (adfGeoTransform[1] == 0 || adfGeoTransform[5] == 0) { ccLog::Warning("Invalid pixel size! Forcing it to (1,1)"); adfGeoTransform[1] = adfGeoTransform[5] = 1; } CCVector3d origin( adfGeoTransform[0], adfGeoTransform[3], 0.0 ); CCVector3d Pshift(0,0,0); //check for 'big' coordinates { bool shiftAlreadyEnabled = (coordinatesShiftEnabled && *coordinatesShiftEnabled && coordinatesShift); if (shiftAlreadyEnabled) Pshift = *coordinatesShift; bool applyAll = false; if ( sizeof(PointCoordinateType) < 8 && ccCoordinatesShiftManager::Handle(origin,0,alwaysDisplayLoadDialog,shiftAlreadyEnabled,Pshift,0,&applyAll)) { pc->setGlobalShift(Pshift); ccLog::Warning("[RasterFilter::loadFile] Raster has been recentered! Translation: (%.2f,%.2f,%.2f)",Pshift.x,Pshift.y,Pshift.z); //we save coordinates shift information if (applyAll && coordinatesShiftEnabled && coordinatesShift) { *coordinatesShiftEnabled = true; *coordinatesShift = Pshift; } } } //create blank raster 'grid' { double z = 0.0 /*+ Pshift.z*/; for (int j=0; j<rasterY; ++j) { double y = adfGeoTransform[3] + static_cast<double>(j) * adfGeoTransform[5] + Pshift.y; CCVector3 P( 0, static_cast<PointCoordinateType>(y), static_cast<PointCoordinateType>(z)); for (int i=0; i<rasterX; ++i) { double x = adfGeoTransform[0] + static_cast<double>(i) * adfGeoTransform[1] + Pshift.x; P.x = static_cast<PointCoordinateType>(x); pc->addPoint(P); } } QVariant xVar = QVariant::fromValue<int>(rasterX); QVariant yVar = QVariant::fromValue<int>(rasterY); pc->setMetaData("raster_width",xVar); pc->setMetaData("raster_height",yVar); } //fetch raster bands bool zRasterProcessed = false; unsigned zInvalid = 0; double zMinMax[2] = {0, 0}; for (int i=1; i<=rasterCount; ++i) { ccLog::Print( "Reading band #%i", i); GDALRasterBand* poBand = poDataset->GetRasterBand(i); GDALColorInterp colorInterp = poBand->GetColorInterpretation(); GDALDataType bandType = poBand->GetRasterDataType(); int nBlockXSize, nBlockYSize; poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); ccLog::Print( "Block=%dx%d Type=%s, ColorInterp=%s", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName(colorInterp) ); //fetching raster scan-line int nXSize = poBand->GetXSize(); int nYSize = poBand->GetYSize(); assert(nXSize == rasterX); assert(nYSize == rasterY); int bGotMin, bGotMax; double adfMinMax[2] = {0, 0}; adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if (!bGotMin || !bGotMax ) //DGM FIXME: if the file is corrupted (e.g. ASCII ArcGrid with missing rows) this method will enter in a infinite loop! GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); ccLog::Print( "Min=%.3fd, Max=%.3f", adfMinMax[0], adfMinMax[1] ); GDALColorTable* colTable = poBand->GetColorTable(); if( colTable != NULL ) printf( "Band has a color table with %d entries", colTable->GetColorEntryCount() ); if( poBand->GetOverviewCount() > 0 ) printf( "Band has %d overviews", poBand->GetOverviewCount() ); if (colorInterp == GCI_Undefined && !zRasterProcessed/*&& !colTable*/) //probably heights? { zRasterProcessed = true; zMinMax[0] = adfMinMax[0]; zMinMax[1] = adfMinMax[1]; double* scanline = (double*) CPLMalloc(sizeof(double)*nXSize); //double* scanline = new double[nXSize]; memset(scanline,0,sizeof(double)*nXSize); for (int j=0; j<nYSize; ++j) { if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/scanline, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Float64, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None) { delete pc; CPLFree(scanline); GDALClose(poDataset); return CC_FERR_READING; } for (int k=0; k<nXSize; ++k) { double z = static_cast<double>(scanline[k]) + Pshift[2]; unsigned pointIndex = static_cast<unsigned>(k + j * rasterX); if (pointIndex <= pc->size()) { if (z < zMinMax[0] || z > zMinMax[1]) { z = zMinMax[0] - 1.0; ++zInvalid; } const_cast<CCVector3*>(pc->getPoint(pointIndex))->z = static_cast<PointCoordinateType>(z); } } } //update bounding-box pc->invalidateBoundingBox(); if (scanline) CPLFree(scanline); scanline = 0; } else //colors { bool isRGB = false; bool isScalar = false; bool isPalette = false; switch(colorInterp) { case GCI_Undefined: isScalar = true; break; case GCI_PaletteIndex: isPalette = true; break; case GCI_RedBand: case GCI_GreenBand: case GCI_BlueBand: isRGB = true; break; case GCI_AlphaBand: if (adfMinMax[0] != adfMinMax[1]) isScalar = true; else ccLog::Warning(QString("Alpha band ignored as it has a unique value (%1)").arg(adfMinMax[0])); break; default: isScalar = true; break; } if (isRGB || isPalette) { //first check that a palette exists if the band is a palette index if (isPalette && !colTable) { ccLog::Warning(QString("Band is declared as a '%1' but no palette is associated!").arg(GDALGetColorInterpretationName(colorInterp))); isPalette = false; } else { //instantiate memory for RBG colors if necessary if (!pc->hasColors() && !pc->setRGBColor(MAX_COLOR_COMP,MAX_COLOR_COMP,MAX_COLOR_COMP)) { ccLog::Warning(QString("Failed to instantiate memory for storing color band '%1'!").arg(GDALGetColorInterpretationName(colorInterp))); } else { assert(bandType <= GDT_Int32); int* colIndexes = (int*) CPLMalloc(sizeof(int)*nXSize); //double* scanline = new double[nXSize]; memset(colIndexes,0,sizeof(int)*nXSize); for (int j=0; j<nYSize; ++j) { if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/colIndexes, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Int32, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None) { CPLFree(colIndexes); delete pc; return CC_FERR_READING; } for (int k=0; k<nXSize; ++k) { unsigned pointIndex = static_cast<unsigned>(k + j * rasterX); if (pointIndex <= pc->size()) { colorType* C = const_cast<colorType*>(pc->getPointColor(pointIndex)); switch(colorInterp) { case GCI_PaletteIndex: assert(colTable); { GDALColorEntry col; colTable->GetColorEntryAsRGB(colIndexes[k],&col); C[0] = static_cast<colorType>(col.c1 & MAX_COLOR_COMP); C[1] = static_cast<colorType>(col.c2 & MAX_COLOR_COMP); C[2] = static_cast<colorType>(col.c3 & MAX_COLOR_COMP); } break; case GCI_RedBand: C[0] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP); break; case GCI_GreenBand: C[1] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP); break; case GCI_BlueBand: C[2] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP); break; default: assert(false); break; } } } } if (colIndexes) CPLFree(colIndexes); colIndexes = 0; pc->showColors(true); } } } else if (isScalar) { ccScalarField* sf = new ccScalarField(GDALGetColorInterpretationName(colorInterp)); if (!sf->resize(pc->size(),true,NAN_VALUE)) { ccLog::Warning(QString("Failed to instantiate memory for storing '%1' as a scalar field!").arg(sf->getName())); sf->release(); sf = 0; } else { double* colValues = (double*) CPLMalloc(sizeof(double)*nXSize); //double* scanline = new double[nXSize]; memset(colValues,0,sizeof(double)*nXSize); for (int j=0; j<nYSize; ++j) { if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/colValues, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Float64, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None) { CPLFree(colValues); delete pc; return CC_FERR_READING; } for (int k=0; k<nXSize; ++k) { unsigned pointIndex = static_cast<unsigned>(k + j * rasterX); if (pointIndex <= pc->size()) { ScalarType s = static_cast<ScalarType>(colValues[k]); sf->setValue(pointIndex,s); } } } if (colValues) CPLFree(colValues); colValues = 0; sf->computeMinAndMax(); pc->addScalarField(sf); if (pc->getNumberOfScalarFields() == 1) pc->setCurrentDisplayedScalarField(0); pc->showSF(true); } } } } if (pc) { if (!zRasterProcessed) { ccLog::Warning("Raster has no height (Z) information: you can convert one of its scalar fields to Z with 'Edit > Scalar Fields > Set SF as coordinate(s)'"); } else if (zInvalid != 0 && zInvalid < pc->size()) { //shall we remove the points with invalid heights? if (QMessageBox::question(0,"Remove NaN points?","This raster has pixels with invalid heights. Shall we remove them?",QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { CCLib::ReferenceCloud validPoints(pc); unsigned count = pc->size(); bool error = true; if (validPoints.reserve(count-zInvalid)) { for (unsigned i=0; i<count; ++i) { if (pc->getPoint(i)->z >= zMinMax[0]) validPoints.addPointIndex(i); } if (validPoints.size() > 0) { validPoints.resize(validPoints.size()); ccPointCloud* newPC = pc->partialClone(&validPoints); if (newPC) { delete pc; pc = newPC; error = false; } } else { assert(false); } } if (error) { ccLog::Error("Not enough memory to remove the points with invalid heights!"); } } } container.addChild(pc); } GDALClose(poDataset); } else { return CC_FERR_UNKNOWN_FILE; } return CC_FERR_NO_ERROR; }
/** * Sets the surface grids based on a ncepNam (surface only!) forecast. * @param input The WindNinjaInputs for misc. info. * @param airGrid The air temperature grid to be filled. * @param cloudGrid The cloud cover grid to be filled. * @param uGrid The u velocity grid to be filled. * @param vGrid The v velocity grid to be filled. * @param wGrid The w velocity grid to be filled (filled with zeros here?). */ void genericSurfInitialization::setSurfaceGrids( WindNinjaInputs &input, AsciiGrid<double> &airGrid, AsciiGrid<double> &cloudGrid, AsciiGrid<double> &uGrid, AsciiGrid<double> &vGrid, AsciiGrid<double> &wGrid ) { int bandNum = -1; //get time list std::vector<boost::local_time::local_date_time> timeList( getTimeList(input.ninjaTimeZone) ); //Search time list for our time to identify our band number for cloud/speed/dir for(unsigned int i = 0; i < timeList.size(); i++) { if(input.ninjaTime == timeList[i]) { bandNum = i + 1; break; } } if(bandNum < 0) throw std::runtime_error("Could not match ninjaTime with a band number in the forecast file."); //get some info from the nam file in input //Acquire a lock to protect the non-thread safe netCDF library #ifdef _OPENMP omp_guard netCDF_guard(netCDF_lock); #endif GDALDataset* poDS; //attempt to grab the projection from the dem? //check for member prjString first std::string dstWkt; dstWkt = input.dem.prjString; if ( dstWkt.empty() ) { //try to open original poDS = (GDALDataset*)GDALOpen( input.dem.fileName.c_str(), GA_ReadOnly ); if( poDS == NULL ) { CPLDebug( "ncepNdfdInitialization::setSurfaceGrids()", "Bad projection reference" ); //throw(); } dstWkt = poDS->GetProjectionRef(); if( dstWkt.empty() ) { CPLDebug( "ncepNdfdInitialization::setSurfaceGrids()", "Bad projection reference" ); //throw() } GDALClose((GDALDatasetH) poDS ); } poDS = (GDALDataset*)GDALOpen( input.forecastFilename.c_str(), GA_ReadOnly ); if( poDS == NULL ) { CPLDebug( "ncepNdfdInitialization::setSurfaceGrids()", "Bad forecast file" ); } else GDALClose((GDALDatasetH) poDS ); // open ds one by one and warp, then write to grid GDALDataset *srcDS, *wrpDS; std::string temp; std::string srcWkt; std::vector<std::string> varList = getVariableList(); /* * Set the initial values in the warped dataset to no data */ GDALWarpOptions* psWarpOptions; for( unsigned int i = 0;i < varList.size();i++ ) { temp = "NETCDF:" + input.forecastFilename + ":" + varList[i]; srcDS = (GDALDataset*)GDALOpenShared( temp.c_str(), GA_ReadOnly ); if( srcDS == NULL ) { CPLDebug( "ncepNdfdInitialization::setSurfaceGrids()", "Bad forecast file" ); } srcWkt = srcDS->GetProjectionRef(); if( srcWkt.empty() ) { CPLDebug( "ncepNdfdInitialization::setSurfaceGrids()", "Bad forecast file" ); //throw } /* * Grab the first band to get the nodata value for the variable, * assume all bands have the same ndv */ GDALRasterBand *poBand = srcDS->GetRasterBand( 1 ); int pbSuccess; double dfNoData = poBand->GetNoDataValue( &pbSuccess ); psWarpOptions = GDALCreateWarpOptions(); int nBandCount = srcDS->GetRasterCount(); psWarpOptions->nBandCount = nBandCount; psWarpOptions->padfDstNoDataReal = (double*) CPLMalloc( sizeof( double ) * nBandCount ); psWarpOptions->padfDstNoDataImag = (double*) CPLMalloc( sizeof( double ) * nBandCount ); for( int b = 0;b < srcDS->GetRasterCount();b++ ) { psWarpOptions->padfDstNoDataReal[b] = dfNoData; psWarpOptions->padfDstNoDataImag[b] = dfNoData; } if( pbSuccess == false ) dfNoData = -9999.0; psWarpOptions->papszWarpOptions = CSLSetNameValue( psWarpOptions->papszWarpOptions, "INIT_DEST", "NO_DATA" ); wrpDS = (GDALDataset*) GDALAutoCreateWarpedVRT( srcDS, srcWkt.c_str(), dstWkt.c_str(), GRA_NearestNeighbour, 1.0, psWarpOptions ); if( varList[i] == "Temperature_height_above_ground" ) { GDAL2AsciiGrid( wrpDS, bandNum, airGrid ); if( CPLIsNan( dfNoData ) ) { airGrid.set_noDataValue(-9999.0); airGrid.replaceNan( -9999.0 ); } } else if( varList[i] == "V-component_of_wind_height_above_ground" ) { GDAL2AsciiGrid( wrpDS, bandNum, vGrid ); if( CPLIsNan( dfNoData ) ) { vGrid.set_noDataValue(-9999.0); vGrid.replaceNan( -9999.0 ); } } else if( varList[i] == "U-component_of_wind_height_above_ground" ) { GDAL2AsciiGrid( wrpDS, bandNum, uGrid ); if( CPLIsNan( dfNoData ) ) { uGrid.set_noDataValue(-9999.0); uGrid.replaceNan( -9999.0 ); } } else if( varList[i] == "Total_cloud_cover" ) { GDAL2AsciiGrid( wrpDS, bandNum, cloudGrid ); if( CPLIsNan( dfNoData ) ) { cloudGrid.set_noDataValue(-9999.0); cloudGrid.replaceNan( -9999.0 ); } } GDALDestroyWarpOptions( psWarpOptions ); GDALClose((GDALDatasetH) srcDS ); GDALClose((GDALDatasetH) wrpDS ); } cloudGrid /= 100.0; wGrid.set_headerData( uGrid ); wGrid = 0.0; }
int main(int argc, char *argv[]){ GDALDataset *poDataset; GDALAllRegister(); if(argc != 3){ std::cout << "usage:\n" << argv[0] << " src_file dest_file\n"; exit(0); } const std::string name = argv[1]; const std::string destName = argv[2]; poDataset = (GDALDataset *) GDALOpen(name.c_str(), GA_ReadOnly ); if( poDataset == NULL ){ std::cout << "Failed to open " << name << "\n"; }else{ const char *pszFormat = "GTiff"; GDALDriver *poDriver; char **papszMetadata; poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); if( poDriver == NULL ){ std::cout << "Cant open driver\n"; exit(1); } papszMetadata = GDALGetMetadata( poDriver, NULL ); if( !CSLFetchBoolean( papszMetadata, GDAL_DCAP_CREATE, FALSE ) ){ std::cout << "Create Method not suported!\n"; } if( !CSLFetchBoolean( papszMetadata, GDAL_DCAP_CREATECOPY, FALSE ) ){ std::cout << "CreateCopy() method not suported.\n"; } char **papszOptions = NULL; GDALDataset *dest = poDriver->Create(destName.c_str() , poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), 3, GDT_Byte, papszOptions ); std::cout << "Reading file " << name << "\n"; std::cout << "x= " << poDataset->GetRasterXSize() << ", h=" << poDataset->GetRasterYSize() << ", bands= " << poDataset->GetRasterCount() << "\n"; GDALRasterBand *data; data = poDataset->GetRasterBand(1); GDALDataType type = data->GetRasterDataType(); printDataType(type); int size = data->GetXSize()*data->GetYSize(); std::cout << "size=" << size << " , w*h = " << poDataset->GetRasterXSize()*poDataset->GetRasterYSize() << "\n"; float *buffer; buffer = (float *) CPLMalloc(sizeof(float)*size); data->RasterIO(GF_Read, 0, 0, data->GetXSize(), data->GetYSize(), buffer, data->GetXSize(), data->GetYSize(), GDT_Float32, 0, 0 ); GDALRasterBand *destBand1 = dest->GetRasterBand(1); GDALRasterBand *destBand2 = dest->GetRasterBand(2); GDALRasterBand *destBand3 = dest->GetRasterBand(3); // GDALRasterBand *destBand4 = dest->GetRasterBand(4); // Metadata, double geot[6]; poDataset->GetGeoTransform(geot); dest->SetGeoTransform(geot);// adfGeoTransform ); dest->SetProjection( poDataset->GetProjectionRef() ); GByte destWrite1[size]; // = (GUInt32 *) CPLMalloc(sizeof(GUInt32)*size); GByte destWrite2[size]; GByte destWrite3[size]; // GByte destWrite4[size]; unsigned int i; float max=0, min=0; for(i=0; i<size; i++){ if(max < buffer[i]){ max = buffer[i]; } if(min > buffer[i]){ min = buffer[i]; } } float range = max - min; std::cout << "range=" << range << ", max=" << max << ", min=" << min << "\n"; std::map<float, unsigned int> counter; for(i=0; i<size; i++){ counter[buffer[i]]++; unsigned int v = buffer[i] * 100; destWrite1[i] = (v & (0xff << 0)) >> 0; destWrite2[i] = (v & (0xff << 8)) >> 8; destWrite3[i] = (v & (0xff << 16)) >> 16; // destWrite4[i] = 0x00; // (v & (0xff << 24)) >> 24; } destBand1->RasterIO( GF_Write, 0, 0, data->GetXSize(), data->GetYSize(), destWrite1, data->GetXSize(), data->GetYSize(), GDT_Byte, 0, 0 ); destBand2->RasterIO( GF_Write, 0, 0, data->GetXSize(), data->GetYSize(), destWrite2, data->GetXSize(), data->GetYSize(), GDT_Byte, 0, 0 ); destBand3->RasterIO( GF_Write, 0, 0, data->GetXSize(), data->GetYSize(), destWrite3, data->GetXSize(), data->GetYSize(), GDT_Byte, 0, 0 ); // destBand4->RasterIO( GF_Write, 0, 0, data->GetXSize(), data->GetYSize(), // destWrite4, data->GetXSize(), data->GetYSize(), GDT_Byte, 0, 0 ); /*std::map<float, unsigned int>::iterator it; std::cout << "Counter: \n"; for(it=counter.begin(); it!=counter.end(); it++){ std::cout << (it->first*1000) << " = " << it->second << "\n"; }*/ /* Once we're done, close properly the dataset */ if( dest != NULL ){ GDALClose(dest ); GDALClose(poDataset ); } /* unsigned int *buffer; buffer = (unsigned int *) CPLMalloc(sizeof(unsigned int)*size); data->RasterIO(GF_Read, 0, 0, size, 1, buffer, size, 1, GDT_UInt32, 0, 0 ); unsigned int i; std::map<unsigned int, unsigned int> counter; for(i=0; i<size; i++){ counter[buffer[i]]++; } std::map<unsigned int, unsigned int>::iterator it; std::cout << "Counter: \n"; for(it=counter.begin(); it!=counter.end(); it++){ std::cout << it->first << " = " << it->second << "\n"; }*/ } exit(0); }
IRaster* ingestGDALRaster() { GDALDataset* ds = gdalDataset; cout << "Reading raster metadata..."; GDALRasterBand* band = ds->GetRasterBand(bandNum); int xSize = band->GetXSize(); int ySize = band->GetYSize(); int hasNoDataValue; double noDataValue = band->GetNoDataValue(&hasNoDataValue); if (hasNoDataValue != 0) noDataValue = NULL_DOUBLE_; double xForm[6]; ds->GetGeoTransform(xForm); double minX = xForm[0]; double cellSizeX = xForm[1]; double skewX = xForm[2]; double minY = xForm[3]; double skewY = xForm[4]; double cellSizeY = xForm[5]; string* spatialRef = new string(ds->GetProjectionRef()); if( ds->GetMetadataItem("NC_GLOBAL#IOAPI_VERSION", "") != NULL) { // Get georeference from IOAPI metadata // See: http://www.baronams.com/products/ioapi/GRIDS.html#horiz // Build the affine transform from metadata minX = atof(ds->GetMetadataItem("NC_GLOBAL#XORIG", "")); minY = atof(ds->GetMetadataItem("NC_GLOBAL#YORIG", "")); cellSizeX = atof(ds->GetMetadataItem("NC_GLOBAL#XCELL", "")); cellSizeY = atof(ds->GetMetadataItem("NC_GLOBAL#YCELL", "")); skewX = 0; skewY = 0; // Build the SpatialReference double xcent, ycent, p_alp, p_bet, p_gam; char *gdnam; OGRSpatialReference* sref = new OGRSpatialReference(""); // Assume datum is WGS84 (may not be, but IO/API files don't (can't?) say...) sref->SetWellKnownGeogCS("WGS84"); int gdtyp = atoi(ds->GetMetadataItem("NC_GLOBAL#GDTYP", "")); switch(gdtyp) { case 0: // Unknown projection (we assume lat-lon) break; case 1: // LATGRD3 -- Latitude/longitude break; case 2: // LAMGRD3 -- Lambert Conformal Conic (two standard parallels) xcent = atof(ds->GetMetadataItem("NC_GLOBAL#XCENT", "")); ycent = atof(ds->GetMetadataItem("NC_GLOBAL#YCENT", "")); p_alp = atof(ds->GetMetadataItem("NC_GLOBAL#P_ALP", "")); p_bet = atof(ds->GetMetadataItem("NC_GLOBAL#P_BET", "")); sref->SetLCC(p_alp, p_bet, ycent, xcent, 0, 0); gdnam = (char *)ds->GetMetadataItem("NC_GLOBAL#GDNAM", ""); sref->SetProjCS(gdnam); break; case 9: // ALBGRD3 -- Albers Equal-Area Conic xcent = atof(ds->GetMetadataItem("NC_GLOBAL#XCENT", "")); ycent = atof(ds->GetMetadataItem("NC_GLOBAL#YCENT", "")); p_alp = atof(ds->GetMetadataItem("NC_GLOBAL#P_ALP", "")); p_bet = atof(ds->GetMetadataItem("NC_GLOBAL#P_BET", "")); sref->SetACEA(p_alp, p_bet, ycent, xcent, 0, 0); gdnam = (char *)ds->GetMetadataItem("NC_GLOBAL#GDNAM", ""); sref->SetProjCS(gdnam); break; case 10: // LEQGRID3 -- Lambert Azimuthal Equal-Area p_alp = atof(ds->GetMetadataItem("NC_GLOBAL#P_ALP", "")); // Correct for bad metadata on some files if(p_alp == 0.0) { xcent = atof(ds->GetMetadataItem("NC_GLOBAL#XCENT", "")); ycent = atof(ds->GetMetadataItem("NC_GLOBAL#YCENT", "")); p_alp = ycent; p_gam = xcent; } else { p_gam = atof(ds->GetMetadataItem("NC_GLOBAL#P_GAM", "")); } sref->SetLAEA(p_alp, p_gam, 0, 0); gdnam = (char *)ds->GetMetadataItem("NC_GLOBAL#GDNAM", ""); sref->SetProjCS(gdnam); break; default: throw new runtime_error("ERROR: Unable to parse IO/API GDTYP variable"); } char* wktSrStr = new char[spatialRef->length()]; strcpy((char *)spatialRef->c_str(), wktSrStr); sref->exportToWkt(&wktSrStr); //CPLFree(sref); spatialRef->assign(wktSrStr); } cout << "...Done.\nReading raster band " << bandNum << "..."; IRaster* result = NULL; CPLErr retval; switch (band->GetRasterDataType()) { //retval = band->RasterIO(GF_Read, 0, 0, band->XSize, band->YSize, floatArray, band->XSize, band->YSize, 0, 0); case GDT_Float32: { float* floatArray = new float[xSize * ySize]; retval = band->RasterIO(GF_Read, 0, 0, xSize, ySize, floatArray, xSize, ySize, band->GetRasterDataType(), 0, 0); if (retval != CE_None) throw new runtime_error("GDALRasterBand::ReadBlock() returned error"); result = new Raster<float>(floatArray, xSize, ySize, cellSizeX, cellSizeY, minX, minY, skewX, skewY, spatialRef, noDataValue); cout << " -- Pixel type: Float32 -- ...Done\n"; } break; case GDT_Float64: { double* doubleArray = new double[xSize * ySize]; retval = band->RasterIO(GF_Read, 0, 0, xSize, ySize, doubleArray, xSize, ySize, band->GetRasterDataType(), 0, 0); if (retval != CE_None) throw new runtime_error("GDALRasterBand::ReadBlock() returned error"); result = new Raster<double>(doubleArray, xSize, ySize, cellSizeX, cellSizeY, minX, minY, skewX, skewY, spatialRef, noDataValue); cout << " -- Pixel type: Float64 -- ...Done\n"; } break; case GDT_Int32: { int* intArray = new int[xSize * ySize]; retval = band->RasterIO(GF_Read, 0, 0, xSize, ySize, intArray, xSize, ySize, band->GetRasterDataType(), 0, 0); if (retval != CE_None) throw new runtime_error("GDALRasterBand::ReadBlock() returned error"); result = new Raster<int>(intArray, xSize, ySize, cellSizeX, cellSizeY, minX, minY, skewX, skewY, spatialRef, noDataValue); cout << " -- Pixel type: Int32 -- ...Done\n"; } break; case GDT_Int16: { short* shortArray = new short[xSize * ySize]; retval = band->RasterIO(GF_Read, 0, 0, xSize, ySize, shortArray, xSize, ySize, band->GetRasterDataType(), 0, 0); if (retval != CE_None) throw new runtime_error("GDALRasterBand::ReadBlock() returned error"); result = new Raster<short>(shortArray, xSize, ySize, cellSizeX, cellSizeY, minX, minY, skewX, skewY, spatialRef, noDataValue); cout << " -- Pixel type: Int32 -- ...Done\n"; } break; case GDT_Byte: { char* byteArray = new char[xSize * ySize]; retval = band->RasterIO(GF_Read, 0, 0, xSize, ySize, byteArray, xSize, ySize, band->GetRasterDataType(), 0, 0); if (retval != CE_None) throw new runtime_error("GDALRasterBand::ReadBlock() returned error"); result = new Raster<char>(byteArray, xSize, ySize, cellSizeX, cellSizeY, minX, minY, skewX, skewY, spatialRef, noDataValue); cout << " -- Pixel type: Byte -- ...Done\n"; } break; default: throw new runtime_error("Unsupported pixel type"); } return result; }
/** * Checks the downloaded data to see if it is all valid. */ void genericSurfInitialization::checkForValidData() { //just make up a "dummy" timezone for use here boost::local_time::time_zone_ptr zone(new boost::local_time::posix_time_zone("MST-07")); //get time list std::vector<boost::local_time::local_date_time> timeList( getTimeList(zone) ); boost::posix_time::ptime pt_low(boost::gregorian::date(1900,boost::gregorian::Jan,1), boost::posix_time::hours(12)); boost::posix_time::ptime pt_high(boost::gregorian::date(2100,boost::gregorian::Jan,1), boost::posix_time::hours(12)); boost::local_time::local_date_time low_time(pt_low, zone); boost::local_time::local_date_time high_time(pt_high, zone); //check times for(unsigned int i = 0; i < timeList.size(); i++) { if(timeList[i].is_special()) //if time is any special value (not_a_date_time, infinity, etc.) throw badForecastFile("Bad time in forecast file."); if(timeList[i] < low_time || timeList[i] > high_time) throw badForecastFile("Bad time in forecast file."); } // open ds variable by variable GDALDataset *srcDS; std::string temp; std::string srcWkt; int nBands = 0; bool noDataValueExists; bool noDataIsNan; std::vector<std::string> varList = getVariableList(); //Acquire a lock to protect the non-thread safe netCDF library #ifdef _OPENMP omp_guard netCDF_guard(netCDF_lock); #endif for( unsigned int i = 0;i < varList.size();i++ ) { temp = "NETCDF:" + wxModelFileName + ":" + varList[i]; srcDS = (GDALDataset*)GDALOpen( temp.c_str(), GA_ReadOnly ); if( srcDS == NULL ) throw badForecastFile("Cannot open forecast file."); srcWkt = srcDS->GetProjectionRef(); if( srcWkt.empty() ) throw badForecastFile("Forecast file doesn't have projection information."); //Get total bands (time steps) nBands = srcDS->GetRasterCount(); int nXSize, nYSize; GDALRasterBand *poBand; int pbSuccess; double dfNoData; double *padfScanline; nXSize = srcDS->GetRasterXSize(); nYSize = srcDS->GetRasterYSize(); //loop over all bands for this variable (bands are time steps) for(int j = 1; j <= nBands; j++) { poBand = srcDS->GetRasterBand( j ); pbSuccess = 0; dfNoData = poBand->GetNoDataValue( &pbSuccess ); if( pbSuccess == false ) noDataValueExists = false; else { noDataValueExists = true; noDataIsNan = CPLIsNan(dfNoData); } //set the data padfScanline = new double[nXSize*nYSize]; poBand->RasterIO(GF_Read, 0, 0, nXSize, nYSize, padfScanline, nXSize, nYSize, GDT_Float64, 0, 0); for(int k = 0;k < nXSize*nYSize; k++) { //Check if value is no data (if no data value was defined in file) if(noDataValueExists) { if(noDataIsNan) { if(CPLIsNan(padfScanline[k])) throw badForecastFile("Forecast file contains no_data values."); }else { if(padfScanline[k] == dfNoData) throw badForecastFile("Forecast file contains no_data values."); } } if( varList[i] == "Temperature_height_above_ground" ) //units are Kelvin { if(padfScanline[k] < 180.0 || padfScanline[k] > 340.0) //these are near the most extreme temperatures ever recored on earth throw badForecastFile("Temperature is out of range in forecast file."); } else if( varList[i] == "V-component_of_wind_height_above_ground" ) //units are m/s { if(std::abs(padfScanline[k]) > 220.0) throw badForecastFile("V-velocity is out of range in forecast file."); } else if( varList[i] == "U-component_of_wind_height_above_ground" ) //units are m/s { if(std::abs(padfScanline[k]) > 220.0) throw badForecastFile("U-velocity is out of range in forecast file."); } else if( varList[i] == "Total_cloud_cover" ) //units are percent { if(padfScanline[k] < 0.0 || padfScanline[k] > 100.0) throw badForecastFile("Total cloud cover is out of range in forecast file."); } } delete [] padfScanline; } GDALClose((GDALDatasetH) srcDS ); } }
GDALDataset *ERSDataset::Open( GDALOpenInfo * poOpenInfo ) { /* -------------------------------------------------------------------- */ /* We assume the user selects the .ers file. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->nHeaderBytes > 15 && EQUALN((const char *) poOpenInfo->pabyHeader,"Algorithm Begin",15) ) { CPLError( CE_Failure, CPLE_OpenFailed, "%s appears to be an algorithm ERS file, which is not currently supported.", poOpenInfo->pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* We assume the user selects the .ers file. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->nHeaderBytes < 15 || !EQUALN((const char *) poOpenInfo->pabyHeader,"DatasetHeader ",14) ) return NULL; /* -------------------------------------------------------------------- */ /* Open the .ers file, and read the first line. */ /* -------------------------------------------------------------------- */ VSILFILE *fpERS = VSIFOpenL( poOpenInfo->pszFilename, "rb" ); if( fpERS == NULL ) return NULL; CPLReadLineL( fpERS ); /* -------------------------------------------------------------------- */ /* Now ingest the rest of the file as a tree of header nodes. */ /* -------------------------------------------------------------------- */ ERSHdrNode *poHeader = new ERSHdrNode(); if( !poHeader->ParseChildren( fpERS ) ) { delete poHeader; VSIFCloseL( fpERS ); return NULL; } VSIFCloseL( fpERS ); /* -------------------------------------------------------------------- */ /* Do we have the minimum required information from this header? */ /* -------------------------------------------------------------------- */ if( poHeader->Find( "RasterInfo.NrOfLines" ) == NULL || poHeader->Find( "RasterInfo.NrOfCellsPerLine" ) == NULL || poHeader->Find( "RasterInfo.NrOfBands" ) == NULL ) { if( poHeader->FindNode( "Algorithm" ) != NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "%s appears to be an algorithm ERS file, which is not currently supported.", poOpenInfo->pszFilename ); } delete poHeader; return NULL; } /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ ERSDataset *poDS; poDS = new ERSDataset(); poDS->poHeader = poHeader; poDS->eAccess = poOpenInfo->eAccess; /* -------------------------------------------------------------------- */ /* Capture some information from the file that is of interest. */ /* -------------------------------------------------------------------- */ int nBands = atoi(poHeader->Find( "RasterInfo.NrOfBands" )); poDS->nRasterXSize = atoi(poHeader->Find( "RasterInfo.NrOfCellsPerLine" )); poDS->nRasterYSize = atoi(poHeader->Find( "RasterInfo.NrOfLines" )); if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize) || !GDALCheckBandCount(nBands, FALSE)) { delete poDS; return NULL; } /* -------------------------------------------------------------------- */ /* Get the HeaderOffset if it exists in the header */ /* -------------------------------------------------------------------- */ GIntBig nHeaderOffset = 0; if( poHeader->Find( "HeaderOffset" ) != NULL ) { nHeaderOffset = atoi(poHeader->Find( "HeaderOffset" )); } /* -------------------------------------------------------------------- */ /* Establish the data type. */ /* -------------------------------------------------------------------- */ GDALDataType eType; CPLString osCellType = poHeader->Find( "RasterInfo.CellType", "Unsigned8BitInteger" ); if( EQUAL(osCellType,"Unsigned8BitInteger") ) eType = GDT_Byte; else if( EQUAL(osCellType,"Signed8BitInteger") ) eType = GDT_Byte; else if( EQUAL(osCellType,"Unsigned16BitInteger") ) eType = GDT_UInt16; else if( EQUAL(osCellType,"Signed16BitInteger") ) eType = GDT_Int16; else if( EQUAL(osCellType,"Unsigned32BitInteger") ) eType = GDT_UInt32; else if( EQUAL(osCellType,"Signed32BitInteger") ) eType = GDT_Int32; else if( EQUAL(osCellType,"IEEE4ByteReal") ) eType = GDT_Float32; else if( EQUAL(osCellType,"IEEE8ByteReal") ) eType = GDT_Float64; else { CPLDebug( "ERS", "Unknown CellType '%s'", osCellType.c_str() ); eType = GDT_Byte; } /* -------------------------------------------------------------------- */ /* Pick up the word order. */ /* -------------------------------------------------------------------- */ int bNative; #ifdef CPL_LSB bNative = EQUAL(poHeader->Find( "ByteOrder", "LSBFirst" ), "LSBFirst"); #else bNative = EQUAL(poHeader->Find( "ByteOrder", "MSBFirst" ), "MSBFirst"); #endif /* -------------------------------------------------------------------- */ /* Figure out the name of the target file. */ /* -------------------------------------------------------------------- */ CPLString osPath = CPLGetPath( poOpenInfo->pszFilename ); CPLString osDataFile = poHeader->Find( "DataFile", "" ); CPLString osDataFilePath; if( osDataFile.length() == 0 ) // just strip off extension. { osDataFile = CPLGetFilename( poOpenInfo->pszFilename ); osDataFile = osDataFile.substr( 0, osDataFile.find_last_of('.') ); } osDataFilePath = CPLFormFilename( osPath, osDataFile, NULL ); /* -------------------------------------------------------------------- */ /* DataSetType = Translated files are links to things like ecw */ /* files. */ /* -------------------------------------------------------------------- */ if( EQUAL(poHeader->Find("DataSetType",""),"Translated") ) { poDS->poDepFile = (GDALDataset *) GDALOpenShared( osDataFilePath, poOpenInfo->eAccess ); if( poDS->poDepFile != NULL && poDS->poDepFile->GetRasterCount() >= nBands ) { int iBand; for( iBand = 0; iBand < nBands; iBand++ ) { // Assume pixel interleaved. poDS->SetBand( iBand+1, poDS->poDepFile->GetRasterBand( iBand+1 ) ); } } } /* ==================================================================== */ /* While ERStorage indicates a raw file. */ /* ==================================================================== */ else if( EQUAL(poHeader->Find("DataSetType",""),"ERStorage") ) { // Open data file. if( poOpenInfo->eAccess == GA_Update ) poDS->fpImage = VSIFOpenL( osDataFilePath, "r+" ); else poDS->fpImage = VSIFOpenL( osDataFilePath, "r" ); poDS->osRawFilename = osDataFilePath; if( poDS->fpImage != NULL ) { int iWordSize = GDALGetDataTypeSize(eType) / 8; int iBand; for( iBand = 0; iBand < nBands; iBand++ ) { // Assume pixel interleaved. poDS->SetBand( iBand+1, new RawRasterBand( poDS, iBand+1, poDS->fpImage, nHeaderOffset + iWordSize * iBand * poDS->nRasterXSize, iWordSize, iWordSize * nBands * poDS->nRasterXSize, eType, bNative, TRUE )); if( EQUAL(osCellType,"Signed8BitInteger") ) poDS->GetRasterBand(iBand+1)-> SetMetadataItem( "PIXELTYPE", "SIGNEDBYTE", "IMAGE_STRUCTURE" ); } } } /* -------------------------------------------------------------------- */ /* Otherwise we have an error! */ /* -------------------------------------------------------------------- */ if( poDS->nBands == 0 ) { delete poDS; return NULL; } /* -------------------------------------------------------------------- */ /* Look for band descriptions. */ /* -------------------------------------------------------------------- */ int iChild, iBand = 0; ERSHdrNode *poRI = poHeader->FindNode( "RasterInfo" ); for( iChild = 0; poRI != NULL && iChild < poRI->nItemCount && iBand < poDS->nBands; iChild++ ) { if( poRI->papoItemChild[iChild] != NULL && EQUAL(poRI->papszItemName[iChild],"BandId") ) { const char *pszValue = poRI->papoItemChild[iChild]->Find( "Value", NULL ); iBand++; if( pszValue ) { CPLPushErrorHandler( CPLQuietErrorHandler ); poDS->GetRasterBand( iBand )->SetDescription( pszValue ); CPLPopErrorHandler(); } pszValue = poRI->papoItemChild[iChild]->Find( "Units", NULL ); if ( pszValue ) { CPLPushErrorHandler( CPLQuietErrorHandler ); poDS->GetRasterBand( iBand )->SetUnitType( pszValue ); CPLPopErrorHandler(); } } } /* -------------------------------------------------------------------- */ /* Look for projection. */ /* -------------------------------------------------------------------- */ OGRSpatialReference oSRS; CPLString osProjection = poHeader->Find( "CoordinateSpace.Projection", "RAW" ); CPLString osDatum = poHeader->Find( "CoordinateSpace.Datum", "WGS84" ); CPLString osUnits = poHeader->Find( "CoordinateSpace.Units", "METERS" ); oSRS.importFromERM( osProjection, osDatum, osUnits ); CPLFree( poDS->pszProjection ); oSRS.exportToWkt( &(poDS->pszProjection) ); /* -------------------------------------------------------------------- */ /* Look for the geotransform. */ /* -------------------------------------------------------------------- */ if( poHeader->Find( "RasterInfo.RegistrationCoord.Eastings", NULL ) && poHeader->Find( "RasterInfo.CellInfo.Xdimension", NULL ) ) { poDS->bGotTransform = TRUE; poDS->adfGeoTransform[0] = CPLAtof( poHeader->Find( "RasterInfo.RegistrationCoord.Eastings", "" )); poDS->adfGeoTransform[1] = CPLAtof( poHeader->Find( "RasterInfo.CellInfo.Xdimension", "" )); poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[3] = CPLAtof( poHeader->Find( "RasterInfo.RegistrationCoord.Northings", "" )); poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = -CPLAtof( poHeader->Find( "RasterInfo.CellInfo.Ydimension", "" )); } else if( poHeader->Find( "RasterInfo.RegistrationCoord.Latitude", NULL ) && poHeader->Find( "RasterInfo.CellInfo.Xdimension", NULL ) ) { poDS->bGotTransform = TRUE; poDS->adfGeoTransform[0] = ERSDMS2Dec( poHeader->Find( "RasterInfo.RegistrationCoord.Longitude", "" )); poDS->adfGeoTransform[1] = CPLAtof( poHeader->Find( "RasterInfo.CellInfo.Xdimension", "" )); poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[3] = ERSDMS2Dec( poHeader->Find( "RasterInfo.RegistrationCoord.Latitude", "" )); poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = -CPLAtof( poHeader->Find( "RasterInfo.CellInfo.Ydimension", "" )); } /* -------------------------------------------------------------------- */ /* Adjust if we have a registration cell. */ /* -------------------------------------------------------------------- */ int iCellX = atoi(poHeader->Find("RasterInfo.RegistrationCellX", "1")); int iCellY = atoi(poHeader->Find("RasterInfo.RegistrationCellY", "1")); if( poDS->bGotTransform ) { poDS->adfGeoTransform[0] -= (iCellX-1) * poDS->adfGeoTransform[1] + (iCellY-1) * poDS->adfGeoTransform[2]; poDS->adfGeoTransform[3] -= (iCellX-1) * poDS->adfGeoTransform[4] + (iCellY-1) * poDS->adfGeoTransform[5]; } /* -------------------------------------------------------------------- */ /* Check for null values. */ /* -------------------------------------------------------------------- */ if( poHeader->Find( "RasterInfo.NullCellValue", NULL ) ) { CPLPushErrorHandler( CPLQuietErrorHandler ); for( iBand = 1; iBand <= poDS->nBands; iBand++ ) poDS->GetRasterBand(iBand)->SetNoDataValue( CPLAtofM(poHeader->Find( "RasterInfo.NullCellValue" )) ); CPLPopErrorHandler(); } /* -------------------------------------------------------------------- */ /* Do we have an "All" region? */ /* -------------------------------------------------------------------- */ ERSHdrNode *poAll = NULL; for( iChild = 0; poRI != NULL && iChild < poRI->nItemCount; iChild++ ) { if( poRI->papoItemChild[iChild] != NULL && EQUAL(poRI->papszItemName[iChild],"RegionInfo") ) { if( EQUAL(poRI->papoItemChild[iChild]->Find("RegionName",""), "All") ) poAll = poRI->papoItemChild[iChild]; } } /* -------------------------------------------------------------------- */ /* Do we have statistics? */ /* -------------------------------------------------------------------- */ if( poAll && poAll->FindNode( "Stats" ) ) { CPLPushErrorHandler( CPLQuietErrorHandler ); for( iBand = 1; iBand <= poDS->nBands; iBand++ ) { const char *pszValue = poAll->FindElem( "Stats.MinimumValue", iBand-1 ); if( pszValue ) poDS->GetRasterBand(iBand)->SetMetadataItem( "STATISTICS_MINIMUM", pszValue ); pszValue = poAll->FindElem( "Stats.MaximumValue", iBand-1 ); if( pszValue ) poDS->GetRasterBand(iBand)->SetMetadataItem( "STATISTICS_MAXIMUM", pszValue ); pszValue = poAll->FindElem( "Stats.MeanValue", iBand-1 ); if( pszValue ) poDS->GetRasterBand(iBand)->SetMetadataItem( "STATISTICS_MEAN", pszValue ); pszValue = poAll->FindElem( "Stats.MedianValue", iBand-1 ); if( pszValue ) poDS->GetRasterBand(iBand)->SetMetadataItem( "STATISTICS_MEDIAN", pszValue ); } CPLPopErrorHandler(); } /* -------------------------------------------------------------------- */ /* Do we have GCPs. */ /* -------------------------------------------------------------------- */ if( poHeader->FindNode( "RasterInfo.WarpControl" ) ) poDS->ReadGCPs(); /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); poDS->TryLoadXML(); // if no SR in xml, try aux const char* pszPrj = poDS->GDALPamDataset::GetProjectionRef(); if( !pszPrj || strlen(pszPrj) == 0 ) { // try aux GDALDataset* poAuxDS = GDALFindAssociatedAuxFile( poOpenInfo->pszFilename, GA_ReadOnly, poDS ); if( poAuxDS ) { pszPrj = poAuxDS->GetProjectionRef(); if( pszPrj && strlen(pszPrj) > 0 ) { CPLFree( poDS->pszProjection ); poDS->pszProjection = CPLStrdup(pszPrj); } GDALClose( poAuxDS ); } } /* -------------------------------------------------------------------- */ /* Check for overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename ); return( poDS ); }
int Raster<T>::ReadFromGDAL(const char* filename) { GDALDataset *poDataset = (GDALDataset *) GDALOpen( filename, GA_ReadOnly ); if( poDataset == NULL ) { cerr << "Open raster file failed.\n"; return -1; } GDALRasterBand *poBand= poDataset->GetRasterBand(1); m_nCols = poBand->GetXSize(); m_nRows = poBand->GetYSize(); m_noDataValue = (float)poBand->GetNoDataValue(); double adfGeoTransform[6]; poDataset->GetGeoTransform(adfGeoTransform); m_dx = adfGeoTransform[1]; m_dy = -adfGeoTransform[5]; m_xllCenter = adfGeoTransform[0]; m_yllCenter = adfGeoTransform[3] - (m_nRows)*m_dy; m_srs = string(poDataset->GetProjectionRef()); //allocate memory DeleteExistingData(); m_data = new T*[m_nRows]; for (int i = 0; i < m_nRows; ++i) { m_data[i] = new T[m_nCols]; } GDALDataType dataType = poBand->GetRasterDataType(); if(dataType == GDT_Int32) { int* pData = (int *) CPLMalloc(sizeof(int)*m_nCols*m_nRows); poBand->RasterIO(GF_Read, 0, 0, m_nCols, m_nRows, pData, m_nCols, m_nRows, GDT_Int32, 0, 0); for (int i = 0; i < m_nRows; i++) { for (int j = 0; j < m_nCols; j++) { int index = i*m_nCols + j; m_data[i][j] = T(pData[index]); } } } else { float* pData = (float *) CPLMalloc(sizeof(float)*m_nCols*m_nRows); poBand->RasterIO(GF_Read, 0, 0, m_nCols, m_nRows, pData, m_nCols, m_nRows, GDT_Float32, 0, 0); for (int i = 0; i < m_nRows; i++) { for (int j = 0; j < m_nCols; j++) { int index = i*m_nCols + j; m_data[i][j] = T(pData[index]); } } } GDALClose(poDataset); return 0; }
/*************************************************************************************************************************************** * 利用源数据文件所在文件夹(sSrcFolder)、文件名前缀(sFileNamePrefix),以及波段列表(nBands)来拼接出源数据文件完整文件名, * 对三个波段进行裁剪,然后拼接保存为jpg格式的文件输出; ****************************************************************************************************************************************/ int CGenerateQuickView::CutImages(std::string sSrcFolder, std::string sFileNamePrefix, int* nBands, std::string sDstFile, double *pdVect) { GDALAllRegister() ; GDALDataset *poSrcDs = NULL ; GDALDataset *poDstDs = NULL ; GDALDataset *pMemDs = NULL ; std::string sSrcFile ; cv::Rect srcRect, dstRect ; // 输入影像感兴趣的区域,输出影像感兴趣区域 int cols, rows ; // 输出影像行列数 GDALDataType dT ; // 打开影像的数据类型 double dDstGeoTrans[6] ; // 输出影像放射变幻参数 std::string sWKT ; // 输入影像投影参数 // 从Landsat或者modis的三个波段文件中读取波段,获取相关范围的影像,然后放入输出文件中 int i ; for (i=0; i<3; i++) { char buffer[200] ; sprintf(buffer, "%s%s_band%d.img", sSrcFolder.c_str(), sFileNamePrefix.c_str(), nBands[i]) ; sSrcFile = buffer ; poSrcDs = (GDALDataset *)GDALOpen(sSrcFile.c_str(), GA_ReadOnly) ; if (poSrcDs == NULL) { return -1 ; } if ( i==0 ) { // 获取原图像的基本信息 int iCols = poSrcDs->GetRasterXSize() ; int iRows = poSrcDs->GetRasterYSize() ; int iBands = poSrcDs->GetRasterCount() ; dT = poSrcDs->GetRasterBand(1)->GetRasterDataType() ; double dGeoTrans[6] ; poSrcDs->GetGeoTransform(dGeoTrans) ; double dPixelX = abs(dGeoTrans[1]) ; double dPixelY = abs(dGeoTrans[5]) ; sWKT = poSrcDs->GetProjectionRef() ; // 获取原图像覆盖范围 double dSrcRect[4] ; dSrcRect[0] = dGeoTrans[0] ; dSrcRect[2] = dGeoTrans[3] ; CUtility::ImageRowCol2Projection(dGeoTrans, iCols, iRows, dSrcRect[1], dSrcRect[3]) ; double dValidRect[4] ; dValidRect[0] = pdVect[0] > dSrcRect[0] ? pdVect[0] : dSrcRect[0] ; dValidRect[1] = pdVect[1] < dSrcRect[1] ? pdVect[1] : dSrcRect[1] ; dValidRect[2] = pdVect[2] < dSrcRect[2] ? pdVect[2] : dSrcRect[2] ; dValidRect[3] = pdVect[3] > dSrcRect[3] ? pdVect[3] : dSrcRect[3] ; // 判断是否是有效区域 if (dValidRect[0]>dValidRect[1] || dValidRect[2]<dValidRect[3]) { return -1 ; } int colrow[4] ; // (0,2)有效区域左上角点对应原图行列号,(1,3)有效区域相对于输出图像行列号 CUtility::Projection2ImageRowCol(dGeoTrans, dValidRect[0], dValidRect[2], colrow[0], colrow[2]) ; srcRect.x = colrow[0] ; srcRect.y = colrow[2] ; srcRect.width = static_cast<int>( ((dValidRect[1]-dValidRect[0]) + dPixelX/2)/dPixelX ) ; srcRect.height = static_cast<int>( ((dValidRect[2]-dValidRect[3]) + dPixelY/2)/dPixelY ) ; dstRect.width = srcRect.width ; dstRect.height = srcRect.height ; // 然后计算目标图像所在矩阵的起始位置(x, y) memcpy(dDstGeoTrans, dGeoTrans, 6*sizeof(double)) ; dDstGeoTrans[0] = pdVect[0] ; dDstGeoTrans[3] = pdVect[2] ; CUtility::Projection2ImageRowCol(dDstGeoTrans, dValidRect[0], dValidRect[2], colrow[1], colrow[3]) ; dstRect.x = colrow[1] ; dstRect.y = colrow[3] ; // 计算输出影像行列号 cols = static_cast<int>( (pdVect[1]-pdVect[0]+dPixelX/2)/dPixelX ) ; rows = static_cast<int>( (pdVect[2]-pdVect[3]+dPixelY/2)/dPixelY ) ; // 打开输出影像的GDALDataset: jpeg 只支持8bits或者12bit数据类型 pMemDs = GetGDALDriverManager()->GetDriverByName("MEM")->Create("", cols, rows, 3, GDT_Byte, NULL) ; // 将dT修改为GDT_Byte if(NULL==pMemDs) { return -1 ; } } // if(i==0) // 将目标GDALDataset的对应波段填充为FILLEDVALUE cv::Mat filledValueMat(rows, cols, CUtility::OpencvDataType(dT)) ; filledValueMat = FILLEDVALUE ; CUtility::RasterDataIO( pMemDs, i+1, GF_Write, cv::Rect(0,0,cols, rows), filledValueMat) ; filledValueMat.release() ; // 开始取值,复制至指定位置 cv::Mat validMat(srcRect.height, srcRect.width ,CUtility::OpencvDataType(dT)) ; cv::Mat validMat_Byte(srcRect.height, srcRect.width ,CV_8U) ; double dMin, dMax ; CUtility::RasterDataIO( poSrcDs, 1, GF_Read, srcRect, validMat ) ; cv::minMaxLoc(validMat, &dMin, &dMax) ; if (dMax==dMin) { validMat.release() ; validMat_Byte = 0 ; CUtility::RasterDataIO( pMemDs, i+1, GF_Write, dstRect, validMat_Byte) ; continue; } // 数据拉伸至0-255 validMat = (validMat-dMin)/(dMax-dMin)*255 ; validMat.convertTo(validMat_Byte, CV_8U) ; validMat.release() ; CUtility::RasterDataIO( pMemDs, i+1, GF_Write, dstRect, validMat_Byte) ; validMat_Byte.release() ; // 关闭输入影像 GDALClose((GDALDatasetH)poSrcDs) ; } // for i poDstDs = GetGDALDriverManager()->GetDriverByName("JPEG")->CreateCopy(sDstFile.c_str(), pMemDs, 0, NULL, NULL, NULL) ; if (NULL==poDstDs) { return -1 ; } poDstDs->SetGeoTransform(dDstGeoTrans) ; poDstDs->SetProjection(sWKT.c_str()) ; GDALClose((GDALDatasetH)pMemDs) ; GDALClose((GDALDatasetH)poDstDs) ; return 0; }
int main(int argc, char* argv[]) { if (argc < 2) { cout << "void-filing-color <infile> <outfile>" << endl;; exit(1); } const char* InFilename = argv[1]; const char* OutFilename = argv[2]; GDALAllRegister(); // Open dataset and get raster band GDALDataset* poDataset = (GDALDataset*) GDALOpen(InFilename, GA_ReadOnly); if(poDataset == NULL) { cout << "Couldn't open dataset " << InFilename << endl; } GDALRasterBand *poInBandr; GDALRasterBand *poInBandg; GDALRasterBand *poInBandb; poInBandr = poDataset->GetRasterBand(1); poInBandg = poDataset->GetRasterBand(2); poInBandb = poDataset->GetRasterBand(3); double adfGeoTransform[6]; poDataset->GetGeoTransform(adfGeoTransform); // Get variables from input dataset const int nXSize = poInBandr->GetXSize(); const int nYSize = poInBandr->GetYSize(); // Create the output dataset and copy over relevant metadata const char* Format = "GTiff"; GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(Format); char** Options = NULL; GDALDataset* poDS = poDriver->Create(OutFilename,nXSize,nYSize,3,GDT_Byte,Options); poDS->SetGeoTransform(adfGeoTransform); poDS->SetProjection(poDataset->GetProjectionRef()); GDALRasterBand* poBandr = poDS->GetRasterBand(1); GDALRasterBand* poBandg = poDS->GetRasterBand(2); GDALRasterBand* poBandb = poDS->GetRasterBand(3); poBandr->SetNoDataValue(0); poBandg->SetNoDataValue(0); poBandb->SetNoDataValue(0); GDALAllRegister(); cout << "Read image." << endl; CImg<unsigned char>* ReadPixels = new CImg<unsigned char>(nXSize, nYSize, 1, 3, 0); for (int i = 0; i < nYSize; i++) { cout << "\r" << i << "/" << nYSize; for (int j = 0; j < nXSize; j++) { unsigned char InPixel; poInBandr->RasterIO(GF_Read, j, i, 1, 1, &InPixel, 1, 1, GDT_Byte, 0, 0); (*ReadPixels)(j, i, 0, 0) = InPixel; poInBandg->RasterIO(GF_Read, j, i, 1, 1, &InPixel, 1, 1, GDT_Byte, 0, 0); (*ReadPixels)(j, i, 0, 1) = InPixel; poInBandb->RasterIO(GF_Read, j, i, 1, 1, &InPixel, 1, 1, GDT_Byte, 0, 0); (*ReadPixels)(j, i, 0, 2) = InPixel; } } cout << endl; cout << "Void filling." << endl; CImg<unsigned char>* InPixels = new CImg<unsigned char>(nXSize, nYSize, 1, 3, 0); for (int i = 0; i < nYSize; i++) { cout << "\r" << i << "/" << nYSize; for (int j = 0; j < nXSize; j++) { if (isEmpty(ReadPixels, j, i) && isEmpty(InPixels, j, i)) { int is = i; int ie = i; int js = j; int je = j; const int maxsize = 2; js = max(0, j-maxsize); je = min(nXSize-1, j+maxsize); is = max(0, i-maxsize); ie = min(nYSize-1, i+maxsize); // cout << endl << js << ", " << je << ", " << is << ", " << ie; float fact = 0; float sumr = 0; float sumg = 0; float sumb = 0; for (int ia = is ; ia <= ie ; ia++) { for (int ja = js ; ja <= je ; ja++) { // cout << endl << ia << ", " << ja; if (!isEmpty(ReadPixels, ja, ia)) { int ik = ia - i; int jk = ja - j; float length = ik*ik+jk*jk; float coef = 1/(length*length); sumr += ((*ReadPixels)(ja, ia, 0, 0))*coef; sumg += ((*ReadPixels)(ja, ia, 0, 1))*coef; sumb += ((*ReadPixels)(ja, ia, 0, 2))*coef; fact += coef; } } } // cout << endl << sumr << ", " << sumg << ", " << sumb << ", " << fact; if (fact == 0) { /* unsigned char InPixelr = 0xb5; // ocean blue unsigned char InPixelg = 0xd0; unsigned char InPixelb = 0xd0;*/ unsigned char InPixelr = 0x98; // green earth unsigned char InPixelg = 0xd7; unsigned char InPixelb = 0x88; poBandr->RasterIO(GF_Write, j, i, 1, 1, &InPixelr, 1, 1, GDT_Byte, 0, 0); poBandg->RasterIO(GF_Write, j, i, 1, 1, &InPixelg, 1, 1, GDT_Byte, 0, 0); poBandb->RasterIO(GF_Write, j, i, 1, 1, &InPixelb, 1, 1, GDT_Byte, 0, 0); } else { unsigned char InPixelr = (unsigned char)(sumr / fact); unsigned char InPixelg = (unsigned char)(sumg / fact); unsigned char InPixelb = (unsigned char)(sumb / fact); poBandr->RasterIO(GF_Write, j, i, 1, 1, &InPixelr, 1, 1, GDT_Byte, 0, 0); poBandg->RasterIO(GF_Write, j, i, 1, 1, &InPixelg, 1, 1, GDT_Byte, 0, 0); poBandb->RasterIO(GF_Write, j, i, 1, 1, &InPixelb, 1, 1, GDT_Byte, 0, 0); } } else if (!isEmpty(ReadPixels, j, i)) { unsigned char InPixelr = (*ReadPixels)(j, i, 0, 0); unsigned char InPixelg = (*ReadPixels)(j, i, 0, 1); unsigned char InPixelb = (*ReadPixels)(j, i, 0, 2); poBandr->RasterIO(GF_Write, j, i, 1, 1, &InPixelr, 1, 1, GDT_Byte, 0, 0); poBandg->RasterIO(GF_Write, j, i, 1, 1, &InPixelg, 1, 1, GDT_Byte, 0, 0); poBandb->RasterIO(GF_Write, j, i, 1, 1, &InPixelb, 1, 1, GDT_Byte, 0, 0); } } } cout << endl; delete poDS; return 0; }
void readFrames( int argc, char* argv[] ) { pfs::DOMIO pfsio; bool verbose = false; // Parse command line parameters static struct option cmdLineOptions[] = { { "help", no_argument, NULL, 'h' }, { "verbose", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char optstring[] = "hv"; pfs::FrameFileIterator it( argc, argv, "rb", NULL, NULL, optstring, cmdLineOptions ); int optionIndex = 0; while( 1 ) { int c = getopt_long (argc, argv, optstring, cmdLineOptions, &optionIndex); if( c == -1 ) break; switch( c ) { case 'h': printHelp(); throw QuietException(); case 'v': verbose = true; break; case '?': throw QuietException(); case ':': throw QuietException(); } } GDALAllRegister(); GDALDataset *poDataset; GDALRasterBand *poBand; double adfGeoTransform[6]; size_t nBlockXSize, nBlockYSize, nBands; int bGotMin, bGotMax; double adfMinMax[2]; float *pafScanline; while( true ) { pfs::FrameFile ff = it.getNextFrameFile(); if( ff.fh == NULL ) break; // No more frames it.closeFrameFile( ff ); VERBOSE_STR << "reading file '" << ff.fileName << "'" << std::endl; if( !( poDataset = (GDALDataset *) GDALOpen( ff.fileName, GA_ReadOnly ) ) ) { std::cerr << "input does not seem to be in a format supported by GDAL" << std::endl; throw QuietException(); } VERBOSE_STR << "GDAL driver: " << poDataset->GetDriver()->GetDescription() << " / " << poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) << std::endl; nBlockXSize = poDataset->GetRasterXSize(); nBlockYSize = poDataset->GetRasterYSize(); nBands = poDataset->GetRasterCount(); VERBOSE_STR << "Data size " << nBlockXSize << "x" << nBlockYSize << "x" << nBands << std::endl; if( poDataset->GetProjectionRef() ) { VERBOSE_STR << "Projection " << poDataset->GetProjectionRef() << std::endl; } if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { VERBOSE_STR << "Origin = (" << adfGeoTransform[0] << ", " << adfGeoTransform[3] << ")" << std::endl; VERBOSE_STR << "Pixel Size = (" << adfGeoTransform[1] << ", " << adfGeoTransform[5] << ")" << std::endl; } if( nBlockXSize==0 || nBlockYSize==0 || ( SIZE_MAX / nBlockYSize < nBlockXSize ) || ( SIZE_MAX / (nBlockXSize * nBlockYSize ) < 4 ) ) { std::cerr << "input data has invalid size" << std::endl; throw QuietException(); } if( !(pafScanline = (float *) CPLMalloc( sizeof(float) * nBlockXSize ) ) ) { std::cerr << "not enough memory" << std::endl; throw QuietException(); } pfs::Frame *frame = pfsio.createFrame( nBlockXSize, nBlockYSize ); pfs::Channel *C[nBands]; char channel_name[32]; frame->getTags()->setString( "X-GDAL_DRIVER_SHORTNAME", poDataset->GetDriver()->GetDescription() ); frame->getTags()->setString( "X-GDAL_DRIVER_LONGNAME", poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); frame->getTags()->setString( "X-PROJECTION", poDataset->GetProjectionRef() ); if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { frame->getTags()->setString( "X-ORIGIN_X", stringify(adfGeoTransform[0]).c_str() ); frame->getTags()->setString( "X-ORIGIN_Y", stringify(adfGeoTransform[3]).c_str() ); frame->getTags()->setString( "X-PIXEL_WIDTH", stringify(adfGeoTransform[1]).c_str() ); frame->getTags()->setString( "X-PIXEL_HEIGHT", stringify(adfGeoTransform[5]).c_str() ); } for ( size_t band = 1; band <= nBands; band++) { size_t nBandXSize, nBandYSize; VERBOSE_STR << "Band " << band << ": " << std::endl; snprintf( channel_name, 32, "X-GDAL%zu", band ); C[band - 1] = frame->createChannel( channel_name ); poBand = poDataset->GetRasterBand( band ); nBandXSize = poBand->GetXSize(); nBandYSize = poBand->GetYSize(); VERBOSE_STR << " " << nBandXSize << "x" << nBandYSize << std::endl; if( nBandXSize != (int)nBlockXSize || nBandYSize != (int)nBlockYSize ) { std::cerr << "data in band " << band << " has different size" << std::endl; throw QuietException(); } VERBOSE_STR << " Type " << GDALGetDataTypeName( poBand->GetRasterDataType() ) << ", " << "Color Interpretation " << GDALGetColorInterpretationName( poBand->GetColorInterpretation() ) << std::endl; adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) { GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); } VERBOSE_STR << " Min " << adfMinMax[0] << ", Max " << adfMinMax[1] << std::endl; C[band - 1]->getTags()->setString( "X-TYPE", GDALGetDataTypeName( poBand->GetRasterDataType() ) ); C[band - 1]->getTags()->setString( "X-COLOR_INTERPRETATION", GDALGetColorInterpretationName( poBand->GetColorInterpretation() ) ); C[band - 1]->getTags()->setString( "X-MIN", stringify(adfMinMax[0]).c_str() ); C[band - 1]->getTags()->setString( "X-MAX", stringify(adfMinMax[1]).c_str() ); for( size_t y = 0; y < nBlockYSize; y++ ) { if( poBand->RasterIO( GF_Read, 0, y, nBlockXSize, 1, pafScanline, nBlockXSize, 1, GDT_Float32, 0, 0) != CE_None ) { std::cerr << "input error" << std::endl; throw QuietException(); } memcpy( C[band - 1]->getRawData() + y * nBlockXSize, pafScanline, nBlockXSize * sizeof(float) ); } } CPLFree( pafScanline ); GDALClose( poDataset ); const char *fileNameTag = strcmp( "-", ff.fileName )==0 ? "stdin" : ff.fileName; frame->getTags()->setString( "FILE_NAME", fileNameTag ); pfsio.writeFrame( frame, stdout ); pfsio.freeFrame( frame ); } }
NV_CHAR *get_geotiff (NV_CHAR *mosaic_file, MISC *misc) { static NV_CHAR string[512]; strcpy (string, "Success"); if (strstr (mosaic_file, ".tif") || strstr (mosaic_file, ".TIF")) { GDALDataset *poDataset; NV_FLOAT64 adfGeoTransform[6]; GDALAllRegister (); poDataset = (GDALDataset *) GDALOpen (mosaic_file, GA_ReadOnly); if (poDataset != NULL) { if (poDataset->GetProjectionRef () != NULL) { QString projRef = QString (poDataset->GetProjectionRef ()); if (projRef.contains ("GEOGCS")) { if (poDataset->GetGeoTransform (adfGeoTransform) == CE_None) { misc->lon_step = adfGeoTransform[1]; misc->lat_step = -adfGeoTransform[5]; misc->mosaic_width = poDataset->GetRasterXSize (); misc->mosaic_height = poDataset->GetRasterYSize (); misc->geotiff_area.min_x = adfGeoTransform[0]; misc->geotiff_area.max_y = adfGeoTransform[3]; misc->geotiff_area.min_y = misc->geotiff_area.max_y - misc->mosaic_height * misc->lat_step; misc->geotiff_area.max_x = misc->geotiff_area.min_x + misc->mosaic_width * misc->lon_step; } else { delete poDataset; sprintf (string, "File %s contains projected data", gen_basename (mosaic_file)); return (string); } } else { delete poDataset; sprintf (string, "File %s contains Non-geographic coordinate system", gen_basename (mosaic_file)); return (string); } } else { delete poDataset; sprintf (string, "File %s contains no datum/projection information", gen_basename (mosaic_file)); return (string); } if (misc->full_res_image != NULL) delete misc->full_res_image; /* This is how I used to read geoTIFFs but for some reason it stopped working along about Qt 4.7.2 so now I use GDAL to read it. I really need to keep testing to see if this starts working again because it's a bit faster and probably a lot more bullet proof. misc->full_res_image = new QImage (mosaic_file); if (misc->full_res_image == NULL || misc->full_res_image->width () == 0 || fmisc->ull_res_image->height () == 0) { sprintf (string, "Unable to read file %s", gen_basename (mosaic_file)); delete poDataset; return (string); } */ // This is how I read geoTIFFs now... GDALRasterBand *poBand[4]; QString dataType[4], colorInt[4]; NV_U_INT32 mult[4] = {0, 0, 0, 0}; NV_INT32 rasterCount = poDataset->GetRasterCount (); if (rasterCount < 3) { delete poDataset; sprintf (string, "Not enough raster bands in geoTIFF"); return (string); } for (NV_INT32 i = 0 ; i < rasterCount ; i++) { poBand[i] = poDataset->GetRasterBand (i + 1); dataType[i] = QString (GDALGetDataTypeName (poBand[i]->GetRasterDataType ())); colorInt[i] = QString (GDALGetColorInterpretationName (poBand[i]->GetColorInterpretation ())); // We can only handle Byte data (i.e. RGB or ARGB) if (dataType[i] != "Byte") { delete poDataset; sprintf (string, "Can only handle Byte data type"); return (string); } mult[i] = getColorOffset (colorInt[i]); } NV_INT32 nXSize = poBand[0]->GetXSize (); NV_INT32 nYSize = poBand[0]->GetYSize (); misc->full_res_image = new QImage (nXSize, nYSize, QImage::Format_ARGB32); if (misc->full_res_image == NULL || misc->full_res_image->width () == 0 || misc->full_res_image->height () == 0) { sprintf (string, "Unable to open image!"); delete poDataset; return (string); } NV_U_INT32 *color = new NV_U_INT32[nXSize]; NV_U_BYTE *pafScanline = (NV_U_BYTE *) CPLMalloc (sizeof (NV_U_BYTE) * nXSize); for (NV_INT32 i = 0 ; i < nYSize ; i++) { // If we don't have an alpha band set it to 255. for (NV_INT32 k = 0 ; k < nXSize ; k++) { if (rasterCount < 4) { color[k] = 0xff000000; } else { color[k] = 0x0; } } // Read the raster bands. for (NV_INT32 j = 0 ; j < rasterCount ; j++) { poBand[j]->RasterIO (GF_Read, 0, i, nXSize, 1, pafScanline, nXSize, 1, GDT_Byte, 0, 0); for (NV_INT32 k = 0 ; k < nXSize ; k++) color[k] += ((NV_U_INT32) pafScanline[k]) * mult[j]; } // Set the image pixels. for (NV_INT32 k = 0 ; k < nXSize ; k++) { misc->full_res_image->setPixel (k, i, color[k]); } } delete (color); CPLFree (pafScanline); delete poDataset; } else { sprintf (string, "Unable to open file %s", gen_basename (mosaic_file)); return (string); } } else { sprintf (string, "File %s is not a GeoTIFF file", gen_basename (mosaic_file)); return (string); } return (string); }
bool vtImageGeo::ReadTIF(const char *filename, bool progress_callback(int)) { // Use GDAL to read a TIF file (or any other format that GDAL is // configured to read) into this OSG image. bool bRet = true; vtString message; setFileName(filename); g_GDALWrapper.RequestGDALFormats(); GDALDataset *pDataset = NULL; GDALRasterBand *pBand; GDALRasterBand *pRed = NULL; GDALRasterBand *pGreen = NULL; GDALRasterBand *pBlue = NULL; GDALRasterBand *pAlpha = NULL; GDALColorTable *pTable; uchar *pScanline = NULL; uchar *pRedline = NULL; uchar *pGreenline = NULL; uchar *pBlueline = NULL; uchar *pAlphaline = NULL; CPLErr Err; bool bColorPalette = false; int iXSize, iYSize; int nxBlocks, nyBlocks; int xBlockSize, yBlockSize; try { pDataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); if(pDataset == NULL ) throw "Couldn't open that file."; // Get size iXSize = pDataset->GetRasterXSize(); iYSize = pDataset->GetRasterYSize(); // Try getting CRS vtProjection temp; bool bHaveProj = false; const char *pProjectionString = pDataset->GetProjectionRef(); if (pProjectionString) { OGRErr err = temp.importFromWkt((char**)&pProjectionString); if (err == OGRERR_NONE) { m_proj = temp; bHaveProj = true; } } if (!bHaveProj) { // check for existence of .prj file bool bSuccess = temp.ReadProjFile(filename); if (bSuccess) { m_proj = temp; bHaveProj = true; } } // Try getting extents double affineTransform[6]; if (pDataset->GetGeoTransform(affineTransform) == CE_None) { m_extents.left = affineTransform[0]; m_extents.right = m_extents.left + affineTransform[1] * iXSize; m_extents.top = affineTransform[3]; m_extents.bottom = m_extents.top + affineTransform[5] * iYSize; } // Raster count should be 3 for colour images (assume RGB) int iRasterCount = pDataset->GetRasterCount(); if (iRasterCount != 1 && iRasterCount != 3 && iRasterCount != 4) { message.Format("Image has %d bands (not 1, 3, or 4).", iRasterCount); throw (const char *)message; } if (iRasterCount == 1) { pBand = pDataset->GetRasterBand(1); // Check the band's data type GDALDataType dtype = pBand->GetRasterDataType(); if (dtype != GDT_Byte) { message.Format("Band is of type %s, but we support type Byte.", GDALGetDataTypeName(dtype)); throw (const char *)message; } GDALColorInterp ci = pBand->GetColorInterpretation(); if (ci == GCI_PaletteIndex) { if (NULL == (pTable = pBand->GetColorTable())) throw "Couldn't get color table."; bColorPalette = true; } else if (ci == GCI_GrayIndex) { // we will assume 0-255 is black to white } else throw "Unsupported color interpretation."; pBand->GetBlockSize(&xBlockSize, &yBlockSize); nxBlocks = (iXSize + xBlockSize - 1) / xBlockSize; nyBlocks = (iYSize + yBlockSize - 1) / yBlockSize; if (NULL == (pScanline = new uchar[xBlockSize * yBlockSize])) throw "Couldnt allocate scan line."; } if (iRasterCount == 3) { for (int i = 1; i <= 3; i++) { pBand = pDataset->GetRasterBand(i); // Check the band's data type GDALDataType dtype = pBand->GetRasterDataType(); if (dtype != GDT_Byte) { message.Format("Band is of type %s, but we support type Byte.", GDALGetDataTypeName(dtype)); throw (const char *)message; } switch (pBand->GetColorInterpretation()) { case GCI_RedBand: pRed = pBand; break; case GCI_GreenBand: pGreen = pBand; break; case GCI_BlueBand: pBlue = pBand; break; } } if ((NULL == pRed) || (NULL == pGreen) || (NULL == pBlue)) throw "Couldn't find bands for Red, Green, Blue."; pRed->GetBlockSize(&xBlockSize, &yBlockSize); nxBlocks = (iXSize + xBlockSize - 1) / xBlockSize; nyBlocks = (iYSize + yBlockSize - 1) / yBlockSize; pRedline = new uchar[xBlockSize * yBlockSize]; pGreenline = new uchar[xBlockSize * yBlockSize]; pBlueline = new uchar[xBlockSize * yBlockSize]; } if (iRasterCount == 4) { #if VTDEBUG VTLOG1("Band interpretations:"); #endif for (int i = 1; i <= 4; i++) { pBand = pDataset->GetRasterBand(i); // Check the band's data type GDALDataType dtype = pBand->GetRasterDataType(); if (dtype != GDT_Byte) { message.Format("Band is of type %s, but we support type Byte.", GDALGetDataTypeName(dtype)); throw (const char *)message; } GDALColorInterp ci = pBand->GetColorInterpretation(); #if VTDEBUG VTLOG(" %d", ci); #endif switch (ci) { case GCI_RedBand: pRed = pBand; break; case GCI_GreenBand: pGreen = pBand; break; case GCI_BlueBand: pBlue = pBand; break; case GCI_AlphaBand: pAlpha = pBand; break; case GCI_Undefined: // If we have four bands: R,G,B,undefined, then assume that // the undefined one is actually alpha if (pRed && pGreen && pBlue && !pAlpha) pAlpha = pBand; break; } } #if VTDEBUG VTLOG1("\n"); #endif if ((NULL == pRed) || (NULL == pGreen) || (NULL == pBlue) || (NULL == pAlpha)) throw "Couldn't find bands for Red, Green, Blue, Alpha."; pRed->GetBlockSize(&xBlockSize, &yBlockSize); nxBlocks = (iXSize + xBlockSize - 1) / xBlockSize; nyBlocks = (iYSize + yBlockSize - 1) / yBlockSize; pRedline = new uchar[xBlockSize * yBlockSize]; pGreenline = new uchar[xBlockSize * yBlockSize]; pBlueline = new uchar[xBlockSize * yBlockSize]; pAlphaline = new uchar[xBlockSize * yBlockSize]; } // Allocate the image buffer if (iRasterCount == 4) { Create(iXSize, iYSize, 32); } else if (iRasterCount == 3 || bColorPalette) { Create(iXSize, iYSize, 24); } else if (iRasterCount == 1) Create(iXSize, iYSize, 8); // Read the data #if LOG_IMAGE_LOAD VTLOG("Reading the image data (%d x %d pixels)\n", iXSize, iYSize); #endif int x, y; int ixBlock, iyBlock; int nxValid, nyValid; int iY, iX; RGBi rgb; RGBAi rgba; if (iRasterCount == 1) { GDALColorEntry Ent; for (iyBlock = 0; iyBlock < nyBlocks; iyBlock++) { if (progress_callback != NULL) progress_callback(iyBlock * 100 / nyBlocks); y = iyBlock * yBlockSize; for (ixBlock = 0; ixBlock < nxBlocks; ixBlock++) { x = ixBlock * xBlockSize; Err = pBand->ReadBlock(ixBlock, iyBlock, pScanline); if (Err != CE_None) throw "Problem reading the image data."; // Compute the portion of the block that is valid // for partial edge blocks. if ((ixBlock+1) * xBlockSize > iXSize) nxValid = iXSize - ixBlock * xBlockSize; else nxValid = xBlockSize; if( (iyBlock+1) * yBlockSize > iYSize) nyValid = iYSize - iyBlock * yBlockSize; else nyValid = yBlockSize; for( iY = 0; iY < nyValid; iY++ ) { for( iX = 0; iX < nxValid; iX++ ) { if (bColorPalette) { pTable->GetColorEntryAsRGB(pScanline[iY * xBlockSize + iX], &Ent); rgb.r = (uchar) Ent.c1; rgb.g = (uchar) Ent.c2; rgb.b = (uchar) Ent.c3; SetPixel24(x + iX, y + iY, rgb); } else SetPixel8(x + iX, y + iY, pScanline[iY * xBlockSize + iX]); } } } } } if (iRasterCount >= 3) { for (iyBlock = 0; iyBlock < nyBlocks; iyBlock++) { if (progress_callback != NULL) progress_callback(iyBlock * 100 / nyBlocks); y = iyBlock * yBlockSize; for (ixBlock = 0; ixBlock < nxBlocks; ixBlock++) { x = ixBlock * xBlockSize; Err = pRed->ReadBlock(ixBlock, iyBlock, pRedline); if (Err != CE_None) throw "Cannot read data."; Err = pGreen->ReadBlock(ixBlock, iyBlock, pGreenline); if (Err != CE_None) throw "Cannot read data."; Err = pBlue->ReadBlock(ixBlock, iyBlock, pBlueline); if (Err != CE_None) throw "Cannot read data."; if (iRasterCount == 4) { Err = pAlpha->ReadBlock(ixBlock, iyBlock, pAlphaline); if (Err != CE_None) throw "Cannot read data."; } // Compute the portion of the block that is valid // for partial edge blocks. if ((ixBlock+1) * xBlockSize > iXSize) nxValid = iXSize - ixBlock * xBlockSize; else nxValid = xBlockSize; if( (iyBlock+1) * yBlockSize > iYSize) nyValid = iYSize - iyBlock * yBlockSize; else nyValid = yBlockSize; for (int iY = 0; iY < nyValid; iY++) { for (int iX = 0; iX < nxValid; iX++) { if (iRasterCount == 3) { rgb.r = pRedline[iY * xBlockSize + iX]; rgb.g = pGreenline[iY * xBlockSize + iX]; rgb.b = pBlueline[iY * xBlockSize + iX]; SetPixel24(x + iX, y + iY, rgb); } else if (iRasterCount == 4) { rgba.r = pRedline[iY * xBlockSize + iX]; rgba.g = pGreenline[iY * xBlockSize + iX]; rgba.b = pBlueline[iY * xBlockSize + iX]; rgba.a = pAlphaline[iY * xBlockSize + iX]; SetPixel32(x + iX, y + iY, rgba); } } } } } } } catch (const char *msg) { VTLOG1("Problem: "); VTLOG1(msg); VTLOG1("\n"); bRet = false; } if (NULL != pDataset) GDALClose(pDataset); if (NULL != pScanline) delete pScanline; if (NULL != pRedline) delete pRedline; if (NULL != pGreenline) delete pGreenline; if (NULL != pBlueline) delete pBlueline; if (NULL != pAlphaline) delete pAlphaline; return bRet; }
std::tuple<boost::shared_ptr<Map_Matrix<DataFormat> >, std::string, GeoTransform> read_in_map(fs::path file_path, GDALDataType data_type, const bool doCategorise) throw(std::runtime_error) { std::string projection; GeoTransform transformation; GDALDriver driver; //Check that the file name is valid if (!(fs::is_regular_file(file_path))) { throw std::runtime_error("Input file is not a regular file"); } // Get GDAL to open the file - code is based on the tutorial at http://www.gdal.org/gdal_tutorial.html GDALDataset *poDataset; GDALAllRegister(); //This registers all availble raster file formats for use with this utility. How neat is that. We can input any GDAL supported rater file format. //Open the Raster by calling GDALOpen. http://www.gdal.org/gdal_8h.html#a6836f0f810396c5e45622c8ef94624d4 //char pszfilename[] = file_path.c_str(); //Set this to the file name, as GDALOpen requires the standard C char pointer as function parameter. poDataset = (GDALDataset *) GDALOpen (file_path.string().c_str(), GA_ReadOnly); if (poDataset == NULL) { throw std::runtime_error("Unable to open file"); } // Print some general information about the raster double adfGeoTransform[6]; //An array of doubles that will be used to save information about the raster - where the origin is, what the raster pizel size is. printf( "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) ); printf( "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() ); if( poDataset->GetProjectionRef() != NULL ) { printf( "Projection is `%s'\n", poDataset->GetProjectionRef() ); projection = poDataset->GetProjectionRef(); } if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { printf( "Origin = (%.6f,%.6f)\n", adfGeoTransform[0], adfGeoTransform[3] ); printf( "Pixel Size = (%.6f,%.6f)\n", adfGeoTransform[1], adfGeoTransform[5] ); transformation.x_origin = adfGeoTransform[0]; transformation.pixel_width = adfGeoTransform[1]; transformation.x_line_space = adfGeoTransform[2]; transformation.y_origin = adfGeoTransform[3]; transformation.pixel_height = adfGeoTransform[4]; transformation.y_line_space = adfGeoTransform[5]; } /// Some raster file formats allow many layers of data (called a 'band', with each having the same pixel size and origin location and spatial extent). We will get the data for the first layer into a Boost Array. //Get the data from the first band, // TODO implement method with input to specify what band. GDALRasterBand *poBand; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; double adfMinMax[2]; poBand = poDataset->GetRasterBand( 1 ); poBand->GetBlockSize( &nBlockXSize, &nBlockYSize ); printf( "Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName( poBand->GetColorInterpretation()) ); adfMinMax[0] = poBand->GetMinimum( &bGotMin ); adfMinMax[1] = poBand->GetMaximum( &bGotMax ); if( ! (bGotMin && bGotMax) ) GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax); printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1] ); if( poBand->GetOverviewCount() > 0 ) printf( "Band has %d overviews.\n", poBand->GetOverviewCount() ); if( poBand->GetColorTable() != NULL ) printf( "Band has a color table with %d entries.\n", poBand->GetColorTable()->GetColorEntryCount() ); DataFormat * pafScanline; int nXSize = poBand->GetXSize(); int nYSize = poBand->GetYSize(); boost::shared_ptr<Map_Matrix<DataFormat> > in_map(new Map_Matrix<DataFormat>(nYSize, nXSize)); //get a c array of this size and read into this. //pafScanline = new DataFormat[nXSize]; //for (int i = 0; i < nYSize; i++) //rows //{ // poBand->RasterIO(GF_Read, 0, i, nXSize, 1, // pafScanline, nXSize, 1, data_type, // 0, 0); // for (int j = 0; j < nXSize; j++) //cols // { // in_map->Get(i, j) = pafScanline[j]; // } //} //get a c array of this size and read into this. pafScanline = new DataFormat[nXSize * nYSize]; //pafScanline = (float *) CPLMalloc(sizeof(float)*nXSize); poBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, pafScanline, nXSize, nYSize, data_type, 0, 0 ); //Copy into Map_Matrix. int pafIterator = 0; // Note: Map Matrixes indexes are in opposite order to C arrays. e.g. map matrix is indexed by (row, Col) which is (y, x) and c matrices are done by (x, y) which is (Col, Row) //for (int i = 0; i < nXSize; i++) //{ // for(int j = 0; j < nYSize; j++) // { // in_map->Get(j, i) = pafScanline[pafIterator]; // pafIterator++; // } //} for (int i = 0; i < nYSize; i++) //rows { for (int j = 0; j < nXSize; j++) //cols { in_map->Get(i, j) = pafScanline[pafIterator]; pafIterator++; } } //free the c array storage delete pafScanline; int pbsuccess; // can be used with get no data value in_map->SetNoDataValue(poBand->GetNoDataValue(&pbsuccess)); //This creates a list (map?) listing all the unique values contained in the raster. if (doCategorise) in_map->updateCategories(); //Close GDAL, freeing the memory GDAL is using GDALClose( (GDALDatasetH)poDataset); return (std::make_tuple(in_map, projection, transformation)); }
int FindSRS( const char *pszInput, OGRSpatialReference &oSRS, int bDebug ) { int bGotSRS = FALSE; VSILFILE *fp = NULL; GDALDataset *poGDALDS = NULL; OGRDataSource *poOGRDS = NULL; OGRLayer *poLayer = NULL; char *pszProjection = NULL; CPLErrorHandler oErrorHandler = NULL; int bIsFile = FALSE; OGRErr eErr = CE_None; /* temporarily supress error messages we may get from xOpen() */ if ( ! bDebug ) oErrorHandler = CPLSetErrorHandler ( CPLQuietErrorHandler ); /* Test if argument is a file */ fp = VSIFOpenL( pszInput, "r" ); if ( fp ) { bIsFile = TRUE; VSIFCloseL( fp ); CPLDebug( "gdalsrsinfo", "argument is a file" ); } /* try to open with GDAL */ CPLDebug( "gdalsrsinfo", "trying to open with GDAL" ); poGDALDS = (GDALDataset *) GDALOpen( pszInput, GA_ReadOnly ); if ( poGDALDS != NULL && poGDALDS->GetProjectionRef( ) != NULL ) { pszProjection = (char *) poGDALDS->GetProjectionRef( ); if( oSRS.importFromWkt( &pszProjection ) == CE_None ) { CPLDebug( "gdalsrsinfo", "got SRS from GDAL" ); bGotSRS = TRUE; } GDALClose( (GDALDatasetH) poGDALDS ); if ( ! bGotSRS ) CPLDebug( "gdalsrsinfo", "did not open with GDAL" ); } #ifdef OGR_ENABLED /* if unsuccessful, try to open with OGR */ if ( ! bGotSRS ) { CPLDebug( "gdalsrsinfo", "trying to open with OGR" ); poOGRDS = OGRSFDriverRegistrar::Open( pszInput, FALSE, NULL ); if( poOGRDS != NULL ) { poLayer = poOGRDS->GetLayer( 0 ); if ( poLayer != NULL ) { OGRSpatialReference *poSRS = poLayer->GetSpatialRef( ); if ( poSRS != NULL ) { CPLDebug( "gdalsrsinfo", "got SRS from OGR" ); bGotSRS = TRUE; OGRSpatialReference* poSRSClone = poSRS->Clone(); oSRS = *poSRSClone; OGRSpatialReference::DestroySpatialReference( poSRSClone ); } } OGRDataSource::DestroyDataSource( poOGRDS ); poOGRDS = NULL; } if ( ! bGotSRS ) CPLDebug( "gdalsrsinfo", "did not open with OGR" ); } #endif // OGR_ENABLED /* Try ESRI file */ if ( ! bGotSRS && bIsFile && (strstr(pszInput,".prj") != NULL) ) { CPLDebug( "gdalsrsinfo", "trying to get SRS from ESRI .prj file [%s]", pszInput ); char **pszTemp; if ( strstr(pszInput,"ESRI::") != NULL ) pszTemp = CSLLoad( pszInput+6 ); else pszTemp = CSLLoad( pszInput ); if( pszTemp ) { eErr = oSRS.importFromESRI( pszTemp ); CSLDestroy( pszTemp ); } else eErr = OGRERR_UNSUPPORTED_SRS; if( eErr != OGRERR_NONE ) { CPLDebug( "gdalsrsinfo", "did not get SRS from ESRI .prj file" ); } else { CPLDebug( "gdalsrsinfo", "got SRS from ESRI .prj file" ); bGotSRS = TRUE; } } /* Last resort, try OSRSetFromUserInput() */ if ( ! bGotSRS ) { CPLDebug( "gdalsrsinfo", "trying to get SRS from user input [%s]", pszInput ); eErr = oSRS.SetFromUserInput( pszInput ); if( eErr != OGRERR_NONE ) { CPLDebug( "gdalsrsinfo", "did not get SRS from user input" ); } else { CPLDebug( "gdalsrsinfo", "got SRS from user input" ); bGotSRS = TRUE; } } /* restore error messages */ if ( ! bDebug ) CPLSetErrorHandler ( oErrorHandler ); return bGotSRS; }