代码之家  ›  专栏  ›  技术社区  ›  Soonmyun Jang

如何从点中找到平均线?

  •  1
  • Soonmyun Jang  · 技术社区  · 3 年前

    我使用OpenCV检测了轮廓,我想从轮廓中找出线条。

    我找到了一个示例代码,用于从散点图中查找直线。

    // Construct line from points
    bool ShapeDetection::FitPoints(const std::vector<cv::Point> &pts) {
      int nPoints = pts.size();
      if( nPoints < 2 ) {
        // Fail: infinitely many lines passing through this single point
        _slope = 0;
        _yInt = 0;
        return false;
      }
      double sumX=0, sumY=0, sumXY=0, sumX2=0;
      for(int i=0; i<nPoints; i++) {
        sumX += pts[i].x;
        sumY += pts[i].y;
        sumXY += pts[i].x * pts[i].y;
        sumX2 += pts[i].x * pts[i].x;
      }
      double xMean = sumX / nPoints;
      double yMean = sumY / nPoints;
      double denominator = sumX2 - sumX * xMean;
      // You can tune the eps (1e-7) below for your specific task
      if( std::fabs(denominator) < 1e-7 ) {
        // Fail: it seems a vertical line
        _slope = 0;
        _yInt = xMean;
    
        return false;
      }
      _slope = (sumXY - sumX * yMean) / denominator;
      _yInt = yMean - _slope * xMean;
    
      return true;
    }
    

    enter image description here

    找到像上面这样的水平线非常有效。但是,它没有找到垂直线,就像这样:

    enter image description here

    我在这个网站上做过类似的测试: https://www.rapidtables.com/tools/scatter-plot.html

    enter image description here

    它必须在h轴上显示一条接近3的垂直线,但不是。

    我应该用什么方法来解决这个问题?

    0 回复  |  直到 3 年前