GDAL栅格矢量化
在这里主要提供直接能用的栅格矢量化代码,这个函数中路径输入为QStrng,如果是其他类型的,请直接转成const char *;
bool Polygonize(const QString& strImg, const QString& strShp) { GDALDataset *poFlagDS = (GDALDataset *)GDALOpen(strImg.toUtf8().constData(),GA_ReadOnly); if (poFlagDS == NULL) { cout<<"can't open "+ strImg.toStdString(); return false; } GDALDriver * poOgrDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("ESRI Shapefile"); if (poOgrDriver == NULL) { cout<<"can't get driver"; GDALClose(poFlagDS); return false; } QFileInfo info(strShp); if (info.exists()) poOgrDriver->Delete(strShp.toUtf8().constData()); GDALDataset* poDstDataset = poOgrDriver->Create(strShp.toUtf8().constData(),0,0,0,GDT_Unknown,NULL); if (poDstDataset == NULL) { GDALClose(poFlagDS); return false; } OGRSpatialReference* pSpecialReference = new OGRSpatialReference(poFlagDS->GetProjectionRef()); const char* layerName = "polygon"; OGRLayer* poLayer = poDstDataset->CreateLayer(layerName,pSpecialReference,wkbPolygon,0); if (poLayer == NULL) { cout<<"can't create layer"; GDALClose(poFlagDS); GDALClose( poDstDataset ); return false; } OGRFieldDefn ofDef_DN( LABELFIELD, OFTInteger ); if ( (poLayer->CreateField(&ofDef_DN) != OGRERR_NONE) ) { cout<<"can't create field"; GDALClose(poFlagDS); GDALClose( poDstDataset ); return false; } char** papszOptions = NULL; papszOptions = CSLSetNameValue(papszOptions,"8CONNECTED","8"); GDALRasterBand *poFlagBand = poFlagDS->GetRasterBand(1); GDALRasterBand *poMaskBand = poFlagBand->GetMaskBand(); CPLErr err = GDALPolygonize((GDALRasterBandH)poFlagBand,(GDALRasterBandH)poMaskBand,(OGRLayerH)poLayer,0,papszOptions,0,0); if (err != CE_None) { cout<<"polygonize failed"; GDALClose(poFlagDS); GDALClose( poDstDataset ); return false; } GDALClose(poFlagDS); GDALClose(poDstDataset); return true; }