2

I have a shapefile with geometries of different regions. Also I have a list of coordinate points(field_lonlat), I want to consider only those points of the list which are outside the polygon geometries using python. Below is my code to check it but trying to find a simpler version of it.

from osgeo import ogr
from shapely.geometry import Point
from shapely.prepared import prep
from shapely.wkb import loads
import json
g = ogr.Open("Polygons.shp")
points = []
for layer in g.GetLayer(0):
    field = loads(layer.GetGeometryRef().ExportToWkb())
    fieldP = prep(field)
    for x,y in field_lonlat: //field_lonlat is my list of points 
        item = Point(x, y)
        if fieldP.contains(item):
            pass
        else:
            points.append((x,y))

But my points list checks for a single polygon once and hence considers only those points which are not in it but which might be inside an another polygon.

2

I think this would make slightly more sense :

from osgeo import ogr
from shapely.geometry import Point
from shapely.prepared import prep
from shapely.wkb import loads
import json

g = ogr.Open("Polygons.shp")
list_to_remove = []
points = field_lonlat[:] # make a copy of the list
for x,y in field_lonlat: 
    item = Point(x,y)
    for layer in g.GetLayer(0):
        field = loads(layer.GetGeometryRef().ExportToWkb())
        fieldP = prep(field)
        if fieldP.contains(item):
            # remove points that are in one of the polygons
            points.remove((x,y))
            # break to avoid checking every polygon if you're already inside of one
            break
7
  • 1
    I came up with the same idea but : if multiple points are inside one polygone, the break only remove the first point. And for a more Pythonic writing : points = field_lonlat.copy(). Aug 27 '20 at 12:16
  • sorry, i really like slicing (it is real fast!) x), it really shouldn't remove only the first point, since the break is only on the inside loop, every single point of the list should be checked against the polygons Aug 27 '20 at 12:24
  • Sorry, I didn't realize that you inverted the two loops ! Aug 27 '20 at 12:55
  • Also, how can I say that point is outside the geometry if it's on the geometry of the polygon as we are only checking the inside condition. Aug 27 '20 at 13:20
  • in the points list we remove every single points that are inside one/multiple of the polygons. So at the end we end up with a list contained only the points that have been found to NOT be inside any of the polygons Aug 27 '20 at 13:24

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.