1

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)
  • 2
    You are mixing GDAL and Shapely. A GDAL Geometry is not a Shapely geometry. – bugmenot123 Aug 14 '17 at 10:01
  • If you want to mix GDAL/OGR and Shapely you need specifically use 'loads' method from shapely.wkt python module. – xunilk Aug 14 '17 at 13:54
1

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

  • I found this method as well via the link below. However, I wasn't able to implement it thus I switched to the one above. But thank you for adding another option. link: gis.stackexchange.com/questions/5405/… – Tins Aug 14 '17 at 13:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.