我試圖繪製給定(x,y)數據點的最佳擬合線。2d中的點的最小二乘擬合不通過對稱軸
在這裏示出的數據點(紅色像素)和估計線(綠色),I得到使用以下庫。對於使用library module
我們可以看到數據點
import numpy as np
m, c = np.linalg.lstsq(A, y)[0]
文檔大致對稱分佈。問題是爲什麼這條線沒有類似於通過數據點的長對稱軸的梯度?你能解釋一下這個結果是否正確?那麼,它如何給出最小誤差? (使用由lstsq
方法返回的漸變繪製的線條正確)。謝謝。
編輯
這裏是我想要的代碼。輸入圖像可以從here下載。在這段代碼中,我並沒有強制這條線穿過像素分佈的中心。 (注:這裏我用polyfit
代替lstsq
兩個給出相同的結果。)
import numpy as np
import cv2
import math
img = cv2.imread('points.jpg',1);
h, w = img.shape[:2]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
points = np.argwhere(gray>10) # get (x,y) pairs where red pixels exist
y = points[:,0]
x = points[:,1]
m, c = np.polyfit(x, y, 1) # calculate least square fit line
# calculate two cordinates (x1,y1),(x2,y2) on the line
angle = np.arctan(m)
x1, y1, length = 0, int(c), 500
x2 = int(round(math.ceil(x1 + length * np.cos(angle)),0))
y2 = int(round(math.ceil(y1 + length * np.sin(angle)),0))
# draw line on the color image
cv2.line(img, (x1, y1), (x2, y2), (0,255,0), 1, cv2.LINE_8)
# show output the image
cv2.namedWindow("Display window", cv2.WINDOW_AUTOSIZE);
cv2.imshow("Display window", img);
cv2.waitKey(0);
cv2.destroyAllWindows()
我怎麼能有行通過像素分佈的最長的對稱軸?我可以使用主成分分析嗎?
我同意綠線看起來不正確 –
然而,這是不可重現的沒有數據 –
這不是一個密度圖。如果情節的長手伸得很薄,而核心是密集的和傾斜的,你可以期望這種適合。最小二乘迴歸也不是一個可靠的方法。我會第二次請求上面張貼的Jared的數據。 –