我有一個以二維陣串列示的影像。我想獲得從點1到點2的直線上的像素坐標。
例如,假設我有一張大小為5x4的影像,就像下面的圖片一樣。我有一條從坐標為(0, 2)的點1到(4, 1)的點2的線。就像下面圖片上的紅線:
所以在這里,我想得到藍色像素的坐標,像這樣的一個串列。[(0,2),(1,2),(2,2),(2,1),(3,1),(4,1)]
我怎樣才能實作這個目標?
我正在使用 Python 和 numpy,但實際上任何語言的解決方案,包括偽代碼都會有幫助。然后我可以嘗試將其轉換為numpy解決方案。uj5u.com熱心網友回復:
你可以用scikit-image:
from skimage.draw import line
# Get coordinates, r=rows, c=cols of your line[/span]。
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的實作
uj5u.com熱心網友回復:
你可以使用Bresenham的線演算法
這里是來自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 ,")
")
# 添加斜率以增加形成的角度。
slope_error_new =slope_error_new m_new
# 斜率錯誤達到極限,時間到了。
# 遞增y并更新斜率錯誤。
if (slope_error_new >= 0) 。
y=y 1.
slope_error_new =slope_error_new - 2 * (x2 - x1)
# driver function[/span]。
if __name__=='__main__'/span>:
x1 = 3.
y1 = 2: y1 = 2.
x2 = 15 5
bresenham(x1, y1, x2, y2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/326883.html
標籤:
上一篇:物理模擬的矢量化?
下一篇:用Python制作三維對角線矩陣

