GDAL 栅格数据转矢量数据

网上有不少关于栅格转矢量的代码,今天参考了别人的代码,写出了一个完整的程序:

 

#include "gdal_priv.h"
#include "ogrsf_frmts.h" //for ogr
#include "gdal_alg.h"  //for GDALPolygonize
#include "cpl_conv.h" //for CPLMalloc() 

int ImagePolygonize(const char * pszSrcFile,const char* pszDstFile,const char* pszFormat);

int main()
{
   const char* pszSrcFile = "H:\\GDAL文件\\gdal栅格矢量化\\classify_bitmap.bmp";
   const char* pszDstFile = "H:\\GDAL文件\\gdal栅格矢量化\\shape.shp";
   ImagePolygonize(pszSrcFile,pszDstFile,"ESRI Shapefile");
  // system("pause");
   return 0;
}

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 );
	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;
}


 


 

可以处理分类后的栅格图像,建议在做矢量化之前,对分类后的图像进行滤波,去除小碎斑块,不然这些小碎斑块会影响处理进度。

 

你可能感兴趣的:(GDAL 栅格数据转矢量数据)