0

I am using opencv in c++ to extract a set of 2D points from an geospatial image. Using those points as vertex i want to create a polygon ESRI shapefile.

Gdal api tutorials (https://gdal.org/1.11/ogr/ogr_apitut.html) only have examples of how to create point and linestring shapefiles. Functions like "OGR_G_AddPoint_2D" do not work for polygon type shapefile.

I have a function that add a single point in a point Layer and works good.

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

Tried to change it for a polygon shape. No error is printed but no shapefile is saved.

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;
};
underfloor
  • 301
  • 3
  • 12

1 Answers1

0

Function OGR_G_SetPoint_2D requires the index i of the point. If all the indices are 0 it will draw a single point instead of a polygon. This works for me:

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