pythonpolygonshapely

How to find the line that pass throughs the center point in polygon in Python?


I have a polygon shape like this enter image description here

And I want to find the red line from these array points enter image description here

The points are

array = [[4095, 2660],
   [4035, 2660],
   [3956, 2666],
   [3881, 2678],
   [3810, 2695],
   [3740, 2718],
   [3656, 2748],
   [3601, 2771],
   [3710, 2767],
   [3722, 2763],
   [3803, 2736],
   [3870, 2719],
   [3946, 2704],
   [4017, 2697],
   [4098, 2695],
   [4095, 2660]]

I try to do it using Shapely but I can't and the point not be exactly like this. I can't use two coordinate to find it


Solution

  • You could try pygeoops.centerline. It won't give the exact result you have drawn, as the centerline calculated e.g. won't touch the "ends" of the polygon. Nonetheless the result will be close or at least it will be a good start.

    Disclaimer: I am the developer of pygeoops.

    Code sample:

    import matplotlib.pyplot
    import pygeoops
    import shapely
    import shapely.plotting
    
    poly = shapely.Polygon(
        [
            [4095, 2660], [4035, 2660], [3956, 2666], [3881, 2678],
            [3810, 2695], [3740, 2718], [3656, 2748], [3601, 2771],
            [3710, 2767], [3722, 2763], [3803, 2736], [3870, 2719],
            [3946, 2704], [4017, 2697], [4098, 2695], [4095, 2660],
        ]
    )
    
    centerline = pygeoops.centerline(poly)
    shapely.plotting.plot_polygon(poly)
    shapely.plotting.plot_line(centerline)
    matplotlib.pyplot.show()
    

    Result: result of plot