【python3】:轻松实现点阵数据 转DXF格式
本文只作为示例,通过从文本读取点阵数据,差值拟合并保存为DXF格式。
import numpy as np
from scipy.interpolate import CubicSpline
import ezdxf
def read_points_from_file(file_path):
coordinates = []
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
line = line.strip()
if line: # 确保行不为空
try:
x, y = map(float, line.split(','))
coordinates.append((x, y))
except ValueError:
print(f"跳过无效行: {line}")
return coordinates
# 从文件中读取点位数据
file_path = 'points.txt' # 替换为你的文件路径
coordinates = read_points_from_file(file_path)
def check_strictly_increasing(points):
"""
检查坐标点列表的x值是否是严格递增的,并打印不符合条件的数据点位信息
参数:
points: 坐标点列表,格式为 [(x1, y1), (x2, y2), ...]
返回值:
列表,包含所有违反规则的点的索引和坐标信息
"""
violations = []
# 确保至少有2个点才能比较
if len(points) < 2:
print("数据点不足,无法进行严格递增检查")
return violations
for i in range(1, len(points)):
prev_x = points[i-1][0]
current_x = points[i][0]
if current_x <= prev_x:
violation_info = (
f"在第 {i} 号点发现违反严格递增:\n"
f" 前一点:[索引 {i-1}] x={prev_x:.4f}\n"
f" 当前点:[索引 {i}] x={current_x:.4f}\n"
f"──────────────────"
)
violations.append({
"prev_index": i-1,
"current_index": i,
"prev_x": prev_x,
"current_x": current_x
})
print(violation_info)
if not violations:
print("所有数据点均满足严格递增要求")
return violations
# 执行检查 ---------------------------------------------------------
print("="*50 + "\n开始执行数据点严格递增检查:\n" + "="*50)
issue_points = check_strictly_increasing(coordinates)
print("\n检查完成,共发现 {} 处递增异常".format(len(issue_points)))
# 分离x(经度)和y(纬度)坐标
x = np.array([p[0] for p in coordinates])
y = np.array([p[1] for p in coordinates])
# 创建自然三次样条插值
cs = CubicSpline(x, y, bc_type='natural')
# 生成用于DWG的密集点集
num_points = 1000
xi = np.linspace(x.min(), x.max(), num_points)
yi = cs(xi)
# 创建新的DWG文件
doc = ezdxf.new('R2010') # 使用AutoCAD 2010格式
msp = doc.modelspace()
# 添加样条曲线实体
#spline = msp.add_spline(
# control_points=list(zip(xi, yi)), # 控制点列表
# degree=3, # 三次样条
# form=ezdxf.SPLINE_FORM_OPEN # 开放式曲线
#)
#
## 设置图层和颜色(可选)
#spline.layer = 'SPLINES'
#spline.color = 4 # 红色(AutoCAD颜色索引)
# 添加样条曲线(使用原始点作为拟合点)
spline = msp.add_spline(
fit_points=[(p[0], p[1]) for p in coordinates] # 关键修改
)
# 设置样式(根据需求调整)
spline.layer = 'SPLINES'
spline.color = 4 # 红色
# 保存为DWG文件
doc.saveas("output.dxf")
print("DWG文件已生成:output.dxf")