Gathering Length of all DXF objects in python

84 views Asked by At

I am trying to write a script to pull the total length of all features in a dxf file using ezdxf and output the result

This is what I've written so far and I'm not getting accurate results when I do the math by hand. Any help would be appreciated!

import ezdxf
import math

# Load the DXF file
doc = ezdxf.readfile("Bumper Spacer.dxf")
msp = doc.modelspace()
lines = msp.query("LINE")
plines = msp.query("POLYLINE")
circles = msp.query("CIRCLE")
splines = msp.query("SPLINE")

perimeter = 0
# Iterate through entities and print their types
for entity in plines:
    points = list(entity.points())
    length = 0
    for i in range(len(points)):
        x1, y1, bulge = points[i]
        if i == len(points) - 1:
            x2, y2, _ = points[0]  # Connect the last point back to the first for a closed POLYLINE
        else:
            x2, y2, _ = points[i + 1]
        length = length + math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
        print(f"SEGMENT: {entity} X1: {x1} Y1: {y1} X2: {x2} Y2: {y2}")
    print(f"PLINE: {length}")
    perimeter = perimeter + length
for entity in circles:
    radius = entity.dxf.radius
    length = 2 * math.pi * radius
    print(f"CIRCLE: {length}")
    perimeter = perimeter + length
for entity in lines:
    length = math.sqrt((entity.dxf.start[0] - entity.dxf.end[0]) ** 2 + (entity.dxf.start[1] - entity.dxf.end[1]) ** 2)
    print(f"LINE: {length}")
    perimeter = perimeter + length
for entity in splines:
    puntos = entity.get_control_points()
    length = 0
    for i in range(len(puntos) - 1):
        length = length + math.sqrt((puntos[i][0] - puntos[i + 1][0]) ** 2 + (puntos[i][1] - puntos[i + 1][1]) **2 )
    print(f"SPLINE: {length}")
    perimeter = perimeter + length
print(perimeter)
0

There are 0 answers