forked from springmeyer/arc.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bezier.py
87 lines (61 loc) · 2.23 KB
/
bezier.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from PIL import Image
import math
# http://stackoverflow.com/questions/3515909/question-about-the-implementation-of-bezier-curves
# draws a single point on our image
def drawPoint( img, loc, size=5, color=(0,0,0) ):
px = img.load()
for x in range(size):
for y in range(size):
xloc = loc[0] + x - size/2
yloc = loc[1] + y - size/2
px[ xloc, yloc ] = color
# draws a simple bezier curve with 4 points
def drawCurve( img, points ):
steps = 20
for i in range(steps):
t = i / float(steps)
xloc = math.pow(1-t,3) * points[0][0] \
+ 3*t*math.pow(1-t,2) * points[1][0] \
+ 3*(1-t)*math.pow(t,2) * points[2][0] \
+ math.pow(t,3) * points[3][0]
yloc = math.pow(1-t,3) * points[0][1] \
+ 3*t*math.pow(1-t,2) * points[1][1] \
+ 3*(1-t)*math.pow(t,2) * points[2][1] \
+ math.pow(t,3) * points[3][1]
drawPoint( img, (xloc,yloc), size=2 )
# draws a bezier curve with any number of points
def drawBezier( img, points ):
for i in range(0,len(points),3):
if( i+4 < len(points) ):
drawCurve( img, points[i:i+4] )
# draws a smooth bezier curve by adding points that
# force smoothness
def drawSmoothBezier( img, points ):
newpoints = []
for i in range(len(points)):
# add the next point (and draw it)
newpoints.append(points[i])
drawPoint( img, points[i], color=(255,0,0) )
if( i % 2 == 0 and i>0 and i+1<len(points) ):
# calculate the midpoint
xloc = (points[i][0] + points[i+1][0]) / 2.0
yloc = (points[i][1] + points[i+1][1]) / 2.0
# add the new point (and draw it)
newpoints.append( (xloc, yloc) )
drawPoint( img, (xloc, yloc), color=(0,255,0) )
drawBezier( img, newpoints )
# Create the image
myImage = Image.new("RGB",(627,271),(255,255,255))
# Create the points
points = [ (54,172),
(121,60),
(220,204),
(284,56),
(376,159),
(444,40),
(515,228),
(595,72) ]
# Draw the curve
drawSmoothBezier( myImage, points )
# Save the image
myImage.save("myfile.png","PNG")