OpenCV:使用最小二乘法对红色激光

时间:2016-11-06 21:35:32

标签: python opencv numpy

我有一个红色激光(点和线性)。我想找到它并使用最小二乘法获得最接近激光图像的线。我用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

因此,使用点激光我必须得到一条穿过激光图像中心的直线。但这就是我得到的: enter image description here

打印(x1,y1,x2,y2)的帮助下,我注意到该功能正好建立在它们上面,不对应于激光位置的坐标。移动相机,我注意到该线几乎与激光图像相对于y = x对称。所以,我使用了反函数如下:

  y1 = (x1-B) / A              
  y2 = (x2-B) / A 

结果是:enter image description here

现在Y-coords看起来像: 4698,29126,3726,805208,19575,-1671,-2952,13194 ....

第二天,我正在努力解决这个问题。我究竟做错了什么?

1 个答案:

答案 0 :(得分:0)

我不知道它为什么会起作用,但它确实有效。我在Y坐标的数组XS位置和YS X坐标中写道:

for (x,y) in new:                  
     xs = np.append(xs,y) #was X
     ys = np.append(ys,x) #was Y

这样一切正常。

这就是结果:enter image description here