使用 ezdxf 计算边界框内的实体

Counting entities within a bounding box with ezdxf

我正在尝试 select ezdxf 中 DXF 层的最密集(就包含的元素而言)区域。 这些盒子的间距和形状均匀。

换句话说:给定一个 BoundingBox2d 实例 bbox,如何获取包含在 ezdxf.layouts.layout.Modelspace 实例 [=15] 中的实体数量(线、折线,基本上 - 所有东西) =] 在那个 bbox 里面? msp 变量包含仅打开一个变量的模型空间。

直觉上应该是这样的:

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)

ezdxf 是 DXF 文件格式接口,不是 CAD 应用程序。所以切换层 on/off 对模型空间的内容没有影响。

但是 ezdxf 为您提供了其他工具 select 基于 DXF 属性的实体,例如 query() 方法。顺便说一句,图层只是一个 DXF 属性,而不是真正的容器:


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

阅读 query() and also read the limitations of the bbox 模块的文档。