参考:
Qt + GDAL 写入矢量图层 shp
windows下的QT(mingw版)+GDAL库下载、安装、测试
已经编译好的GDAL库下载:
https://download.csdn.net/download/carry_qt/10648004
浏览shp格式的小软件:Shape Viewer
https://download.csdn.net/download/lclhurricane/2925573
https://shape-viewer.software.informer.com/
https://shapeviewer.software.informer.com/
Qt中添加GDAL库:
INCLUDEPATH += D:\GDAL\include
LIBS += -LD:\GDAL\bin -lgdal-1
位图转矢量图写入shp或json文件:
//保存json文件,pszFormat="geojson"
//保存shp文件,pszFormat="ESRI Shapefile"
int ImagePolygonize(const char * pszSrcFile,const char* pszDstFile,const char* pszFormat="geojson"); //矢量化,得到json文件
int ImagePolygonize(const char * pszSrcFile,const char* pszDstFile,const char* pszFormat)
{
GDALAllRegister();
OGRRegisterAll();//记得添加驱动注册
CPLSetConfigOption("GDAL_FILENAME_IS_UTF8","NO");
GDALDataset* poSrcDS=(GDALDataset*)GDALOpen(pszSrcFile,GA_ReadOnly);
if(poSrcDS==NULL)
{
return 0;
}
// 创建输出矢量文件
OGRSFDriver *poDriver;
poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName( pszFormat ); //GTiff
if (poDriver == NULL)
{
GDALClose((GDALDatasetH)poSrcDS);
return 0;
}
//根据文件名创建输出矢量文件
OGRDataSource* poDstDS=poDriver->CreateDataSource(pszDstFile);
if (poDstDS==NULL)
{
GDALClose((GDALDatasetH)poSrcDS);
return 0;
}
// 定义空间参考,与输入图像相同;
OGRSpatialReference *poSpatialRef = new OGRSpatialReference(poSrcDS->GetProjectionRef());
OGRLayer* poLayer = poDstDS->CreateLayer("Result", poSpatialRef, wkbPolygon, NULL);
if (poDstDS == NULL)
{
GDALClose((GDALDatasetH)poSrcDS);
OGRDataSource::DestroyDataSource(poDstDS);
delete poSpatialRef;
poSpatialRef = NULL;
return 0;
}
OGRFieldDefn ofieldDef("Segment", OFTInteger); //创建属性表,只有一个字段即“Segment”,里面保存对应的栅格的像元值
poLayer->CreateField(&ofieldDef);
GDALRasterBandH hSrcBand = (GDALRasterBandH) poSrcDS->GetRasterBand(1); //获取图像的第一个波段
GDALPolygonize(hSrcBand, NULL, (OGRLayerH)poLayer, 0, NULL, NULL, NULL); //调用栅格矢量化
GDALClose(poSrcDS); //关闭文件
OGRDataSource::DestroyDataSource(poDstDS);
return 1;
}