查找图像中一条线上的像素坐标
Finding the coordinates of pixels over a line in an image
我有一个表示为二维数组的图像。我想获取从点 1 到点 2 的直线上的像素坐标。
例如,假设我有一张尺寸为 5x4 的图像,如下图所示。我有一条线,从坐标 (0, 2)
处的点 1 到 (4, 1)
处的点 2。就像下图中的红线:
所以在这里我想得到蓝色像素的坐标作为这样一个列表:[(0, 2), (1, 2), (2, 2), (2, 1), (3, 1), (4, 1)]
我怎样才能做到这一点?
我正在使用 Python 和 numpy,但实际上任何语言(包括伪代码)的解决方案都会有所帮助。然后我可以尝试将其转换为 numpy 解决方案。
您可以使用 scikit-image 来做到这一点:
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's line algorithm
这是来自 geeksforgeeks
的 Python 代码
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)
我有一个表示为二维数组的图像。我想获取从点 1 到点 2 的直线上的像素坐标。
例如,假设我有一张尺寸为 5x4 的图像,如下图所示。我有一条线,从坐标 (0, 2)
处的点 1 到 (4, 1)
处的点 2。就像下图中的红线:
所以在这里我想得到蓝色像素的坐标作为这样一个列表:[(0, 2), (1, 2), (2, 2), (2, 1), (3, 1), (4, 1)]
我怎样才能做到这一点?
我正在使用 Python 和 numpy,但实际上任何语言(包括伪代码)的解决方案都会有所帮助。然后我可以尝试将其转换为 numpy 解决方案。
您可以使用 scikit-image 来做到这一点:
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's line algorithm
这是来自 geeksforgeeks
的 Python 代码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)