Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute the centroid of a polygon in Python

I am wondering if there any algorithm where I can compute the center of a polygon in OSM because I've found that each polygon has a different parameters expression:

"POLYGON((-171379.35 5388068.23,-171378.8 5388077.59,-171368.44 5388076.82,-171368.89 5388067.46,-171379.35 5388068.23))"

"POLYGON((-171379.3 5374226.42,-171375.96 5374227.32,-171378.95 5374239.82,-171365.69 5374243.03,-171364.16 5374237.14,-171365.92 5374236.76,-171364.26 5374230.26,-171362.67 5374230.63,-171360.11 5374220.19,-171376.6 5374216.13,-171379.3 5374226.42))"

In this expression each one has a different number of parameters so how can i compute the centroid of it?

I am using the postgis to get the polygon information from the spatial information.

like image 803
user3623674 Avatar asked Feb 13 '23 00:02

user3623674


2 Answers

The polygons are described using WKT.

Using Python? Use Shapely.

from shapely import wkt
p1 = wkt.loads("POLYGON((-171379.35 5388068.23,-171378.8 5388077.59,
                -171368.44 5388076.82,-171368.89 5388067.46,
                -171379.35 5388068.23))")
p2 = wkt.loads("POLYGON((-171379.3 5374226.42,-171375.96 5374227.32,
                -171378.95 5374239.82,-171365.69 5374243.03,
                -171364.16 5374237.14,-171365.92 5374236.76,
                -171364.26 5374230.26,-171362.67 5374230.63,
                -171360.11 5374220.19,-171376.6 5374216.13,
                -171379.3 5374226.42))")
print(p1.centroid.wkt) # POINT (-171373.8710815240337979 5388072.5175872016698122)
print(p2.centroid.wkt) # POINT (-171370.4190352254081517 5374229.0108996396884322)
like image 136
Mike T Avatar answered Mar 07 '23 11:03

Mike T


You can use PostGIS functionality or for example the python lib shapely to realize it.

like image 34
MaM Avatar answered Mar 07 '23 13:03

MaM