Fishnet 2.0.1
Framework for Graph-Based Analysis of GIS Vector Data
Loading...
Searching...
No Matches
GISConverter.hpp
Go to the documentation of this file.
1#pragma once
2#include <expected>
3#include "Shapefile.hpp"
4#include "GeoTiff.hpp"
5#include <filesystem>
6#include <gdal/gdal.h>
7#include <gdal_alg.h>
8#include <ogrsf_frmts.h>
9#include <gdal/ogr_core.h>
10#include <gdal/gdal_priv.h>
12
13namespace fishnet{
15public:
24 static std::expected<Shapefile,std::string> convert(const GeoTiff & geoTiff,bool maskZero = true, bool showProgress=false) noexcept{
25 GDALAllRegister();
26 GDALDataset *src = (GDALDataset *) GDALOpen(geoTiff.getPath().c_str(), GA_ReadOnly);
27 if(src == nullptr)
28 return std::unexpected("Could not open Geotiff-Dataset: "+geoTiff.getPath().string());
29 auto driver = GetGDALDriverManager()->GetDriverByName("ESRI Shapefile");
30 if(driver == nullptr)
31 return std::unexpected("No suitable ESRI Shapefile driver detected");
32 std::filesystem::path conversionOutputDir = std::filesystem::current_path() / "conversion_output";
33 std::filesystem::create_directories(conversionOutputDir);
34 std::filesystem::path destPath = conversionOutputDir / geoTiff.getPath().stem().replace_extension(".shp");
35 GDALDataset *dest = driver->Create(destPath.c_str(), 0,0, 0, GDT_Unknown,nullptr);
36 auto spatialReference = src->GetSpatialRef();
37 OGRLayer * layer = dest->CreateLayer(destPath.stem().c_str(),spatialReference->Clone(),wkbPolygon, nullptr);
38 const char *fieldName = "pixel_val";
39 OGRFieldDefn fieldDefn = OGRFieldDefn(fieldName, OFTInteger);
40 if(layer->CreateField(&fieldDefn)!=OGRERR_NONE)
41 return std::unexpected("Could not create field for pixel values");
42 int fieldID = layer->GetLayerDefn()->GetFieldIndex(fieldName);
43 char ** papszOptions = nullptr;
44 papszOptions = CSLSetNameValue(papszOptions, "8CONNECTED", "8");
45 GDALPolygonize(
46 src->GetRasterBand(1),
47 maskZero?src->GetRasterBand(1):nullptr,
48 OGRLayer::ToHandle(layer),
49 fieldID,
50 papszOptions,
51 showProgress?GDALTermProgress:nullptr,
52 nullptr
53 );
54 layer->SyncToDisk();
55 GDALClose(src);
56 GDALClose(dest);
57 return Shapefile(destPath);
58 }
59};
60}
const std::filesystem::path & getPath() const noexcept
Definition GISFile.hpp:65
Definition GISConverter.hpp:14
static std::expected< Shapefile, std::string > convert(const GeoTiff &geoTiff, bool maskZero=true, bool showProgress=false) noexcept
Tries to convert a GeoTiff to Shp file.
Definition GISConverter.hpp:24
GeoTiff handle implementation.
Definition GeoTiff.hpp:8
Shapefile handle implementation.
Definition Shapefile.hpp:14
Definition BFSClustering.hpp:5