📌 函数作用一句话
把"距离过近"的节点(或端点)合并成一个,避免重复。
🎯 应用场景
-
节点去重
- 霍夫变换或交点计算后,同一物理节点 可能得到 多个像素级坐标(±1~3 px)。
- 例如:两条导线的交点被算成
(124, 200)
、(125, 201)
、(126, 200)
→ 需要合并为一个(125, 200)
。
-
端点聚类
- 元件边框与导线交点可能 密集成群(手绘粗细、锯齿)。
- 例如:一个引脚附近出现 5 个交点 → 合并成 1 个代表点。
-
可视化降噪
- 让最终 节点/端点的数量 = 实际电路点数,图更干净。
⚙️ 原理拆解
步骤 | 代码片段 | 解释 |
---|---|---|
1. 输入 | nodes = [(x1,y1), (x2,y2), ...] |
原始点列表,可能有重复/过近。 |
2. 转 NumPy | pts = np.array(nodes) |
方便广播计算欧氏距离。 |
3. 贪心聚类 | for i, p in enumerate(pts): ... |
每个未用点作为"种子",找所有距离 < eps 的点归为一组。 |
4. 计算新坐标 | np.round(np.mean(group, axis=0)) |
用组内点的几何中心作为合并后的新坐标,避免偏移。 |
5. 去重输出 | return list(set(...)) |
防止重复添加。 |
📏 参数 eps
怎么选?
场景 | 推荐 eps |
---|---|
手绘电路,像素粗 | 8 ~ 12 |
高清扫描/矢量图 | 3 ~ 5 |
不确定 | 先试 8 ,再视结果微调。 |
✅ 一句话总结
把"像素级误差"的多个点 → 聚类成"物理级"唯一节点/引脚。
bash
# 合并相邻节点
def merge_nearby_nodes(nodes, eps=10):
"""
合并相邻节点(欧氏距离 < eps)
输入:[(x1,y1), (x2,y2), ...]
输出:合并后的节点列表
"""
if not nodes:
return []
# 转成 numpy,便于广播计算
pts = np.array(nodes).reshape(-1, 2)
merged = []
used = np.zeros(len(pts), dtype=bool)
for i, p in enumerate(pts):
if used[i]:
continue
group = [p]
used[i] = True
for j, q in enumerate(pts[i+1:], start=i+1):
if not used[j] and np.linalg.norm(p - q) < eps:
group.append(q)
used[j] = True
# 取平均坐标作为合并后的节点
merged.append(tuple(np.round(np.mean(group, axis=0)).astype(int)))
return merged