Bresenham's line algorithm

Last updated

Bresenham's line algorithm is a line drawing algorithm that determines the points of an n-dimensional raster that should be selected in order to form a close approximation to a straight line between two points. It is commonly used to draw line primitives in a bitmap image (e.g. on a computer screen), as it uses only integer addition, subtraction, and bit shifting, all of which are very cheap operations in historically common computer architectures. It is an incremental error algorithm, and one of the earliest algorithms developed in the field of computer graphics. An extension to the original algorithm called the midpoint circle algorithm may be used for drawing circles.

Contents

While algorithms such as Wu's algorithm are also frequently used in modern computer graphics because they can support antialiasing, Bresenham's line algorithm is still important because of its speed and simplicity. The algorithm is used in hardware such as plotters and in the graphics chips of modern graphics cards. It can also be found in many software graphics libraries. Because the algorithm is very simple, it is often implemented in either the firmware or the graphics hardware of modern graphics cards.

The label "Bresenham" is used today for a family of algorithms extending or modifying Bresenham's original algorithm.

History

Bresenham's line algorithm is named after Jack Elton Bresenham who developed it in 1962 at IBM. In 2001 Bresenham wrote: [1]

I was working in the computation lab at IBM's San Jose development lab. A Calcomp plotter had been attached to an IBM 1401 via the 1407 typewriter console. [The algorithm] was in production use by summer 1962, possibly a month or so earlier. Programs in those days were freely exchanged among corporations so Calcomp (Jim Newland and Calvin Hefte) had copies. When I returned to Stanford in Fall 1962, I put a copy in the Stanford comp center library. A description of the line drawing routine was accepted for presentation at the 1963 ACM national convention in Denver, Colorado. It was a year in which no proceedings were published, only the agenda of speakers and topics in an issue of Communications of the ACM. A person from the IBM Systems Journal asked me after I made my presentation if they could publish the paper. I happily agreed, and they printed it in 1965.

Method

Illustration of the result of Bresenham's line algorithm. (0,0) is at the top left corner of the grid, (1,1) is at the top left end of the line and (11, 5) is at the bottom right end of the line. Bresenham.svg
Illustration of the result of Bresenham's line algorithm. (0,0) is at the top left corner of the grid, (1,1) is at the top left end of the line and (11, 5) is at the bottom right end of the line.

The following conventions will be utilized:

The endpoints of the line are the pixels at and , where the first coordinate of the pair is the column and the second is the row.

The algorithm will be initially presented only for the octant in which the segment goes down and to the right ( and ), and its horizontal projection is longer than the vertical projection (the line has a positive slope less than 1). In this octant, for each column x between and , there is exactly one row y (computed by the algorithm) containing a pixel of the line, while each row between and may contain multiple rasterized pixels.

Bresenham's algorithm chooses the integer y corresponding to the pixel center that is closest to the ideal (fractional) y for the same x; on successive columns y can remain the same or increase by 1. The general equation of the line through the endpoints is given by:

.

Since we know the column, x, the pixel's row, y, is given by rounding this quantity to the nearest integer:

.

The slope depends on the endpoint coordinates only and can be precomputed, and the ideal y for successive integer values of x can be computed starting from and repeatedly adding the slope.

In practice, the algorithm does not keep track of the y coordinate, which increases by m = ∆y/∆x each time the x increases by one; it keeps an error bound at each stage, which represents the negative of the distance from (a) the point where the line exits the pixel to (b) the top edge of the pixel. This value is first set to (due to using the pixel's center coordinates), and is incremented by m each time the x coordinate is incremented by one. If the error becomes greater than 0.5, we know that the line has moved upwards one pixel, and that we must increment our y coordinate and readjust the error to represent the distance from the top of the new pixel – which is done by subtracting one from error. [2]

Derivation

To derive Bresenham's algorithm, two steps must be taken. The first step is transforming the equation of a line from the typical slope-intercept form into something different; and then using this new equation to draw a line based on the idea of accumulation of error.

Line equation

y=f(x)=.5x+1 or f(x,y)=x-2y+2=0 Line 1.5x+1.svg
y=f(x)=.5x+1 or f(x,y)=x-2y+2=0
Positive and negative half-planes Line 1.5x+1 -- planes.svg
Positive and negative half-planes

The slope-intercept form of a line is written as

where is the slope and is the y-intercept. Because this is a function of only , it can't represent a vertical line. Therefore, it would be useful to make this equation written as a function of both and, to be able to draw lines at any angle. The angle (or slope) of a line can be stated as "rise over run", or . Then, using algebraic manipulation,

Letting this last equation be a function of and , it can be written as

where the constants are

The line is then defined for some constants , , and anywhere . That is, for any not on the line, . This form involves only integers if and are integers, since the constants , , and are defined as integers.

As an example, the line then this could be written as . The point (2,2) is on the line

and the point (2,3) is not on the line

and neither is the point (2,1)

Notice that the points (2,1) and (2,3) are on opposite sides of the line and evaluates to positive or negative. A line splits a plane into halves and the half-plane that has a negative can be called the negative half-plane, and the other half can be called the positive half-plane. This observation is very important in the remainder of the derivation.

Algorithm

Clearly, the starting point is on the line

only because the line is defined to start and end on integer coordinates (though it is entirely reasonable to want to draw a line with non-integer end points).

Candidate point (2,2) in blue and two candidate points in green (3,2) and (3,3) Line 1.5x+1 -- candidates.svg
Candidate point (2,2) in blue and two candidate points in green (3,2) and (3,3)

Keeping in mind that the slope is at most , the problem now presents itself as to whether the next point should be at or . Perhaps intuitively, the point should be chosen based upon which is closer to the line at . If it is closer to the former then include the former point on the line, if the latter then the latter. To answer this, evaluate the line function at the midpoint between these two points:

If the value of this is positive then the ideal line is below the midpoint and closer to the candidate point ; i.e. the y coordinate should increase. Otherwise, the ideal line passes through or above the midpoint, and the y coordinate should stay the same; in which case the point is chosen. The value of the line function at this midpoint is the sole determinant of which point should be chosen.

The adjacent image shows the blue point (2,2) chosen to be on the line with two candidate points in green (3,2) and (3,3). The black point (3, 2.5) is the midpoint between the two candidate points.

Algorithm for integer arithmetic

Alternatively, the difference between points can be used instead of evaluating f(x,y) at midpoints. This alternative method allows for integer-only arithmetic, which is generally faster than using floating-point arithmetic. To derive the other method, define the difference to be as follows:

For the first decision, this formulation is equivalent to the midpoint method since at the starting point. Simplifying this expression yields:

Just as with the midpoint method, if is positive, then choose , otherwise choose .

If is chosen, the change in D will be:

If is chosen the change in D will be:

If the new D is positive then is chosen, otherwise . This decision can be generalized by accumulating the error on each subsequent point.

Plotting the line from (0,1) to (6,4) showing a plot of grid lines and pixels Line 1.5x+1 -- points.svg
Plotting the line from (0,1) to (6,4) showing a plot of grid lines and pixels

All of the derivation for the algorithm is done. One performance issue is the 1/2 factor in the initial value of D. Since all of this is about the sign of the accumulated difference, then everything can be multiplied by 2 with no consequence.

This results in an algorithm that uses only integer arithmetic.

plotLine(x0, y0, x1, y1)     dx = x1 - x0     dy = y1 - y0     D = 2*dy - dx     y = y0      for x from x0 to x1         plot(x, y)         if D > 0             y = y + 1             D = D - 2*dx         end if         D = D + 2*dy

Running this algorithm for from (0,1) to (6,4) yields the following differences with dx=6 and dy=3:

D=2*3-6=0 Loop from 0 to 6  * x=0: plot(0, 1), D≤0: D=0+6=6  * x=1: plot(1, 1), D>0: D=6-12=-6, y=1+1=2, D=-6+6=0  * x=2: plot(2, 2), D≤0: D=0+6=6  * x=3: plot(3, 2), D>0: D=6-12=-6, y=2+1=3, D=-6+6=0  * x=4: plot(4, 3), D≤0: D=0+6=6  * x=5: plot(5, 3), D>0: D=6-12=-6, y=3+1=4, D=-6+6=0  * x=6: plot(6, 4), D≤0: D=0+6=6

The result of this plot is shown to the right. The plotting can be viewed by plotting at the intersection of lines (blue circles) or filling in pixel boxes (yellow squares). Regardless, the plotting is the same.

All cases

However, as mentioned above this only works for octant zero, that is lines starting at the origin with a slope between 0 and 1 where x increases by exactly 1 per iteration and y increases by 0 or 1.

The algorithm can be extended to cover slopes between 0 and -1 by checking whether y needs to increase or decrease (i.e. dy < 0)

plotLineLow(x0, y0, x1, y1)     dx = x1 - x0     dy = y1 - y0     yi = 1     if dy < 0         yi = -1         dy = -dy     end if     D = (2 * dy) - dx     y = y0      for x from x0 to x1         plot(x, y)         if D > 0             y = y + yi             D = D + (2 * (dy - dx))         else             D = D + 2*dy         end if

By switching the x and y axis an implementation for positive or negative steep slopes can be written as

plotLineHigh(x0, y0, x1, y1)     dx = x1 - x0     dy = y1 - y0     xi = 1     if dx < 0         xi = -1         dx = -dx     end if     D = (2 * dx) - dy     x = x0      for y from y0 to y1         plot(x, y)         if D > 0             x = x + xi             D = D + (2 * (dx - dy))         else             D = D + 2*dx         end if

A complete solution would need to detect whether x1 > x0 or y1 > y0 and reverse the input coordinates before drawing, thus

plotLine(x0, y0, x1, y1)     if abs(y1 - y0) < abs(x1 - x0)         if x0 > x1             plotLineLow(x1, y1, x0, y0)         else             plotLineLow(x0, y0, x1, y1)         end ifelseif y0 > y1             plotLineHigh(x1, y1, x0, y0)         else             plotLineHigh(x0, y0, x1, y1)         end ifend if

In low level implementations which access the video memory directly, it would be typical for the special cases of vertical and horizontal lines to be handled separately as they can be highly optimized.

Some versions use Bresenham's principles of integer incremental error to perform all octant line draws, balancing the positive and negative error between the x and y coordinates. [3]

plotLine(x0, y0, x1, y1)     dx = abs(x1 - x0)     sx = x0 < x1 ? 1 : -1     dy = -abs(y1 - y0)     sy = y0 < y1 ? 1 : -1     error = dx + dy          while true         plot(x0, y0)         if x0 == x1 && y0 == y1 break         e2 = 2 * error         if e2 >= dy             if x0 == x1 break             error = error + dy             x0 = x0 + sx         end ifif e2 <= dx             if y0 == y1 break             error = error + dx             y0 = y0 + sy         end ifend while

Similar algorithms

The Bresenham algorithm can be interpreted as slightly modified digital differential analyzer (using 0.5 as error threshold instead of 0, which is required for non-overlapping polygon rasterizing).

The principle of using an incremental error in place of division operations has other applications in graphics. It is possible to use this technique to calculate the U,V co-ordinates during raster scan of texture mapped polygons. [4] The voxel heightmap software-rendering engines seen in some PC games also used this principle.

Bresenham also published a Run-Slice computational algorithm: while the above described Run-Length algorithm runs the loop on the major axis, the Run-Slice variation loops the other way. [5] This method has been represented in a number of US patents:

5,815,163Method and apparatus to draw line slices during calculation
5,740,345Method and apparatus for displaying computer graphics data stored in a compressed format with an efficient color indexing system
5,657,435Run slice line draw engine with non-linear scaling capabilities
5,627,957Run slice line draw engine with enhanced processing capabilities
5,627,956Run slice line draw engine with stretching capabilities
5,617,524Run slice line draw engine with shading capabilities
5,611,029Run slice line draw engine with non-linear shading capabilities
5,604,852Method and apparatus for displaying a parametric curve on a video display
5,600,769Run slice line draw engine with enhanced clipping techniques

The algorithm has been extended to:

See also

Notes

  1. Paul E. Black. Dictionary of Algorithms and Data Structures, NIST. https://xlinux.nist.gov/dads/HTML/bresenham.html
  2. Joy, Kenneth. "Bresenham's Algorithm" (PDF). Visualization and Graphics Research Group, Department of Computer Science, University of California, Davis. Retrieved 20 December 2016.
  3. 1 2 Zingl, Alois (2012). A Rasterizing Algorithm for Drawing Curves (PDF) (Report).
    HTML abstract and demo: Zingl, Alois (2016). "Bresenham". members.chello.at.
  4. US 5739818,Spackman, John Neil,"Apparatus and method for performing perspectively correct interpolation in computer graphics",published 1998-04-14, assigned to Canon KK
  5. "Michael Abrash's Graphics Programming Black Book Special Edition: The Good, the Bad, and the Run-Sliced". www.phatcode.net. Retrieved 13 February 2024.;
  6. "Murphy's Modified Bresenham Line Algorithm". homepages.enterprise.net. Retrieved 2018-06-09. ('Line Thickening by Modification to Bresenham's Algorithm' in the IBM Technical Disclosure Bulletin Vol. 20 No. 12 May 1978 pages 5358-5366.)

Related Research Articles

<span class="mw-page-title-main">Slope</span> Mathematical term

In mathematics, the slope or gradient of a line is a number that describes the direction and steepness of the line. Often denoted by the letter m, slope is calculated as the ratio of the vertical change to the horizontal change between two distinct points on the line, giving the same number for any choice of points. A line descending left-to-right has negative rise and negative slope. The line may be physical – as set by a road surveyor, pictorial as in a diagram of a road or roof, or abstract.

<span class="mw-page-title-main">Probability density function</span> Function whose integral over a region describes the probability of an event occurring in that region

In probability theory, a probability density function (PDF), density function, or density of an absolutely continuous random variable, is a function whose value at any given sample in the sample space can be interpreted as providing a relative likelihood that the value of the random variable would be equal to that sample. Probability density is the probability per unit length, in other words, while the absolute likelihood for a continuous random variable to take on any particular value is 0, the value of the PDF at two different samples can be used to infer, in any particular draw of the random variable, how much more likely it is that the random variable would be close to one sample compared to the other sample.

<span class="mw-page-title-main">Differential calculus</span> Area of mathematics; subarea of calculus

In mathematics, differential calculus is a subfield of calculus that studies the rates at which quantities change. It is one of the two traditional divisions of calculus, the other being integral calculus—the study of the area beneath a curve.

<span class="mw-page-title-main">Line drawing algorithm</span> Methods of approximating line segments for pixel displays

In computer graphics, a line drawing algorithm is an algorithm for approximating a line segment on discrete graphical media, such as pixel-based displays and printers. On such media, line drawing requires an approximation. Basic algorithms rasterize lines in one color. A better representation with multiple color gradations requires an advanced process, spatial anti-aliasing.

<span class="mw-page-title-main">Xiaolin Wu's line algorithm</span> Line algorithm with antialiasing

Xiaolin Wu's line algorithm is an algorithm for line antialiasing.

In vector calculus, Green's theorem relates a line integral around a simple closed curve C to a double integral over the plane region D bounded by C. It is the two-dimensional special case of Stokes' theorem.

In mathematics, a Gaussian function, often simply referred to as a Gaussian, is a function of the base form

<span class="mw-page-title-main">Perlin noise</span> Type of gradient noise in computer graphics

Perlin noise is a type of gradient noise developed by Ken Perlin in 1983. It has many uses, including but not limited to: procedurally generating terrain, applying pseudo-random changes to a variable, and assisting in the creation of image textures. It is most commonly implemented in two, three, or four dimensions, but can be defined for any number of dimensions.

In mathematics, Laplace's method, named after Pierre-Simon Laplace, is a technique used to approximate integrals of the form

In computer graphics, the Liang–Barsky algorithm is a line clipping algorithm. The Liang–Barsky algorithm uses the parametric equation of a line and inequalities describing the range of the clipping window to determine the intersections between the line and the clip window. With these intersections it knows which portion of the line should be drawn. So this algorithm is significantly more efficient than Cohen–Sutherland. The idea of the Liang–Barsky clipping algorithm is to do as much testing as possible before computing line intersections.

In geometry, the Hessian curve is a plane curve similar to folium of Descartes. It is named after the German mathematician Otto Hesse. This curve was suggested for application in elliptic curve cryptography, because arithmetic in this curve representation is faster and needs less memory than arithmetic in standard Weierstrass form.

In geometric topology, Busemann functions are used to study the large-scale geometry of geodesics in Hadamard spaces and in particular Hadamard manifolds. They are named after Herbert Busemann, who introduced them; he gave an extensive treatment of the topic in his 1955 book "The geometry of geodesics".

In computer graphics, the Cohen–Sutherland algorithm is an algorithm used for line clipping. The algorithm divides a two-dimensional space into 9 regions and then efficiently determines the lines and portions of lines that are visible in the central region of interest.

In computer graphics, a digital differential analyzer (DDA) is hardware or software used for interpolation of variables over an interval between start and end point. DDAs are used for rasterization of lines, triangles and polygons. They can be extended to non linear functions, such as perspective correct texture mapping, quadratic curves, and traversing voxels.

For digital image processing, the Focus recovery from a defocused image is an ill-posed problem since it loses the component of high frequency. Most of the methods for focus recovery are based on depth estimation theory. The Linear canonical transform (LCT) gives a scalable kernel to fit many well-known optical effects. Using LCTs to approximate an optical system for imaging and inverting this system, theoretically permits recovery of a defocused image.

In the field of mathematical analysis, an interpolation space is a space which lies "in between" two other Banach spaces. The main applications are in Sobolev spaces, where spaces of functions that have a noninteger number of derivatives are interpolated from the spaces of functions with integer number of derivatives.

<span class="mw-page-title-main">Summed-area table</span> Type of data structure algorithm

A summed-area table is a data structure and algorithm for quickly and efficiently generating the sum of values in a rectangular subset of a grid. In the image processing domain, it is also known as an integral image. It was introduced to computer graphics in 1984 by Frank Crow for use with mipmaps. In computer vision it was popularized by Lewis and then given the name "integral image" and prominently used within the Viola–Jones object detection framework in 2001. Historically, this principle is very well known in the study of multi-dimensional probability distribution functions, namely in computing 2D probabilities from the respective cumulative distribution functions.

In calculus, the differential represents the principal part of the change in a function with respect to changes in the independent variable. The differential is defined by

Theta* is an any-angle path planning algorithm that is based on the A* search algorithm. It can find near-optimal paths with run times comparable to those of A*.

<span class="mw-page-title-main">Plotting algorithms for the Mandelbrot set</span> Algorithms and methods of plotting the Mandelbrot set on a computing device

There are many programs and algorithms used to plot the Mandelbrot set and other fractals, some of which are described in fractal-generating software. These programs use a variety of algorithms to determine the color of individual pixels efficiently.

References

Further reading