'Counting entities within a bounding box with ezdxf
I'm trying to select the densest (in terms contained elements) areas of a DXF layer in ezdxf.
These boxes are evenly spaced and shaped.
In other words: given a BoundingBox2d instance bbox, how to obtain number of entities (lines, poly lines, basically - everything) contained in ezdxf.layouts.layout.Modelspace instance msp within that bbox?
The msp variable contains modelspace with only one variable turned on.
Intuitively, it should be something like:
def count_elements_in_layer_and_bbox(msp: Modelspace, layer: str, bbox: BoundingBox2d) -> int
# turn off all layers but one
for l in msp.layers:
if layer == l.dxf.name:
l.on()
else:
l.off()
# get entities within the bbox - this is the line I don't know how to approach
entities = msp.intersect(bbox).dxf.entities
return len(enitites)
Solution 1:[1]
ezdxf is a DXF file format interface not a CAD application. So switching layers on/off has no influence on the content of the modelspace.
But ezdxf gives you other tools to select entities based on DXF attributes like the query() method. BTW a layer is just a DXF attribute and not a real container:
from ezdxf import bbox
def count_entities(msp, layer, selection_box):
count = 0
# select all entities of a certain layer
for e in msp.query(f"*[layer=='{layer}']"):
# put a single entity into a list to get its bounding box
entity_box = bbox.extents([e])
if selection_box.has_intersection(entity_box):
count += 1
return count
Read the docs for query() and also read the limitations of the bbox module.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozman |
