Python SVG是否查找相邻、相邻或相交的路径?

2024-06-28 20:36:21 发布

您现在位置:Python中文网/ 问答频道 /正文

一项看似简单的任务让我头疼了好几个小时。。。 我的问题是,有没有一种方法可以使用python查找所有相邻、相邻或相交的路径?使用"svgpathtools"我还没有得到答案。 使用此代码:

p1 = Path("M159,511L154,511L150,514L147,515L145,519L149,523L149,523L150,523L150,523L153,523L156,526L157,527L159,527L159,526L160,524L163,522L163,518L163,516L162,517L159,512L160,512L159,511Z")
p2 = Path("M176,511L174,509L171,510L168,510L162,506L161,506L161,506L162,509L161,510L160,512L159,512L162,517L163,516L163,518L163,522L160,524L159,526L159,527L160,527L165,527L168,525L171,521L172,521L171,519L170,516L173,515L178,511L177,511L176,511Z")

intersections = []
for (T1, seg1, t1), (T2, seg2, t2) in p1.intersect(p2):
    intersections.append(p1.point(T1))
print(intersections)

我只得到“断言错误”。任何其他用python实现的方法都将不胜感激

我的猜测是,该函数将不起作用,因为没有交叉点,但生成的路径彼此相邻,因此,如果这些路径彼此相邻/是邻居,那么哪个函数将返回“True”


Tags: path方法函数答案代码路径fort1
1条回答
网友
1楼 · 发布于 2024-06-28 20:36:21

我用一个简单的JS处理了您的数据(参见下面的代码片段)。 您只需解析path字符串并计算两条路径中的公共点(共有9个)。如果至少有两个具有顺序索引的公共点,则路径是相邻的

&13; 第13部分,;
const getPathPoints = pathId => {
    const path = d3.select(`#${pathId}`).attr('d');
  
  const p = path.split(/[\s,MLZ]+/).slice(1, -1).reduce((all, coord, index) => {
  if (index % 2 === 0) 
    all.push({x: coord});
  else 
    all[all.length - 1].y = coord;
  return all;
  }, [])
  return p;
};

const first = getPathPoints('path1');
const second = getPathPoints('path2');
const common = first.reduce((all, point, index) => {
  const samePointIndex = second.findIndex(sp => sp.x === point.x && sp.y === point.y);
  if (samePointIndex >= 0)
    return {...all, [index]: samePointIndex};
  return all;  
}, {});

console.log('Common points: ', Object.keys(common).length);
svg {
  border: 1px solid red;
}

path {
  fill: none;
  stroke-opacity: 0.5;
}

#path1 {
  stroke: blue;
}

#path2 {
  stroke: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="200" height="150">
  <g transform="scale(5) translate(-140,-500)"> 
  <path id="path1" d="M159,511L154,511L150,514L147,515L145,519L149,523L149,523L150,523L150,523L153,523L156,526L157,527L159,527L159,526L160,524L163,522L163,518L163,516L162,517L159,512L160,512L159,511Z"/>
  <path id="path2" d=M176,511L174,509L171,510L168,510L162,506L161,506L161,506L162,509L161,510L160,512L159,512L162,517L163,516L163,518L163,522L160,524L159,526L159,527L160,527L165,527L168,525L171,521L172,521L171,519L170,516L173,515L178,511L177,511L176,511Z" />
  </g>
</svg>
和#13;
和#13;

相关问题 更多 >