Point in polygon using shapely?
Asked Answered
S

2

7

I am running the following script which I believe should be returning TRUE for the point being in the polygon but it is returning FALSE.

from shapely import geometry

polygon = [(-1571236.8349707182, 8989180.222117377), (1599362.9654156454, 8924317.946336618), (-1653179.0745812152, 8922145.163675062), (-1626237.6614402141, 8986445.107619021)]

Point_X = -1627875.474
Point_Y = 8955472.968

line = geometry.LineString(polygon)
point = geometry.Point(Point_X, Point_Y)

print(line.contains(point))

When I plot the polygon and point in Matlab I get the following shape

enter image description here

from matplotlib import pylab as plt
poly = [[-1571236.8349707182, 8989180.222117377],
    [1599362.9654156454, 8924317.946336618],
    [-1653179.0745812152, 8922145.163675062],
    [-1626237.6614402141, 8986445.107619021]]

x = [point[0] for point in poly]
y = [point[1] for point in poly]

p1 = [-1627875.474, 8955472.968]
p2 = [-1627875.474, 8955472.968]
plt.plot(x,y,p1[0],p1[1],'*r',p2[0],p2[1],'*b')
plt.show()

Any idea why the shapely script is returning FALSE?

Strained answered 11/9, 2018 at 17:15 Comment(2)
It might be because your shape isnt closed. It doesn't know if it's convex or concave, so it can't really make a shape out of what you've given it. You might need to make sure it begins and ends at the same point.Felten
I tried that -- unfortunately, I get the same answer (FALSE) when I add the beginning point as a fifth coordinate as well.Strained
M
20

What you are testing is whether your point is on the object LineString.

If you want to test that the point is in the polygon you must use the contains methods of class Polygon

from shapely import geometry

polygon = [(-1571236.8349707182, 8989180.222117377), (1599362.9654156454, 8924317.946336618), (-1653179.0745812152, 8922145.163675062), (-1626237.6614402141, 8986445.107619021)]

Point_X = -1627875.474
Point_Y = 8955472.968

line = geometry.LineString(polygon)
point = geometry.Point(Point_X, Point_Y)
polygon = geometry.Polygon(line)

print(polygon.contains(point))

ouput

True

see https://shapely.readthedocs.io/en/latest/manual.html

Margaux answered 11/9, 2018 at 19:58 Comment(1)
That works! Thanks so much -- I misunderstood the LineString object.Strained
A
0

This code uses geopandas to find point(s) within polygon(s).

import geopandas as gpd
points_gpd = gpd.GeoDataFrame(geometry=gpd.points_from_xy(x, y)) #point coordinates to geopandas dataframe
polygons_gpd = gpd.GeoDataFrame(geometry=polygons) #polygons is a list of shapely polygons
pt2poly = gpd.sjoin(points_gpd,polygons_gpd, predicate='within').index_right #for each point index in the points, it stores the polygon index containing that point
Acetyl answered 25/8, 2022 at 0:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.