0

I'm trying to modifiy the following OpenCV code to Java.

    std::vector<cv::Vec4i> lines;  
    cv::HoughLinesP(bw,lines,1,CV_PI/180,70,30,10);   

    for (unsigned int i = 0;i<lines.size();i++)  
    {  
       cv::Vec4i v = lines[i];  
       lines[i][0] = 0;  
       lines[i][1] = ((float)v[1] - v[3])/(v[0] - v[2])* -v[0] + v[1];  
       lines[i][2] = src.cols;  
       lines[i][3] = ((float)v[1] - v[3])/(v[0] - v[2])*(src.cols - v[2]) + v[3];    
    }  

   std::vector<cv::Point2f> corners;
   for (unsigned int i = 0;i<lines.size();i++)  
   {  
       for (unsigned int j=i+1;j<lines.size();j++)  
       {  
           cv::Point2f pt = computeIntersect(lines[i],lines[j]);  
           if (pt.x >= 0 && pt.y >=0)  
           {  
               corners.push_back(pt);  
           }  
       }  
   }  
Anthon
  • 69,918
  • 32
  • 186
  • 246
兰海德
  • 11
  • 1
  • 3

1 Answers1

0

So you have two line segments (lines[i] and lines[j]) given by their end points and you are interested in estimating their intersection (the function computeIntersect()):

computeIntersect(lines[i], lines[j]);

The point where the segments intersect is given by solving two simple equations. You should read the description here for more details. And also here you have some good SO answer about the problem.

/**
 * Computes the intersection between two lines. The calculated point is approximate, 
 * since integers are used. If you need a more precise result, use doubles
 * everywhere. 
 * (c) 2007 Alexander Hristov. Use Freely (LGPL license). http://www.ahristov.com
 *
 * @param x1 Point 1 of Line 1
 * @param y1 Point 1 of Line 1
 * @param x2 Point 2 of Line 1
 * @param y2 Point 2 of Line 1
 * @param x3 Point 1 of Line 2
 * @param y3 Point 1 of Line 2
 * @param x4 Point 2 of Line 2
 * @param y4 Point 2 of Line 2
 * @return Point where the segments intersect, or null if they don't
 */
public Point intersection(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
    int d = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4);
    if (d == 0) return null;

    int xi = ((x3-x4)*(x1*y2-y1*x2)-(x1-x2)*(x3*y4-y3*x4))/d;
    int yi = ((y3-y4)*(x1*y2-y1*x2)-(y1-y2)*(x3*y4-y3*x4))/d;

    return new Point(xi,yi);
}
Community
  • 1
  • 1
Kornel
  • 5,264
  • 2
  • 21
  • 28
  • Thank you very much. I have one more question: how to declare vector and vector in Java? thanks. – 兰海德 May 07 '15 at 01:20
  • Essentially `cv::Vec4i` is a four element array of integers and `cv::Point2f` is a 2 element point that is represented by single precision floating point x, y coordinates. – Kornel May 07 '15 at 11:27