说明: 需要GDAL库
#include <boost/filesystem.hpp>
#include <boost/function.hpp>
#include <gdal.h>
#include <gdal_alg.h>
#include <gdal_priv.h>
#include <ogrsf_frmts.h>
#include <iostream>
#include <sstream>
using namespace std;
/*!
* @brief 线类型 结构体
* param min_x, min_y, min_z 右侧点xyz值
* max_x, max_y, max_z 左侧点 xyz值
* category 属性类别
*/
struct dotted
{
int category;
double min_x;
double min_y;
double min_z;
double max_x;
double max_y;
double max_z;
dotted()
{
category = 0;
min_x = min_y = min_z = max_x = max_y = max_z = 0.0;
}
};
/*!
* @brief 写shp文件函数
* param[in] base_folder_name: 根目录文件夹 vec_dotted:线结构体容器 file_index:shp文件序号
*
*/
bool writeShp(const string &base_folder_name, vector<dotted> &vec_dotted, int file_index)
{
string outputFolder = base_folder_name + "/Vectorized Road Marking (shp)";
if (!boost::filesystem::exists(outputFolder))
{
boost::filesystem::create_directory(outputFolder);
}
string filename;
ostringstream oss;
oss << "/Vectorized Road Markings_" << file_index << ".shp";
filename = outputFolder + oss.str();
const char *pszDriverName = "ESRI Shapefile";
GDALAllRegister();
OGRRegisterAll();
GDALDriver *poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName);
if (poDriver == NULL)
{
cout << "ESRI Shapefile : This driver is not available" << endl;
}
GDALDataset *poDs = poDriver->Create(filename.c_str(), 0, 0, 0, GDT_Unknown, NULL);
if (poDs == NULL)
{
cout << "Failed in creating Dataset" << endl;
}
else
cout << "Creating dataset done" << endl;
//创建图层
OGRLayer *poLayer = poDs->CreateLayer("roadmarking", NULL, wkbLineStringZM, NULL);
if (poLayer == NULL)
{
cout << "Layer creation failed!" << endl;
}
else
cout << "Creating Layer done" << endl;
//创建属性字段
OGRFieldDefn poFieldID("ID", OFTInteger);
poFieldID.SetWidth(40);
OGRFieldDefn poFieldType("Type", OFTInteger);
poFieldType.SetWidth(40);
if (poLayer->CreateField(&poFieldID) != OGRERR_NONE) {
cout << "ID field creation failed" << endl;
}
if (poLayer->CreateField(&poFieldType) != OGRERR_NONE) {
cout << "Type field creation failed" << endl;
}
//画线
int line_N = vec_dotted.size();
for (int i = 0; i < line_N; i++) {
OGRFeature *poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());
poFeature->SetField("ID", i);
poFeature->SetField("Type", vec_dotted[i].category);
OGRLineString line;
line.addPoint(vec_dotted[i].min_x, vec_dotted[i].min_y);
line.addPoint(vec_dotted[i].max_x, vec_dotted[i].max_y);
poFeature->SetGeometry(&line);
if (poLayer->CreateFeature(poFeature) != OGRERR_NONE) {
cout << "Failed to create feature in shapefile" << endl;
}
OGRFeature::DestroyFeature(poFeature);
}
GDALClose(poDs);
cout << "Output vectorized roadmarking done \n";
return 1;
}