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); }
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); }
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; }
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; }
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 OGRErr CreateAndFillOutputDataset(OGRLayer* poSrcLayer, const char* pszDestDataSource, const char* pszFormat, const char* pszLayer, char** papszDSCO, char** papszLCO, int bQuiet) { GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); if( poDriver == NULL ) { fprintf( stderr, "%s driver not available\n", pszFormat ); return OGRERR_FAILURE; } if( !CSLTestBoolean( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) ) { fprintf( stderr, "%s driver does not support data source creation.\n", pszFormat ); return OGRERR_FAILURE; } GDALDataset* poODS = poDriver->Create( pszDestDataSource, 0, 0, 0, GDT_Unknown, papszDSCO ); if( poODS == NULL ) { fprintf( stderr, "%s driver failed to create %s\n", pszFormat, pszDestDataSource ); return OGRERR_FAILURE; } if(NULL == pszLayer) pszLayer = poSrcLayer->GetName(); int nError; GetLayerAndOverwriteIfNecessary(poODS, pszLayer, TRUE, &nError); if(nError == TRUE) { return OGRERR_FAILURE; } // create layer OGRLayer * poLayer = poODS->CopyLayer(poSrcLayer, pszLayer, papszLCO); if (NULL == poLayer) { fprintf(stderr, "\nFAILURE: Can not copy path to %s\n", pszDestDataSource); GDALClose(poODS); return OGRERR_FAILURE; } if (bQuiet == FALSE) { printf("\nPath successfully copied and added to the network at %s\n", pszDestDataSource); } GDALClose(poODS); return OGRERR_NONE; }
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; }
int InCoreInterp::outputFile(const std::string& outputName, int outputFormat, unsigned int outputType, double *adfGeoTransform, const char* wkt) { int i,j,k; FILE **arcFiles; char arcFileName[1024]; FILE **gridFiles; char gridFileName[1024]; const char *ext[6] = {".min", ".max", ".mean", ".idw", ".den", ".std"}; unsigned int type[6] = {OUTPUT_TYPE_MIN, OUTPUT_TYPE_MAX, OUTPUT_TYPE_MEAN, OUTPUT_TYPE_IDW, OUTPUT_TYPE_DEN, OUTPUT_TYPE_STD}; int numTypes = 6; // open ArcGIS files if(outputFormat == OUTPUT_FORMAT_ARC_ASCII || outputFormat == OUTPUT_FORMAT_ALL) { if((arcFiles = (FILE **)malloc(sizeof(FILE *) * numTypes)) == NULL) { cerr << "Arc File open error: " << endl; return -1; } for(i = 0; i < numTypes; i++) { if(outputType & type[i]) { strncpy(arcFileName, outputName.c_str(), sizeof(arcFileName)); strncat(arcFileName, ext[i], strlen(ext[i])); strncat(arcFileName, ".asc", strlen(".asc")); if((arcFiles[i] = fopen(arcFileName, "w+")) == NULL) { cerr << "File open error: " << arcFileName << endl; return -1; } } else { arcFiles[i] = NULL; } } } else { arcFiles = NULL; } // open Grid ASCII files if(outputFormat == OUTPUT_FORMAT_GRID_ASCII || outputFormat == OUTPUT_FORMAT_ALL) { if((gridFiles = (FILE **)malloc(sizeof(FILE *) * numTypes)) == NULL) { cerr << "File array allocation error" << endl; return -1; } for(i = 0; i < numTypes; i++) { if(outputType & type[i]) { strncpy(gridFileName, outputName.c_str(), sizeof(arcFileName)); strncat(gridFileName, ext[i], strlen(ext[i])); strncat(gridFileName, ".grid", strlen(".grid")); if((gridFiles[i] = fopen(gridFileName, "w+")) == NULL) { cerr << "File open error: " << gridFileName << endl; return -1; } } else { gridFiles[i] = NULL; } } } else { gridFiles = NULL; } // print ArcGIS headers if(arcFiles != NULL) { for(i = 0; i < numTypes; i++) { if(arcFiles[i] != NULL) { fprintf(arcFiles[i], "ncols %d\n", GRID_SIZE_X); fprintf(arcFiles[i], "nrows %d\n", GRID_SIZE_Y); fprintf(arcFiles[i], "xllcorner %f\n", min_x - 0.5*GRID_DIST_X); fprintf(arcFiles[i], "yllcorner %f\n", min_y - 0.5*GRID_DIST_Y); fprintf(arcFiles[i], "cellsize %f\n", GRID_DIST_X); fprintf(arcFiles[i], "NODATA_value -9999\n"); } } } // print Grid headers if(gridFiles != NULL) { for(i = 0; i < numTypes; i++) { if(gridFiles[i] != NULL) { fprintf(gridFiles[i], "north: %f\n", min_y - 0.5*GRID_DIST_Y + GRID_DIST_Y*GRID_SIZE_Y); fprintf(gridFiles[i], "south: %f\n", min_y - 0.5*GRID_DIST_Y); fprintf(gridFiles[i], "east: %f\n", min_x - 0.5*GRID_DIST_X + GRID_DIST_X*GRID_SIZE_X); fprintf(gridFiles[i], "west: %f\n", min_x - 0.5*GRID_DIST_X); fprintf(gridFiles[i], "rows: %d\n", GRID_SIZE_Y); fprintf(gridFiles[i], "cols: %d\n", GRID_SIZE_X); } } } // print data for(i = GRID_SIZE_Y - 1; i >= 0; i--) { for(j = 0; j < GRID_SIZE_X; j++) { if(arcFiles != NULL) { // Zmin if(arcFiles[0] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(arcFiles[0], "-9999 "); else fprintf(arcFiles[0], "%f ", interp[j][i].Zmin); } // Zmax if(arcFiles[1] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(arcFiles[1], "-9999 "); else fprintf(arcFiles[1], "%f ", interp[j][i].Zmax); } // Zmean if(arcFiles[2] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(arcFiles[2], "-9999 "); else fprintf(arcFiles[2], "%f ", interp[j][i].Zmean); } // Zidw if(arcFiles[3] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(arcFiles[3], "-9999 "); else fprintf(arcFiles[3], "%f ", interp[j][i].Zidw); } // count if(arcFiles[4] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(arcFiles[4], "-9999 "); else fprintf(arcFiles[4], "%d ", interp[j][i].count); } // count if(arcFiles[5] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(arcFiles[5], "-9999 "); else fprintf(arcFiles[5], "%f ", interp[j][i].Zstd); } } if(gridFiles != NULL) { // Zmin if(gridFiles[0] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(gridFiles[0], "-9999 "); else fprintf(gridFiles[0], "%f ", interp[j][i].Zmin); } // Zmax if(gridFiles[1] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(gridFiles[1], "-9999 "); else fprintf(gridFiles[1], "%f ", interp[j][i].Zmax); } // Zmean if(gridFiles[2] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(gridFiles[2], "-9999 "); else fprintf(gridFiles[2], "%f ", interp[j][i].Zmean); } // Zidw if(gridFiles[3] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(gridFiles[3], "-9999 "); else fprintf(gridFiles[3], "%f ", interp[j][i].Zidw); } // count if(gridFiles[4] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(gridFiles[4], "-9999 "); else fprintf(gridFiles[4], "%d ", interp[j][i].count); } // count if(gridFiles[5] != NULL) { if(interp[j][i].empty == 0 && interp[j][i].filled == 0) fprintf(gridFiles[5], "-9999 "); else fprintf(gridFiles[5], "%f ", interp[j][i].Zstd); } } } if(arcFiles != NULL) for(k = 0; k < numTypes; k++) { if(arcFiles[k] != NULL) fprintf(arcFiles[k], "\n"); } if(gridFiles != NULL) for(k = 0; k < numTypes; k++) { if(gridFiles[k] != NULL) fprintf(gridFiles[k], "\n"); } } #ifdef HAVE_GDAL GDALDataset **gdalFiles; char gdalFileName[1024]; // open GDAL GeoTIFF files if(outputFormat == OUTPUT_FORMAT_GDAL_GTIFF || outputFormat == OUTPUT_FORMAT_ALL) { GDALAllRegister(); if((gdalFiles = (GDALDataset **)malloc(sizeof(GDALDataset *) * numTypes)) == NULL) { cerr << "File array allocation error" << endl; return -1; } for(i = 0; i < numTypes; i++) { if(outputType & type[i]) { strncpy(gdalFileName, outputName.c_str(), sizeof(gdalFileName)); strncat(gdalFileName, ext[i], strlen(ext[i])); strncat(gdalFileName, ".tif", strlen(".tif")); char **papszMetadata; const char *pszFormat = "GTIFF"; GDALDriver* tpDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); if (tpDriver) { papszMetadata = tpDriver->GetMetadata(); if (CSLFetchBoolean(papszMetadata, GDAL_DCAP_CREATE, FALSE)) { char **papszOptions = NULL; gdalFiles[i] = tpDriver->Create(gdalFileName, GRID_SIZE_X, GRID_SIZE_Y, 1, GDT_Float32, papszOptions); if (gdalFiles[i] == NULL) { cerr << "File open error: " << gdalFileName << endl; return -1; } else { if (adfGeoTransform) { gdalFiles[i]->SetGeoTransform(adfGeoTransform); } else { double defaultTransform [6] = { min_x - 0.5*GRID_DIST_X, // top left x (double)GRID_DIST_X, // w-e pixel resolution 0.0, // no rotation/shear min_y - 0.5*GRID_DIST_Y + GRID_DIST_Y*GRID_SIZE_Y, // top left y 0.0, // no rotation/shear -(double)GRID_DIST_Y }; // n-x pixel resolution (negative value) gdalFiles[i]->SetGeoTransform(defaultTransform); } if (wkt) gdalFiles[i]->SetProjection(wkt); } } } } else { gdalFiles[i] = NULL; } } } else { gdalFiles = NULL; } if (gdalFiles != NULL) { for (i = 0; i < numTypes; i++) { if (gdalFiles[i] != NULL) { float *poRasterData = new float[GRID_SIZE_X*GRID_SIZE_Y]; for (int j = 0; j < GRID_SIZE_X*GRID_SIZE_Y; j++) { poRasterData[j] = 0; } for(j = GRID_SIZE_Y - 1; j >= 0; j--) { for(k = 0; k < GRID_SIZE_X; k++) { int index = (GRID_SIZE_Y - 1 - j) * GRID_SIZE_X + k; if(interp[k][j].empty == 0 && interp[k][j].filled == 0) { poRasterData[index] = -9999.f; } else { switch (i) { case 0: poRasterData[index] = interp[k][j].Zmin; break; case 1: poRasterData[index] = interp[k][j].Zmax; break; case 2: poRasterData[index] = interp[k][j].Zmean; break; case 3: poRasterData[index] = interp[k][j].Zidw; break; case 4: poRasterData[index] = interp[k][j].count; break; case 5: poRasterData[index] = interp[k][j].Zstd; break; } } } } GDALRasterBand *tBand = gdalFiles[i]->GetRasterBand(1); tBand->SetNoDataValue(-9999.f); if (GRID_SIZE_X > 0 && GRID_SIZE_Y > 0) tBand->RasterIO(GF_Write, 0, 0, GRID_SIZE_X, GRID_SIZE_Y, poRasterData, GRID_SIZE_X, GRID_SIZE_Y, GDT_Float32, 0, 0); GDALClose((GDALDatasetH) gdalFiles[i]); delete [] poRasterData; } } } #endif // HAVE_GDAL // close files if(gridFiles != NULL) { for(i = 0; i < numTypes; i++) { if(gridFiles[i] != NULL) fclose(gridFiles[i]); } } if(arcFiles != NULL) { for(i = 0; i < numTypes; i++) { if(arcFiles[i] != NULL) fclose(arcFiles[i]); } } return 0; }
int OutCoreInterp::outputFile(char *outputName, int outputFormat, unsigned int outputType, double *adfGeoTransform, const char* wkt) { int i, j, k, l, t; FILE **arcFiles; char arcFileName[1024]; FILE **gridFiles; char gridFileName[1024]; const char *ext[6] = {".min", ".max", ".mean", ".idw", ".den", ".std"}; unsigned int type[6] = {OUTPUT_TYPE_MIN, OUTPUT_TYPE_MAX, OUTPUT_TYPE_MEAN, OUTPUT_TYPE_IDW, OUTPUT_TYPE_DEN, OUTPUT_TYPE_STD}; int numTypes = 6; // open ArcGIS files if(outputFormat == OUTPUT_FORMAT_ARC_ASCII || outputFormat == OUTPUT_FORMAT_ALL) { if((arcFiles = (FILE **)malloc(sizeof(FILE *) * numTypes)) == NULL) { cerr << "Arc File open error: " << endl; return -1; } for(i = 0; i < numTypes; i++) { if(outputType & type[i]) { strncpy(arcFileName, outputName, sizeof(arcFileName)); strncat(arcFileName, ext[i], strlen(ext[i])); strncat(arcFileName, ".asc", strlen(".asc")); if((arcFiles[i] = fopen(arcFileName, "w+")) == NULL) { cerr << "File open error: " << arcFileName << endl; return -1; } } else { arcFiles[i] = NULL; } } } else { arcFiles = NULL; } // open Grid ASCII files if(outputFormat == OUTPUT_FORMAT_GRID_ASCII || outputFormat == OUTPUT_FORMAT_ALL) { if((gridFiles = (FILE **)malloc(sizeof(FILE *) * numTypes)) == NULL) { cerr << "File array allocation error" << endl; return -1; } for(i = 0; i < numTypes; i++) { if(outputType & type[i]) { strncpy(gridFileName, outputName, sizeof(arcFileName)); strncat(gridFileName, ext[i], strlen(ext[i])); strncat(gridFileName, ".grid", strlen(".grid")); if((gridFiles[i] = fopen(gridFileName, "w+")) == NULL) { cerr << "File open error: " << gridFileName << endl; return -1; } } else { gridFiles[i] = NULL; } } } else { gridFiles = NULL; } // print ArcGIS headers if(arcFiles != NULL) { for(i = 0; i < numTypes; i++) { if(arcFiles[i] != NULL) { fprintf(arcFiles[i], "ncols %d\n", GRID_SIZE_X); fprintf(arcFiles[i], "nrows %d\n", GRID_SIZE_Y); fprintf(arcFiles[i], "xllcorner %f\n", min_x); fprintf(arcFiles[i], "yllcorner %f\n", min_y); fprintf(arcFiles[i], "cellsize %f\n", GRID_DIST_X); fprintf(arcFiles[i], "NODATA_value -9999\n"); } } } // print Grid headers if(gridFiles != NULL) { for(i = 0; i < numTypes; i++) { if(gridFiles[i] != NULL) { fprintf(gridFiles[i], "north: %f\n", max_y); fprintf(gridFiles[i], "south: %f\n", min_y); fprintf(gridFiles[i], "east: %f\n", max_x); fprintf(gridFiles[i], "west: %f\n", min_x); fprintf(gridFiles[i], "rows: %d\n", GRID_SIZE_Y); fprintf(gridFiles[i], "cols: %d\n", GRID_SIZE_X); } } } for(i = numFiles -1; i >= 0; i--) { GridFile *gf = gridMap[i]->getGridFile(); gf->map(); int start = gridMap[i]->getLowerBound() - gridMap[i]->getOverlapLowerBound(); int end = gridMap[i]->getUpperBound() - gridMap[i]->getOverlapLowerBound() + 1; //int start = (gridMap[i]->getLowerBound() - gridMap[i]->getOverlapLowerBound()) * GRID_SIZE_X; //int end = (gridMap[i]->getUpperBound() - gridMap[i]->getOverlapLowerBound() + 1) * GRID_SIZE_X; cerr << "Merging " << i << ": from " << (start) << " to " << (end) << endl; cerr << " " << i << ": from " << (start/GRID_SIZE_X) << " to " << (end/GRID_SIZE_X) << endl; for(j = end - 1; j >= start; j--) { for(k = 0; k < GRID_SIZE_X; k++) { int index = j * GRID_SIZE_X + k; if(arcFiles != NULL) { // Zmin if(arcFiles[0] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) //if(gf->interp[k][j].Zmin == 0) fprintf(arcFiles[0], "-9999 "); else //fprintf(arcFiles[0], "%f ", gf->interp[j][i].Zmin); fprintf(arcFiles[0], "%f ", gf->interp[index].Zmin); } // Zmax if(arcFiles[1] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(arcFiles[1], "-9999 "); else fprintf(arcFiles[1], "%f ", gf->interp[index].Zmax); } // Zmean if(arcFiles[2] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(arcFiles[2], "-9999 "); else fprintf(arcFiles[2], "%f ", gf->interp[index].Zmean); } // Zidw if(arcFiles[3] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(arcFiles[3], "-9999 "); else fprintf(arcFiles[3], "%f ", gf->interp[index].Zidw); } // count if(arcFiles[4] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(arcFiles[4], "-9999 "); else fprintf(arcFiles[4], "%d ", gf->interp[index].count); } // Zstd if(arcFiles[5] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(arcFiles[5], "-9999 "); else fprintf(arcFiles[5], "%f ", gf->interp[index].Zstd); } } if(gridFiles != NULL) { // Zmin if(gridFiles[0] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(gridFiles[0], "-9999 "); else fprintf(gridFiles[0], "%f ", gf->interp[index].Zmin); } // Zmax if(gridFiles[1] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(gridFiles[1], "-9999 "); else fprintf(gridFiles[1], "%f ", gf->interp[index].Zmax); } // Zmean if(gridFiles[2] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(gridFiles[2], "-9999 "); else fprintf(gridFiles[2], "%f ", gf->interp[index].Zmean); } // Zidw if(gridFiles[3] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(gridFiles[3], "-9999 "); else fprintf(gridFiles[3], "%f ", gf->interp[index].Zidw); } // count if(gridFiles[4] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(gridFiles[4], "-9999 "); else fprintf(gridFiles[4], "%d ", gf->interp[index].count); } // Zstd if(gridFiles[5] != NULL) { if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) fprintf(gridFiles[5], "-9999 "); else fprintf(gridFiles[5], "%f ", gf->interp[index].Zstd); } } } if(arcFiles != NULL) for(l = 0; l < numTypes; l++) { if(arcFiles[l] != NULL) fprintf(arcFiles[l], "\n"); } if(gridFiles != NULL) for(l = 0; l < numTypes; l++) { if(gridFiles[l] != NULL) fprintf(gridFiles[l], "\n"); } } gf->unmap(); } #ifdef HAVE_GDAL GDALDataset **gdalFiles; char gdalFileName[1024]; // open GDAL GeoTIFF files if(outputFormat == OUTPUT_FORMAT_GDAL_GTIFF || outputFormat == OUTPUT_FORMAT_ALL) { GDALAllRegister(); if((gdalFiles = (GDALDataset **)malloc(sizeof(GDALDataset *) * numTypes)) == NULL) { cerr << "File array allocation error" << endl; return -1; } for(i = 0; i < numTypes; i++) { if(outputType & type[i]) { strncpy(gdalFileName, outputName, sizeof(gdalFileName)); strncat(gdalFileName, ext[i], strlen(ext[i])); strncat(gdalFileName, ".tif", strlen(".tif")); char **papszMetadata; const char *pszFormat = "GTIFF"; GDALDriver* tpDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); if (tpDriver) { papszMetadata = tpDriver->GetMetadata(); if (CSLFetchBoolean(papszMetadata, GDAL_DCAP_CREATE, FALSE)) { char **papszOptions = NULL; gdalFiles[i] = tpDriver->Create(gdalFileName, GRID_SIZE_X, GRID_SIZE_Y, 1, GDT_Float32, papszOptions); if (gdalFiles[i] == NULL) { cerr << "File open error: " << gdalFileName << endl; return -1; } else { if (adfGeoTransform) gdalFiles[i]->SetGeoTransform(adfGeoTransform); if (wkt) gdalFiles[i]->SetProjection(wkt); } } } } else { gdalFiles[i] = NULL; } } } else { gdalFiles = NULL; } if(gdalFiles != NULL) { for(t = 0; t < numTypes; t++) { if(gdalFiles[t] != NULL) { for(i = numFiles -1; i >= 0; i--) { GridFile *gf = gridMap[i]->getGridFile(); gf->map(); int start = gridMap[i]->getLowerBound() - gridMap[i]->getOverlapLowerBound(); int end = gridMap[i]->getUpperBound() - gridMap[i]->getOverlapLowerBound() + 1; cerr << "Merging " << i << ": from " << (start) << " to " << (end) << endl; cerr << " " << i << ": from " << (start/GRID_SIZE_X) << " to " << (end/GRID_SIZE_X) << endl; float *poRasterData = new float[GRID_SIZE_X*GRID_SIZE_Y]; for (int j = 0; j < GRID_SIZE_X*GRID_SIZE_Y; j++) { poRasterData[j] = 0; } for(j = end - 1; j >= start; j--) { for(k = 0; k < GRID_SIZE_X; k++) { int index = j * GRID_SIZE_X + k; if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) { poRasterData[index] = -9999.f; } else { switch (t) { case 0: poRasterData[index] = gf->interp[index].Zmin; break; case 1: poRasterData[index] = gf->interp[index].Zmax; break; case 2: poRasterData[index] = gf->interp[index].Zmean; break; case 3: poRasterData[index] = gf->interp[index].Zidw; break; case 4: poRasterData[index] = gf->interp[index].count; break; case 5: poRasterData[index] = gf->interp[index].Zstd; break; } } } } GDALRasterBand *tBand = gdalFiles[t]->GetRasterBand(1); tBand->SetNoDataValue(-9999.f); if (GRID_SIZE_X > 0 && GRID_SIZE_Y > 0) tBand->RasterIO(GF_Write, 0, 0, GRID_SIZE_X, GRID_SIZE_Y, poRasterData, GRID_SIZE_X, GRID_SIZE_Y, GDT_Float32, 0, 0); GDALClose((GDALDatasetH) gdalFiles[t]); delete [] poRasterData; } } } } #endif // HAVE_GDAL // close files if(gridFiles != NULL) { for(i = 0; i < numTypes; i++) { if(gridFiles[i] != NULL) fclose(gridFiles[i]); } } if(arcFiles != NULL) { for(i = 0; i < numTypes; i++) { if(arcFiles[i] != NULL) fclose(arcFiles[i]); } } return 0; }
int main( int nArgc, char ** papszArgv ) { int nFirstSourceDataset = -1, bLayersWildcarded = TRUE, iArg; const char *pszFormat = "ESRI Shapefile"; const char *pszTileIndexField = "LOCATION"; const char *pszOutputName = NULL; int write_absolute_path = FALSE; int skip_different_projection = FALSE; char* current_path = NULL; int accept_different_schemas = FALSE; int bFirstWarningForNonMatchingAttributes = TRUE; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(papszArgv[0])) exit(1); /* -------------------------------------------------------------------- */ /* Register format(s). */ /* -------------------------------------------------------------------- */ OGRRegisterAll(); /* -------------------------------------------------------------------- */ /* Processing command line arguments. */ /* -------------------------------------------------------------------- */ for( iArg = 1; iArg < nArgc; iArg++ ) { if( EQUAL(papszArgv[iArg], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against GDAL %s\n", papszArgv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); return 0; } else if( EQUAL(papszArgv[iArg],"-f") && iArg < nArgc-1 ) { pszFormat = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg],"-write_absolute_path")) { write_absolute_path = TRUE; } else if( EQUAL(papszArgv[iArg],"-skip_different_projection")) { skip_different_projection = TRUE; } else if( EQUAL(papszArgv[iArg],"-accept_different_schemas")) { accept_different_schemas = TRUE; } else if( EQUAL(papszArgv[iArg],"-tileindex") && iArg < nArgc-1 ) { pszTileIndexField = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg],"-lnum") || EQUAL(papszArgv[iArg],"-lname") ) { iArg++; bLayersWildcarded = FALSE; } else if( papszArgv[iArg][0] == '-' ) Usage(); else if( pszOutputName == NULL ) pszOutputName = papszArgv[iArg]; else if( nFirstSourceDataset == -1 ) nFirstSourceDataset = iArg; } if( pszOutputName == NULL || nFirstSourceDataset == -1 ) Usage(); /* -------------------------------------------------------------------- */ /* Try to open as an existing dataset for update access. */ /* -------------------------------------------------------------------- */ GDALDataset *poDstDS; OGRLayer *poDstLayer = NULL; poDstDS = (GDALDataset*) OGROpen( pszOutputName, TRUE, NULL ); /* -------------------------------------------------------------------- */ /* If that failed, find the driver so we can create the tile index.*/ /* -------------------------------------------------------------------- */ if( poDstDS == NULL ) { OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); GDALDriver *poDriver = NULL; int iDriver; for( iDriver = 0; iDriver < poR->GetDriverCount() && poDriver == NULL; iDriver++ ) { if( EQUAL(poR->GetDriver(iDriver)->GetDescription(),pszFormat) ) { poDriver = poR->GetDriver(iDriver); } } if( poDriver == NULL ) { fprintf( stderr, "Unable to find driver `%s'.\n", pszFormat ); fprintf( stderr, "The following drivers are available:\n" ); for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { fprintf( stderr, " -> `%s'\n", poR->GetDriver(iDriver)->GetDescription() ); } exit( 1 ); } if( !CSLTestBoolean( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) ) { fprintf( stderr, "%s driver does not support data source creation.\n", pszFormat ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Now create it. */ /* -------------------------------------------------------------------- */ poDstDS = poDriver->Create( pszOutputName, 0, 0, 0, GDT_Unknown, NULL ); if( poDstDS == NULL ) { fprintf( stderr, "%s driver failed to create %s\n", pszFormat, pszOutputName ); exit( 1 ); } if( poDstDS->GetLayerCount() == 0 ) { OGRFieldDefn oLocation( pszTileIndexField, OFTString ); oLocation.SetWidth( 200 ); if( nFirstSourceDataset < nArgc && papszArgv[nFirstSourceDataset][0] == '-' ) { nFirstSourceDataset++; } OGRSpatialReference* poSrcSpatialRef = NULL; /* Fetches the SRS of the first layer and use it when creating the tileindex layer */ if (nFirstSourceDataset < nArgc) { GDALDataset* poDS = (GDALDataset*) OGROpen(papszArgv[nFirstSourceDataset], FALSE, NULL); if (poDS) { int iLayer; for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { int bRequested = bLayersWildcarded; OGRLayer *poLayer = poDS->GetLayer(iLayer); for( iArg = 1; iArg < nArgc && !bRequested; iArg++ ) { if( EQUAL(papszArgv[iArg],"-lnum") && atoi(papszArgv[iArg+1]) == iLayer ) bRequested = TRUE; else if( EQUAL(papszArgv[iArg],"-lname") && EQUAL(papszArgv[iArg+1], poLayer->GetLayerDefn()->GetName()) ) bRequested = TRUE; } if( !bRequested ) continue; if ( poLayer->GetSpatialRef() ) poSrcSpatialRef = poLayer->GetSpatialRef()->Clone(); break; } } GDALClose( (GDALDatasetH)poDS ); } poDstLayer = poDstDS->CreateLayer( "tileindex", poSrcSpatialRef ); poDstLayer->CreateField( &oLocation, OFTString ); OGRSpatialReference::DestroySpatialReference( poSrcSpatialRef ); } } /* -------------------------------------------------------------------- */ /* Identify target layer and field. */ /* -------------------------------------------------------------------- */ int iTileIndexField; poDstLayer = poDstDS->GetLayer(0); if( poDstLayer == NULL ) { fprintf( stderr, "Can't find any layer in output tileindex!\n" ); exit( 1 ); } iTileIndexField = poDstLayer->GetLayerDefn()->GetFieldIndex( pszTileIndexField ); if( iTileIndexField == -1 ) { fprintf( stderr, "Can't find %s field in tile index dataset.\n", pszTileIndexField ); exit( 1 ); } OGRFeatureDefn* poFeatureDefn = NULL; /* Load in memory existing file names in SHP */ int nExistingLayers = 0; char** existingLayersTab = NULL; OGRSpatialReference* alreadyExistingSpatialRef = NULL; int alreadyExistingSpatialRefValid = FALSE; nExistingLayers = (int)poDstLayer->GetFeatureCount(); if (nExistingLayers) { int i; existingLayersTab = (char**)CPLMalloc(nExistingLayers * sizeof(char*)); for(i=0;i<nExistingLayers;i++) { OGRFeature* feature = poDstLayer->GetNextFeature(); existingLayersTab[i] = CPLStrdup(feature->GetFieldAsString( iTileIndexField)); if (i == 0) { GDALDataset *poDS; char* filename = CPLStrdup(existingLayersTab[i]); int j; for(j=strlen(filename)-1;j>=0;j--) { if (filename[j] == ',') break; } if (j >= 0) { int iLayer = atoi(filename + j + 1); filename[j] = 0; poDS = (GDALDataset*) OGROpen(filename, FALSE, NULL); if (poDS) { OGRLayer *poLayer = poDS->GetLayer(iLayer); if (poLayer) { alreadyExistingSpatialRefValid = TRUE; alreadyExistingSpatialRef = (poLayer->GetSpatialRef()) ? poLayer->GetSpatialRef()->Clone() : NULL; if (poFeatureDefn == NULL) poFeatureDefn = poLayer->GetLayerDefn()->Clone(); } GDALClose( (GDALDatasetH)poDS ); } } } } } if (write_absolute_path) { current_path = CPLGetCurrentDir(); if (current_path == NULL) { fprintf( stderr, "This system does not support the CPLGetCurrentDir call. " "The option -write_absolute_path will have no effect\n"); write_absolute_path = FALSE; } } /* ==================================================================== */ /* Process each input datasource in turn. */ /* ==================================================================== */ for(; nFirstSourceDataset < nArgc; nFirstSourceDataset++ ) { int i; GDALDataset *poDS; if( papszArgv[nFirstSourceDataset][0] == '-' ) { nFirstSourceDataset++; continue; } char* fileNameToWrite; VSIStatBuf sStatBuf; if (write_absolute_path && CPLIsFilenameRelative( papszArgv[nFirstSourceDataset] ) && VSIStat( papszArgv[nFirstSourceDataset], &sStatBuf ) == 0) { fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path,papszArgv[nFirstSourceDataset])); } else { fileNameToWrite = CPLStrdup(papszArgv[nFirstSourceDataset]); } poDS = (GDALDataset*) OGROpen( papszArgv[nFirstSourceDataset], FALSE, NULL ); if( poDS == NULL ) { fprintf( stderr, "Failed to open dataset %s, skipping.\n", papszArgv[nFirstSourceDataset] ); CPLFree(fileNameToWrite); continue; } /* -------------------------------------------------------------------- */ /* Check all layers, and see if they match requests. */ /* -------------------------------------------------------------------- */ int iLayer; for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { int bRequested = bLayersWildcarded; OGRLayer *poLayer = poDS->GetLayer(iLayer); for( iArg = 1; iArg < nArgc && !bRequested; iArg++ ) { if( EQUAL(papszArgv[iArg],"-lnum") && atoi(papszArgv[iArg+1]) == iLayer ) bRequested = TRUE; else if( EQUAL(papszArgv[iArg],"-lname") && EQUAL(papszArgv[iArg+1], poLayer->GetLayerDefn()->GetName()) ) bRequested = TRUE; } if( !bRequested ) continue; /* Checks that the layer is not already in tileindex */ for(i=0;i<nExistingLayers;i++) { char szLocation[5000]; sprintf( szLocation, "%s,%d", fileNameToWrite, iLayer ); if (EQUAL(szLocation, existingLayersTab[i])) { fprintf(stderr, "Layer %d of %s is already in tileindex. Skipping it.\n", iLayer, papszArgv[nFirstSourceDataset]); break; } } if (i != nExistingLayers) { continue; } OGRSpatialReference* spatialRef = poLayer->GetSpatialRef(); if (alreadyExistingSpatialRefValid) { if ((spatialRef != NULL && alreadyExistingSpatialRef != NULL && spatialRef->IsSame(alreadyExistingSpatialRef) == FALSE) || ((spatialRef != NULL) != (alreadyExistingSpatialRef != NULL))) { fprintf(stderr, "Warning : layer %d of %s is not using the same projection system as " "other files in the tileindex. This may cause problems when " "using it in MapServer for example.%s\n", iLayer, papszArgv[nFirstSourceDataset], (skip_different_projection) ? " Skipping it" : ""); if (skip_different_projection) { continue; } } } else { alreadyExistingSpatialRefValid = TRUE; alreadyExistingSpatialRef = (spatialRef) ? spatialRef->Clone() : NULL; } /* -------------------------------------------------------------------- */ /* Check if all layers in dataset have the same attributes schema. */ /* -------------------------------------------------------------------- */ if( poFeatureDefn == NULL ) { poFeatureDefn = poLayer->GetLayerDefn()->Clone(); } else if ( !accept_different_schemas ) { OGRFeatureDefn* poFeatureDefnCur = poLayer->GetLayerDefn(); assert(NULL != poFeatureDefnCur); int fieldCount = poFeatureDefnCur->GetFieldCount(); if( fieldCount != poFeatureDefn->GetFieldCount()) { fprintf( stderr, "Number of attributes of layer %s of %s does not match ... skipping it.\n", poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]); if (bFirstWarningForNonMatchingAttributes) { fprintf( stderr, "Note : you can override this behaviour with -accept_different_schemas option\n" "but this may result in a tileindex incompatible with MapServer\n"); bFirstWarningForNonMatchingAttributes = FALSE; } continue; } int bSkip = FALSE; for( int fn = 0; fn < poFeatureDefnCur->GetFieldCount(); fn++ ) { OGRFieldDefn* poField = poFeatureDefn->GetFieldDefn(fn); OGRFieldDefn* poFieldCur = poFeatureDefnCur->GetFieldDefn(fn); /* XXX - Should those pointers be checked against NULL? */ assert(NULL != poField); assert(NULL != poFieldCur); if( poField->GetType() != poFieldCur->GetType() || poField->GetWidth() != poFieldCur->GetWidth() || poField->GetPrecision() != poFieldCur->GetPrecision() || !EQUAL( poField->GetNameRef(), poFieldCur->GetNameRef() ) ) { fprintf( stderr, "Schema of attributes of layer %s of %s does not match ... skipping it.\n", poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]); if (bFirstWarningForNonMatchingAttributes) { fprintf( stderr, "Note : you can override this behaviour with -accept_different_schemas option\n" "but this may result in a tileindex incompatible with MapServer\n"); bFirstWarningForNonMatchingAttributes = FALSE; } bSkip = TRUE; break; } } if (bSkip) continue; } /* -------------------------------------------------------------------- */ /* Get layer extents, and create a corresponding polygon */ /* geometry. */ /* -------------------------------------------------------------------- */ OGREnvelope sExtents; OGRPolygon oRegion; OGRLinearRing oRing; if( poLayer->GetExtent( &sExtents, TRUE ) != OGRERR_NONE ) { fprintf( stderr, "GetExtent() failed on layer %s of %s, skipping.\n", poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset] ); continue; } oRing.addPoint( sExtents.MinX, sExtents.MinY ); oRing.addPoint( sExtents.MinX, sExtents.MaxY ); oRing.addPoint( sExtents.MaxX, sExtents.MaxY ); oRing.addPoint( sExtents.MaxX, sExtents.MinY ); oRing.addPoint( sExtents.MinX, sExtents.MinY ); oRegion.addRing( &oRing ); /* -------------------------------------------------------------------- */ /* Add layer to tileindex. */ /* -------------------------------------------------------------------- */ char szLocation[5000]; OGRFeature oTileFeat( poDstLayer->GetLayerDefn() ); sprintf( szLocation, "%s,%d", fileNameToWrite, iLayer ); oTileFeat.SetGeometry( &oRegion ); oTileFeat.SetField( iTileIndexField, szLocation ); if( poDstLayer->CreateFeature( &oTileFeat ) != OGRERR_NONE ) { fprintf( stderr, "Failed to create feature on tile index ... terminating." ); GDALClose( (GDALDatasetH) poDstDS ); exit( 1 ); } } /* -------------------------------------------------------------------- */ /* Cleanup this data source. */ /* -------------------------------------------------------------------- */ CPLFree(fileNameToWrite); GDALClose( (GDALDatasetH)poDS ); } /* -------------------------------------------------------------------- */ /* Close tile index and clear buffers. */ /* -------------------------------------------------------------------- */ GDALClose( (GDALDatasetH) poDstDS ); OGRFeatureDefn::DestroyFeatureDefn( poFeatureDefn ); if (alreadyExistingSpatialRef != NULL) OGRSpatialReference::DestroySpatialReference( alreadyExistingSpatialRef ); CPLFree(current_path); if (nExistingLayers) { int i; for(i=0;i<nExistingLayers;i++) { CPLFree(existingLayersTab[i]); } CPLFree(existingLayersTab); } OGRCleanupAll(); return 0; }
//--------------------------------------------------------- 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 ); }
int Delaunay(maps*& conf,maps*& inputs,maps*& outputs){ #ifdef DEBUG fprintf(stderr,"\nService internal print\nStarting\n"); #endif maps* cursor=inputs; OGRGeometryH geometry,res; int bufferDistance; map* tmpm=NULL; OGRRegisterAll(); std::vector<Point> points; if(int res=parseInput(conf,inputs,&points,"/vsimem/tmp")!=SERVICE_SUCCEEDED) return res; DelaunayT T; T.insert(points.begin(), points.end()); /* -------------------------------------------------------------------- */ /* Try opening the output datasource as an existing, writable */ /* -------------------------------------------------------------------- */ #if GDAL_VERSION_MAJOR >= 2 GDALDataset *poODS; GDALDriverManager* poR=GetGDALDriverManager(); GDALDriver *poDriver = NULL; #else OGRDataSource *poODS; OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); OGRSFDriver *poDriver = NULL; #endif int iDriver; map *tmpMap=getMapFromMaps(outputs,"Result","mimeType"); const char *oDriver; oDriver="GeoJSON"; if(tmpMap!=NULL){ if(strcmp(tmpMap->value,"text/xml")==0){ oDriver="GML"; } } for( iDriver = 0; iDriver < poR->GetDriverCount() && poDriver == NULL; iDriver++ ) { #ifdef DEBUG #if GDAL_VERSION_MAJOR >= 2 fprintf(stderr,"D:%s\n",poR->GetDriver(iDriver)->GetDescription()); #else fprintf(stderr,"D:%s\n",poR->GetDriver(iDriver)->GetName()); #endif #endif if( EQUAL( #if GDAL_VERSION_MAJOR >= 2 poR->GetDriver(iDriver)->GetDescription() #else poR->GetDriver(iDriver)->GetName() #endif , oDriver) ) { poDriver = poR->GetDriver(iDriver); } } if( poDriver == NULL ) { char emessage[8192]; sprintf( emessage, "Unable to find driver `%s'.\n", oDriver ); sprintf( emessage, "%sThe following drivers are available:\n",emessage ); for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { #if GDAL_VERSION_MAJOR >= 2 sprintf( emessage, "%s -> `%s'\n", emessage, poR->GetDriver(iDriver)->GetDescription() ); #else sprintf( emessage, "%s -> `%s'\n", emessage, poR->GetDriver(iDriver)->GetName() ); #endif } setMapInMaps(conf,"lenv","message",emessage); return SERVICE_FAILED; } #if GDAL_VERSION_MAJOR >=2 if( !CPLTestBool( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) ) #else if( !poDriver->TestCapability( ODrCCreateDataSource ) ) #endif { char emessage[1024]; sprintf( emessage, "%s driver does not support data source creation.\n", "json" ); setMapInMaps(conf,"lenv","message",emessage); return SERVICE_FAILED; } /* -------------------------------------------------------------------- */ /* Create the output data source. */ /* -------------------------------------------------------------------- */ char *pszDestDataSource=(char*)malloc(100); char **papszDSCO=NULL; sprintf(pszDestDataSource,"/vsimem/result_%d",getpid()); #if GDAL_VERSION_MAJOR >=2 poODS = poDriver->Create( pszDestDataSource, 0, 0, 0, GDT_Unknown, papszDSCO ); #else poODS = poDriver->CreateDataSource( pszDestDataSource, papszDSCO ); #endif if( poODS == NULL ){ char emessage[1024]; sprintf( emessage, "%s driver failed to create %s\n", "json", pszDestDataSource ); setMapInMaps(conf,"lenv","message",emessage); return SERVICE_FAILED; } /* -------------------------------------------------------------------- */ /* Create the layer. */ /* -------------------------------------------------------------------- */ if( !poODS->TestCapability( ODsCCreateLayer ) ) { char emessage[1024]; sprintf( emessage, "Layer %s not found, and CreateLayer not supported by driver.", "Result" ); setMapInMaps(conf,"lenv","message",emessage); return SERVICE_FAILED; } CPLErrorReset(); OGRLayer *poDstLayer = poODS->CreateLayer( "Result", NULL,wkbPolygon,NULL); if( poDstLayer == NULL ){ setMapInMaps(conf,"lenv","message","Layer creation failed.\n"); return SERVICE_FAILED; } for(DelaunayT::Finite_faces_iterator fit = T.finite_faces_begin(); fit != T.finite_faces_end(); ++fit) { DelaunayT::Face_handle face = fit; OGRFeatureH hFeature = OGR_F_Create( OGR_L_GetLayerDefn( poDstLayer ) ); OGRGeometryH hCollection = OGR_G_CreateGeometry( wkbGeometryCollection ); OGRGeometryH currLine=OGR_G_CreateGeometry(wkbLinearRing); OGRGeometryH currPoly=OGR_G_CreateGeometry(wkbPolygon); OGR_G_AddPoint_2D(currLine,T.triangle(face)[0].x(),T.triangle(face)[0].y()); OGR_G_AddPoint_2D(currLine,T.triangle(face)[1].x(),T.triangle(face)[1].y()); OGR_G_AddPoint_2D(currLine,T.triangle(face)[2].x(),T.triangle(face)[2].y()); OGR_G_AddPoint_2D(currLine,T.triangle(face)[0].x(),T.triangle(face)[0].y()); OGR_G_AddGeometryDirectly( currPoly, currLine ); OGR_G_AddGeometryDirectly( hCollection, currPoly ); OGR_F_SetGeometry( hFeature, hCollection ); OGR_G_DestroyGeometry(hCollection); if( OGR_L_CreateFeature( poDstLayer, hFeature ) != OGRERR_NONE ){ setMapInMaps(conf,"lenv","message","Failed to create feature in file.\n"); return SERVICE_FAILED; } OGR_F_Destroy( hFeature ); } OGR_DS_Destroy( poODS ); #ifdef DEBUG std::cerr << "The Voronoi diagram has " << ns << " finite edges " << " and " << nr << " rays" << std::endl; #endif char *res1=readVSIFile(conf,pszDestDataSource); if(res1==NULL) return SERVICE_FAILED; setMapInMaps(outputs,"Result","value",res1); free(res1); if(strcmp(oDriver,"GML")==0) setMapInMaps(outputs,"Result","mimeType","text/xml"); else setMapInMaps(outputs,"Result","mimeType","application/json"); setMapInMaps(outputs,"Result","encoding","UTF-8"); OGRCleanupAll(); return SERVICE_SUCCEEDED; }
MAIN_START(argc, argv) { /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(argv[0])) exit(1); EarlySetConfigOptions(argc, argv); /* -------------------------------------------------------------------- */ /* Generic arg processing. */ /* -------------------------------------------------------------------- */ GDALAllRegister(); argc = GDALGeneralCmdLineProcessor(argc, &argv, 0); if( argc < 1 ) exit( -argc ); for( int i = 0; i < argc; i++ ) { if( EQUAL(argv[i], "--utility_version") ) { printf("%s was compiled against GDAL %s and " "is running against GDAL %s\n", argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); CSLDestroy(argv); return 0; } else if( EQUAL(argv[i], "--help") ) { Usage(); } } GDALRasterizeOptionsForBinary* psOptionsForBinary = GDALRasterizeOptionsForBinaryNew(); // coverity[tainted_data] GDALRasterizeOptions *psOptions = GDALRasterizeOptionsNew(argv + 1, psOptionsForBinary); CSLDestroy(argv); if( psOptions == nullptr ) { Usage(); } if( !(psOptionsForBinary->bQuiet) ) { GDALRasterizeOptionsSetProgress(psOptions, GDALTermProgress, nullptr); } if( psOptionsForBinary->pszSource == nullptr ) Usage("No input file specified."); if( psOptionsForBinary->pszDest == nullptr ) Usage("No output file specified."); /* -------------------------------------------------------------------- */ /* Open input file. */ /* -------------------------------------------------------------------- */ GDALDatasetH hInDS = GDALOpenEx( psOptionsForBinary->pszSource, GDAL_OF_VECTOR | GDAL_OF_VERBOSE_ERROR, nullptr, nullptr, nullptr); if( hInDS == nullptr ) exit(1); /* -------------------------------------------------------------------- */ /* Open output file if it exists. */ /* -------------------------------------------------------------------- */ GDALDatasetH hDstDS = nullptr; if( !(psOptionsForBinary->bCreateOutput) ) { CPLPushErrorHandler(CPLQuietErrorHandler); hDstDS = GDALOpenEx( psOptionsForBinary->pszDest, GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR | GDAL_OF_UPDATE, nullptr, nullptr, nullptr ); CPLPopErrorHandler(); } if( psOptionsForBinary->pszFormat != nullptr && (psOptionsForBinary->bCreateOutput || hDstDS == nullptr) ) { GDALDriverManager *poDM = GetGDALDriverManager(); GDALDriver *poDriver = poDM->GetDriverByName(psOptionsForBinary->pszFormat); char** papszDriverMD = (poDriver) ? poDriver->GetMetadata(): nullptr; if( poDriver == nullptr || !CPLTestBool(CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_RASTER, "FALSE")) || !CPLTestBool(CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_CREATE, "FALSE")) ) { fprintf(stderr, "Output driver `%s' not recognised or does not support " "direct output file creation.\n", psOptionsForBinary->pszFormat); fprintf(stderr, "The following format drivers are configured and " "support direct output:\n" ); for( int iDriver = 0; iDriver < poDM->GetDriverCount(); iDriver++ ) { GDALDriver* poIter = poDM->GetDriver(iDriver); papszDriverMD = poIter->GetMetadata(); if( CPLTestBool( CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_RASTER, "FALSE")) && CPLTestBool( CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_CREATE, "FALSE")) ) { fprintf(stderr, " -> `%s'\n", poIter->GetDescription()); } } exit(1); } } int bUsageError = FALSE; GDALDatasetH hRetDS = GDALRasterize(psOptionsForBinary->pszDest, hDstDS, hInDS, psOptions, &bUsageError); if(bUsageError == TRUE) Usage(); const int nRetCode = hRetDS ? 0 : 1; GDALClose(hInDS); GDALClose(hRetDS); GDALRasterizeOptionsFree(psOptions); GDALRasterizeOptionsForBinaryFree(psOptionsForBinary); GDALDestroyDriverManager(); return nRetCode; }
void ccRasterizeTool::generateRaster() const { #ifdef CC_GDAL_SUPPORT if (!m_cloud || !m_grid.isValid()) return; GDALAllRegister(); ccLog::PrintDebug("(GDAL drivers: %i)", GetGDALDriverManager()->GetDriverCount()); const char *pszFormat = "GTiff"; GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); if (!poDriver) { ccLog::Error("[GDAL] Driver %s is not supported", pszFormat); return; } char** papszMetadata = poDriver->GetMetadata(); if( !CSLFetchBoolean( papszMetadata, GDAL_DCAP_CREATE, FALSE ) ) { ccLog::Error("[GDAL] Driver %s doesn't support Create() method", pszFormat); return; } //which (and how many) bands shall we create? bool heightBand = true; //height by default bool densityBand = false; bool allSFBands = false; int sfBandIndex = -1; //scalar field index int totalBands = 0; bool interpolateSF = (getTypeOfSFInterpolation() != INVALID_PROJECTION_TYPE); ccPointCloud* pc = m_cloud->isA(CC_TYPES::POINT_CLOUD) ? static_cast<ccPointCloud*>(m_cloud) : 0; bool hasSF = interpolateSF && pc && !m_grid.scalarFields.empty(); RasterExportOptionsDlg reoDlg; reoDlg.dimensionsLabel->setText(QString("%1 x %2").arg(m_grid.width).arg(m_grid.height)); reoDlg.exportHeightsCheckBox->setChecked(heightBand); reoDlg.exportDensityCheckBox->setChecked(densityBand); reoDlg.exportDisplayedSFCheckBox->setEnabled(hasSF); reoDlg.exportAllSFCheckBox->setEnabled(hasSF); reoDlg.exportAllSFCheckBox->setChecked(allSFBands); if (!reoDlg.exec()) return; //we ask the output filename AFTER displaying the export parameters ;) QString outputFilename; { QSettings settings; settings.beginGroup(ccPS::HeightGridGeneration()); QString imageSavePath = settings.value("savePathImage",QApplication::applicationDirPath()).toString(); outputFilename = QFileDialog::getSaveFileName(0,"Save height grid raster",imageSavePath+QString("/raster.tif"),"geotiff (*.tif)"); if (outputFilename.isNull()) return; //save current export path to persistent settings settings.setValue("savePathImage",QFileInfo(outputFilename).absolutePath()); } heightBand = reoDlg.exportHeightsCheckBox->isChecked(); densityBand = reoDlg.exportDensityCheckBox->isChecked(); if (hasSF) { assert(pc); allSFBands = reoDlg.exportAllSFCheckBox->isChecked() && hasSF; if (!allSFBands && reoDlg.exportDisplayedSFCheckBox->isChecked()) { sfBandIndex = pc->getCurrentDisplayedScalarFieldIndex(); if (sfBandIndex < 0) ccLog::Warning("[Rasterize] Cloud has no active (displayed) SF!"); } } totalBands = heightBand ? 1 : 0; if (densityBand) { ++totalBands; } if (allSFBands) { assert(hasSF); for (size_t i=0; i<m_grid.scalarFields.size(); ++i) if (m_grid.scalarFields[i]) ++totalBands; } else if (sfBandIndex >= 0) { ++totalBands; } if (totalBands == 0) { ccLog::Warning("[Rasterize] Warning, can't output a raster with no band! (check export parameters)"); return; } //data type GDALDataType dataType = (std::max(sizeof(PointCoordinateType),sizeof(ScalarType)) > 4 ? GDT_Float64 : GDT_Float32); char **papszOptions = NULL; GDALDataset* poDstDS = poDriver->Create(qPrintable(outputFilename), static_cast<int>(m_grid.width), static_cast<int>(m_grid.height), totalBands, dataType, papszOptions); if (!poDstDS) { ccLog::Error("[GDAL] Failed to create output raster (not enough memory?)"); return; } ccBBox box = getCustomBBox(); assert(box.isValid()); //vertical dimension const unsigned char Z = getProjectionDimension(); assert(Z >= 0 && Z <= 2); const unsigned char X = Z == 2 ? 0 : Z +1; const unsigned char Y = X == 2 ? 0 : X +1; double shiftX = box.minCorner().u[X]; double shiftY = box.minCorner().u[Y]; double stepX = m_grid.gridStep; double stepY = m_grid.gridStep; if (pc) { const CCVector3d& shift = pc->getGlobalShift(); shiftX -= shift.u[X]; shiftY -= shift.u[Y]; double scale = pc->getGlobalScale(); assert(scale != 0); stepX /= scale; stepY /= scale; } double adfGeoTransform[6] = { shiftX, //top left x stepX, //w-e pixel resolution (can be negative) 0, //0 shiftY, //top left y 0, //0 stepY //n-s pixel resolution (can be negative) }; poDstDS->SetGeoTransform( adfGeoTransform ); //OGRSpatialReference oSRS; //oSRS.SetUTM( 11, TRUE ); //oSRS.SetWellKnownGeogCS( "NAD27" ); //char *pszSRS_WKT = NULL; //oSRS.exportToWkt( &pszSRS_WKT ); //poDstDS->SetProjection( pszSRS_WKT ); //CPLFree( pszSRS_WKT ); double* scanline = (double*) CPLMalloc(sizeof(double)*m_grid.width); int currentBand = 0; //exort height band? if (heightBand) { GDALRasterBand* poBand = poDstDS->GetRasterBand(++currentBand); assert(poBand); poBand->SetColorInterpretation(GCI_Undefined); EmptyCellFillOption fillEmptyCellsStrategy = getFillEmptyCellsStrategy(fillEmptyCellsComboBox); double emptyCellHeight = 0; switch (fillEmptyCellsStrategy) { case LEAVE_EMPTY: emptyCellHeight = m_grid.minHeight-1.0; poBand->SetNoDataValue(emptyCellHeight); //should be transparent! break; case FILL_MINIMUM_HEIGHT: emptyCellHeight = m_grid.minHeight; break; case FILL_MAXIMUM_HEIGHT: emptyCellHeight = m_grid.maxHeight; break; case FILL_CUSTOM_HEIGHT: emptyCellHeight = getCustomHeightForEmptyCells(); break; case FILL_AVERAGE_HEIGHT: emptyCellHeight = m_grid.meanHeight; break; default: assert(false); } for (unsigned j=0; j<m_grid.height; ++j) { const RasterCell* aCell = m_grid.data[j]; for (unsigned i=0; i<m_grid.width; ++i,++aCell) { scanline[i] = aCell->h == aCell->h ? aCell->h : emptyCellHeight; } if (poBand->RasterIO( GF_Write, 0, static_cast<int>(j), static_cast<int>(m_grid.width), 1, scanline, static_cast<int>(m_grid.width), 1, GDT_Float64, 0, 0 ) != CE_None) { ccLog::Error("[GDAL] An error occurred while writing the height band!"); if (scanline) CPLFree(scanline); GDALClose( (GDALDatasetH) poDstDS ); return; } } } //export density band if (densityBand) { GDALRasterBand* poBand = poDstDS->GetRasterBand(++currentBand); assert(poBand); poBand->SetColorInterpretation(GCI_Undefined); for (unsigned j=0; j<m_grid.height; ++j) { const RasterCell* aCell = m_grid.data[j]; for (unsigned i=0; i<m_grid.width; ++i,++aCell) { scanline[i] = aCell->nbPoints; } if (poBand->RasterIO( GF_Write, 0, static_cast<int>(j), static_cast<int>(m_grid.width), 1, scanline, static_cast<int>(m_grid.width), 1, GDT_Float64, 0, 0 ) != CE_None) { ccLog::Error("[GDAL] An error occurred while writing the height band!"); if (scanline) CPLFree(scanline); GDALClose( (GDALDatasetH) poDstDS ); return; } } } //export SF bands if (allSFBands || sfBandIndex >= 0) { for (size_t k=0; k<m_grid.scalarFields.size(); ++k) { double* _sfGrid = m_grid.scalarFields[k]; if (_sfGrid && (allSFBands || sfBandIndex == static_cast<int>(k))) //valid SF grid { GDALRasterBand* poBand = poDstDS->GetRasterBand(++currentBand); double sfNanValue = static_cast<double>(CCLib::ScalarField::NaN()); poBand->SetNoDataValue(sfNanValue); //should be transparent! assert(poBand); poBand->SetColorInterpretation(GCI_Undefined); for (unsigned j=0; j<m_grid.height; ++j) { const RasterCell* aCell = m_grid.data[j]; for (unsigned i=0; i<m_grid.width; ++i,++_sfGrid,++aCell) { scanline[i] = aCell->nbPoints ? *_sfGrid : sfNanValue; } if (poBand->RasterIO( GF_Write, 0, static_cast<int>(j), static_cast<int>(m_grid.width), 1, scanline, static_cast<int>(m_grid.width), 1, GDT_Float64, 0, 0 ) != CE_None) { //the corresponding SF should exist on the input cloud CCLib::ScalarField* formerSf = pc->getScalarField(static_cast<int>(k)); assert(formerSf); ccLog::Error(QString("[GDAL] An error occurred while writing the '%1' scalar field band!").arg(formerSf->getName())); k = m_grid.scalarFields.size(); //quick stop break; } } } } } if (scanline) CPLFree(scanline); scanline = 0; /* Once we're done, close properly the dataset */ GDALClose( (GDALDatasetH) poDstDS ); ccLog::Print(QString("[Rasterize] Raster '%1' succesfully saved").arg(outputFilename)); #else assert(false); ccLog::Error("[Rasterize] GDAL not supported by this version! Can't generate a raster..."); #endif }
static void Usage(const char* pszAdditionalMsg, int bShort) { OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); printf( "Usage: ogr2ogr [--help-general] [-skipfailures] [-append] [-update]\n" " [-select field_list] [-where restricted_where|@filename]\n" " [-progress] [-sql <sql statement>|@filename] [-dialect dialect]\n" " [-preserve_fid] [-fid FID]\n" " [-spat xmin ymin xmax ymax] [-spat_srs srs_def] [-geomfield field]\n" " [-a_srs srs_def] [-t_srs srs_def] [-s_srs srs_def]\n" " [-f format_name] [-overwrite] [[-dsco NAME=VALUE] ...]\n" " dst_datasource_name src_datasource_name\n" " [-lco NAME=VALUE] [-nln name] \n" " [-nlt type|PROMOTE_TO_MULTI|CONVERT_TO_LINEAR|CONVERT_TO_CURVE]\n" " [-dim 2|3|layer_dim] [layer [layer ...]]\n" "\n" "Advanced options :\n" " [-gt n] [-ds_transaction]\n" " [[-oo NAME=VALUE] ...] [[-doo NAME=VALUE] ...]\n" " [-clipsrc [xmin ymin xmax ymax]|WKT|datasource|spat_extent]\n" " [-clipsrcsql sql_statement] [-clipsrclayer layer]\n" " [-clipsrcwhere expression]\n" " [-clipdst [xmin ymin xmax ymax]|WKT|datasource]\n" " [-clipdstsql sql_statement] [-clipdstlayer layer]\n" " [-clipdstwhere expression]\n" " [-wrapdateline][-datelineoffset val]\n" " [[-simplify tolerance] | [-segmentize max_dist]]\n" " [-addfields] [-unsetFid]\n" " [-relaxedFieldNameMatch] [-forceNullable] [-unsetDefault]\n" " [-fieldTypeToString All|(type1[,type2]*)] [-unsetFieldWidth]\n" " [-mapFieldType srctype|All=dsttype[,srctype2=dsttype2]*]\n" " [-fieldmap identity | index1[,index2]*]\n" " [-splitlistfields] [-maxsubfields val]\n" " [-explodecollections] [-zfield field_name]\n" " [-gcp pixel line easting northing [elevation]]* [-order n | -tps]\n" " [-nomd] [-mo \"META-TAG=VALUE\"]* [-noNativeData]\n"); if (bShort) { printf( "\nNote: ogr2ogr --long-usage for full help.\n"); if( pszAdditionalMsg ) fprintf(stderr, "\nFAILURE: %s\n", pszAdditionalMsg); exit( 1 ); } printf("\n -f format_name: output file format name, possible values are:\n"); std::vector<CPLString> aoSetDrivers; for( int iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { GDALDriver *poDriver = poR->GetDriver(iDriver); if( CPLTestBool( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) ) aoSetDrivers.push_back( poDriver->GetDescription() ); } std::sort (aoSetDrivers.begin(), aoSetDrivers.end(), StringCISortFunction); for( size_t i = 0; i < aoSetDrivers.size(); i++ ) { printf( " -f \"%s\"\n", aoSetDrivers[i].c_str() ); } printf( " -append: Append to existing layer instead of creating new if it exists\n" " -overwrite: delete the output layer and recreate it empty\n" " -update: Open existing output datasource in update mode\n" " -progress: Display progress on terminal. Only works if input layers have the \n" " \"fast feature count\" capability\n" " -select field_list: Comma-delimited list of fields from input layer to\n" " copy to the new layer (defaults to all)\n" " -where restricted_where: Attribute query (like SQL WHERE)\n" " -wrapdateline: split geometries crossing the dateline meridian\n" " (long. = +/- 180deg)\n" " -datelineoffset: offset from dateline in degrees\n" " (default long. = +/- 10deg,\n" " geometries within 170deg to -170deg will be split)\n" " -sql statement: Execute given SQL statement and save result.\n" " -dialect value: select a dialect, usually OGRSQL to avoid native sql.\n" " -skipfailures: skip features or layers that fail to convert\n" " -gt n: group n features per transaction (default 20000). n can be set to unlimited\n" " -spat xmin ymin xmax ymax: spatial query extents\n" " -simplify tolerance: distance tolerance for simplification.\n" " -segmentize max_dist: maximum distance between 2 nodes.\n" " Used to create intermediate points\n" " -dsco NAME=VALUE: Dataset creation option (format specific)\n" " -lco NAME=VALUE: Layer creation option (format specific)\n" " -oo NAME=VALUE: Input dataset open option (format specific)\n" " -doo NAME=VALUE: Destination dataset open option (format specific)\n" " -nln name: Assign an alternate name to the new layer\n" " -nlt type: Force a geometry type for new layer. One of NONE, GEOMETRY,\n" " POINT, LINESTRING, POLYGON, GEOMETRYCOLLECTION, MULTIPOINT,\n" " MULTIPOLYGON, or MULTILINESTRING, or PROMOTE_TO_MULTI or CONVERT_TO_LINEAR. Add \"25D\" for 3D layers.\n" " Default is type of source layer.\n" " -dim dimension: Force the coordinate dimension to the specified value.\n" " -fieldTypeToString type1,...: Converts fields of specified types to\n" " fields of type string in the new layer. Valid types are : Integer,\n" " Integer64, Real, String, Date, Time, DateTime, Binary, IntegerList, Integer64List, RealList,\n" " StringList. Special value All will convert all fields to strings.\n" " -fieldmap index1,index2,...: Specifies the list of field indexes to be\n" " copied from the source to the destination. The (n)th value specified\n" " in the list is the index of the field in the target layer definition\n" " in which the n(th) field of the source layer must be copied. Index count\n" " starts at zero. There must be exactly as many values in the list as\n" " the count of the fields in the source layer. We can use the 'identity'\n" " setting to specify that the fields should be transferred by using the\n" " same order. This setting should be used along with the append setting."); printf(" -a_srs srs_def: Assign an output SRS\n" " -t_srs srs_def: Reproject/transform to this SRS on output\n" " -s_srs srs_def: Override source SRS\n" "\n" " Srs_def can be a full WKT definition (hard to escape properly),\n" " or a well known definition (i.e. EPSG:4326) or a file with a WKT\n" " definition.\n" ); if( pszAdditionalMsg ) fprintf(stderr, "\nFAILURE: %s\n", pszAdditionalMsg); }