为什么java和c ++中的opencv的HoughLines的结果不同

时间:2017-04-29 10:19:58

标签: java c++ opencv

我是Opencv的新手,我正在阅读名为OpenCV 3.0 Computer Vision的书 来自DanielLélisBaggio的Java。我从opencv网站测试一个试图检测线条的图像但是我得到了不同的结果,只有一行检测到DanielLélisBaggiojava代码。我不知道为什么这段代码不能正常工作。书中的守则:

else if(houghString.equals(operation)){
        Mat canny = new Mat();
        Imgproc.Canny(originalImage, canny,10 , 50, aperture, false);
        image = originalImage.clone();
        Mat lines = new Mat();

        Imgproc.HoughLines(canny, lines, 1, Math.PI/180, lowThreshold);

        for( int i = 0; i < lines.cols(); i++ )
        {
          double rho = lines.get(0, i)[0];
          double theta = lines.get(0, i)[1];
          Point pt1 = new Point(), pt2= new Point();
          double a = Math.cos(theta), b = Math.sin(theta);
          double x0 = a*rho, y0 = b*rho;
          pt1.x = Math.round(x0 + 1000*(-b));
          pt1.y = Math.round(y0 + 1000*(a));
          pt2.x = Math.round(x0 - 1000*(-b));
          pt2.y = Math.round(y0 - 1000*(a));
          Imgproc.line( image, pt1, pt2, new Scalar(255,0,0), 2, Core.LINE_AA,0);
        }   
    }
else if(pHoughString.equals(operation)){
        Mat canny = new Mat();
        Imgproc.Canny(originalImage, canny,10 , 50, aperture, false);
        //canny = originalImage.clone();
        image = originalImage.clone();

        //Imgproc.cvtColor(image, image, Imgproc.COLOR_GRAY2BGR);

    Mat lines = new Mat();

    Imgproc.HoughLinesP(canny, lines, 1, 360,  lowThreshold, 50, 5 );
    for( int i = 0; i < lines.cols(); i++ )
    {
        double a = lines.get(0, i)[0];
        double b = lines.get(0, i)[1];
        double c = lines.get(0, i)[2];
        double d = lines.get(0, i)[3];
        Imgproc.line( image, new Point(a, b), new Point(c, d), new Scalar(0,0,255), 1, Core.LINE_AA,0);

    }

来自opencv site for c ++的代码如下:

Mat dst, cdst;
 Canny(src, dst, 50, 200, 3);
 cvtColor(dst, cdst, CV_GRAY2BGR);

 #if 0
  vector<Vec2f> lines;
  HoughLines(dst, lines, 1, CV_PI/180, 100, 0, 0 );

  for( size_t i = 0; i < lines.size(); i++ )
  {
 float rho = lines[i][0], theta = lines[i][1];
 Point pt1, pt2;
 double a = cos(theta), b = sin(theta);
 double x0 = a*rho, y0 = b*rho;
 pt1.x = cvRound(x0 + 1000*(-b));
 pt1.y = cvRound(y0 + 1000*(a));
 pt2.x = cvRound(x0 - 1000*(-b));
 pt2.y = cvRound(y0 - 1000*(a));
 line( cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
  }
 #else
  vector<Vec4i> lines;
  HoughLinesP(dst, lines, 1, CV_PI/180, 50, 50, 10 );
  for( size_t i = 0; i < lines.size(); i++ )
  {
  Vec4i l = lines[i];
line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
  }
 #endif

Java代码的结果:

Result with Daniel Lélis Baggio java code

和opencv网站的结果:

Opencv HoughLines

为什么使用java和c ++的图像有不同的结果?

1 个答案:

答案 0 :(得分:0)

已经晚了,但我刚打了同样的szenario,这可能会帮助其他人...

行返回的是行而不是列,因此正确的循环应该是:

for( int i = 0; i < lines.rows(); i++ ) {
      double rho = lines.get(i, 0)[0];
      double theta = lines.get(i, 0)[1];
      ...
}