本文的主要參考爲官方文檔OpenCV249-fitLine和博客-OpenCV 學習(直線擬合)
以及《Learning OpenCV 3》page425-426
OpenCV中提供的直線擬合API如下:
void fitLine(InputArray points, OutputArray line, int distType, double param, double reps, double aeps)
輸入:二維點集。存儲在std::vector<> or Mat
算法:OpenCV中共提供了6種直線擬合的算法,如下圖所示,其中第一種就是最常用的最小二乘法。但是最小二乘法受噪聲的影響很大,別的方法具有一定的抗干擾性,但是具體的數學原理不是很理解。
輸出:擬合結果爲一個四元素的容器,比如Vec4f - (vx, vy, x0, y0)。其中(vx, vy) 是直線的方向向量,(x0, y0) 是直線上的一個點。
示例代碼如下:
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main( )
{
const char* filename = "1.bmp";
Mat src_image = imread(filename,1);
if( src_image.empty() )
{
cout << "Couldn't open image!" << filename;
return 0;
}
int img_width = src_image.cols;
int img_height = src_image.rows;
Mat gray_image,bool_image;
cvtColor(src_image,gray_image,CV_RGB2GRAY);
threshold(gray_image,bool_image,0,255,CV_THRESH_OTSU);
imshow("二值圖", bool_image);
//獲取二維點集
vector<Point> point_set;
Point point_temp;
for( int i = 0; i < img_height; ++i)
{
for( int j = 0; j < img_width; ++j )
{
if (bool_image.at<unsigned char>(i,j) < 255)
{
point_temp.x = j;
point_temp.y = i;
point_set.push_back(point_temp);
}
}
}
//直線擬合
//擬合結果爲一個四元素的容器,比如Vec4f - (vx, vy, x0, y0)
//其中(vx, vy) 是直線的方向向量
//(x0, y0) 是直線上的一個點
Vec4f fitline;
//擬合方法採用最小二乘法
fitLine(point_set,fitline,CV_DIST_L2,0,0.01,0.01);
//求出直線上的兩個點
double k_line = fitline[1]/fitline[0];
Point p1(0,k_line*(0 - fitline[2]) + fitline[3]);
Point p2(img_width - 1,k_line*(img_width - 1 - fitline[2]) + fitline[3]);
//顯示擬合出的直線方程
char text_equation[1024];
sprintf(text_equation,"y-%.2f=%.2f(x-%.2f)",fitline[3],k_line,fitline[2]);
putText(src_image,text_equation,Point(30,50),CV_FONT_HERSHEY_COMPLEX,0.5,Scalar(0,0,255),1,8);
//顯示擬合出的直線
line(src_image,p1,p2,Scalar(0,0,255),2);
imshow("原圖+擬合結果", src_image);
waitKey();
return 0;
}