使用Python实现从CAD中选择多段线并提取坐标

使用Python实现从CAD中选择多段线并提取坐标

直接上代码案例

import pythoncom
import win32com.client

def vtpnt(x, y, z=0):
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y, z))


def vtobj(obj):
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_DISPATCH, obj)


def vtfloat(lst):
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, lst)

def selectObject():
    polylineCoord = []
    wincad = win32com.client.Dispatch("AutoCAD.Application")
    doc = wincad.ActiveDocument
    msp = doc.ModelSpace
    try:
        doc.SelectionSets.Item("SS1").Delete()
    except:
        print("Delete selection failed")
    slt = doc.SelectionSets.Add("SS1")
    doc.Utility.Prompt("请选择多段线,右键结束\n")
    slt.SelectOnScreen()
    if slt.Count == 0:
        doc.Utility.Prompt("未选择对象!\n")
    else:
        entity = slt[0]
        name = entity.EntityName
        for i in range(len(entity.Coordinates)):
            polylineCoord.append(round(entity.Coordinates[i]))
    # 坐标分组
    polylineCoord = [polylineCoord[x:x+2] for x in range(0,len(polylineCoord),2)]
    print(polylineCoord)


if __name__ == '__main__':
    selectObject()

运行步骤:

  1. 在Python中右键,点击Run
    在这里插入图片描述
  2. 在CAD中通过鼠标选择多段线对象,按空格键结束在这里插入图片描述
  3. 结束
    运行结果(坐标在程序中做了不保留小数点,如要保留可以自行更改):
[[54154, 9795], [54066, 9795], [54066, 9795], [54026, 9795], [51204, 9795], [51164, 9795], [49764, 9795], [49764, 5407], [49991, 5407], [49991, 4833], [49764, 4833], [49764, 3397], [53322, 3185], [53322, 3185], [53322, 3185], [54154, 3140]]

该结果为多段线坐标,坐标顺序为从多段线的起点开始到终点,该顺序也与CAD中查看该多段线特性时显示的顶点顺序一致。
在CAD中查看多段线顶点坐标的方法:
选择多段线对象,右键选择特性查看
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42455308/article/details/127668845
今日推荐