我尝试了@Rick建议的代码,但它没有起作用。然后我去了Xiaolin's code,它是用Matlab编写的,我将其翻译成了Python:
def xiaoline(x0, y0, x1, y1):
x=[]
y=[]
dx = x1-x0
dy = y1-y0
steep = abs(dx) < abs(dy)
if steep:
x0,y0 = y0,x0
x1,y1 = y1,x1
dy,dx = dx,dy
if x0 > x1:
x0,x1 = x1,x0
y0,y1 = y1,y0
gradient = float(dy) / float(dx)
""" handle first endpoint """
xend = round(x0)
yend = y0 + gradient * (xend - x0)
xpxl0 = int(xend)
ypxl0 = int(yend)
x.append(xpxl0)
y.append(ypxl0)
x.append(xpxl0)
y.append(ypxl0+1)
intery = yend + gradient
""" handles the second point """
xend = round (x1);
yend = y1 + gradient * (xend - x1);
xpxl1 = int(xend)
ypxl1 = int (yend)
x.append(xpxl1)
y.append(ypxl1)
x.append(xpxl1)
y.append(ypxl1 + 1)
""" main loop """
for px in range(xpxl0 + 1 , xpxl1):
x.append(px)
y.append(int(intery))
x.append(px)
y.append(int(intery) + 1)
intery = intery + gradient;
if steep:
y,x = x,y
coords=zip(x,y)
return coords
最后,我使用了上述代码并加上了一个绘图脚本:
import numpy as np
import demo_interpolate_pixels_along_line as interp
import matplotlib.pyplot as plt
A=np.zeros((21,21))
p0=(5,15)
p1=(20,5)
coords=interp.xiaoline(p0[0],p0[1],p1[0],p1[1])
for c in coords:
A[c]=1
A[p0]=0.2
A[p1]=0.8
plt.figure()
plt.imshow(A.T,interpolation='none',
origin='lower',
cmap='gist_earth_r',
vmin=0,
vmax=1)
plt.grid(which='major')
plt.xlabel('X')
plt.ylabel('Y')
plt.text(p0[0],p0[1],'0',fontsize=18,color='r')
plt.text(p1[0],p1[1],'1',fontsize=18,color='r')
plt.show()
我没有足够的声望来发布图片 :(