我试图绘制给定(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的数据。 –