python bresenham line algorithm

Solutions on MaxInterview for python bresenham line algorithm by the best coders in the world

showing results for - "python bresenham line algorithm"
Felix
07 Jul 2020
1def get_line(start, end):
2    """Bresenham's Line Algorithm
3    Produces a list of tuples from start and end
4 
5    >>> points1 = get_line((0, 0), (3, 4))
6    >>> points2 = get_line((3, 4), (0, 0))
7    >>> assert(set(points1) == set(points2))
8    >>> print points1
9    [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
10    >>> print points2
11    [(3, 4), (2, 3), (1, 2), (1, 1), (0, 0)]
12    """
13    # Setup initial conditions
14    x1, y1 = start
15    x2, y2 = end
16    dx = x2 - x1
17    dy = y2 - y1
18 
19    # Determine how steep the line is
20    is_steep = abs(dy) > abs(dx)
21 
22    # Rotate line
23    if is_steep:
24        x1, y1 = y1, x1
25        x2, y2 = y2, x2
26 
27    # Swap start and end points if necessary and store swap state
28    swapped = False
29    if x1 > x2:
30        x1, x2 = x2, x1
31        y1, y2 = y2, y1
32        swapped = True
33 
34    # Recalculate differentials
35    dx = x2 - x1
36    dy = y2 - y1
37 
38    # Calculate error
39    error = int(dx / 2.0)
40    ystep = 1 if y1 < y2 else -1
41 
42    # Iterate over bounding box generating points between start and end
43    y = y1
44    points = []
45    for x in range(x1, x2 + 1):
46        coord = (y, x) if is_steep else (x, y)
47        points.append(coord)
48        error -= abs(dy)
49        if error < 0:
50            y += ystep
51            error += dx
52 
53    # Reverse the list if the coordinates were swapped
54    if swapped:
55        points.reverse()
56    return points