I've vector which looks something like this Line 1 Line 2

My question is how I can make it smoother/straighter with less points and curves.

Note: I've tried using simplify api from Shapely, but no luck.

Update: I'm actually creating a given line from polygon (using CenterLine python lib), and polygon is created using rasterio.features.shapes method which reads this bitmap.


bin_closing = ... # cleaned bitmap (https://drive.google.com/file/d/0BxZWwp6ZizJEVTBzVlEwc2lKeVE/view)
results = ({'geometry':s, 'properties': {'id': v}}
               for i, (s, v) in enumerate(shapes(bin_closing.astype(rasterio.uint8), mask=None, connectivity=8, transform=src.transform)))
    geoms = list(results)
    schema= {
      'geometry': 'LineString', 
      'properties': {'id': 'int'}
    with fiona.open('out-bin-closing.shp', 'w', crs=src.crs, driver='ESRI Shapefile', schema=schema) as output:
        for i, g in enumerate(geoms):
            poly = shape(g['geometry'])

            # id 1 is actually masked (black part) of bitmap, dont consider it
            if g['properties']['id'] == 1.0 and poly.is_valid:                

                # dont process small polygons
                if len(poly.exterior.coords) < 10:

                newline = {}

                # try smoothing polygon
                fx = poly.buffer(50, 2).buffer(-50, 3)

                if fx.is_empty:

                # create centerline from smoothen polygon
                geo = Centerline(fx, 10).createCenterline()

                if geo.is_empty:

                newline['geometry'] = mapping(geo)
                newline['properties'] = {'id': i + 1}
  • 1
    That simplify api is one valid alternative. It seems that you have done something wrong and you must give more details. – user30184 Mar 8 '17 at 9:58
  • @user30184, I've updated the question – sagarr Mar 8 '17 at 10:48
  • 1
    Add so much code that others can test it. A link to test data would be excellent. – user30184 Mar 8 '17 at 10:52
  • Please provide the code which does not work, and then we'll be able to help you out. – Devdatta Tengshe Mar 8 '17 at 10:56
  • added link to bitmap and code – sagarr Mar 8 '17 at 11:21

Solved by first applying shapely.ops.linemerge and then simplifying it. Patch code follows:

geo = Centerline(fx, 10).createCenterline()
# make a single line from multilinestring
line = shapely.ops.linemerge(geo)
# simplify
line = line.simplify(5)
  • 2
    Would be great if you could edit this answer to include the final code you used and the image of the result :) – Joseph Mar 9 '17 at 12:19
  • @Joseph done, kept it to the point, havent copy-pasted code as it is again. – sagarr Mar 13 '17 at 10:37

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.