如何将 SVG 路径插入 Python 中的像素坐标(不仅仅是光栅)

How to interpolate SVG path into a pixel coordinates (not simply raster) in Python

我需要转换路径的 SVG 描述,即。类似于:

M400 597 C235 599 478 607 85 554 C310 675 2 494 399 718 C124 547 569 828 68 400 C-108 317 304 703 96 218 L47 215 L400 290 C602 -146 465 467 550 99 L548 35 L706 400 L580 686 C546 614 591 672 529 629 L400 597 Z

进入将落在该路径上的所有像素的列表中(假设 canvas 是显示器的大小。如您所见,我需要处理的路径相当于涂鸦并且是相当复杂。理想情况下,我想生成这样的路径,然后将整个事物转换为逐像素描述,即。

p= [(403, 808), (403, 807), (403, 805), (403, 802), (403, 801), (403, 800), (403, 799), 
(403, 797), (403, 794), (403, 792), (402, 789), (401, 787), (400, 785), (399, 784), 
(399, 783), (398, 782)]  # ... it'd be much longer, but you get the idea

或者,我会满足于 any 生成具有曲线和直线成分的路径的方法(例如,SVG 就是我迄今为止实现这一目标的方式) .上下文有点特殊;这是一个认知心理学的实验,其中我需要逐渐动画一个点遍历根据特定规则生成的路径, 将该路径导出为像素数据。

为了制作动画,我打算简单地重绘路径上每个 x,y 位置的点——因此需要上述列表。

我的数学技能不是很好——我是从设计而不是 CS 开始编写代码的——而且路径会变得非常复杂,这意味着仅用数学计算这些点是……也许不会超出我的范围,但绝对比我的目标要求更高。

库、技巧、策略——都欢迎和赞赏。

我在 different post from unutbu(第二个答案)中找到了大部分答案。

这是我对他的基本功能的修改,加上一些额外的功能来解决我上面的问题。我必须为线段编写一个类似的函数,但这显然要容易得多,并且在它们之间将能够拼凑出曲线和直线段的任意组合以实现我如上所述的目标。

def pascal_row(n):
    # This is over my designer's brain, but unutbu says:
    # "This returns the nth row of Pascal's Triangle"
    result = [1]
    x, numerator = 1, n
    for denominator in range(1, n//2+1):
        # print(numerator,denominator,x)
        x *= numerator
        x /= denominator
        result.append(x)
        numerator -= 1
    if n&1 == 0:
        # n is even
        result.extend(reversed(result[:-1]))
    else:
        result.extend(reversed(result))
    return result


def bezier_interpolation(origin, destination, control_o, control_d=None):
        points = [origin, control_o, control_d, destination] if control_d else [origin, control_o, destination]
        n = len(points)
        combinations = pascal_row(n - 1)

        def bezier(transitions):
            # I don't really understand any of this math, but it works!
            result = []
            for t in transitions:
                t_powers = (t ** i for i in range(n))
                u_powers = reversed([(1 - t) ** i for i in range(n)])
                coefficients = [c * a * b for c, a, b in zip(combinations, t_powers, u_powers)]
                result.append(
                    list(sum([coef * p for coef, p in zip(coefficients, ps)]) for ps in zip(*points)))
            return result


        def line_segments(points, size):
            # it's more convenient for my purposes to have the pairs of x,y  
            # coordinates that eventually become the very small line segments 
            # that constitute my "curves
            for i in range(0, len(points), size):
                yield points[i:i + size]


        # unutbu's function creates waaay more points than needed, and 
        # these extend well through the "destination" point I want to end at, so,
        # I keep inspecting the line segments until one of them passes through 
        # my intended stop point (ie. "destination") and then manually stop 
        # collecting, returning the subset I want; probably not efficient,
        # but it works
        break_next = False  
        segments = []
        for pos in line_segments(bezier([0.01 * t for t in range(101)]), 2):
            if break_next:
                segments.append([break_next, destination])
                break
            try:
                if [int(i) for i in pos[0]] == destination:
                    break_next = pos[0]
                    continue
                segments.append(pos)
            except IndexError:
                # not guaranteed to get an even number of points from bezier()
                break
            return segments

出于某些奇怪的目的,我需要将 SVG 路径转换为离散点。显然没有这样做的灯光库。我最终创建了自己的解析器。

输入文件主要由贝塞尔曲线组成。我为此编写了一个快速函数:

def cubic_bezier_sample(start, control1, control2, end):
    inputs = np.array([start, control1, control2, end])
    cubic_bezier_matrix = np.array([
        [-1,  3, -3,  1],
        [ 3, -6,  3,  0],
        [-3,  3,  0,  0],
        [ 1,  0,  0,  0]
    ])
    partial = cubic_bezier_matrix.dot(inputs)

    return (lambda t: np.array([t**3, t**2, t, 1]).dot(partial))

def quadratic_sample(start, control, end):
    # Quadratic bezier curve is just cubic bezier curve
    # with the same control points.
    return cubic_bezier_sample(start, control, control, end)

生成10个样本的方法如下:

n = 10
curve = cubic_bezier_sample((50,0), (50,100), (100,100), (50,0))
points = [curve(float(t)/n) for t in xrange(0, n + 1)]

代码需要numpy。如果你愿意,你也可以在没有 numpy 的情况下进行点积。我可以使用 svg.path.

获取参数

完整代码示例

import numpy as np
import matplotlib.pyplot as plt

def cubic_bezier_sample(start, control1, control2, end):
    inputs = np.array([start, control1, control2, end])
    cubic_bezier_matrix = np.array([
        [-1,  3, -3,  1],
        [ 3, -6,  3,  0],
        [-3,  3,  0,  0],
        [ 1,  0,  0,  0]
    ])
    partial = cubic_bezier_matrix.dot(inputs)

    return (lambda t: np.array([t**3, t**2, t, 1]).dot(partial))

# == control points ==
start = np.array([0, 0])
control1 = np.array([60, 5])
control2 = np.array([40, 95])
end = np.array([100, 100])

# number of segments to generate
n_segments = 100
# get curve segment generator
curve = cubic_bezier_sample(start, control1, control2, end)
# get points on curve
points = np.array([curve(t) for t in np.linspace(0, 1, n_segments)])

# == plot ==
controls = np.array([start, control1, control2, end])
# segmented curve
plt.plot(points[:, 0], points[:, 1], '-')
# control points
plt.plot(controls[:,0], controls[:,1], 'o')
# misc lines
plt.plot([start[0], control1[0]], [start[1], control1[1]], '-', lw=1)
plt.plot([control2[0], end[0]], [control2[1], end[1]], '-', lw=1)

plt.show()

svg path interpolator JavaScript 库将 svg 路径转换为多边形点数据,并带有样本大小和保真度选项。这个库支持完整的 SVG 规范,并将考虑路径上的转换。它接受一个 svg 输入并产生 JSON 代表插值点。