D
D
Dragon12020-10-03 15:48:21
Python
Dragon1, 2020-10-03 15:48:21

How can code be optimized (Bresenham's algorithm)?

It prints the numbers 0 3 7 using vertical and horizontal lines, but is there any way to optimize the code?

import numpy as np
import matplotlib.pyplot as plt
img=np.ones((10,30,3)) 
def DrawLine(x1,y1,x2,y2):
    dx = abs(x2-x1)
    dy = abs(y2-y1)

    if x1<x2:
        xs=1 
    else:
        xs=-1   
        
    if y1<y2:
        ys=1
    else:
        ys=-1
     
    x=x1
    y=y1  
    
    p=2*dy-dx   
    

    if dx>dy:
        while x<x2:
            x=x+xs
            if p > 0:
                y=y+ys
                p=p+2*dy-2*dx
            else:
                p=p+2*dy  
                
            img[y,x]= 0
     
    return;
def DrawLine1(y1,x1,y2,x2):
    dy = abs(y2-y1)
    dx = abs(x2-x1)

    if y1<y2:
        ys=1 
    else:
        ys=-1   
        
    if x1<x2:
        xs=1
    else:
        xs=-1
     
    y=y1
    x=x1  
    
    p=2*dx-dy   
    

    if dy>dx:
        while y<y2:
            y=y+ys
            if p > 0:
                x=x+xs
                p=p+2*dx-2*dy
            else:
                p=p+2*dx  
                
            img[y,x]= 0
     
    return;
"201rdb037"
"0"
DrawLine(4,2,8,2)
DrawLine(4,6,8,6)
DrawLine1(2,8,6,8)
DrawLine1(2,4,6,4)
"3"
DrawLine(10,2,15,2)
DrawLine1(2,15,4,15)
DrawLine(10,4,15,4)
DrawLine1(4,15,6,15)
DrawLine(10,6,15,6)
"7"
DrawLine(17,2,23,2)
DrawLine1(2,23,6,23)
DrawLine(21,5,24,5)
plt.imshow(img)
plt.show()

5f78b0f949a4d128897088.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iMaximus, 2020-10-03
@Dragon1

You run the file where you wrote the method, but you don't call it.
Add a method call below and pass arguments.
For example,
print(get_line((111,145), (544,44)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question