1

我有一个由 5 条边组成的多边形。每条边都有自己的宽度,这里是在 0.2 到 0.5 之间随机生成的,用于说明目的。

代码

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.path import Path

import math as mt
import random

def buildRectPath(edge, width):
    theta = mt.atan((edge[1][1]-edge[0][1]) / (edge[1][0]-edge[0][0]+0.0000001)) # avoid ZeroDivisionError
    x_left_top = edge[0][0] - mt.sin(theta) * width
    y_left_top = edge[0][1] + mt.cos(theta) * width
    x_left_bottom = edge[0][0]
    y_left_bottom = edge[0][1]
    x_right_top = edge[1][0] - mt.sin(theta) * width
    y_right_top = edge[1][1] + mt.cos(theta) * width
    x_right_bottom = edge[1][0]
    y_right_bottom = edge[1][1]
    verts = [(x_left_bottom, y_left_bottom), # left, bottom
             (x_left_top, y_left_top), # left, top
             (x_right_top, y_right_top), # right, top
             (x_right_bottom, y_right_bottom), # right, bottom
             (x_left_bottom, y_left_bottom),] # ignored
    codes = [Path.MOVETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.CLOSEPOLY,]
    path = Path(verts, codes)
    return path

fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.axis('equal')
poly = [(1, 1), (2, 4), (4, 6), (6, 6), (8, 3), (1, 1)] # construct a random polygon
# expand each edge of the polygon (to different widths)
edges = [[(1, 1), (2, 4)], [(2, 4), (4, 6)], [(4, 6), (6, 6)], [(6, 6), (8, 3)], [(8, 3), (1, 1)]]
widths = [random.uniform(0.2, 0.5) for cnt in xrange(5)] # generate random widths for the 5 edges
for i, edge in enumerate(edges):
    axes.plot([edge[0][0], edge[1][0]], [edge[0][1], edge[1][1]], color='b')
    rectPath = buildRectPath(edge, widths[i])
    rectPatch = patches.PathPatch(rectPath, facecolor='yellow', alpha=0.5)
    axes.add_patch(rectPatch)

输出

在此处输入图像描述

目标

我想获得形状的平滑轮廓。基本上,我期待两条曲线,一条用于内环,另一条用于外环。

注意

  • 由于线条的宽度不同,我正在寻找的轮廓有点像一条考虑所有宽度的拟合线。
  • 目前,矩形之间存在间隙。轮廓应该是无间隙的连续曲线。
4

0 回答 0