forked from grvlbit/stringart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bresenham.py
58 lines (46 loc) · 1.21 KB
/
bresenham.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
def bresenham_path(start, end, shape):
"""
Bresenham's Line Algorithm
Produces an numpy array
"""
# Setup initial conditions
x1, y1 = start
x2, y2 = end
x1 = max(0, min(round(x1), shape[0]-1))
y1 = max(0, min(round(y1), shape[1]-1))
x2 = max(0, min(round(x2), shape[0]-1))
y2 = max(0, min(round(y2), shape[1]-1))
dx = x2 - x1
dy = y2 - y1
# Prepare output array
path = []
if (start == end):
return path
# Determine how steep the line is
is_steep = abs(dy) > abs(dx)
# Rotate line
if is_steep:
x1, y1 = y1, x1
x2, y2 = y2, x2
# Swap start and end points if necessary and store swap state
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
# Recalculate differentials
dx = x2 - x1
dy = y2 - y1
# Calculate error
error = int(dx / 2.0)
ystep = 1 if y1 < y2 else -1
# Iterate over bounding box generating points between start and end
y = y1
for x in range(x1, x2 + 1):
if is_steep:
path.append([y, x])
else:
path.append([x, y])
error -= abs(dy)
if error < 0:
y += ystep
error += dx
return path