如何使用java和opencv

时间:2017-08-08 22:54:32

标签: java opencv

我目前正在设计车道检测程序,需要填写多行之间的区域。我怎样才能找到极点(左右最高点+左右最低点)。 这是我目前正在使用的图像(image)。

作为注释,图像可以被视为坐标平面,因为所有线都有一个起点和终点,我可以检索它们的坐标。

这就是我想要的(蓝色极点):image

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

根据提供的信息和示例图像,以下是我将如何解决此问题:

前提条件

由于红色标记是由HoughLinesP创建的行,因此每行都有以下信息: x1 y1 ,< em> x2 , y2 其中 x1 y1 是起点和 x2 y2 该行的终点。

出于测试目的,我创建了3行:

3 lines for testing purpose

管道

  1. 创建一个点列表(我的代码中为contour),其中包含每行的开始结束点
  2. 使用convexHull计算点列表的凸包。
  3. 此时你会得到这种味道的东西:

    Green convex hull without approximation

    请注意,生成的船体(绿色)确实包含超过4点(即,不仅是极值点)。所以我们接下来要做的是简化船体以便仅保留4个极值点

    1. 使用approxPolyDP
    2. 简化船体
    3. 船体剩下的4个点应该是极值近似
    4. 在这里,您可以看到最终结果,其中近似船体为绿色,4个极值点为黄色:

      final result, extreme points in yellow

      Python代码

      最后,作为参考,这里是我使用的Python代码(这不应该很难移植到Java中):

      import numpy as np
      import cv2
      
      input_img = np.zeros((400,400,3), np.uint8)
      # 3 lines added for testing purpose
      lines = []
      lines.append(((350,350),(250,200))) # (start point, end point)
      lines.append(((50,350),(55,330)))
      lines.append(((60,250),(80,200)))
      
      contour = [] #in Java you'd use a List of Points
      
      for line in lines:
          # we create a contour with the start and end points of each line
          contour.append(line[0])
          contour.append(line[1])
          # we draw the lines (in your case, detected by HoughLinesP)
          cv2.line(input_img,line[0],line[1],(0,0,255),3)
      
      contour = np.array(contour)
      hull = cv2.convexHull(contour) # we compute the convex hull of our contour
      
      epsilon = 0.05*cv2.arcLength(hull,True) # epsilon may need to be tweaked
      approx_hull = cv2.approxPolyDP(hull,epsilon,True)
      
      # we check that there are only 4 points left in the approximate hull (if there are more, then you'd need to increase epsilon
      if(len(approx_hull) == 4): 
          for final_point in approx_hull :
              # we draw the 4 points contained in the approximate hull 
              cv2.circle(input_img, (final_point[0][0], final_point[0][1]),5,(0,242,255),2)
      
      cv2.drawContours(input_img, [approx_hull], 0, (0,255,0),1)
      cv2.imshow("result",input_img)
      

      替代

      我认为来自@YvesDaoust的这个solution也可以起作用。我没有时间测试它,所以如果你这样做,请让我更新。 :)

相关问题