In: Computer Science
Compute the pixel co-ordinates for lines 1 and 2 given below using i) Bresenham algorithm Line 2: (xp = 0, yp = 8) to (xq = 5, yq = 1) Show all the steps involved and mark the computed pixels on the blank pixel grid (attached) for each case.
Bresenham’s Line Generation Algorithm:-
Given coordinate of two points A(x1, y1) and B(x2, y2). The task to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates.
Examples:
Below are some assumptions to keep algorithm simple.
Let us understand the process by considering the naive way first.
Above algorithm works, but it is slow. The idea of Bresenham’s algorithm is to avoid floating point multiplication and addition to compute mx + c, and then computing round value of (mx + c) in every step. In Bresenham’s algorithm, we move across the x-axis in unit intervals.
We need to a decision parameter to decide whether to pick Yk + 1 or Yk as next point. The idea is to keep track of slope error from previous increment to y. If the slope 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.
How to avoid floating point arithmetic
The above algorithm still includes floating point arithmetic. To
avoid floating point arithmetic, consider the value below value
m.
m = (y2 – y1)/(x2 – x1)
We multiply both sides by (x2 – x1)
We also change slope_error to slope_error * (x2 – x1). To avoid comparison with 0.5, we further change it to slope_error * (x2 – x1) * 2.
Also, it is generally preferred to compare with 0 than 1.
The initial value of slope_error_new is 2*(y2 – y1) – (x2 – x1). Refer this for proof of this value
Below is the implementation of above algorithms.
Here is the implementation of Bresenham’s Line Generation Algorithm using python:-
# Python 3 program for Bresenham’s Line Generation
# Assumptions :
# 1) Line is drawn from left to right.
# 2) x1 < x2 and y1 < y2
# 3) Slope of the line is between 0 and 1.
# We draw a line from lower left to upper
# right.
# function for line generation
def bresenham(x1,y1,x2, y2):
m_new = 2 * (y2 - y1)
slope_error_new = m_new - (x2 - x1)
y=y1
for x in range(x1,x2+1):
print("(",x ,",",y ,")\n")
# Add slope to increment angle formed
slope_error_new =slope_error_new + m_new
# Slope error reached limit, time to
# increment y and update slope error.
if (slope_error_new >= 0):
y=y+1
slope_error_new =slope_error_new - 2 * (x2 - x1)
# driver function
if __name__=='__main__':
x1 = 0
y1 = 8
x2 = 5
y2 = 1
output:-
( 0 , 8 )
( 1 , 8 )
( 2 , 8 )
( 3 , 8 )
( 4 , 8 )
( 5 , 8 )