感謝Gareth(請參閱我的問題的評論)我能夠弄清楚這一點。霍夫轉換是我正在尋找的解決方案。
Scipy有一個功能來做到這一點。該文檔可以找到here和一個很好的演示和解釋可以發現here。
我在上面的問題中實現瞭解決方案。我還添加了一個例子,其中一個像素不在一條直線上,但「足夠直」。這可能受probabilistic_hough_line
函數的參數影響。
import numpy as np
import matplotlib.pylab as plt
from matplotlib import gridspec
from skimage.transform import probabilistic_hough_line
background = np.zeros((60,60))
one = background.copy() # straight line
one[10,5:30:1] = 1
# Here I'd like to count 25 from both directions
two = background.copy() # diagonal line, this stands for all angles the diagonal line could have, not just 45degrees!
two[[range(10,35)],[range(5,30)]] = 1
# Here I'd like to count 25 from both directions
three = background.copy() # line with right angle
three[10,5:15:1] = 1
three[10:25:1,15] = 1
# Here I'd like to count 10 from one end and 15 from the other
four = background.copy() # line with one value out of place and a right angle
four[10,5:8:1] = 1
four[11,8] = 1
four[10,9:15] = 1
four[10:25:1,15] = 1
# Here I'd like to count 10 from one side and 15 from the other side
gs = gridspec.GridSpec(2,2)
fig = plt.figure()
line_plt = fig.add_subplot(gs[0,0])
diag = fig.add_subplot(gs[0,1])
angle = fig.add_subplot(gs[1,0])
angle_dirty = fig.add_subplot(gs[1,1])
line_plt.imshow(one), line_plt.set_title('Count 25 from both sides')
diag.imshow(two), diag.set_title('Count 25 from both sides')
angle.imshow(three), angle.set_title('Count 10 from one side and 15 from the other')
angle_dirty.imshow(four), angle_dirty.set_title('Count 10 from one side and 15 from the other')
# This function returns the List of lines identified, lines in format ((x0, y0), (x1, y0)), indicating line start and end.
lines_one = probabilistic_hough_line(one, threshold=10, line_length=5, line_gap=3)
# Now to the plotting on top of the original image
for line in lines_one:
p0, p1 = line
line_plt.plot((p0[0], p1[0]), (p0[1], p1[1]))
lines_two = probabilistic_hough_line(two, threshold=10, line_length = 5, line_gap = 3)
for line in lines_two:
p0, p1 = line
diag.plot((p0[0], p1[0]), (p0[1], p1[1]))
lines_three = probabilistic_hough_line(three, threshold=10, line_length = 5, line_gap = 3)
for line in lines_three:
p0, p1 = line
angle.plot((p0[0], p1[0]), (p0[1], p1[1]))
lines_four = probabilistic_hough_line(four, threshold=10, line_length = 5, line_gap = 3)
for line in lines_four:
p0, p1 = line
angle_dirty.plot((p0[0], p1[0]), (p0[1], p1[1]))
![enter image description here](https://i.stack.imgur.com/V8YGB.png)
當你說「所有二維方向」,你的意思是8「顯而易見」的方向,或者你想包括其他中間的方向嗎? (它們與8個基本方向的不同之處在於,對於那些相關像素的中心實際上是在一條直線上。) –
你想要的輸出到底是什麼?如果你在不同的方向上輸入不同長度的線,你只需要最長線的長度,或每個方向最長線的長度,或者所有線的長度,或者什麼? –
你能告訴我們你需要什麼? (例如,這可能會影響效率的重要性。) –