Home > Enterprise >  How to extract coordinates from Sympy Polygon as a List
How to extract coordinates from Sympy Polygon as a List

Time:10-07

I have got a Sympy Polygon after splitting given polygon to two polygons. I am wondering how to extract the coordinates of upper or lower polygons as a list of coordinates back like polycord.

from sympy import Polygon, Line
polycord=[(0, 0),
 (100, 0),
 (100, 300),
 (0, 300),
 (0, 0)]
T_sec= Polygon(*polycord)
t = T_sec.cut_section(Line((0, 200), slope=0))
upper_segment, lower_segment = t
poly_up=upper_segment
poly_up  # how to express this as a list like polycord

Thanks.

CodePudding user response:

In this case, you can call tuple on the vertices of the polygons:

from sympy import Polygon, Line

polycord = [(0, 0),
            (100, 0),
            (100, 300),
            (0, 300),
            (0, 0)]
T_sec = Polygon(*polycord)
upper_segment, lower_segment = T_sec.cut_section(Line((0, 200), slope=0))

uppercord = [tuple(v) for v in upper_segment.vertices]
# [(100, 200), (100, 300), (0, 300), (0, 200)]
lowercord = [tuple(v) for v in lower_segment.vertices]
# [(0, 0), (100, 0), (100, 200), (0, 200)]

Note that in more general cases, the coordinates could be symbolic (e.g. containing fractions), or they could be 3D.

Here is a more general approach:


from sympy import Polygon, Line, N

polycord = [(0, 0),
            (100, 0),
            (100, 300),
            (0, 300),
            (0, 0)]
T_sec = Polygon(*polycord)
upper_segment, lower_segment = T_sec.cut_section(Line((0, 200), slope=7))

uppercord = [tuple([N(vi) for vi in v]) for v in upper_segment.vertices]
lowercord = [tuple([N(vi) for vi in v]) for v in lower_segment.vertices]
# [(14.2857142857143, 300.0), (0, 300.0), (0, 200.0)]
# [(0, 0), (100.0, 0), (100.0, 300.0), (14.2857142857143, 300.0), (0, 200.0)]
  • Related