4

I've written an implementation of Bresenham's algorithm in Python (following the Wikipedia article), and it works correctly except for lines at certain angles. All lines that should extend between 45 and 90 degrees, or between 135 and 270 degrees, will instead extend along the line y = x.

Here's my code:

def bresenham(origin, dest):
    # debug code
    print origin
    print dest
    # end debug code
    x0 = origin[0]; y0 = origin[1]
    x1 = dest[0]; y1 = dest[1]
    steep = abs(y1 - y0) > abs(x1 - x0)
    backward = x0 > x1

    if steep:
        x0, y0 = y0, x0
        x1, y1 = y1, x1
    if backward:
        x0, x1 = x1, x0
        y0, y1 = y1, y0

    dx = x1 - x0
    dy = abs(y1 - y0)
    error = dx / 2
    y = y0

    if y0 < y1: ystep = 1 
    else: ystep = -1

    result = []
    #if x0 > x1: xstep = -1
    #else: xstep = 1
    # debug code
    print "x0 = %d" % (x0)
    print "x1 = %d" % (x1)
    print "y0 = %d" % (y0)
    print "y1 = %d" % (y1)
    for x in range(x0, x1):
        if steep: result.append((y,x))
        else: result.append((x,y))
        error -= dy
        if error < 0:
            y += ystep
            error += dx 
    # ensure the line extends from the starting point to the destination
    # and not vice-versa
    if backward: result.reverse()
    print result
    return result

Anyone see what I'm screwing up?


EDIT:

I added some printing code to the function.

(0,0) is at the top left of the display.

My test framework is pretty simple. It's a standalone function, so I just pass two points to it:

origin = (416, 384)
dest = (440, 347)
bresenham(origin, dest)
(416, 384)
(440, 347)
x0 = 384
x1 = 347
y0 = 416
y1 = 440
[]

Max
  • 1,295
  • 6
  • 16
  • 31
  • @aaa carp: Nope. Thanks for the answer, though. – Max Sep 15 '10 at 00:20
  • Aside from `if x0 > x1: xstep = -1` being unnecessary, I don't see anything wrong with your code, so your problem is likely to be elsewhere. You'll need to post your actual results so we can see what's happening. – Gabe Sep 15 '10 at 00:26
  • @Gabe: `xstep` is needed because without it, if `x0 > x1`, then the for loop will terminate immediately, as the default step for a Python for loop is 1. Aside from that, what kind of results do you want? When it goes wrong, it returns a list of points where each point is (1,1) above or below what came before it. – Max Sep 15 '10 at 00:45
  • 1
    Max: Please post a few sample inputs and the incorrect outputs they produce. You don't need to check for `if x0 > x1` because you swap `x0` and `x1` before that line runs. – Gabe Sep 15 '10 at 00:55
  • Silly Q: can you show your test framework (my Python-fu is all twisted up) and examples calls of it working and not working (that's just two lines of code). I don't think the data is crucial. – Jonathan Leffler Sep 15 '10 at 01:03
  • Also - which version of Python on which platform? Did you build it or download it? – Jonathan Leffler Sep 15 '10 at 01:04
  • @Gabe: I posted some sample inputs and outputs in a comment in Blaenk's answer. – Max Sep 15 '10 at 01:05
  • @Jonathan Leffler: I'm using Python 2.6 on Ubuntu 9.10. – Max Sep 15 '10 at 01:13
  • I posted the solution by the way. – Jorge Israel Peña Sep 15 '10 at 01:14

3 Answers3

4

I don't know why you're using an xstep variable. You don't really need one with the algorithm you're using.

@Gabe: xstep is needed because without it, if x0 > x1, then the for loop will terminate immediately, as the default step for a Python for loop is 1.

The reason you don't need an xstep variable is because, if it's going backwards, the coordinates were already switched (in the if backward: conditional at the beginning) so that the end-point is now the start-point and vice-versa, such that we now are still going left-to-right.

You just need this:

result = []

for x in range(x0, x1):
    if steep: result.append((y, x))
    else: result.append((x, y))
    error -= dy
    if error < 0:
        y += ystep
        error += dx

return result

If you want the list of coordinates in order from start to end-point, then you can do the check at the end:

if backward: return result.reverse()
else: return result

EDIT: The problem is that the backward boolean is being evaluated before it needs to be. If the steep conditional executes, then the values change, but by then your backward conditional is different. To fix this, instead of using a backward boolean, make it an explicit expression:

if x0 > x1:
    # swapping here

Then again, since you end up using the boolean later on, you could just define it before the conditional:

backward = x0 > x1

if backward:
Jorge Israel Peña
  • 36,800
  • 16
  • 93
  • 123
  • Originally I had it like you were suggesting, but when I tried to make a line in the angles mentioned in my question, the function would return nothing, since the for loop would terminate immediately. `xstep` was a fix for that. Perhaps that's indicative of something else wrong with my implementation? – Max Sep 15 '10 at 00:48
  • The loop shouldn't fail because remember, we swapped the coordinates such that it's still going from left-to-right (ex. x0, x1 = x1, x0). Perhaps you should print out x0 and x1 before the loop to verify. – Jorge Israel Peña Sep 15 '10 at 00:50
  • I did, and x0 was indeed greater than x1. – Max Sep 15 '10 at 00:53
  • @Max: your comment here suggests that the range is not set correctly. Have you printed the x0, x1, y0, y1 values you end up with? The whole point of the algorithm is that it works with increasing x values. If x0 > x1 when you do the range, then you'd end up with an empty range - and a quick loop. – Jonathan Leffler Sep 15 '10 at 00:56
  • Yeah. Think about it. The conditional at the top checks to see if x0 > x1, and IF IT IS, then it swaps them. So in no way should the loop's range consider that x0 > x1, do you see the disconnect here? Perhaps your swapping isn't working. Do what Jonathan said and print out the values to verify. – Jorge Israel Peña Sep 15 '10 at 00:58
  • I realized you guys were right after I thought about it a bit. Something must be more wrong than I thought. Here's some printouts from the algorithm. origin: (416, 384) dest = (440, 347) x0 = 384, x1 = d47, y0 = 416, y1 = 440. Does that shed any light on the subject? – Max Sep 15 '10 at 01:02
  • Turns out it was a pretty simple problem that I overlooked. It took me some scratch paper and a pencil to run it through my head to see the problem xD – Jorge Israel Peña Sep 15 '10 at 01:13
  • Yes, it was fairly obvious once I looked at the test data. – Gabe Sep 15 '10 at 01:16
4

The problem is that you are computing x0 > x1 before you swap x and y.

Instead of:

backward = x0 > x1 

if steep: 
    x0, y0 = y0, x0 
    x1, y1 = y1, x1 
if backward: 
    x0, x1 = x1, x0 
    y0, y1 = y1, y0 

You should have:

if steep: 
    x0, y0 = y0, x0 
    x1, y1 = y1, x1 

backward = x0 > x1 
if backward: 
    x0, x1 = x1, x0 
    y0, y1 = y1, y0 
Gabe
  • 84,912
  • 12
  • 139
  • 238
  • 1
    Guess I don't deserve even a measly upvote for all the work I did, side from the fact I posted the solution before him ;_; Props to Gabe though for spotting it too :) – Jorge Israel Peña Sep 15 '10 at 01:17
  • @Blaenk. Sorry, you're right. Got it a whole minute earlier. Fixed, and upvoted to boot. Thanks for your help. :) – Max Sep 15 '10 at 01:38
0

Here is an implementation I am using, which is much faster than pure Python thanks to numba

from numba import njit
from typing import Tuple
import numpy as np


@njit
def bresenham_numba(x0, y0, x1, y1, w, h):
    dx = abs(x1 - x0)
    dy = abs(y1 - y0)
    sx = -1 if x0 > x1 else 1
    sy = -1 if y0 > y1 else 1
    err = dx - dy
    points = [(x0, y0)]
    while x0 != x1 or y0 != y1:
        e2 = err * 2
        if e2 > -dy:
            err -= dy
            x0 += sx
        if e2 < dx:
            err += dx
            y0 += sy
        points.append((x0, y0))

    points = [p for p in points if 0 <= p[0] < h and 0 <= p[1] < w]
    return points


def calculate_bresenham(start_point: Tuple[int, int], end_point: Tuple[int, int], resolution: Tuple[int, int]):
    w, h = resolution
    x0, y0 = start_point
    x1, y1 = end_point
    bresenham_list = bresenham_numba(x0, y0, x1, y1, w, h)
    return np.array(bresenham_list)

Gulzar
  • 23,452
  • 27
  • 113
  • 201