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); };
void Raster<T>::OutputGTiff(const char* rasterName) { const char *pszFormat = "GTiff"; GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); char **papszOptions = poDriver->GetMetadata(); //papszOptions = CSLSetNameValue( papszOptions, "TILED", "YES" ); //papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "PACKBITS" ); GDALDataset *poDstDS = poDriver->Create(rasterName, m_nCols, m_nRows, 1, m_dType, papszOptions); //write the data to new file GDALRasterBand *poDstBand= poDstDS->GetRasterBand(1); poDstBand->RasterIO(GF_Write, 0, 0, m_nCols, m_nRows, m_data, m_nCols, m_nRows, m_dType, 0, 0); poDstBand->SetNoDataValue(m_noDataValue); double geoTrans[6]; geoTrans[0] = m_xMin; geoTrans[1] = m_dx; geoTrans[2] = 0; geoTrans[3] = m_yMax; geoTrans[4] = 0; geoTrans[5] = -m_dy; poDstDS->SetGeoTransform(geoTrans); poDstDS->SetProjection(m_proj.c_str()); GDALClose(poDstDS); }
static GDALDataset* createMemDS(int width, int height, double minX, double minY, double maxX, double maxY, const std::string &projection) { //Get the MEM driver GDALDriver* memDriver = (GDALDriver*)GDALGetDriverByName("MEM"); if (!memDriver) { OE_NOTICE << "[osgEarth::GeoData] Could not get MEM driver" << std::endl; } //Create the in memory dataset. GDALDataset* ds = memDriver->Create("", width, height, 4, GDT_Byte, 0); //Initialize the color interpretation ds->GetRasterBand(1)->SetColorInterpretation(GCI_RedBand); ds->GetRasterBand(2)->SetColorInterpretation(GCI_GreenBand); ds->GetRasterBand(3)->SetColorInterpretation(GCI_BlueBand); ds->GetRasterBand(4)->SetColorInterpretation(GCI_AlphaBand); //Initialize the geotransform double geotransform[6]; double x_units_per_pixel = (maxX - minX) / (double)width; double y_units_per_pixel = (maxY - minY) / (double)height; geotransform[0] = minX; geotransform[1] = x_units_per_pixel; geotransform[2] = 0; geotransform[3] = maxY; geotransform[4] = 0; geotransform[5] = -y_units_per_pixel; ds->SetGeoTransform(geotransform); ds->SetProjection(projection.c_str()); return ds; }
void write_map(fs::path file_path, GDALDataType data_type, boost::shared_ptr<Map_Matrix<DataFormat> > data, std::string WKTprojection, GeoTransform transform, std::string driverName) throw(std::runtime_error) { 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. const char *pszFormat = driverName.c_str(); GDALDriver * poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); if (poDriver == NULL) { throw std::runtime_error("No driver for file tyle found"); } char ** papszMetadata = poDriver->GetMetadata(); if (!(CSLFetchBoolean(papszMetadata, GDAL_DCAP_CREATE, FALSE))) { throw std::runtime_error("Driver does not support raster creation"); } char **papszOptions = NULL; papszOptions = CSLSetNameValue(papszOptions, "COMPRESS", "LZW"); GDALDataset *poDstDS = poDriver->Create(file_path.string().c_str(), (int)data->NCols(), (int)data->NRows(), 1, data_type, papszOptions); double adfGeoTransform[6] = {1, 1, 1, 1, 1, 1}; adfGeoTransform[0] = transform.x_origin; adfGeoTransform[1] = transform.pixel_width; adfGeoTransform[2] = transform.x_line_space; adfGeoTransform[3] = transform.y_origin; adfGeoTransform[4] = transform.pixel_height; adfGeoTransform[5] = transform.y_line_space; const char * psz_WKT = WKTprojection.c_str(); poDstDS->SetGeoTransform(adfGeoTransform); poDstDS->SetProjection(psz_WKT); DataFormat * pafScanline = new DataFormat[data->NCols() * data->NRows()]; int pafIterator = 0; for (int i = 0; i < data->NRows(); i++) { for (int j = 0; j < data->NCols(); j++) { pafScanline[pafIterator] = data->Get(i, j); pafIterator++; } } GDALRasterBand * poBand = poDstDS->GetRasterBand(1); poBand->SetNoDataValue(data->NoDataValue()); poBand->RasterIO(GF_Write, 0, 0, (int) data->NCols(), (int) data->NRows(), pafScanline, (int) data->NCols(), (int) data->NRows(), data_type, 0, 0); GDALClose( (GDALDatasetH) poDstDS); }
GDALDataset* CreateGDALRaster(TeRasterParams& params) { // Gets the appropriate GDAL driver std::string path = params.fileName_; if(path.empty()) return 0; std::string extension = TeGetExtension(path.c_str()); std::string driverName = TeGDALDecoder::getGDALDriverName(extension); if(driverName.empty()) return 0; GDALDriverManager* driverManager = GetGDALDriverManager(); GDALDriver* driver = driverManager->GetDriverByName(driverName.c_str()); if(driver == 0) return 0; // Converts the raster data type GDALDataType gDataType = Convert2GDAL(params.dataType_[0]); // Creates the raster GDAL GDALDataset* ds = driver->Create(path.c_str(), params.ncols_, params.nlines_, params.nBands(), gDataType, 0); if(ds == 0) return 0; // Sets the geometric transformations double gt[6]; Convert2GDAL(gt, params); ds->SetGeoTransform(gt); // Sets the raster projection TeProjection* proj = params.projection(); if(proj) { int epsg = proj->epsgCode(); OGRSpatialReference oSRS; oSRS.importFromEPSG(epsg); char* projWKT = 0; if(oSRS.exportToWkt(&projWKT) == OGRERR_NONE) { ds->SetProjection(projWKT); OGRFree(projWKT); } } return ds; }
//fn is the name of the file that contains the original image data, //dst is the filename to save the change detection results void ChangeDetector::SaveChange(const CString&fn, const CString&dst)const { assure(buf,"saving void change results!"); GDALDataset* m_pDataset=(GDALDataset *) GDALOpen(fn,GA_ReadOnly); GDALRasterBand *poBand=NULL; GDALDataType dataType=GDT_Byte; const char *pszFormat = "GTiff"; GDALDriver *poDriver; poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); if( poDriver == NULL) { AfxMessageBox("This format is not able to be created!"); return; } //using create GDALDataset *poDstDS; char **papszOptions = NULL; // OGRSpatialReference oSRS; double adfGeoTransform[6]= { 444720, 30, 0, 3751320, 0, -30 }; poDstDS = poDriver->Create( dst,width,height, 1,dataType, papszOptions ); if(CE_None==m_pDataset->GetGeoTransform( adfGeoTransform )) poDstDS->SetGeoTransform( adfGeoTransform ); const char *pszSRS_WKT=m_pDataset->GetProjectionRef(); poDstDS->SetProjection( pszSRS_WKT ); CPLFree( (void*)pszSRS_WKT ); poBand = poDstDS->GetRasterBand(1); if (poBand) { if (CE_None!=poBand->RasterIO( GF_Write,0,0, width, height, buf, width,height,GDT_Byte, 0, 0 )) { AfxMessageBox("error write mpdataset!"); } } GDALClose((GDALDatasetH)m_pDataset); GDALClose( (GDALDatasetH) poDstDS ); }
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); }
/* added RSB 20060212 */ SEXP RGDAL_SetProject(SEXP sxpDataset, SEXP proj4string) { OGRSpatialReference oSRS; char *pszSRS_WKT = NULL; GDALDataset *pDataset = getGDALDatasetPtr(sxpDataset); oSRS.importFromProj4(CHAR(STRING_ELT(proj4string, 0))); oSRS.exportToWkt( &pszSRS_WKT ); OGRErr err = pDataset->SetProjection(pszSRS_WKT); CPLFree( pszSRS_WKT ); if (err == CE_Failure) warning("Failed to set projection\n"); return(sxpDataset); }
Dataset::Dataset ( const std::string& filename, const Extents& extents, unsigned int width, unsigned int height, int bands, unsigned int type ) : BaseClass(), _data ( 0x0 ) { // Make an in memory raster. const std::string format ( "MEM" ); // Find a driver for in memory raster. GDALDriver *driver ( GetGDALDriverManager()->GetDriverByName ( format.c_str() ) ); // Return now if we didn't find a driver. if ( 0x0 == driver ) return; // Create the file. GDALDataset *data ( driver->Create ( filename.c_str(), width, height, bands, static_cast<GDALDataType> ( type ), 0x0 ) ); if ( 0x0 == data ) return; // Make the transform. OGRSpatialReference dst; dst.SetWellKnownGeogCS ( "WGS84" ); // Create the geo transform. std::vector<double> geoTransform ( 6 ); Dataset::createGeoTransform ( geoTransform, extents, width, height ); if ( CE_None != data->SetGeoTransform( &geoTransform[0] ) ) return; char *wkt ( 0x0 ); if ( CE_None != dst.exportToWkt ( &wkt ) ) return; if ( CE_None != data->SetProjection( wkt ) ) return; // If we get here, everything succeeded. Set the internal pointer. _data = data; }
int Raster<T>::OutputGeoTiff(const char* filename) { /// Output GeoTiff all set as float datatype. by LJ. int n = m_nRows * m_nCols; float *data = new float[n]; int index = 0; for (int i = 0; i < m_nRows; ++i) { for (int j = 0; j < m_nCols; ++j) { data[i*m_nCols+j] = float(m_data[i][j]); } } const char *pszFormat = "GTiff"; GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); char **papszOptions = poDriver->GetMetadata(); GDALDataset *poDstDS = poDriver->Create(filename, m_nCols, m_nRows, 1, GDT_Float32, papszOptions ); /// Write the data to new file GDALRasterBand *poDstBand= poDstDS->GetRasterBand(1); poDstBand->RasterIO(GF_Write, 0, 0, m_nCols, m_nRows, data, m_nCols, m_nRows, GDT_Float32, 0, 0); poDstBand->SetNoDataValue(m_noDataValue); double geoTrans[6]; geoTrans[0] = m_xllCenter; geoTrans[1] = m_dx; geoTrans[2] = 0; geoTrans[3] = m_yllCenter + m_nRows*m_dx; geoTrans[4] = 0; geoTrans[5] = -m_dx; poDstDS->SetGeoTransform(geoTrans); poDstDS->SetProjection(m_srs.c_str()); GDALClose(poDstDS); delete[] data; return 0; }
int main( int nArgc, char ** papszArgv ) { // register drivers GDALAllRegister(); if( nArgc < 2 ) return EXIT_FAILURE; double dfaCornersX[5] = {0}; double dfaCornersY[5] = {0}; CPLString sFileName; // parse input values for( int iArg = 1; iArg < nArgc; iArg++ ) { if( EQUAL(papszArgv[iArg],"-nw")) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); const char* pszCoord = papszArgv[++iArg]; dfaCornersY[1] = CPLAtofM(pszCoord); pszCoord = papszArgv[++iArg]; dfaCornersX[1] = CPLAtofM(pszCoord); } else if( EQUAL(papszArgv[iArg],"-ne")) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); const char* pszCoord = papszArgv[++iArg]; dfaCornersY[2] = CPLAtofM(pszCoord); pszCoord = papszArgv[++iArg]; dfaCornersX[2] = CPLAtofM(pszCoord); } else if( EQUAL(papszArgv[iArg],"-se")) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); const char* pszCoord = papszArgv[++iArg]; dfaCornersY[3] = CPLAtofM(pszCoord); pszCoord = papszArgv[++iArg]; dfaCornersX[3] = CPLAtofM(pszCoord); } else if( EQUAL(papszArgv[iArg],"-sw")) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); const char* pszCoord = papszArgv[++iArg]; dfaCornersY[4] = CPLAtofM(pszCoord); pszCoord = papszArgv[++iArg]; dfaCornersX[4] = CPLAtofM(pszCoord); } else if( EQUAL(papszArgv[iArg],"-c")) { CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2); const char* pszCoord = papszArgv[++iArg]; dfaCornersY[0] = CPLAtofM(pszCoord); pszCoord = papszArgv[++iArg]; dfaCornersX[0] = CPLAtofM(pszCoord); } else if(sFileName.empty()) sFileName = papszArgv[iArg]; } OGRSpatialReference oOGRSpatialReference(SRS_WKT_WGS84); int nZoneNo = ceil( (180.0 + dfaCornersX[0]) / 6.0 ); OGRSpatialReference oDstSpatialReference(SRS_WKT_WGS84); oDstSpatialReference.SetUTM(nZoneNo, dfaCornersY[0] > 0); // transform coordinates from WGS84 to UTM OGRCoordinateTransformation *poCT = OGRCreateCoordinateTransformation( &oOGRSpatialReference, &oDstSpatialReference); if(!poCT) { Usage("get coordinate transformation failed"); return EXIT_FAILURE; } int nResult = poCT->Transform(5, dfaCornersX, dfaCornersY, NULL); if(!nResult) { Usage("transformation failed"); return EXIT_FAILURE; } // open input dataset GDALDataset *poSrcDataset = (GDALDataset *) GDALOpen( sFileName, GA_ReadOnly ); // GA_Update char* pszSpaRefDef = NULL; if( oDstSpatialReference.exportToWkt(&pszSpaRefDef) != OGRERR_NONE) { CPLFree( pszSpaRefDef ); GDALClose( (GDALDatasetH) poSrcDataset ); return EXIT_FAILURE; } // search point along image // add GCP to opened raster OGRPoint ptCenter(dfaCornersX[0], dfaCornersY[0]); OGRPoint pt1(dfaCornersX[1], dfaCornersY[1]); // NW Cormer OGRPoint pt2(dfaCornersX[2], dfaCornersY[2]); // NE Corner OGRPoint pt3(dfaCornersX[3], dfaCornersY[3]); // SE Corner OGRPoint pt4(dfaCornersX[4], dfaCornersY[4]); // SW Corner int nGCPCount = 0; OGREnvelope DstEnv; GDAL_GCP *paGSPs = PrepareGCP(sFileName, &pt1, &pt2, &pt3, &pt4, &ptCenter, oDstSpatialReference, poSrcDataset->GetRasterXSize(), poSrcDataset->GetRasterYSize(), nGCPCount, DstEnv); if(poSrcDataset->SetGCPs(nGCPCount, paGSPs, pszSpaRefDef) != CE_None) { Usage( "Set GCPs failed" ); return EXIT_FAILURE; } // create warper char **papszTO = NULL; papszTO = CSLSetNameValue( papszTO, "METHOD", "GCP_TPS" ); papszTO = CSLSetNameValue( papszTO, "NUM_THREADS", "4" ); papszTO = CSLSetNameValue( papszTO, "DST_SRS", pszSpaRefDef ); papszTO = CSLSetNameValue( papszTO, "SRC_SRS", pszSpaRefDef ); papszTO = CSLSetNameValue( papszTO, "INSERT_CENTER_LONG", "FALSE" ); GDALDriver *poOutputDriver = (GDALDriver *) GDALGetDriverByName( "GTiff" ); CPLSetConfigOption( "CHECK_WITH_INVERT_PROJ", "TRUE" ); void* hTransformArg = GDALCreateGenImgProjTransformer2( poSrcDataset, NULL, papszTO ); GDALTransformerInfo* psInfo = (GDALTransformerInfo*)hTransformArg; double adfThisGeoTransform[6]; double adfExtent[4]; int nThisPixels, nThisLines; // suggest the raster output size if( GDALSuggestedWarpOutput2( poSrcDataset, psInfo->pfnTransform, hTransformArg, adfThisGeoTransform, &nThisPixels, &nThisLines, adfExtent, 0 ) != CE_None ) { Usage( "Suggest Output failed" ); return EXIT_FAILURE; } adfThisGeoTransform[0] = DstEnv.MinX; adfThisGeoTransform[3] = DstEnv.MaxY; int nPixels = (int) ((DstEnv.MaxX - DstEnv.MinX) / adfThisGeoTransform[1] + 0.5); int nLines = (int) ((DstEnv.MaxY - DstEnv.MinY) / -adfThisGeoTransform[5] + 0.5); GDALSetGenImgProjTransformerDstGeoTransform( hTransformArg, adfThisGeoTransform); // create new raster CPLString sOutputRasterPath = CPLResetExtension(sFileName, "tif"); GDALDataset *poDstDataset = poOutputDriver->Create(sOutputRasterPath, nPixels, nLines, poSrcDataset->GetRasterCount(), GDT_Byte, NULL ); if( NULL == poDstDataset ) { Usage( "Create Output failed" ); return EXIT_FAILURE; } poDstDataset->SetProjection( pszSpaRefDef ); poDstDataset->SetGeoTransform( adfThisGeoTransform ); #ifdef APRROX_MAXERROR hTransformArg = GDALCreateApproxTransformer( GDALGenImgProjTransform, hTransformArg, APRROX_MAXERROR); GDALTransformerFunc pfnTransformer = GDALApproxTransform; GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE); #else GDALTransformerFunc pfnTransformer = GDALGenImgProjTransform; #endif // APRROX_MAXERROR // warp GDALWarpOptions *psWO = GDALCreateWarpOptions(); psWO->eWorkingDataType = GDT_Byte; psWO->eResampleAlg = GRA_NearestNeighbour; psWO->hSrcDS = poSrcDataset; psWO->hDstDS = poDstDataset; psWO->pfnTransformer = pfnTransformer; psWO->pTransformerArg = hTransformArg; psWO->pfnProgress = GDALTermProgress; psWO->nBandCount = poSrcDataset->GetRasterCount(); psWO->panSrcBands = (int *) CPLMalloc(psWO->nBandCount*sizeof(int)); psWO->panDstBands = (int *) CPLMalloc(psWO->nBandCount*sizeof(int)); for(int i = 0; i < psWO->nBandCount; ++i ) { psWO->panSrcBands[i] = i+1; psWO->panDstBands[i] = i+1; } GDALWarpOperation oWO; if( oWO.Initialize( psWO ) == CE_None ) { #ifdef MULTI if( oWO.ChunkAndWarpMulti( 0, 0, poDstDataset->GetRasterXSize(), poDstDataset->GetRasterYSize() ) != CE_None) #else //MULTI if( oWO.ChunkAndWarpImage( 0, 0, poDstDataset->GetRasterXSize(), poDstDataset->GetRasterYSize() ) != CE_None) #endif //MULTI { const char* err = CPLGetLastErrorMsg(); Usage( CPLSPrintf("Warp failed.%s", err) ); return EXIT_FAILURE; } } // cleanup GDALDestroyWarpOptions( psWO ); CSLDestroy( papszTO ); CPLFree( pszSpaRefDef ); GDALClose( (GDALDatasetH) poSrcDataset ); GDALClose( (GDALDatasetH) poDstDataset ); GDALDestroyDriverManager(); return EXIT_SUCCESS; }
int meaningful_change(string cd_map_file, string result_file) { GdalRasterApp cd_map; cd_map.open(cd_map_file.c_str()); int iBandCount = cd_map.nBand(); int iTileCountX = cd_map.getTileCountX(); int iTileCountY = cd_map.getTileCountY(); int iWidth = cd_map.width(); int iHeight = cd_map.height(); GDALDriver *poDriver; //驱动,用于创建新的文件 poDriver=GetGDALDriverManager()->GetDriverByName("GTIFF"); char **papszMetadata = poDriver->GetMetadata();//获取格式类型 GDALDataset *poDatasetNew; // 输出栅格 poDatasetNew = poDriver->Create(result_file.c_str(), iWidth, iHeight, 1, GDT_Byte, papszMetadata);//根据文件路径文件名,图像宽,高,波段数,数据类型,文件类型,创建新的数据集 poDatasetNew->SetProjection(cd_map.getGetProjectionRef()); poDatasetNew->SetGeoTransform(cd_map.getGeoTransform());//坐标赋值,与全色相同 int nCount = 0; double norm_threshold = 20.0; int bgColor = 0; int fgColor = 255; for (int i = 0;i < iTileCountX;++i) { for (int j = 0;j < iTileCountY;++j) { GdalRasterApp::RasterBuf *pBuf = cd_map.getTileData(i, j, iBandCount); int bufWidth = pBuf->iBufWidth; int bufHeight = pBuf->iBufHeight; int bufBand = pBuf->iBandCount; int offsetX, offsetY; cd_map.getTileOffset(i, j, offsetX, offsetY); cv::Mat change_image(cv::Size(bufWidth, bufHeight), CV_8UC1, cv::Scalar(fgColor)); //cv::Mat lbp_change(cv::Size(bufWidth, bufHeight), CV_8UC1); cv::Mat lbp_change = img_int2byte_band(pBuf, 0); //cv::Mat lbp_change = img_float2byte_band(pBuf, 0); //memcpy(lbp_change.data, pBuf->data, bufWidth*bufHeight); //cv::imwrite("E:\\minus.tif", lbp_change); int lbp_change_threshold = cvThresholdOtsu(lbp_change); int step = change_image.step; // change detection for (int row = 0; row < bufHeight; ++row) { for (int col = 0; col < bufWidth; ++col) { int lbp_change_ = lbp_change.data[row*lbp_change.step+col]; // 判断是否变化很小 if (lbp_change_ < lbp_change_threshold) { change_image.data[row*step+col] = bgColor; continue; } std::vector<double> change_vector(pFeatureBuf->iBandCount); for (int k = 0;k < pFeatureBuf->iBandCount;++k) { int pos = row * bufWidth * pFeatureBuf->iBandCount + col*pFeatureBuf->iBandCount + k; change_vector[k] = ((float*)pFeatureBuf->data)[pos]; } //如果变化是否和样本相似 for (int m = 0; m < (int)samples.size(); m++) { double angle_ = samples[m][0] - change_vector[0]; double norm_ = samples[m][1] - change_vector[1]; //double similarity = VectorSimilarity(samples[m], change_vector); //double distance = VectorDistance(samples[m], change_vector); //double angle = VectorAngle(samples[m], change_vector); //if (fabs(similarity) > similarityThreshold && distance < 15.0) //if (fabs(angle) < 10.0 && distance < 20.0) //if (fabs(similarity) < similarityThreshold) if (fabs(angle_) < similarityThreshold && fabs(norm_) < 10.0) //if (fabs(norm) < 10.0) { change_image.data[row*step+col] = bgColor; break; } } } } //RasterBuf2Opencv(pBuf, change_image); //cv::Mat change_image(bufHeight, bufWidth, CV_8U(bufBand)); //int nBandDataSize = GDALGetDataTypeSize( pBuf->eDataType ) / 8; //memcpy(change_image.data, (GByte*)(pBuf->data), bufWidth*bufHeight*bufBand*nBandDataSize); //cvtColor( change_image, change_image, CV_BGR2GRAY ); //int threshold = cvThresholdOtsu(change_image); //threshold = 60; //cv::threshold( change_image, change_image, threshold, 255, CV_THRESH_BINARY); //cv::Mat element = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3)); //cv::morphologyEx(change_image, change_image, cv::MORPH_CLOSE, element); //element = cv::getStructuringElement(cv::MORPH_CROSS , cv::Size(7, 7)); //cv::morphologyEx(change_image, change_image, cv::MORPH_OPEN, element); //element = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(7, 7)); //cv::morphologyEx(change_image, change_image, cv::MORPH_OPEN, element); //cv::GaussianBlur(change_image, change_image, cv::Size(5,5), 1.5); //cv::morphologyEx(change_image, change_image, cv::MORPH_CLOSE, element); //cv::imwrite("E:\\test0.tif", change_image); cv::Mat element = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(2,2)); //cv::morphologyEx(change_image, change_image, cv::MORPH_CLOSE, element); int nTemplate = sqrt(smallArea); nTemplate = nTemplate / 2 * 2 + 1; cv::medianBlur(change_image, change_image, nTemplate); //cv::imwrite("E:\\test1.tif", change_image); // 先闭运算 nTemplate = nTemplate / 2; element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5,5)); cv::morphologyEx(change_image, change_image, cv::MORPH_CLOSE, element); // 再开运算 //element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(10, 10)); //cv::morphologyEx(change_image, change_image, cv::MORPH_OPEN, element); //cv::imwrite("E:\\test2.tif", change_image); BinaryRemoveSmall(change_image, change_image, smallArea, bgColor, fgColor); //cv::Mat tmpMat = change_image.clone(); ////cv::GaussianBlur(tmpMat, tmpMat, cv::Size(5,5), 1.5); //std::vector<std::vector<cv::Point> > contours; //std::vector<cv::Vec4i> hierarchy; //cv::findContours(tmpMat, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) ); ////for (std::vector<std::vector<cv::Point> >::iterator iter_Contours = contours.begin(); iter_Contours != contours.end();++iter_Contours) //int nContours = (int)contours.size(); //for (int iContours = 0; iContours < nContours;++iContours) //{ // std::vector<cv::Point> contour = contours[iContours]; // double tempArea = fabs(cv::contourArea(contour)); // cv::Rect rect = cv::boundingRect(contour); // //当连通域的中心点为白色,而且面积较小时,用黑色进行填充 // if (tempArea < miniArea) // { // int pos_center = step*(rect.y+rect.height/2)+rect.x+rect.width/2; // //if (255 == change_image.data[pos_center]) // { // for(int y = rect.y;y<rect.y+rect.height;y++) // { // for(int x =rect.x;x<rect.x+rect.width;x++) // { // int pos_ = y*step+x; // if(255 == change_image.data[pos_]) // { // change_image.data[pos_] = 0; // } // } // } // } // } //} //cv::imwrite("E:\\test3.tif", change_image); ////cv::imwrite("E:\\test.tif", change_image); if (_changeOutType::raster == outType) { // 输出栅格 CPLErr gdal_err = poDatasetNew->RasterIO(GF_Write, offsetX, offsetY, bufWidth, bufHeight, change_image.data, bufWidth, bufHeight,\ GDT_Byte, 1, 0, 0, 0, 0); } else if (_changeOutType::vector == outType) { // 输出矢量 std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours(change_image, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) ); addContour2ShapeArea(contours, out_layer_file, raster_minus.getGeoTransform(), raster_minus.getGetProjectionRef(), nCount, raster_minus.getBufInfo()->iBufOffsetX, raster_minus.getBufInfo()->iBufOffsetY); nCount += (int)contours.size(); } pBuf = NULL; } } raster_minus.close(); raster_feature.close(); poDatasetNew->FlushCache(); GDALClose(poDatasetNew); }
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; }
bool GDALUtilities::createRasterFile(QString& theFilename, QString& theFormat, GDALDataType theType, int theBands, int theRows, int theCols, void ** theData, double * theGeoTransform, const QgsCoordinateReferenceSystem * theCrs, double theNodataValue) { if ( theBands <= 0 ) return false; if ( theRows <= 0 ) return false; if ( theCols <= 0 ) return false; if ( !theData ) return false; /* bool formatSupported = false; QMapIterator<QString, QString> i(mSupportedFormats); while (i.hasNext()) { i.next(); if( theFormat == i.key()) { formatSupported = true; break; } } if ( !formatSupported ) return false; */ //GDALAllRegister(); GDALDriver * driver; //set format char * format = new char[theFormat.size() + 1]; strcpy( format, theFormat.toLocal8Bit().data() ); driver = GetGDALDriverManager()->GetDriverByName(format); if( driver == NULL ) return false; char ** metadata = driver->GetMetadata(); if( !CSLFetchBoolean( metadata, GDAL_DCAP_CREATE, FALSE ) ) return false; GDALDataset * dstDS; //set options char ** options = NULL; options = CSLSetNameValue( options, "COMPRESS", "LZW" ); //if it is a GeoTIFF format set correct compression options if ( !strcmp( format, "GTiff" ) ) { if( theType == GDT_Byte ) { options = CSLSetNameValue( options, "PREDICTOR", "1" ); } else { if ( theType == GDT_UInt16 || theType == GDT_Int16 || theType == GDT_UInt32 || theType == GDT_Int32 ) { options = CSLSetNameValue( options, "PREDICTOR", "2" ); } else { options = CSLSetNameValue( options, "PREDICTOR", "3" ); } } } //set filename char * dstFilename = new char[theFilename.size() + 1]; strcpy( dstFilename, theFilename.toLocal8Bit().data() ); dstDS = driver->Create( dstFilename, theCols, theRows, theBands, theType, options ); delete dstFilename; delete [] options; //set geotransform dstDS->SetGeoTransform( theGeoTransform ); //set CRS char * crsWkt = new char[theCrs->toWkt().size() + 1]; strcpy( crsWkt, theCrs->toWkt().toLocal8Bit().data()); dstDS->SetProjection( crsWkt ); delete crsWkt; GDALRasterBand * band; for( int i=1; i <= theBands; i++ ) { band = dstDS->GetRasterBand( i ); band->SetNoDataValue( theNodataValue ); band->RasterIO( GF_Write, 0, 0, theCols, theRows, theData[ i-1 ], theCols, theRows, theType, 0, 0); } GDALClose( (GDALDatasetH) dstDS ); return true; }
void output_geotiff ( rgb_image & out ) { int i, r, c; int val; char s[2]; OGRSpatialReference ref; GDALDataset *df; char *wkt = NULL; GDALRasterBand *bd; double trans[6]; GDALDriver *gt; char **options = NULL; int ov[] = { 2, 4, 8, 16, 32 }; int nov; int n; int bands[] = { 1, 2, 3 }; char file[1000]; int block, ir, rows; options = CSLSetNameValue ( options, "TILED", "NO" ); options = CSLSetNameValue ( options, "BLOCKXSIZE", "256" ); options = CSLSetNameValue ( options, "BLOCKYSIZE", "256" ); options = CSLSetNameValue ( options, "COMPRESS", "LZW" ); gt = GetGDALDriverManager()->GetDriverByName("GTiff"); if ( !gt ) { fprintf(stderr,"Could not get GTiff driver\n"); exit(1); } strcpy ( file, p.value("output_file").c_str() ); df = gt->Create( file, out.cols, out.rows, 3, GDT_Byte, options ); if( df == NULL ) { fprintf(stderr,"Could not create %s\n", file ); exit(1); } trans[0] = p.dvalue("easting_left"); trans[1] = p.dvalue("output_cell_size"); trans[2] = 0.0; trans[3] = p.dvalue("northing_top"); trans[4] = 0.0; trans[5] = -p.dvalue("output_cell_size"); df->SetGeoTransform ( trans ); ref.SetUTM ( p.ivalue("utm_zone") ); ref.SetWellKnownGeogCS ( "NAD27" ); ref.exportToWkt ( &wkt ); df->SetProjection(wkt); CPLFree ( wkt ); for ( ir = 0; ir < out.rows; ir += bs ) { rows = out.rows - ir; if ( rows > bs ) rows = bs; //printf("Writer waiting for %d\n",ir ); pe.wait_for("data",ir); for ( i = 0; i < 3; i++ ) { bd = df->GetRasterBand(i+1); bd->RasterIO( GF_Write, 0, ir, out.cols, rows, out.img[i].data+ir*out.cols, out.cols, rows, GDT_Byte, 0, 0 ); } } delete df; df = (GDALDataset *)GDALOpen ( file, GA_Update ); if( df == NULL ) { fprintf(stderr,"Could not open for update %s\n", file ); exit(1); } nov = p.ivalue("overviews"); if ( nov > 5 ) nov = 5; if ( nov > 0 ) { df->BuildOverviews("NEAREST", nov, ov, 3, bands, NULL, NULL ); } }
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; }
int Raster::Copy(const char * pOutputRaster, double * dNewCellSize, double fLeft, double fTop, int nRows, int nCols) { if (fLeft <=0) return LEFT_ERROR; if (fTop <=0) return TOP_ERROR; if (nRows <=0) return ROWS_ERROR; if (nCols <=0) return COLS_ERROR; // Open the original dataset GDALDataset * pDSOld = (GDALDataset*) GDALOpen(m_sFilePath, GA_ReadOnly); if (pDSOld == NULL) return INPUT_FILE_ERROR; GDALRasterBand * pRBInput = pDSOld->GetRasterBand(1); /* Create the new dataset. Determine the driver from the output file extension. * Enforce LZW compression for TIFs. The predictor 3 is used for floating point prediction. * Not using this value defaults the LZW to prediction to 1 which causes striping. */ char **papszOptions = NULL; GDALDriver * pDR = NULL; std::string psDR = ""; const char * pSuffix = ExtractFileExt(pOutputRaster); if (pSuffix == NULL) return OUTPUT_FILE_EXT_ERROR; else { if (strcmp(pSuffix, ".tif") == 0) { psDR = "GTiff"; pDR = GetGDALDriverManager()->GetDriverByName(psDR.c_str()); papszOptions = CSLSetNameValue(papszOptions, "COMPRESS", "LZW"); //papszOptions = CSLSetNameValue(papszOptions, "PREDICTOR", "3"); } else if (strcmp(pSuffix, ".img") == 0){ psDR = "HFA"; pDR = GetGDALDriverManager()->GetDriverByName(psDR.c_str()); } else return OUTPUT_UNHANDLED_DRIVER; } double dNewCellHeight = (*dNewCellSize) * -1; RasterMeta OutputMeta(fTop, fLeft, nRows, nCols, &dNewCellHeight, dNewCellSize, GetNoDataValuePtr(), psDR.c_str(), GetGDALDataType(), GetProjectionRef() ); //const char * pC = pDR->GetDescription(); GDALDataset * pDSOutput = pDR->Create(pOutputRaster, nCols, nRows, 1, *GetGDALDataType(), papszOptions); CSLDestroy( papszOptions ); if (pDSOutput == NULL) return OUTPUT_FILE_ERROR; if (HasNoDataValue()) { CPLErr er = pDSOutput->GetRasterBand(1)->SetNoDataValue(GetNoDataValue()); if (er == CE_Failure || er == CE_Fatal) return OUTPUT_NO_DATA_ERROR; } pDSOutput->SetGeoTransform(OutputMeta.GetGeoTransform()); pDSOutput->SetProjection(pDSOld->GetProjectionRef()); int nInputCols = pRBInput->GetXSize(); int nInputRows = pRBInput->GetYSize(); double * pInputLine = (double *) CPLMalloc(sizeof(double)*nInputCols); double * pOutputLine = (double *) CPLMalloc(sizeof(double)*pDSOutput->GetRasterBand(1)->GetXSize()); int nRowTrans = GetRowTranslation(&OutputMeta); int nColTrans = GetColTranslation(&OutputMeta); /* * Loop over the raster rows. Note that geographic coordinate origin is bottom left. But * the GDAL image anchor is top left. The cell height is negative. * * The loop is over the centres of the output raster cells. Two rows are read from the * input raster. The line just above the output cell and the line just below. The line * just above is called the "anchor" row. */ int nOldRow, nOldCol; int i, j; for (i = 0; i < nRows; i++) { nOldRow = i - nRowTrans; if (nOldRow >= 0 && nOldRow < nInputRows) { pRBInput->RasterIO(GF_Read, 0, nOldRow, nInputCols, 1, pInputLine, nInputCols, 1, GDT_Float64, 0, 0); for (j = 0; j < nCols; j++) { nOldCol = j + nColTrans; if (nOldCol >=0 && nOldCol < nInputCols) { pOutputLine[j] = pInputLine[nOldCol]; } else { if (HasNoDataValue()) { pOutputLine[j] = GetNoDataValue(); } else { pOutputLine[j] = 0; } } } } else { // Outside the bounds of the input image. Loop over all cells in current output row and set to NoData. for (j = 0; j < nCols; j++) { pOutputLine[j] = GetNoDataValue(); } } pDSOutput->GetRasterBand(1)->RasterIO(GF_Write, 0, i, pDSOutput->GetRasterBand(1)->GetXSize(), 1, pOutputLine, pDSOutput->GetRasterBand(1)->GetXSize(), 1, GDT_Float64, 0, 0); } CPLFree(pInputLine); CPLFree(pOutputLine); CalculateStats(pDSOutput->GetRasterBand(1)); GDALClose(pDSOld); GDALClose(pDSOutput); GDALDumpOpenDatasets(stderr); return PROCESS_OK; }
GDALDataset *SAGADataset::CreateCopy( const char *pszFilename, GDALDataset *poSrcDS, int bStrict, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressData ) { if( pfnProgress == NULL ) pfnProgress = GDALDummyProgress; int nBands = poSrcDS->GetRasterCount(); if (nBands == 0) { CPLError( CE_Failure, CPLE_NotSupported, "SAGA driver does not support source dataset with zero band.\n"); return NULL; } else if (nBands > 1) { if( bStrict ) { CPLError( CE_Failure, CPLE_NotSupported, "Unable to create copy, SAGA Binary Grid " "format only supports one raster band.\n" ); return NULL; } else CPLError( CE_Warning, CPLE_NotSupported, "SAGA Binary Grid format only supports one " "raster band, first band will be copied.\n" ); } GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( 1 ); char** papszCreateOptions = NULL; papszCreateOptions = CSLSetNameValue(papszCreateOptions, "FILL_NODATA", "NO"); int bHasNoDataValue = FALSE; double dfNoDataValue = poSrcBand->GetNoDataValue(&bHasNoDataValue); if (bHasNoDataValue) papszCreateOptions = CSLSetNameValue(papszCreateOptions, "NODATA_VALUE", CPLSPrintf("%.16g", dfNoDataValue)); GDALDataset* poDstDS = Create(pszFilename, poSrcBand->GetXSize(), poSrcBand->GetYSize(), 1, poSrcBand->GetRasterDataType(), papszCreateOptions); CSLDestroy(papszCreateOptions); if (poDstDS == NULL) return NULL; /* -------------------------------------------------------------------- */ /* Copy band data. */ /* -------------------------------------------------------------------- */ CPLErr eErr; eErr = GDALDatasetCopyWholeRaster( (GDALDatasetH) poSrcDS, (GDALDatasetH) poDstDS, NULL, pfnProgress, pProgressData ); if (eErr == CE_Failure) { delete poDstDS; return NULL; } double adfGeoTransform[6]; poSrcDS->GetGeoTransform( adfGeoTransform ); poDstDS->SetGeoTransform( adfGeoTransform ); poDstDS->SetProjection( poSrcDS->GetProjectionRef() ); return poDstDS; }
OGRErr PDFWritableVectorDataset::SyncToDisk() { if (nLayers == 0 || !bModified) return OGRERR_NONE; bModified = FALSE; OGREnvelope sGlobalExtent; int bHasExtent = FALSE; for(int i=0;i<nLayers;i++) { OGREnvelope sExtent; if (papoLayers[i]->GetExtent(&sExtent) == OGRERR_NONE) { bHasExtent = TRUE; sGlobalExtent.Merge(sExtent); } } if (!bHasExtent || sGlobalExtent.MinX == sGlobalExtent.MaxX || sGlobalExtent.MinY == sGlobalExtent.MaxY) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot compute spatial extent of features"); return OGRERR_FAILURE; } PDFCompressMethod eStreamCompressMethod = COMPRESS_DEFLATE; const char* pszStreamCompressMethod = CSLFetchNameValue(papszOptions, "STREAM_COMPRESS"); if (pszStreamCompressMethod) { if( EQUAL(pszStreamCompressMethod, "NONE") ) eStreamCompressMethod = COMPRESS_NONE; else if( EQUAL(pszStreamCompressMethod, "DEFLATE") ) eStreamCompressMethod = COMPRESS_DEFLATE; else { CPLError( CE_Warning, CPLE_NotSupported, "Unsupported value for STREAM_COMPRESS."); } } const char* pszGEO_ENCODING = CSLFetchNameValueDef(papszOptions, "GEO_ENCODING", "ISO32000"); double dfDPI = CPLAtof(CSLFetchNameValueDef(papszOptions, "DPI", "72")); if (dfDPI < 72.0) dfDPI = 72.0; const char* pszNEATLINE = CSLFetchNameValue(papszOptions, "NEATLINE"); int nMargin = atoi(CSLFetchNameValueDef(papszOptions, "MARGIN", "0")); PDFMargins sMargins; sMargins.nLeft = nMargin; sMargins.nRight = nMargin; sMargins.nTop = nMargin; sMargins.nBottom = nMargin; const char* pszLeftMargin = CSLFetchNameValue(papszOptions, "LEFT_MARGIN"); if (pszLeftMargin) sMargins.nLeft = atoi(pszLeftMargin); const char* pszRightMargin = CSLFetchNameValue(papszOptions, "RIGHT_MARGIN"); if (pszRightMargin) sMargins.nRight = atoi(pszRightMargin); const char* pszTopMargin = CSLFetchNameValue(papszOptions, "TOP_MARGIN"); if (pszTopMargin) sMargins.nTop = atoi(pszTopMargin); const char* pszBottomMargin = CSLFetchNameValue(papszOptions, "BOTTOM_MARGIN"); if (pszBottomMargin) sMargins.nBottom = atoi(pszBottomMargin); const char* pszExtraImages = CSLFetchNameValue(papszOptions, "EXTRA_IMAGES"); const char* pszExtraStream = CSLFetchNameValue(papszOptions, "EXTRA_STREAM"); const char* pszExtraLayerName = CSLFetchNameValue(papszOptions, "EXTRA_LAYER_NAME"); const char* pszOGRDisplayField = CSLFetchNameValue(papszOptions, "OGR_DISPLAY_FIELD"); const char* pszOGRDisplayLayerNames = CSLFetchNameValue(papszOptions, "OGR_DISPLAY_LAYER_NAMES"); int bWriteOGRAttributes = CSLFetchBoolean(papszOptions, "OGR_WRITE_ATTRIBUTES", TRUE); const char* pszOGRLinkField = CSLFetchNameValue(papszOptions, "OGR_LINK_FIELD"); const char* pszOffLayers = CSLFetchNameValue(papszOptions, "OFF_LAYERS"); const char* pszExclusiveLayers = CSLFetchNameValue(papszOptions, "EXCLUSIVE_LAYERS"); const char* pszJavascript = CSLFetchNameValue(papszOptions, "JAVASCRIPT"); const char* pszJavascriptFile = CSLFetchNameValue(papszOptions, "JAVASCRIPT_FILE"); /* -------------------------------------------------------------------- */ /* Create file. */ /* -------------------------------------------------------------------- */ VSILFILE* fp = VSIFOpenL(GetDescription(), "wb"); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Unable to create PDF file %s.\n", GetDescription() ); return OGRERR_FAILURE; } GDALPDFWriter oWriter(fp); double dfRatio = (sGlobalExtent.MaxY - sGlobalExtent.MinY) / (sGlobalExtent.MaxX - sGlobalExtent.MinX); int nWidth, nHeight; if (dfRatio < 1) { nWidth = 1024; nHeight = nWidth * dfRatio; } else { nHeight = 1024; nWidth = nHeight / dfRatio; } GDALDataset* poSrcDS = MEMDataset::Create( "MEM:::", nWidth, nHeight, 0, GDT_Byte, NULL ); double adfGeoTransform[6]; adfGeoTransform[0] = sGlobalExtent.MinX; adfGeoTransform[1] = (sGlobalExtent.MaxX - sGlobalExtent.MinX) / nWidth; adfGeoTransform[2] = 0; adfGeoTransform[3] = sGlobalExtent.MaxY; adfGeoTransform[4] = 0; adfGeoTransform[5] = - (sGlobalExtent.MaxY - sGlobalExtent.MinY) / nHeight; poSrcDS->SetGeoTransform(adfGeoTransform); OGRSpatialReference* poSRS = papoLayers[0]->GetSpatialRef(); if (poSRS) { char* pszWKT = NULL; poSRS->exportToWkt(&pszWKT); poSrcDS->SetProjection(pszWKT); CPLFree(pszWKT); } oWriter.SetInfo(poSrcDS, papszOptions); oWriter.StartPage(poSrcDS, dfDPI, pszGEO_ENCODING, pszNEATLINE, &sMargins, eStreamCompressMethod, bWriteOGRAttributes); int iObj = 0; char** papszLayerNames = CSLTokenizeString2(pszOGRDisplayLayerNames,",",0); for(int i=0;i<nLayers;i++) { CPLString osLayerName; if (CSLCount(papszLayerNames) < nLayers) osLayerName = papoLayers[i]->GetName(); else osLayerName = papszLayerNames[i]; oWriter.WriteOGRLayer((OGRDataSourceH)this, i, pszOGRDisplayField, pszOGRLinkField, osLayerName, bWriteOGRAttributes, iObj); } CSLDestroy(papszLayerNames); oWriter.EndPage(pszExtraImages, pszExtraStream, pszExtraLayerName, pszOffLayers, pszExclusiveLayers); if (pszJavascript) oWriter.WriteJavascript(pszJavascript); else if (pszJavascriptFile) oWriter.WriteJavascriptFile(pszJavascriptFile); oWriter.Close(); delete poSrcDS; return OGRERR_NONE; }
/*************************************************************************************************************************************** * 利用源数据文件所在文件夹(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; }
// Slot called when the menu item is triggered // If you created more menu items / toolbar buttons in initiGui, you should // create a separate handler for each action - this single run() method will // not be enough void Heatmap::run() { HeatmapGui d( mQGisIface->mainWindow(), QgisGui::ModalDialogFlags, &mSessionSettings ); if ( d.exec() == QDialog::Accepted ) { // everything runs here // Get the required data from the dialog QgsRectangle myBBox = d.bbox(); int columns = d.columns(); int rows = d.rows(); double cellsize = d.cellSizeX(); // or d.cellSizeY(); both have the same value mDecay = d.decayRatio(); int kernelShape = d.kernelShape(); // Start working on the input vector QgsVectorLayer* inputLayer = d.inputVectorLayer(); // Getting the rasterdataset in place GDALAllRegister(); GDALDataset *emptyDataset; GDALDriver *myDriver; myDriver = GetGDALDriverManager()->GetDriverByName( d.outputFormat().toUtf8() ); if ( myDriver == NULL ) { QMessageBox::information( 0, tr( "GDAL driver error" ), tr( "Cannot open the driver for the specified format" ) ); return; } double geoTransform[6] = { myBBox.xMinimum(), cellsize, 0, myBBox.yMinimum(), 0, cellsize }; emptyDataset = myDriver->Create( d.outputFilename().toUtf8(), columns, rows, 1, GDT_Float32, NULL ); emptyDataset->SetGeoTransform( geoTransform ); // Set the projection on the raster destination to match the input layer emptyDataset->SetProjection( inputLayer->crs().toWkt().toLocal8Bit().data() ); GDALRasterBand *poBand; poBand = emptyDataset->GetRasterBand( 1 ); poBand->SetNoDataValue( NO_DATA ); float* line = ( float * ) CPLMalloc( sizeof( float ) * columns ); for ( int i = 0; i < columns ; i++ ) { line[i] = NO_DATA; } // Write the empty raster for ( int i = 0; i < rows ; i++ ) { poBand->RasterIO( GF_Write, 0, i, columns, 1, line, columns, 1, GDT_Float32, 0, 0 ); } CPLFree( line ); //close the dataset GDALClose(( GDALDatasetH ) emptyDataset ); // open the raster in GA_Update mode GDALDataset *heatmapDS; heatmapDS = ( GDALDataset * ) GDALOpen( d.outputFilename().toUtf8(), GA_Update ); if ( !heatmapDS ) { QMessageBox::information( 0, tr( "Raster update error" ), tr( "Could not open the created raster for updating. The heatmap was not generated." ) ); return; } poBand = heatmapDS->GetRasterBand( 1 ); QgsAttributeList myAttrList; int rField = 0; int wField = 0; // Handle different radius options double radius; double radiusToMapUnits = 1; int myBuffer = 0; if ( d.variableRadius() ) { rField = d.radiusField(); myAttrList.append( rField ); QgsDebugMsg( QString( "Radius Field index received: %1" ).arg( rField ) ); // If not using map units, then calculate a conversion factor to convert the radii to map units if ( d.radiusUnit() == HeatmapGui::Meters ) { radiusToMapUnits = mapUnitsOf( 1, inputLayer->crs() ); } } else { radius = d.radius(); // radius returned by d.radius() is already in map units myBuffer = bufferSize( radius, cellsize ); } if ( d.weighted() ) { wField = d.weightField(); myAttrList.append( wField ); } // This might have attributes or mightnot have attibutes at all // based on the variableRadius() and weighted() QgsFeatureIterator fit = inputLayer->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( myAttrList ) ); int totalFeatures = inputLayer->featureCount(); int counter = 0; QProgressDialog p( tr( "Creating heatmap" ), tr( "Abort" ), 0, totalFeatures, mQGisIface->mainWindow() ); p.setWindowModality( Qt::ApplicationModal ); p.show(); QgsFeature myFeature; while ( fit.nextFeature( myFeature ) ) { counter++; p.setValue( counter ); QApplication::processEvents(); if ( p.wasCanceled() ) { QMessageBox::information( 0, tr( "Heatmap generation aborted" ), tr( "QGIS will now load the partially-computed raster." ) ); break; } QgsGeometry* myPointGeometry; myPointGeometry = myFeature.geometry(); // convert the geometry to point QgsPoint myPoint; myPoint = myPointGeometry->asPoint(); // avoiding any empty points or out of extent points if (( myPoint.x() < myBBox.xMinimum() ) || ( myPoint.y() < myBBox.yMinimum() ) || ( myPoint.x() > myBBox.xMaximum() ) || ( myPoint.y() > myBBox.yMaximum() ) ) { continue; } // If radius is variable then fetch it and calculate new pixel buffer size if ( d.variableRadius() ) { radius = myFeature.attribute( rField ).toDouble() * radiusToMapUnits; myBuffer = bufferSize( radius, cellsize ); } int blockSize = 2 * myBuffer + 1; //Block SIDE would be more appropriate // calculate the pixel position unsigned int xPosition, yPosition; xPosition = (( myPoint.x() - myBBox.xMinimum() ) / cellsize ) - myBuffer; yPosition = (( myPoint.y() - myBBox.yMinimum() ) / cellsize ) - myBuffer; // get the data float *dataBuffer = ( float * ) CPLMalloc( sizeof( float ) * blockSize * blockSize ); poBand->RasterIO( GF_Read, xPosition, yPosition, blockSize, blockSize, dataBuffer, blockSize, blockSize, GDT_Float32, 0, 0 ); double weight = 1.0; if ( d.weighted() ) { weight = myFeature.attribute( wField ).toDouble(); } for ( int xp = 0; xp <= myBuffer; xp++ ) { for ( int yp = 0; yp <= myBuffer; yp++ ) { double distance = sqrt( pow( xp, 2.0 ) + pow( yp, 2.0 ) ); // is pixel outside search bandwidth of feature? if ( distance > myBuffer ) { continue; } double pixelValue = weight * calculateKernelValue( distance, myBuffer, kernelShape ); // clearing anamolies along the axes if ( xp == 0 && yp == 0 ) { pixelValue /= 4; } else if ( xp == 0 || yp == 0 ) { pixelValue /= 2; } int pos[4]; pos[0] = ( myBuffer + xp ) * blockSize + ( myBuffer + yp ); pos[1] = ( myBuffer + xp ) * blockSize + ( myBuffer - yp ); pos[2] = ( myBuffer - xp ) * blockSize + ( myBuffer + yp ); pos[3] = ( myBuffer - xp ) * blockSize + ( myBuffer - yp ); for ( int p = 0; p < 4; p++ ) { if ( dataBuffer[ pos[p] ] == NO_DATA ) { dataBuffer[ pos[p] ] = 0; } dataBuffer[ pos[p] ] += pixelValue; } } } poBand->RasterIO( GF_Write, xPosition, yPosition, blockSize, blockSize, dataBuffer, blockSize, blockSize, GDT_Float32, 0, 0 ); CPLFree( dataBuffer ); } // Finally close the dataset GDALClose(( GDALDatasetH ) heatmapDS ); // Open the file in QGIS window mQGisIface->addRasterLayer( d.outputFilename(), QFileInfo( d.outputFilename() ).baseName() ); } }
/* * Algorithm taken from: http://www.quantdec.com/SYSEN597/GTKAV/section9/map_algebra.htm * */ int Raster::ReSample(const char * pOutputRaster, double fNewCellSize, double fNewLeft, double fNewTop, int nNewRows, int nNewCols) { if (fNewCellSize <= 0) return CELL_SIZE_ERROR; if (fNewLeft <=0) return LEFT_ERROR; if (fNewTop <=0) return TOP_ERROR; if (nNewRows <=0) return ROWS_ERROR; if (nNewCols <=0) return COLS_ERROR; /************************************************************************************************* * Open the original dataset and retrieve its basic properties */ GDALDataset * pDSOld = (GDALDataset*) GDALOpen(m_sFilePath, GA_ReadOnly); if (pDSOld == NULL) return INPUT_FILE_ERROR; GDALRasterBand * pRBInput = pDSOld->GetRasterBand(1); /************************************************************************************************* * Create the new dataset. Determine the driver from the output file extension. * Enforce LZW compression for TIFs. The predictor 3 is used for floating point prediction. * Not using this value defaults the LZW to prediction to 1 which causes striping. */ char **papszOptions = NULL; GDALDriver * pDR = NULL; const char * pSuffix = ExtractFileExt(pOutputRaster); if (pSuffix == NULL) return OUTPUT_FILE_EXT_ERROR; else { if (strcmp(pSuffix, ".tif") == 0) { pDR = GetGDALDriverManager()->GetDriverByName("GTiff"); papszOptions = CSLSetNameValue(papszOptions, "COMPRESS", "LZW"); //papszOptions = CSLSetNameValue(papszOptions, "PREDICTOR", "3"); } else if (strcmp(pSuffix, ".img") == 0) pDR = GetGDALDriverManager()->GetDriverByName("HFA"); else return OUTPUT_UNHANDLED_DRIVER; } GDALDataset * pDSOutput = pDR->Create(pOutputRaster, nNewCols, nNewRows, 1, *GetGDALDataType(), papszOptions); CSLDestroy( papszOptions ); if (pDSOutput == NULL) return OUTPUT_FILE_ERROR; GDALRasterBand * pRBOutput = pDSOutput->GetRasterBand(1); if (HasNoDataValue()) { CPLErr er = pRBOutput->SetNoDataValue(this->GetNoDataValue()); if (er == CE_Failure || er == CE_Fatal) return OUTPUT_NO_DATA_ERROR; } double newTransform[6]; newTransform[0] = fNewLeft; newTransform[1] = fNewCellSize; newTransform[2] = 0; newTransform[3] = fNewTop; newTransform[4] = 0; newTransform[5] = -1 * fNewCellSize; pDSOutput->SetGeoTransform(newTransform); pDSOutput->SetProjection(GetProjectionRef()); ReSampleRaster(pRBInput, pRBOutput, fNewCellSize, fNewLeft, fNewTop, nNewRows, nNewCols); CalculateStats(pDSOutput->GetRasterBand(1)); GDALClose(pDSOld); GDALClose(pDSOutput); return PROCESS_OK; }
//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); } }
//--------------------------------------------------------- bool CGDAL_Export::On_Execute(void) { char **pOptions = NULL; int x, y, n; double *zLine; CSG_String File_Name; CSG_Parameter_Grid_List *pGrids; CSG_Grid *pGrid; GDALDataType gdal_Type; GDALDriver *pDriver; GDALDataset *pDataset; GDALRasterBand *pBand; //----------------------------------------------------- pGrids = Parameters("GRIDS") ->asGridList(); File_Name = Parameters("FILE") ->asString(); //----------------------------------------------------- switch( Parameters("TYPE")->asInt() ) { default: case 0: gdal_Type = g_GDAL_Driver.Get_GDAL_Type(pGrids); break; // match input data case 1: gdal_Type = GDT_Byte; break; // Eight bit unsigned integer case 2: gdal_Type = GDT_UInt16; break; // Sixteen bit unsigned integer case 3: gdal_Type = GDT_Int16; break; // Sixteen bit signed integer case 4: gdal_Type = GDT_UInt32; break; // Thirty two bit unsigned integer case 5: gdal_Type = GDT_Int32; break; // Thirty two bit signed integer case 6: gdal_Type = GDT_Float32; break; // Thirty two bit floating point case 7: gdal_Type = GDT_Float64; break; // Sixty four bit floating point } //----------------------------------------------------- if( (pDriver = g_GDAL_Driver.Get_Driver(SG_STR_SGTOMB(m_DriverNames[Parameters("FORMAT")->asInt()]))) == NULL ) { Message_Add(_TL("Driver not found.")); } else if( CSLFetchBoolean(pDriver->GetMetadata(), GDAL_DCAP_CREATE, false) == false ) { Message_Add(_TL("Driver does not support file creation.")); } else if( (pDataset = pDriver->Create(File_Name.b_str(), Get_NX(), Get_NY(), pGrids->Get_Count(), gdal_Type, pOptions)) == NULL ) { Message_Add(_TL("Could not create dataset.")); } else { g_GDAL_Driver.Set_Transform(pDataset, Get_System()); if( pGrids->asGrid(0)->Get_Projection().Get_Type() != SG_PROJ_TYPE_CS_Undefined ) { pDataset->SetProjection(SG_STR_SGTOMB(pGrids->asGrid(0)->Get_Projection().Get_WKT())); } zLine = (double *)SG_Malloc(Get_NX() * sizeof(double)); for(n=0; n<pGrids->Get_Count(); n++) { Process_Set_Text(CSG_String::Format(SG_T("%s %d"), _TL("Band"), n + 1)); pGrid = pGrids->asGrid(n); pBand = pDataset->GetRasterBand(n + 1); for(y=0; y<Get_NY() && Set_Progress(y, Get_NY()); y++) { for(x=0; x<Get_NX(); x++) { zLine[x] = pGrid->asDouble(x, Get_NY() - 1 - y); } pBand->RasterIO(GF_Write, 0, y, Get_NX(), 1, zLine, Get_NX(), 1, GDT_Float64, 0, 0); } } //------------------------------------------------- SG_Free(zLine); GDALClose(pDataset); return( true ); } //----------------------------------------------------- return( false ); }
void clsRasterData::outputGTiff(map<string,float> header,int nValidCells,float** position, float* value,string filename) { float noDataValue = header["NODATA_VALUE"]; int nCols = header["NCOLS"]; int nRows = header["NROWS"]; float xll = header["XLLCENTER"]; float yll = header["YLLCENTER"]; float dx = header["CELLSIZE"]; int n = nRows * nCols; float *data = new float[n]; int index = 0; for (int i = 0; i < nRows; ++i) { for (int j = 0; j < nCols; ++j) { if(index < nValidCells) { if(position[index][0] == i && position[index][1] == j) { data[i*nCols+j] = value[index]; index++; } else data[i*nCols+j] = noDataValue; } else data[i*nCols+j] = noDataValue; } } const char *pszFormat = "GTiff"; GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); char **papszOptions = poDriver->GetMetadata(); GDALDataset *poDstDS = poDriver->Create(filename.c_str(), nCols, nRows, 1, GDT_Float32, papszOptions ); //write the data to new file GDALRasterBand *poDstBand= poDstDS->GetRasterBand(1); poDstBand->RasterIO(GF_Write, 0, 0, nCols, nRows, data, nCols, nRows, GDT_Float32, 0, 0); poDstBand->SetNoDataValue(noDataValue); double geoTrans[6]; geoTrans[0] = xll; geoTrans[1] = dx; geoTrans[2] = 0; geoTrans[3] = yll + nRows*dx; geoTrans[4] = 0; geoTrans[5] = -dx; poDstDS->SetGeoTransform(geoTrans); OGRSpatialReference srs; srs.SetACEA(25, 47, 0, 105, 0, 0); srs.SetWellKnownGeogCS("WGS84"); char *pSrsWkt = NULL; srs.exportToWkt(&pSrsWkt); poDstDS->SetProjection(pSrsWkt); CPLFree(pSrsWkt); GDALClose(poDstDS); delete[] data; }
void output_dist_geotiff ( image<float> & dist, image<unsigned char> & v ) { int r, c; int val; OGRSpatialReference ref; GDALDataset *df; char *wkt = NULL; GDALRasterBand *bd; double trans[6]; GDALDriver *gt; char **options = NULL; int ov[] = { 2, 4, 8, 16, 32 }; int nov; int n; char file[1000]; options = CSLSetNameValue ( options, "TILED", "NO" ); options = CSLSetNameValue ( options, "COMPRESS", "LZW" ); gt = GetGDALDriverManager()->GetDriverByName("GTiff"); if ( !gt ) { fprintf(stderr,"Could not get GTiff driver\n"); exit(1); } strcpy ( file, p.value("dist_file").c_str() ); df = gt->Create( file, dist.cols, dist.rows, 1, GDT_Byte, options ); if( df == NULL ) { fprintf(stderr,"Could not create %s\n", file ); exit(1); } trans[0] = p.dvalue("easting_left"); trans[1] = p.dvalue("output_cell_size"); trans[2] = 0.0; trans[3] = p.dvalue("northing_top"); trans[4] = 0.0; trans[5] = -p.dvalue("output_cell_size"); df->SetGeoTransform ( trans ); ref.SetUTM ( p.ivalue("utm_zone") ); ref.SetWellKnownGeogCS ( "NAD27" ); ref.exportToWkt ( &wkt ); df->SetProjection(wkt); CPLFree ( wkt ); for ( r=0; r < dist.rows; r++ ) { for ( c=0; c < dist.cols; c++ ) { val = int(sqrt(dist[r][c])+0.5); if ( val > 255 ) val = 255; v[r][c] = val; } } bd = df->GetRasterBand(1); bd->RasterIO( GF_Write, 0, 0, v.cols, v.rows, v.data, v.cols, v.rows, GDT_Byte, 0, 0 ); delete df; df = (GDALDataset *)GDALOpen ( file, GA_Update ); if( df == NULL ) { fprintf(stderr,"Could not open for update %s\n", file ); exit(1); } nov = p.ivalue("overviews"); if ( nov > 5 ) nov = 5; if ( nov > 0 ) { n = 1; df->BuildOverviews("NEAREST", nov, ov, 1, &n, NULL, NULL ); } }
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); }
/** *@brief 浓密植被法获得TM、ETM、GEOEYE的气溶胶 *@param *@return */ bool InvAod::invAod_HJ(const char* imgBand1, const char* imgBand2, const char* imgBand3, const char* imgBand4, const char* SunZenithImg, const char* SunAzimuthImg, const char* obserZenithImg, const char* obserAzimuthImg, info_HJ &calInfoHJ, const char* outputImg, string tmpdata) { EnumAeroType eAeroType = continent; EnumSensorType HJsensorType; if (calInfoHJ.HJSensor == "HJ1ACCD1") { HJsensorType = HJ1ACCD1; } else if (calInfoHJ.HJSensor == "HJ1ACCD2") { HJsensorType = HJ1ACCD2; } else if (calInfoHJ.HJSensor == "HJ1BCCD1") { HJsensorType = HJ1BCCD1; } else if (calInfoHJ.HJSensor == "HJ1BCCD2") { HJsensorType = HJ1BCCD2; } GDALDriver *poDriver; GDALDataset *poOutDataset; const char *format = "GTiff"; poDriver = GetGDALDriverManager()->GetDriverByName(format); char ** papszMetadata = NULL; GDALDataset *poDatasetBand1,*poDatasetBand2,*poDatasetBand3,*poDatasetBand4; GDALDataset *poDatasetSunZenith,*poDatasetSunAzimuth,*poDatasetobserZenith,*poDatasetobserAzimuth; poDatasetBand1 = (GDALDataset *) GDALOpen(imgBand1, GA_ReadOnly ); poDatasetBand2 = (GDALDataset *) GDALOpen(imgBand2, GA_ReadOnly ); poDatasetBand3 = (GDALDataset *) GDALOpen(imgBand3, GA_ReadOnly ); poDatasetBand4 = (GDALDataset *) GDALOpen(imgBand4, GA_ReadOnly ); poDatasetSunZenith = (GDALDataset *) GDALOpen(SunZenithImg, GA_ReadOnly ); poDatasetSunAzimuth = (GDALDataset *) GDALOpen(SunAzimuthImg, GA_ReadOnly ); poDatasetobserZenith = (GDALDataset *) GDALOpen(obserZenithImg, GA_ReadOnly ); poDatasetobserAzimuth = (GDALDataset *) GDALOpen(obserAzimuthImg, GA_ReadOnly ); if(( poDatasetBand1 == NULL )|| ( poDatasetBand2 == NULL )|| ( poDatasetBand3 == NULL )|| ( poDatasetBand4 == NULL )|| ( poDatasetSunZenith == NULL )|| ( poDatasetSunAzimuth == NULL )|| ( poDatasetobserZenith == NULL )|| ( poDatasetobserAzimuth == NULL )) { printf("文件打开失败"); return 2; } //6个坐标参数 double oriadfGeoTransform[6]; poDatasetBand2->GetGeoTransform(oriadfGeoTransform); //投影信息 char projection[SIZE]; memset(projection, '\0', SIZE*sizeof(char)); strcpy(projection, poDatasetBand2->GetProjectionRef()); //输入图像原始尺寸 nXSize=poDatasetBand2->GetRasterXSize(); nYSize=poDatasetBand2->GetRasterYSize(); //获得图片存储类型 GDALRasterBand* poRasterBand = poDatasetBand2->GetRasterBand(1); GDALDataType Datatype = poRasterBand->GetRasterDataType(); //创建要输出图片 poOutDataset = poDriver->Create(outputImg,nXSize,nYSize,1,GDT_Float32,papszMetadata); GDALRasterBand *pRasterBand1 = poDatasetBand1->GetRasterBand(1); GDALRasterBand *pRasterBand2 = poDatasetBand2->GetRasterBand(1); GDALRasterBand *pRasterBand3 = poDatasetBand3->GetRasterBand(1); GDALRasterBand *pRasterBand4 = poDatasetBand4->GetRasterBand(1); GDALRasterBand *pRasterSunZenith = poDatasetSunZenith->GetRasterBand(1); GDALRasterBand *pRasterSunAzimuth = poDatasetSunAzimuth->GetRasterBand(1); GDALRasterBand *pRasterobserZenith = poDatasetobserZenith->GetRasterBand(1); GDALRasterBand *pRasterobserAzimuth = poDatasetobserAzimuth->GetRasterBand(1); int offx = 0, offy = 0; pafsizey = CHUNK_HEIGHT; pafsizex = nXSize; float* band1 = (float*)CPLMalloc(sizeof(float)*pafsizex*pafsizey); float* band2 = (float*)CPLMalloc(sizeof(float)*pafsizex*pafsizey); float* band3 = (float*)CPLMalloc(sizeof(float)*pafsizex*pafsizey); float* band4 = (float*)CPLMalloc(sizeof(float)*pafsizex*pafsizey); float* SunZenith = (float*)CPLMalloc(sizeof(float)*pafsizex*pafsizey); float* SunAzimuth = (float*)CPLMalloc(sizeof(float)*pafsizex*pafsizey); float* obserZenith = (float*)CPLMalloc(sizeof(float)*pafsizex*pafsizey); float* obserAzimuth = (float*)CPLMalloc(sizeof(float)*pafsizex*pafsizey); float* aod = (float*)CPLMalloc(sizeof(float)*pafsizex*pafsizey); int numY = (nYSize-1)/CHUNK_HEIGHT + 1; GDALRasterBand *pRasterBandOut; pRasterBandOut = poOutDataset->GetRasterBand(1); LUT getlut; float* lutData = getlut.getLut(1,calInfoHJ,tmpdata); for (int i = 0; i < numY; i ++) { if (i == (numY-1)) { pafsizey = nYSize%CHUNK_HEIGHT; } offy = i *CHUNK_HEIGHT; pRasterBand1->RasterIO( GF_Read,offx,offy,pafsizex,pafsizey, band1,pafsizex,pafsizey, GDT_Float32,0,0); pRasterBand2->RasterIO( GF_Read,offx,offy,pafsizex,pafsizey, band2,pafsizex,pafsizey, GDT_Float32,0,0); pRasterBand3->RasterIO( GF_Read,offx,offy,pafsizex,pafsizey, band3,pafsizex,pafsizey, GDT_Float32,0,0); pRasterBand4->RasterIO( GF_Read,offx,offy,pafsizex,pafsizey, band4,pafsizex,pafsizey, GDT_Float32,0,0); pRasterSunZenith->RasterIO( GF_Read,offx,offy,pafsizex,pafsizey, SunZenith,pafsizex,pafsizey, GDT_Float32,0,0); pRasterSunAzimuth->RasterIO( GF_Read,offx,offy,pafsizex,pafsizey, SunAzimuth,pafsizex,pafsizey, GDT_Float32,0,0); pRasterobserZenith->RasterIO( GF_Read,offx,offy,pafsizex,pafsizey, obserZenith,pafsizex,pafsizey, GDT_Float32,0,0); pRasterobserAzimuth->RasterIO( GF_Read,offx,offy,pafsizex,pafsizey, obserAzimuth,pafsizex,pafsizey, GDT_Float32,0,0); for (int k = 0; k < pafsizex*pafsizey; k++) { if(obserAzimuth[k]>360.0) obserAzimuth[k]-=360.0; obserAzimuth[k]=fabs(obserAzimuth[k]-SunAzimuth[k]); if(obserAzimuth[k]>180.0) obserAzimuth[k]=fabs(obserAzimuth[k]-360.0f); obserZenith[k]=fabs(obserZenith[k]); if(obserZenith[k]>40.0) obserZenith[k]=40.0f; } // if (calInfoHJ.date[1] > 4 && calInfoHJ.date[1] < 11) // { // InvertAODSum(band1,band3,band4,aod,obserZenith,SunZenith,obserAzimuth,lutData); // }else // { //对夏季冬季都采用浓密植被和阴影进行气溶跤反演 InvertAODWin(band1,band2,band3,band4,aod,obserZenith,SunZenith,obserAzimuth,lutData,eAeroType); // } pRasterBandOut->RasterIO(GF_Write,offx,offy,pafsizex,pafsizey, aod,pafsizex,pafsizey,GDT_Float32,0,0); } CPLFree(band1); CPLFree(band2); CPLFree(band3); CPLFree(band4); CPLFree(SunZenith); CPLFree(SunAzimuth); CPLFree(obserZenith); CPLFree(obserAzimuth); CPLFree(aod); delete[] lutData; poOutDataset->SetGeoTransform(oriadfGeoTransform); poOutDataset->SetProjection(projection); if(poOutDataset != NULL) { GDALClose(poOutDataset); } if(poDatasetBand2 != NULL) { GDALClose(poDatasetBand2); } if(poDatasetBand3 != NULL) { GDALClose(poDatasetBand3); } if(poDatasetBand4 != NULL) { GDALClose(poDatasetBand4); } if(poDatasetBand1 != NULL) { GDALClose(poDatasetBand1); } if(poDatasetSunZenith != NULL) { GDALClose(poDatasetSunZenith); } if(poDatasetSunAzimuth != NULL) { GDALClose(poDatasetSunAzimuth); } if(poDatasetobserZenith != NULL) { GDALClose(poDatasetobserZenith); } if(poDatasetobserAzimuth != NULL) { GDALClose(poDatasetobserAzimuth); } return true; }