如何使用Python的PIL绘制贝塞尔曲线?

时间:2008-10-29 11:59:08

标签: python python-imaging-library bezier imaging

我正在使用Python的成像库,我想绘制一些贝塞尔曲线。 我想我可以逐像素计算,但我希望有更简单的东西。

5 个答案:

答案 0 :(得分:18)

def make_bezier(xys):
    # xys should be a sequence of 2-tuples (Bezier control points)
    n = len(xys)
    combinations = pascal_row(n-1)
    def bezier(ts):
        # This uses the generalized formula for bezier curves
        # http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization
        result = []
        for t in ts:
            tpowers = (t**i for i in range(n))
            upowers = reversed([(1-t)**i for i in range(n)])
            coefs = [c*a*b for c, a, b in zip(combinations, tpowers, upowers)]
            result.append(
                tuple(sum([coef*p for coef, p in zip(coefs, ps)]) for ps in zip(*xys)))
        return result
    return bezier

def pascal_row(n, memo={}):
    # This returns the nth row of Pascal's Triangle
    if n in memo:
        return memo[n]
    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))
    memo[n] = result
    return result

例如,这会引起一颗心:

from PIL import Image
from PIL import ImageDraw

if __name__ == '__main__':
    im = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) 
    draw = ImageDraw.Draw(im)
    ts = [t/100.0 for t in range(101)]

    xys = [(50, 100), (80, 80), (100, 50)]
    bezier = make_bezier(xys)
    points = bezier(ts)

    xys = [(100, 50), (100, 0), (50, 0), (50, 35)]
    bezier = make_bezier(xys)
    points.extend(bezier(ts))

    xys = [(50, 35), (50, 0), (0, 0), (0, 50)]
    bezier = make_bezier(xys)
    points.extend(bezier(ts))

    xys = [(0, 50), (20, 80), (50, 100)]
    bezier = make_bezier(xys)
    points.extend(bezier(ts))

    draw.polygon(points, fill = 'red')
    im.save('out.png')

答案 1 :(得分:11)

bezier曲线并不难以吸引自己。给定三个点ABC,您需要三个线性插值才能绘制曲线。我们使用标量t作为线性插值的参数:

P0 = A * t + (1 - t) * B
P1 = B * t + (1 - t) * C

这在我们创建的两条边之间插值,边AB和边BC。我们现在要做的唯一一件事就是计算我们必须绘制的点是在P0和P1之间使用相同的t进行插值,如下所示:

Pfinal = P0 * t + (1 - t) * P1

在我们实际绘制曲线之前,有几件事需要完成。首先,我们将走一些dt(delta t),我们需要注意0 <= t <= 1。正如您可能想象的那样,这不会给我们一条平滑的曲线,相反,它只会产生一组离散的位置。解决这个问题的最简单方法是在当前点和前一点之间画一条线。

答案 2 :(得分:8)

您可以在PIL顶部使用aggdraw,贝塞尔曲线为supported

修改

我举了一个例子,发现Path课程中存在关于curveto的错误:(

无论如何这是一个例子:

from PIL import Image
import aggdraw

img = Image.new("RGB", (200, 200), "white")
canvas = aggdraw.Draw(img)

pen = aggdraw.Pen("black")
path = aggdraw.Path()
path.moveto(0, 0)
path.curveto(0, 60, 40, 100, 100, 100)
canvas.path(path.coords(), path, pen)
canvas.flush()

img.save("curve.png", "PNG")
img.show()
如果您要重新编译模块,

This应该修复错误...

答案 3 :(得分:5)

虽然bezier curveto路径不能与Aggdraw一起使用,正如@ToniRuža所提到的,在Aggdraw中还有另一种方法可以做到这一点。使用Aggdraw而不是PIL或你自己的贝塞尔函数的好处是,Aggdraw将对图像进行抗锯齿处理,使其看起来更平滑(参见底部的图片)。

抽取符号

除了使用aggdraw.Path()类绘制之外,您可以使用基本相同的aggdraw.Symbol(pathstring)类,除非您将路径写为字符串。根据Aggdraw文档,将路径编写为字符串的方法是使用SVG路径语法(请参阅:http://www.w3.org/TR/SVG/paths.html)。基本上,路径的每个添加(节点)通常以

开头
  • 表示绘图操作的字母(绝对路径为大写,相对路径为小写),后跟(中间没有空格)
  • x坐标(如果是负数或方向,则前面带有减号)
  • 逗号
  • y坐标(如果是负数或方向,则前面带有减号)

在您的路径字符串中,只需用空格分隔多个节点即可。创建符号后,请记住将其作为draw.symbol(args)的参数之一传递给它。

Aggdraw符号中的Bezier曲线

特别是对于三次贝塞尔曲线,你写下字母“C”或“c”后跟6个数字(3组xy坐标x1,y1,x2,y2,x3,y3,数字之间有逗号但不是第一个数字和字母)。根据文档,还有其他bezier版本使用字母“S(平滑立方贝塞尔曲线),Q(二次贝塞尔曲线),T(平滑二次贝塞尔曲线)”。这是一个完整的示例代码(需要PIL和aggdraw):

print "initializing script"

# imports
from PIL import Image
import aggdraw

# setup
img = Image.new("RGBA", (1000,1000)) # last part is image dimensions
draw = aggdraw.Draw(img)
outline = aggdraw.Pen("black", 5) # 5 is the outlinewidth in pixels
fill = aggdraw.Brush("yellow")

# the pathstring:
#m for starting point
#c for bezier curves
#z for closing up the path, optional
#(all lowercase letters for relative path)
pathstring = " m0,0 c300,300,700,600,300,900 z"

# create symbol
symbol = aggdraw.Symbol(pathstring)

# draw and save it
xy = (20,20) # xy position to place symbol
draw.symbol(xy, symbol, outline, fill)
draw.flush()
img.save("testbeziercurves.png") # this image gets saved to same folder as the script

print "finished drawing and saved!"

输出是一个光滑的弯曲bezier图: Result from script above using aggdraw bezier curve symbol

答案 4 :(得分:0)

我发现了一种更简单的方法来创建贝塞尔曲线(没有aggraw且没有复杂的函数)。

import math
from PIL import Image
from PIL import ImageDraw

image = Image.new('RGB',(1190,841),'white')
draw = ImageDraw.Draw(image)
curve_smoothness = 100

#First, select start and end of curve (pixels)
curve_start = [(167,688)] 
curve_end = [(678,128)]

#Second, split the path into segments
curve = [] 
for i in range(1,curve_smoothness,1):
    split = (curve_end[0][0] - curve_start[0][0])/curve_smoothness
    x = curve_start[0][0] + split * i 
    curve.append((x, -7 * math.pow(10,-7) * math.pow(x,3) - 0.0011 * math.pow(x,2) + 0.235 * x + 682.68))

#Third, edit any other corners of polygon
other =[(1026,721), (167,688)]

#Finally, combine all parts of polygon into one list
xys = curve_start + curve + curve_end + other #putting all parts of the polygon together
draw.polygon(xys, fill = None, outline = 256)

image.show()