from skimage.draw import line
# Get coordinates, r=rows, c=cols of your line
rr, cc = line(0,2,4,1)
print(list(zip(rr,cc)))
[(0, 2), (1, 2), (2, 1), (3, 1), (4, 1)]
查看已实现算法的源代码:https://github.com/scikit-image/scikit-image/blob/main/skimage/draw/_draw.pyx#L44
这是Bresenham线算法的一个实现。
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 = 3
y1 = 2
x2 = 15
y2 = 5
bresenham(x1, y1, x2, y2)