Skip to main content

graphics - Bresenham's line algorithm


Bresenham's line algorithm is producing discretized line for given two points for purpose of plotting for example.



Like that:


enter image description here


I have to stress that I'm interested in positions, not a plot.


Wikipedia link I've provided includes an algorithm of course. I've just rewritten it thoughtlessly, I don't have time now or special need to work on neat implementation.


But if someone want to improve it (compile e.g.), got it already or know something more, I think this thread may be usefull for future visitors.


Very nice implementation can be found on rossetacode :P, according to that this algorithm should be built in so maybe someone knows how to get it.


Anyway, here's that code:


bresenham[{x1_, y1_}, {x2_, y2_}] := 
Module[{dx, xi, dy, yi, ai, bi, x, y, d},
If[x1 < x2, {xi, dx} = {1, x2 - x1};, {xi, dx} = {-1, x1 - x2};];

If[y1 < y2, {yi, dy} = {1, y2 - y1};, {yi, dy} = {-1, y1 - y2};];
x = x1; y = y1;
Sow[{x, y}];
If[dx > dy,
(ai = 2 (dy - dx); bi = 2 dy; d = bi - dx;
While[
If[d >= 0,
{x, y, d} += {xi, yi, ai},
{x, d} += {xi, bi}];
Sow[{x, y}];

x != x2])
,
(ai = 2 (dx - dy); bi = 2 dx; d = bi - dy;
While[
If[d >= 0,
{x, y, d} += {xi, yi, ai},
{y, d} += {yi, bi}];
Sow[{x, y}];
y != y2])
]] // Reap // Last // First


Answer



Original Bresenham


I guess I can come of with a somewhat shorter implementation without using Reap and Sow. If someone is interested, it follows almost exactly the pseudo-code here


bresenham[p0_, p1_] := Module[{dx, dy, sx, sy, err, newp},
{dx, dy} = Abs[p1 - p0];
{sx, sy} = Sign[p1 - p0];
err = dx - dy;
newp[{x_, y_}] :=
With[{e2 = 2 err}, {If[e2 > -dy, err -= dy; x + sx, x],
If[e2 < dx, err += dx; y + sy, y]}];

NestWhileList[newp, p0, # =!= p1 &, 1]
]

To test this I use the setup given by the comment of Kuba under this answer:


p1 = {17, 1}; p2 = {7, 25}; 
Graphics[{EdgeForm[{Thick, RGBColor[203/255, 5/17, 22/255]}],
FaceForm[RGBColor[131/255, 148/255, 10/17]],
Rectangle /@ (bresenham[p1, p2] - .5), {RGBColor[0, 43/255, 18/85],
Thick, Line[{p1, p2}]}},
GridLines -> {Range[150], Range[150]} - .5]


Mathematica graphics


Exercise implementation


What follows was only a fun project I did with my wife. Actually, this is not the original Bresenham algorithm. The task for this weekend-fun was to re-invent the algorithm (the iterative steps and the required correction steps) on the blackboard.


For simplicity this algorithm only makes correction steps in one direction (meaning the points stay always on one half-plane of the line) and therefore, the final points are not as close to the original line as with the real Bresenham algorithm.


Anyway, this is my Mathematica implementation of what my wife had to do in Python:


bresenham[p1 : {x1_, y1_}, p2 : {x2_, y2_}] := 
Module[{dx, dy, dir, corr, test, side},
{dx, dy} = p2 - p1;
dir = If[Abs[dx] > Abs[dy], {Sign[dx], 0}, {0, Sign[dy]}];

test[{x_, y_}] := dy*x - dx*y + dx*y1 - dy*x1;
side = Sign[test[p1 + dir]];
corr = side*{-1, 1}*Reverse[dir];
NestWhileList[
Block[{new = # + dir}, If[Sign[test[new]] == side, new += corr];
new] &, p1, #1 =!= p2 &, 1, 500]]

Here a small dynamic test whether the calculated points do indeed look like a line:


DynamicModule[{p = {{0, 0}, {50, 40}}},
LocatorPane[Dynamic[p],

Dynamic@
Graphics[{Line[bresenham @@ Round[p]], Red, PointSize[Large],
Dynamic[Point[p]]}, PlotRange -> {{-200, 200}, {-200, 200}},
ImageSize -> 400, Frame -> True, FrameTicks -> False,
GridLines -> True],
Appearance -> None
]
]



Mathematica graphics



Comments

Popular posts from this blog

plotting - How to draw lines between specified dots on ListPlot?

I would like to create a plot where I have unconnected dots and some connected. So far, I have figured out how to draw the dots. My code is the following: ListPlot[{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4,13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full] I have thought using ListLinePlot command, but I don't know how to specify to the command to draw only selected lines between the dots. Do have any suggestions/hints on how to do that? Thank you. Answer One possibility would be to use Epilog with Line : ListPlot[ {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4, 13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full, Epilog -> { Line[ ...

dynamic - How can I make a clickable ArrayPlot that returns input?

I would like to create a dynamic ArrayPlot so that the rectangles, when clicked, provide the input. Can I use ArrayPlot for this? Or is there something else I should have to use? Answer ArrayPlot is much more than just a simple array like Grid : it represents a ranged 2D dataset, and its visualization can be finetuned by options like DataReversed and DataRange . These features make it quite complicated to reproduce the same layout and order with Grid . Here I offer AnnotatedArrayPlot which comes in handy when your dataset is more than just a flat 2D array. The dynamic interface allows highlighting individual cells and possibly interacting with them. AnnotatedArrayPlot works the same way as ArrayPlot and accepts the same options plus Enabled , HighlightCoordinates , HighlightStyle and HighlightElementFunction . data = {{Missing["HasSomeMoreData"], GrayLevel[ 1], {RGBColor[0, 1, 1], RGBColor[0, 0, 1], GrayLevel[1]}, RGBColor[0, 1, 0]}, {GrayLevel[0], GrayLevel...

Is there a way to do conditional matrix loop using 'continue'

I have the following: n = 3; m = 5; ww = RandomReal[{0, 0.1}, {n, n}]; uu = RandomReal[{0, 1}, {m, n}]; pp = RandomReal[{0, 1}, {n, n}]; ss = RandomInteger[{0, 5}, {m, n}]; Grid[{{"ww", "uu", "pp", "ss"}, {ww // TableForm, uu // TableForm, pp // TableForm, ss // TableForm}}, Spacings -> {5, 2}, Dividers -> All] where I would like to look at every element of matrix ss and produce a matrix tt , with zeroes at the locations in ss which have zeroes, and in all other positions do the following: tt = (-1/Subscript[ww, m]) Log[(1 - uu)/(Subscript[pp, m - 1])], where Subscript[ww, m] is the value at index of ww matrix and where Subscript[pp, m - 1] is the value at index-1 of pp matrix. So for example if the first value ever read from matrix ss happens to be 2, then value taken from matrix ww would be from the row 2, but from pp would be from row 1. Also how to tell difference between a 0 as a valid value from within the matrix elemen...