[英]How to draw a line on an image given the slope and the intercept coordinates (x, y) using Python
[英]Wrong slope direction while calculating line equation with X and y coordinates
我需要從光柵化圖像中檢測一些線條。 在檢索到所有 X 和 Y 坐標后,我可以完美地為水平線、垂直線和幾乎對角線創建相應的線方程。
但我剛剛偶然發現了一個罕見的案例:
我給出以下 X 坐標:
[[283.5], [283.5], [283.5], [283.5], [284.0], [284.5], [285.0], [285.5], [286.0],
[287.5], [287.5], [287.5], [288.0], [289.0], [289.0], [289.5], [289.5], [290.0],
[290.0], [291.0], [292.0], [292.0], [292.0], [293.0], [293.0], [294.0], [294.0],
[294.0], [294.0], [295.0], [296.0], [296.0], [296.0], [297.0], [297.0], [298.0],
[298.0], [298.0], [298.0], [299.0], [299.0], [300.0], [300.5], [300.5], [301.0],
[301.5], [302.0], [302.5], [302.5], [302.5], [302.5], [303.0], [303.5], [304.5],
[305.0], [305.5], [306.0], [306.5], [307.0], [307.0], [307.0], [307.0]]
使用以下 Y 坐標:
[215.0, 214.0, 213.0, 212.0, 211.0, 210.0, 209.0, 208.0, 207.0, 206.0, 205.0, 204.0,
203.0, 202.0, 201.0, 200.0, 199.0, 198.0, 197.0, 196.0, 195.0, 194.0, 193.0, 192.0,
191.0, 190.0, 189.0, 188.0, 187.0, 186.0, 185.0, 184.0, 183.0, 182.0, 181.0, 180.0,
179.0, 178.0, 177.0, 176.0, 175.0, 174.0, 173.0, 172.0, 171.0, 170.0, 169.0, 168.0,
167.0, 166.0, 165.0, 164.0, 163.0, 162.0, 161.0, 160.0, 159.0, 158.0, 157.0, 156.0,
155.0, 154.0]
我得到以下b
值: 913.00073
m
為: -2.4654503
給出以下結果:
似乎m
應該是正數。
我已經嘗試過使用 sklearn 的 LinearRegression 並手動進行,得到相同的方程結果。
def compute_line_equation_sklearn(self):
X = []
y = []
for slice in self._slices:
X.append([slice.center[1]])
y.append(slice.center[0])
lr = LinearRegression()
reg = lr.fit(X, y)
self._m = reg.coef_[0]
self._b = reg.intercept_
def compute_line_equation_manual(self):
X = []
pairs = []
for current_slice in self._slices:
X.append(current_slice.center[1])
pairs.append([current_slice.center[1], current_slice.center[0]])
sx = sy = sxx = sxy = syy = 0.0
n = len(pairs)
for x, y in pairs:
sx = sx + x
sy = sy + y
sxx = sxx + x * x
sxy = sxy + x * y
syy = syy + y * y
self._m = ((n * sxy) - (sx * sy)) / ((n * sxx) - sx ** 2)
self._b = (sy - (self._m * sx)) / n
self._r = ((n * sxy) - (sx * sy)) / (np.sqrt((n * sxx) - (sx ** 2)) *
np.sqrt((n * syy) - (sy ** 2)))
您能否給我一些關於在這種情況下可能出現問題的提示?
在圖像中,Y 軸向下增加,從頂部的 0 開始。 因此,為了得到正確的結果,在計算斜率之前翻轉 Y 坐標的符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.