[GIS] GDAL/Shapely how to use representative_point()

gdalpython-2.7shapely

I am trying to create a single point inside each polygon of a dataset using shapely's representative_point() function. According to the documentation here it is called on a geometry object, so it should work similarly to calling Centroid() on a geometry object. However, when I try to do so I get:

AttributeError: 'Geometry' object has no attribute 'representative_point()'.

import shapely
...

    for bld in xrange(bld_layer.GetFeatureCount()):
        bld_feat = bld_layer.GetFeature(bld)
        bld_geom = bld_layer.GetGeometryRef()
        bld_point = bld_geom.representative_point()
        ...

UPDATE

Based on the comments and after more searching a combination of Fiona and Shapely (here) seems to work:

import fiona
from shapely.geometry import shape, mapping

src = r'C:\data\segments.shp' 
out = r'C:\data\segments_points.shp' 
data = fiona.open(src, 'r')
data_schema = data.schema
data_schema['geometry'] = 'Point'
with fiona.open(out, 'w', crs = data.crs, driver = data.driver, schema = data_schema) as dst:
    for f in data:
        point = shape(f['geometry']).representative_point()
        f['geometry'] = mapping(point)
        dst.write(f)

Best Answer

If you want to mix GDAL/OGR and Shapely you need specifically use 'loads' method from shapely.wkt python module. For instance, next code does the job:

from osgeo import ogr
from shapely.wkt import loads

path = '/home/zeito/pyqgis_data/polygon8.shp'

dataSource = ogr.Open(path, 1)
layer = dataSource.GetLayer()

for feature in layer:
    geom = feature.GetGeometryRef()
    print loads(geom.ExportToWkt()).representative_point()

dataSource = None

After running it, it was printed at Python Console each representative_point in WKT format.

enter image description here