16

I discovered shapely but I did not find how to calculated the center of gravity of a polygon!

Does someone have the solution?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Vianney Bailleux
  • 373
  • 2
  • 7
  • 15

3 Answers3

32

If your polygon has a uniform density, its center of mass coincides with its centroid. In shapely, the centroid can be directly calculated as:

from shapely.geometry import Polygon

P = Polygon([[0, 0], [1, 0], [1, 1], [0, 1]])

print(P.centroid)
#POINT (0.5 0.5)
ewcz
  • 12,819
  • 1
  • 25
  • 47
12

The above answer is right. But some times you do not want to work with such format. So to get the values you can use:

from shapely.geometry import Polygon
centroid =   list(Polygon([[0, 0], [1, 0], [1, 1], [0, 1]]).centroid.coords)
#[(0.5, 0.5)]

I have tested this method for more complex geometries and it works nicely.

5

A solution without shapely

You can also calculate it by hand, using just numpy.

import numpy as np

def polygon_area(xs, ys):
    """https://en.wikipedia.org/wiki/Centroid#Of_a_polygon"""
    # https://stackoverflow.com/a/30408825/7128154
    return 0.5 * (np.dot(xs, np.roll(ys, 1)) - np.dot(ys, np.roll(xs, 1)))

def polygon_centroid(xs, ys):
    """https://en.wikipedia.org/wiki/Centroid#Of_a_polygon"""
    xy = np.array([xs, ys])
    c = np.dot(xy + np.roll(xy, 1, axis=1),
               xs * np.roll(ys, 1) - np.roll(xs, 1) * ys
               ) / (6 * polygon_area(xs, ys))
    return c

print(polygon_centroid(xs=[0, 1, 1, 0], ys=[0, 0, 1, 1]),
      'expect: [.5, .5]')
print(polygon_centroid(xs=[0, 0, 2], ys=[1, -1, 0]),
      'expect: [2/3, 0]')
print(polygon_centroid(xs=[0, 0, 2], ys=[-1, 1, 0]),
      'expect: [2/3, 0]')

# https://wolfram.com/xid/0e5bspgmqyj9a5-cfx5ps
print(polygon_centroid(xs=[0, 1, 1.5, 1, 0, -.5], ys=[0, 0, .5, 1, 1, .5]),
      'expect: [.5, .5]')

Output

[0.5 0.5]          expect: [.5, .5]
[0.66666667 -0. ]  expect: [2/3, 0]
[0.66666667 0.  ]  expect: [2/3, 0]
[0.5 0.5]          expect: [.5, .5]
petezurich
  • 9,280
  • 9
  • 43
  • 57
Markus Dutschke
  • 9,341
  • 4
  • 63
  • 58