我正在c ++中使用opencv从地理空间图像中提取一组2D点。使用这些点作为顶点,我想创建一个多边形ESRI shapefile。
Gdal api教程(https://gdal.org/1.11/ogr/ogr_apitut.html)仅包含有关如何创建点和线串shapefile的示例。像“ OGR_G_AddPoint_2D”之类的功能不适用于多边形类型shapefile。
我有一个功能,可以在点图层中添加一个点,并且效果很好。
void addPoint(OGRLayerH hLayer, long x, long y, const char *szName){
OGRFeatureH hFeature;
hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) );
OGR_F_SetFieldString( hFeature, OGR_F_GetFieldIndex(hFeature, "Name"), szName );
OGRGeometryH hPt;
hPt = OGR_G_CreateGeometry(wkbPoint);
OGR_G_SetPoint_2D(hPt, 0, x, y);
OGR_F_SetGeometry( hFeature, hPt );
OGR_G_DestroyGeometry(hPt);
if( OGR_L_CreateFeature( hLayer, hFeature ) != OGRERR_NONE ){
printf( "Failed to create feature in shapefile.\n" );
exit(1);
}
OGR_F_Destroy( hFeature );
};
试图将其更改为多边形。没有错误打印,但没有保存shapefile。
void addPolygon(OGRLayerH hLayer, double *x, double *y, const char *szName){
OGRFeatureH hFeature;
hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) );
OGR_F_SetFieldString(hFeature, OGR_F_GetFieldIndex(hFeature, "Name"), szName);
OGRGeometryH hGeo;
hGeo = OGR_G_CreateGeometry(wkbLineString);
cout << "Performing for loop" << endl;
for (int i=0; i < 4; i++){
OGR_G_SetPoint_2D(hGeo, 0, x[i], y[i]);
}
OGR_G_CloseRings(hGeo);
hGeo = OGR_G_ForceToPolygon(hGeo);
if( OGR_L_CreateFeature( hLayer, hFeature ) != OGRERR_NONE ){
printf( "Failed to create feature in shapefile.\n" );
exit(1);
}
OGR_F_Destroy( hFeature );
return;
};
答案 0 :(得分:0)
函数OGR_G_SetPoint_2D需要该点的索引i。如果所有索引均为0,它将绘制一个点而不是一个多边形。这对我有用:
void addPolygon(OGRLayerH hLayer, double *x, double *y, int n, const char *szName)
{ OGRFeatureH hFeature=OGR_F_Create(OGR_L_GetLayerDefn(hLayer));
OGR_F_SetFieldString(hFeature,OGR_F_GetFieldIndex(hFeature,"Name"),szName);
OGRGeometryH hGeo=OGR_G_CreateGeometry(wkbLinearRing);
printf("Performing LinearRing of %d vertices\n",n);
for(int i=0;i<n;i++) { OGR_G_SetPoint_2D(hGeo,i,x[i],y[i]); }
OGR_G_CloseRings(hGeo);
hGeo=OGR_G_ForceToPolygon(hGeo);
OGR_F_SetGeometry(hFeature,hGeo);
OGR_G_DestroyGeometry(hGeo);
if(OGR_L_CreateFeature(hLayer,hFeature) != OGRERR_NONE)
{ printf("Failed to create feature in shapefile.\n"); exit(1); }
OGR_F_Destroy(hFeature);
return;
}