How to calculate area of closed contour #1139
Answered
by
gswifort
dizzysan84
asked this question in
Q&A
-
Hello, I get an dxf file from metal forming simulation software with closed contour of billet made by LINES entities. Could you please guide my how to calculate area of the contour? I have check @catalinanesia thread but it doesn't work in my case as consider only LWPOLYLINE and POLYLINE. |
Beta Was this translation helpful? Give feedback.
Answered by
gswifort
Aug 4, 2024
Replies: 1 comment 2 replies
-
Check this solution. import ezdxf
import ezdxf.entities
import numpy as np
import shapely
def get_vertices(ents):
for ent in ents:
if isinstance(ent, ezdxf.entities.Line):
yield tuple(ent.dxf.start)[:2], tuple(ent.dxf.end)[:2]
elif isinstance(ent, ezdxf.entities.LWPolyline):
yield tuple(ent.vertices())
def iter_sorted(vertices, order):
_order = dict(order)
p1, p2 = _order.popitem()
yield from vertices[p1][:-1]
yield from vertices[p2][:-1]
while _order:
p2 = _order.pop(p2)
yield from vertices[p2][:-1]
def main():
doc = ezdxf.readfile(r"d:\Users\GSWI\Download\Contour1.dxf")
msp = doc.modelspace()
ents = msp.query("LINE LWPOLYLINE")
vertices = tuple(get_vertices(ents))
start = np.array([i[0] for i in vertices])
end = np.array([i[-1] for i in vertices])
se_match = np.all(np.isclose(start[:, None], end), axis=-1)
assert np.all(np.sum(se_match, axis=-1) == 1)
match_pos = np.argmax(se_match, axis=-1)
order = np.hstack((match_pos[:, None], np.arange(match_pos.shape[0])[:, None]))
polygon = shapely.Polygon(tuple(iter_sorted(vertices, order)))
print(f"Area: {polygon.area}")
if __name__ == "__main__":
main() |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can also do it simpler :)