shp文件转换为CAD文件(dxf格式)

文摘   2024-08-29 18:53   广东  


今天晚上来试一下SHP文件转换为CAD文件。

看到一个粉丝留言说能不能实现arcgis图斑转CAD填充的代码。

首先我对CAD不熟,基本没接触过,查了查DWG是CAD的专有文件。在网上查资料又发现CAD软件支持DXF格式。

昨天写了《三种通过代码创建矢量文件的方法及例子》,依稀记得geopandas就支持shp转为dxf格式。

事情好像闭环了起来。

立刻改了改代码,代码如下:

import osimport geopandas as gpd
class Shp2Dxf: def __init__(self, in_file): self.in_file = in_file self.out_file = os.path.splitext(in_file)[0] + '.DXF'
def shp2dxf(self) -> None: out_data = gpd.read_file(self.in_file) crs = out_data.crs out_data = gpd.GeoSeries(out_data.geometry, crs=crs) out_data.to_file(self.out_file, driver='DXF', encoding="utf-8") print("successfully convert shapefile to dxf")if __name__ == '__main__': in_file = r'd://temp/create_shp_by_fiona.shp'
converter = Shp2Dxf(in_file) converter.shp2dxf()

输入文件是一个shp文件,在qgis打开如下:


运行完程序后,会在输入文件所在的文件夹,生成一个dxf文件。

立刻下载CAD2007版软件,完成安装后,CAD2007打开该dxf文件如下:

因为很久不用CAD了,CAD软件也是刚刚安装的。所以无法判断这个结果是否正确,无法验证是否转换程序是否正确。

我去问了一下 文心一言,CAD有WGS84坐标吗?

看它回答我有点晕。。。

又问了一下 文心一言,DXF有地理坐标吗?

暂时先这样,没接触过CAD,不知道这些也是正常的。

再改改代码,把输入参数改为从命令行获取,然后把程序打包一下,方便使用。

import osimport geopandas as gpd
class Shp2Dxf: def __init__(self, in_file): self.in_file = in_file self.out_file = os.path.splitext(in_file)[0] + '.DXF'
def shp2dxf(self) -> None: out_data = gpd.read_file(self.in_file) crs = out_data.crs out_data = gpd.GeoSeries(out_data.geometry, crs=crs) out_data.to_file(self.out_file, driver='DXF', encoding="utf-8") print("successfully convert shapefile to geojson")if __name__ == '__main__': # in_file = r'd://temp/create_shp_by_fiona.shp' in_file = input("输入shp文件路径:") try: converter = Shp2Dxf(in_file) converter.shp2dxf() except Exception as e: print(e)


然后程序打包需要一个图标,在网上找一个小图标,下载到本地,命名为ico.png。

然后在程序所在的文件夹输入:cmd

进入命令行,在命令行终端打包,用pyinstaller打包。

使用说明如下:

输入:shp文件路径

输出为:在同文件夹下生成一个dxf文件。

程序已上传到baidu云盘,链接是

通过网盘分享的文件:shp2dxf.exe

链接: https://pan.baidu.com/s/1ht1ag-DR2ygI80i6uBpjhA?pwd=47bk 提取码: 47bk

文件链接在一个月后过期。


remote sensing
一个专注于测绘、地信、遥感的公众号
 最新文章