1

I want to segment a Polygon or PolyLine in segment of line and remove some segments. I have an polygon that i convert in polyline by the code below and it work well:

from shapely.geometry import mapping, LineString
import fiona as fn
import operator
from functools import reduce

with fn.open('multipolygon.shp', 'r') as source:
    source.profile['schema']['geometry'] = 'LineString'
    with fn.open('segment_line.shp', 'w', **source.meta) as sink:
        for feat in source:
            xcoords_poly = feat['geometry']['coordinates']
            liste_coords = reduce(operator.concat, xcoords_poly)
            lines = LineString(liste_coords)
            assert lines.is_valid
            assert lines.geom_type == 'LineString'
            feat['geometry'] = mapping(lines)
            sink.write(feat)

After this step i want to remove some segments (lines) of my polyline where they overlays with some polygons as this picture show it : enter image description here

For doing that i make the code below :

# great function that i find here to get coords of geometry
def pair(list):
'''Iterate over pairs in a list -> pair of points '''
for i in range(1, len(list)):
    yield list[i-1], list[i]

to_del = []
fn_obs = fn.open('obs.shp')
with fn.open('segment_line.shp', 'r') as source:
    with fn.open('avoid_obstacle.shp', 'w', **source.meta) as sink:
        for f in source:
            geom_f = shape(f['geometry'])
            try:
                for ob in fn_obs:
                    xob = shape(ob['geometry'])
                    if(geom_f.intersects(xob)):
                        to_keep = []

                        for seg_start, seg_end in pair(geom_f.coords):
                            line_start = Point(seg_start)
                            line_end = Point(seg_end)
                            segment = LineString([line_start.coords[0], line_end.coords[0]])
                            if(segment.intersects(xob)):
                                to_del.append(segment)
                            else:
                                to_keep.append(segment)
                        new_seg = linemerge(to_keep)
                        f['geometry'] = mapping(new_seg)                       
                sink.write(f)

            except (Exception):
                logging.exception("Error type of file:", f)

And i got this results : Result i got

It's like good but what i want it to remove all the line as this picture show it :enter image description here

Your Answer

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

Browse other questions tagged or ask your own question.