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( !CPLTestBool( 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; }
CPLErr GDALDefaultOverviews::CreateMaskBand( int nFlags, int nBand ) { if( nBand < 1 ) nFlags |= GMF_PER_DATASET; /* -------------------------------------------------------------------- */ /* ensure existing file gets opened if there is one. */ /* -------------------------------------------------------------------- */ HaveMaskFile(); /* -------------------------------------------------------------------- */ /* Try creating the mask file. */ /* -------------------------------------------------------------------- */ if( poMaskDS == NULL ) { CPLString osMskFilename; GDALDriver *poDr = (GDALDriver *) GDALGetDriverByName( "GTiff" ); char **papszOpt = NULL; int nBX, nBY; int nBands; if( poDr == NULL ) return CE_Failure; GDALRasterBand *poTBand = poDS->GetRasterBand(1); if( poTBand == NULL ) return CE_Failure; if( nFlags & GMF_PER_DATASET ) nBands = 1; else nBands = poDS->GetRasterCount(); papszOpt = CSLSetNameValue( papszOpt, "COMPRESS", "DEFLATE" ); papszOpt = CSLSetNameValue( papszOpt, "INTERLEAVE", "BAND" ); poTBand->GetBlockSize( &nBX, &nBY ); // try to create matching tile size if legal in TIFF. if( (nBX % 16) == 0 && (nBY % 16) == 0 ) { papszOpt = CSLSetNameValue( papszOpt, "TILED", "YES" ); papszOpt = CSLSetNameValue( papszOpt, "BLOCKXSIZE", CPLString().Printf("%d",nBX) ); papszOpt = CSLSetNameValue( papszOpt, "BLOCKYSIZE", CPLString().Printf("%d",nBY) ); } osMskFilename.Printf( "%s.msk", poDS->GetDescription() ); poMaskDS = poDr->Create( osMskFilename, poDS->GetRasterXSize(), poDS->GetRasterYSize(), nBands, GDT_Byte, papszOpt ); CSLDestroy( papszOpt ); if( poMaskDS == NULL ) // presumably error already issued. return CE_Failure; bOwnMaskDS = TRUE; } /* -------------------------------------------------------------------- */ /* Save the mask flags for this band. */ /* -------------------------------------------------------------------- */ if( nBand > poMaskDS->GetRasterCount() ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create a mask band for band %d of %s,\n" "but the .msk file has a PER_DATASET mask.", nBand, poDS->GetDescription() ); return CE_Failure; } int iBand; for( iBand = 0; iBand < poDS->GetRasterCount(); iBand++ ) { // we write only the info for this band, unless we are // using PER_DATASET in which case we write for all. if( nBand != iBand + 1 && !(nFlags | GMF_PER_DATASET) ) continue; poMaskDS->SetMetadataItem( CPLString().Printf("INTERNAL_MASK_FLAGS_%d", iBand+1 ), CPLString().Printf("%d", nFlags ) ); } return CE_None; }
int OutCoreInterp::outputFile(const std::string& 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.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); } } } 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.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(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 (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; int out_index = (end - 1 - j) * GRID_SIZE_X + k; if(gf->interp[index].empty == 0 && gf->interp[index].filled == 0) { poRasterData[out_index] = -9999.f; } else { switch (t) { case 0: poRasterData[out_index] = gf->interp[index].Zmin; break; case 1: poRasterData[out_index] = gf->interp[index].Zmax; break; case 2: poRasterData[out_index] = gf->interp[index].Zmean; break; case 3: poRasterData[out_index] = gf->interp[index].Zidw; break; case 4: poRasterData[out_index] = gf->interp[index].count; break; case 5: poRasterData[out_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 OGRGPSBabelWriteDataSource::Create( const char * pszNameIn, char **papszOptions ) { GDALDriver* poGPXDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("GPX"); if (poGPXDriver == NULL) { CPLError( CE_Failure, CPLE_AppDefined, "GPX driver is necessary for GPSBabel write support" ); return FALSE; } if (!STARTS_WITH_CI(pszNameIn, "GPSBABEL:")) { const char* pszOptionGPSBabelDriverName = CSLFetchNameValue(papszOptions, "GPSBABEL_DRIVER"); if (pszOptionGPSBabelDriverName != NULL) pszGPSBabelDriverName = CPLStrdup(pszOptionGPSBabelDriverName); else { CPLError( CE_Failure, CPLE_AppDefined, "GPSBABEL_DRIVER dataset creation option expected" ); return FALSE; } pszFilename = CPLStrdup(pszNameIn); } else { const char* pszSep = strchr(pszNameIn + 9, ':'); if (pszSep == NULL) { CPLError( CE_Failure, CPLE_AppDefined, "Wrong syntax. Expected GPSBabel:driver_name[,options]*:" "file_name" ); return FALSE; } pszGPSBabelDriverName = CPLStrdup(pszNameIn + 9); *(strchr(pszGPSBabelDriverName, ':')) = '\0'; pszFilename = CPLStrdup(pszSep+1); } /* A bit of validation to avoid command line injection */ if (!OGRGPSBabelDataSource::IsValidDriverName(pszGPSBabelDriverName)) return FALSE; const char* pszOptionUseTempFile = CSLFetchNameValue(papszOptions, "USE_TEMPFILE"); if (pszOptionUseTempFile == NULL) pszOptionUseTempFile = CPLGetConfigOption("USE_TEMPFILE", NULL); if (pszOptionUseTempFile && CPLTestBool(pszOptionUseTempFile)) osTmpFileName = CPLGenerateTempFilename(NULL); else osTmpFileName.Printf("/vsimem/ogrgpsbabeldatasource_%p", this); poGPXDS = poGPXDriver->Create( osTmpFileName.c_str(), 0, 0, 0, GDT_Unknown, papszOptions); if (poGPXDS == NULL) return FALSE; this->pszName = CPLStrdup(pszNameIn); return TRUE; }
int main(int argc, char* argv[]) { if (argc < 6) { cout << "webco <infile> <minlat> <minlon> <maxlat> <maxlon> <outfile>" << endl; exit(1); } const char* InFilename = argv[1]; int minlatpixel; int minlonpixel; int maxlatpixel; int maxlonpixel; { double minlat = atoi(argv[2]); double minlon = atoi(argv[3]); double maxlat = atoi(argv[4]); double maxlon = atoi(argv[5]); minlatpixel = minlat*RESOLUTION; minlonpixel = minlon*RESOLUTION; maxlatpixel = maxlat*RESOLUTION; maxlonpixel = maxlon*RESOLUTION; if (minlon == -180.0) { minlonpixel += MARGIN; maxlonpixel += MARGIN; } if (maxlon == 180.0) { minlonpixel -= MARGIN; maxlonpixel -= MARGIN; } } const char* OutFilename = argv[6]; GDALAllRegister(); // Create the output dataset and copy over relevant metadata const char* Format = "GTiff"; GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(Format); char** Options = NULL; FILE *file = fopen(InFilename, "r"); cout << "Remove header." << endl; fseek(file, 611, SEEK_CUR); { cout << "Seek to lon/lat." << endl; int seeklat = (90*RESOLUTION-maxlatpixel-MARGIN)*2*WIDTH; int seeklon = (minlonpixel+180*RESOLUTION-MARGIN)*2; fseek(file, seeklon+seeklat, SEEK_CUR); /* if (maxlon == 180) { fseek(file, 1, SEEK_CUR); }*/ } cout << "Process image." << endl; GDALDataset* poDS; GDALRasterBand* poBand; /* char filename[20]; { char ns = maxlat < 0 ? 'S' : 'N'; char ew = minlon < 0 ? 'W' : 'E'; // sprintf(filename, "multi/%c%02i%c%03i.tif", ns, abs(maxlat), ew, abs(minlon)); sprintf(filename, "%c%02i%c%03i.tif", ns, abs(maxlat), ew, abs(minlon)); }*/ poDS = poDriver->Create(OutFilename,(maxlonpixel-minlonpixel)+2*MARGIN,(maxlatpixel-minlatpixel)+2*MARGIN,1,GDT_Float32,Options); // top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution double adfGeoTransform[6] = { (minlonpixel-MARGIN)*1.0/RESOLUTION, 1.0/RESOLUTION, 0, (maxlatpixel+MARGIN)*1.0/RESOLUTION, 0, -1.0/RESOLUTION }; poDS->SetGeoTransform(adfGeoTransform); // poDS->SetProjection(poDataset->GetProjectionRef()); poBand = poDS->GetRasterBand(1); poBand->SetNoDataValue(-9999); GDALAllRegister(); for (int y = 0; y < (maxlatpixel-minlatpixel)+2*MARGIN; y++) { cout << "\r" << y << "/" << (maxlatpixel-minlatpixel)+2*MARGIN; for (int x = 0; x < (maxlonpixel-minlonpixel)+2*MARGIN; x++) { int16_t height; int size = fread(&height, 2, 1, file); float pixel = (float)height; poBand->RasterIO(GF_Write, x, y, 1, 1, &pixel, 1, 1, GDT_Float32, 0, 0); } fseek(file, ((360*RESOLUTION-maxlonpixel+minlonpixel)-2*MARGIN)*2, SEEK_CUR); } cout << endl; delete poDS; fclose(file); return 0; }
bool Shape::save(const std::string& filename) { if (shapeType == -1) { std::cout << "Shape type is not set." << std::endl; return false; } if (shapeObjects.size() == 0) { std::cout << "No shape exists." << std::endl; return false; } const char *pszDriverName = "ESRI Shapefile"; GDALDriver *poDriver; GDALAllRegister(); poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName); if (poDriver == NULL) { printf("%s driver not available.\n", pszDriverName); return false; } GDALDataset *poDS; poDS = poDriver->Create(filename.c_str(), 0, 0, 0, GDT_Unknown, NULL); if (poDS == NULL) { printf("Creation of output file failed.\n"); return false; } OGRLayer *poLayer; if (shapeType == wkbPoint) { poLayer = poDS->CreateLayer("point_out", NULL, wkbPoint, NULL); } else if (shapeType == wkbLineString) { poLayer = poDS->CreateLayer("point_out", NULL, wkbLineString, NULL); } else if (shapeType == wkbPolygon) { poLayer = poDS->CreateLayer("point_out", NULL, wkbPolygon, NULL); } if (poLayer == NULL) { printf("Layer creation failed.\n"); return false; } for (auto it = shapeObjects[0].attributes.begin(); it != shapeObjects[0].attributes.end(); ++it) { OGRFieldDefn oField(it->first.c_str(), static_cast<OGRFieldType>(it->second.type)); if (it->second.type == OFTString) { oField.SetWidth(it->second.stringValue().size()); } if (poLayer->CreateField(&oField) != OGRERR_NONE) { printf("Creating Name field failed.\n"); return false; } } for (int i = 0; i < shapeObjects.size(); ++i) { if (shapeObjects[i].parts.size() == 0) continue; OGRFeature *poFeature; poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn()); // 属性をセット for (auto it = shapeObjects[i].attributes.begin(); it != shapeObjects[i].attributes.end(); ++it) { poFeature->SetField(it->first.c_str(), it->second.stringValue().c_str()); } // ジオメトリ情報をセット if (shapeType == wkbPoint) { OGRPoint point; point.setX(shapeObjects[i].parts[0].points[0].x); point.setY(shapeObjects[i].parts[0].points[0].y); point.setZ(shapeObjects[i].parts[0].points[0].z); poFeature->SetGeometry(&point); } else if (shapeType == wkbLineString) { OGRLineString lineString; for (int k = 0; k < shapeObjects[i].parts[0].points.size(); ++k) { lineString.addPoint(shapeObjects[i].parts[0].points[k].x, shapeObjects[i].parts[0].points[k].y, shapeObjects[i].parts[0].points[k].z); } poFeature->SetGeometry(&lineString); } else if (shapeType == wkbPolygon) { OGRPolygon polygon; for (int j = 0; j < shapeObjects[i].parts.size(); ++j) { OGRLinearRing linearRing; for (int k = 0; k < shapeObjects[i].parts[j].points.size(); ++k) { linearRing.addPoint(shapeObjects[i].parts[j].points[k].x, shapeObjects[i].parts[j].points[k].y, shapeObjects[i].parts[j].points[k].z); } polygon.addRing(&linearRing); } poFeature->SetGeometry(&polygon); } if (poLayer->CreateFeature(poFeature) != OGRERR_NONE) { printf("Failed to create feature in shapefile.\n"); return false; } OGRFeature::DestroyFeature(poFeature); } GDALClose(poDS); return true; }
void SavePolygons( const std::vector< std::string > InFilenames, const char *OutFilename, const cv::Mat klabels, const std::vector< cv::Mat > raster, const std::vector< u_int32_t > labelpixels, const std::vector< std::vector <double> > sumCH, const std::vector< std::vector <double> > avgCH, const std::vector< std::vector <double> > stdCH, std::vector< std::vector< LINE > >& linelists ) { CPLLocaleC oLocaleCForcer(); CPLErrorReset(); const char *pszDriverName = "ESRI Shapefile"; GDALDriver *liDriver; liDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName ); if( liDriver == NULL ) { printf( "\nERROR: %s driver not available.\n", pszDriverName ); exit( 1 ); } const size_t m_bands = raster.size(); const size_t m_labels = labelpixels.size(); GDALDataset *liDS; liDS = liDriver->Create( OutFilename, 0, 0, 0, GDT_Unknown, NULL ); if( liDS == NULL ) { printf( "\nERROR: Creation of output file failed.\n" ); exit( 1 ); } // dataset GDALDataset* piDataset; piDataset = (GDALDataset*) GDALOpen(InFilenames[0].c_str(), GA_ReadOnly); // spatialref OGRSpatialReference oSRS; oSRS.SetProjCS( piDataset->GetProjectionRef() ); OGRLayer *liLayer; liLayer = liDS->CreateLayer( "segments", &oSRS, wkbPolygon, NULL ); if( liLayer == NULL ) { printf( "\nERROR: Layer creation failed.\n" ); exit( 1 ); } // spatial transform double adfGeoTransform[6]; double oX = 0.0f; double oY = 0.0f; double mX = 1.0f; double mY = -1.0f; if( piDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { oX = adfGeoTransform[0]; oY = adfGeoTransform[3]; mX = adfGeoTransform[1]; mY = adfGeoTransform[5]; } GDALClose( (GDALDatasetH) piDataset ); OGRFieldDefn *clsIdField = new OGRFieldDefn( "CLASS", OFTInteger ); liLayer->CreateField( clsIdField ); OGRFieldDefn *pixArField = new OGRFieldDefn( "AREA", OFTInteger ); liLayer->CreateField( pixArField ); for ( size_t b = 0; b < m_bands; b++ ) { stringstream value; value << b+1; std::string FieldName = value.str() + "_AVERAGE"; OGRFieldDefn *lavrgField = new OGRFieldDefn( FieldName.c_str(), OFTReal ); liLayer->CreateField( lavrgField ); } for ( size_t b = 0; b < m_bands; b++ ) { stringstream value; value << b+1; std::string FieldName = value.str() + "_STDDEV"; OGRFieldDefn *lavrgField = new OGRFieldDefn( FieldName.c_str(), OFTReal ); liLayer->CreateField( lavrgField ); } int multiring = 0; printf ("Write File: %s (polygon)\n", OutFilename); for (size_t k = 0; k < m_labels; k++) { if (multiring == 1) { k = k - 1; multiring = 0; } if (linelists[k].size() == 0) continue; // insert field data OGRFeature *liFeature; liFeature = OGRFeature::CreateFeature( liLayer->GetLayerDefn() ); liFeature->SetField( "CLASS", (int) k ); liFeature->SetField( "AREA", (int) labelpixels.at(k) ); for ( size_t b = 0; b < m_bands; b++ ) { stringstream value; value << b+1; std::string FieldName = value.str() + "_AVERAGE"; liFeature->SetField( FieldName.c_str(), (double) avgCH[b].at(k) ); } for ( size_t b = 0; b < m_bands; b++ ) { stringstream value; value << b+1; std::string FieldName = value.str() + "_STDDEV"; liFeature->SetField( FieldName.c_str(), stdCH[b].at(k) ); } // initiate polygon start OGRLinearRing linestring; linestring.setCoordinateDimension(2); linestring.addPoint( oX + (double) linelists[k][0].sX * mX, oY + mY * (double) linelists[k][0].sY ); linestring.addPoint( oX + (double) linelists[k][0].eX * mX, oY + mY * (double) linelists[k][0].eY ); linelists[k].erase( linelists[k].begin() ); // construct polygon from lines while ( linelists[k].size() > 0 ) { if (multiring == 1) break; vector<LINE>::iterator it = linelists[k].begin(); for (; it != linelists[k].end(); ++it) { double ltX = linestring.getX(linestring.getNumPoints()-1); double ltY = linestring.getY(linestring.getNumPoints()-1); double csX = oX + (double) it->sX * mX; double csY = oY + mY * (double) it->sY; double ceX = oX + (double) it->eX * mX; double ceY = oY + mY * (double) it->eY; if ( ( csX == ltX ) && ( csY == ltY ) ) { linestring.addPoint(ceX, ceY); linelists[k].erase(it); break; } if ( ( ceX == ltX ) && ( ceY == ltY ) ) { linestring.addPoint(csX, csY); linelists[k].erase(it); break; } if (it == linelists[k].end()-1) { multiring = 1; break; } } } OGRPolygon polygon; linestring.closeRings(); // simplify poligons // remove colinear vertices OGRLinearRing linesimple; float pointPrevX = 0, pointPrevY = 0; for (int i = 0; i < linestring.getNumPoints(); i++) { OGRPoint point; linestring.getPoint(i, &point); // start if ( i == 0) { linesimple.addPoint( &point ); pointPrevX = point.getX(); pointPrevY = point.getY(); continue; } // end vertex if ( i == linestring.getNumPoints() - 1 ) { linesimple.addPoint( &point ); continue; } OGRPoint pointNext; linestring.getPoint(i+1, &pointNext); // | x1 y1 1 | // det | x2 y2 1 | = 0 => p1,p2,p3 are colinear // | x3 y3 1 | // x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2) == 0 // only if not colinear with previous and next if ( pointPrevX*(point.getY()-pointNext.getY()) + point.getX()*(pointNext.getY()-pointPrevY) + pointNext.getX()*(pointPrevY-point.getY()) != 0 ) { linesimple.addPoint( &point ); pointPrevX = point.getX(); pointPrevY = point.getY(); } } // as polygon geometry polygon.addRing( &linesimple ); liFeature->SetGeometry( &polygon ); if( liLayer->CreateFeature( liFeature ) != OGRERR_NONE ) { printf( "\nERROR: Failed to create feature in shapefile.\n" ); exit( 1 ); } OGRFeature::DestroyFeature( liFeature ); GDALTermProgress( (float)(k+1) / (float)(m_labels), NULL, NULL ); } GDALTermProgress( 1.0f, NULL, NULL ); GDALClose( liDS ); }