我有一个红色激光(点和线性)。我想找到它并使用最小二乘法获得最接近激光图像的线。我用this Numpy function来获取系数,Python 2.7和OpenCV 3.1。
所以,这是我的代码:
while loop == 1:
rval, frame = vc.read()
frame = imutils.resize(frame, width=640, height=480)
red, green, blue = cv2.split(frame)
rbin, thresholdImg = cv2.threshold(red, 240, 255, cv2.THRESH_BINARY)
new = np.argwhere(thresholdImg == 255) #Get only RED pixels
if len(new) == 0: #If laser lost
assistantView(3,assistantImg)
else:
xs = []
ys = []
for (x,y) in new: #Extract red pixels positions
xs = np.append(xs,x)
ys = np.append(ys,y)
ArrayToResult = np.vstack([xs, np.ones(len(xs))]).T
m, c = np.linalg.lstsq(ArrayToResult, ys)[0] #Applying least squares method
A = m
B = c
x1 = np.amin(xs) #Take "left" and "right" X-coords
x2 = np.amax(xs)
ymin = int(np.amin(ys))
ymax = int(np.amax(ys))
y1 = x1*A + B #Get line
y2 = x2*A + B
x1 = int(x1)
x2 = int(x2)
y1 = int(y1)
y2 = int(y2)
print(x1, y1, x2, y2)
cv2.line(thresholdImg,(x1,y1),(x2,y2),(255,0,0),1) #Draw a line
因此,使用点激光我必须得到一条穿过激光图像中心的直线。但这就是我得到的:
在打印(x1,y1,x2,y2)的帮助下,我注意到该功能正好建立在它们上面,不对应于激光位置的坐标。移动相机,我注意到该线几乎与激光图像相对于y = x对称。所以,我使用了反函数如下:
y1 = (x1-B) / A
y2 = (x2-B) / A
现在Y-coords看起来像: 4698,29126,3726,805208,19575,-1671,-2952,13194 ....
第二天,我正在努力解决这个问题。我究竟做错了什么?