失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > opencv之fitline直线拟合

opencv之fitline直线拟合

时间:2020-11-13 02:51:09

相关推荐

opencv之fitline直线拟合

fitline拟合函数:

CV_EXPORTS_W void fitLine( InputArray points, //待输入点集OutputArray line, //输出点集(一个是方向向量,另一个是拟合直线上的点)int distType,//拟合方法double param, //以下参数使用默认值double reps, double aeps );

拟合方法总结:

CV_DIST_USER =-1, /* User defined distance */CV_DIST_L1=1, /* distance = |x1-x2| + |y1-y2| */CV_DIST_L2=2, /* the simple euclidean distance */CV_DIST_C =3, /* distance = max(|x1-x2|,|y1-y2|) */CV_DIST_L12=4, /* L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */CV_DIST_FAIR =5, /* distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */CV_DIST_WELSCH =6, /* distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */CV_DIST_HUBER =7 /* distance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345 */

在这里不讨论最小二乘法原理和直线方面的知识。

通过寻找图片中灰度为0的像素(直线)进行拟合。

// fitLine.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include<iostream>#include <opencv2/opencv.hpp>using namespace std;using namespace cv;Mat image,gray;const double PI = 3.1415926535897;vector<Point> getPoints(Mat &image, int value)//we find all the pixels that are equal to zero{int nl = image.rows; // number of linesint nc = image.cols;vector<Point> points;for (int j = 0; j < nl; j++){uchar* data = image.ptr<uchar>(j);for (int i = 0; i < nc; i++){if(data[i] == value){points.push_back(Point(i, j));}}}return points;}void drawLine(Mat&image, double theta, double rho, Scalar color){if (theta < PI/4. || theta > 3.*PI/4.)// ~vertical line{Point pt1(rho/cos(theta), 0);Point pt2((rho - image.rows * sin(theta))/cos(theta), image.rows);line( image, pt1, pt2, color, 1);}else{Point pt1(0, rho/sin(theta));Point pt2(image.cols, (rho - image.cols * cos(theta))/sin(theta));line(image, pt1, pt2, Scalar(255,0,0), 1);}}int main(){image=imread("D://vvoo//liness.jpg");image.copyTo(gray);cvtColor(gray,gray,CV_BGR2GRAY);vector<Point> points;//get all the intresting pointsVec4f line;points=getPoints(gray, 0);fitLine(points,line, CV_DIST_L2,0,0.01,0.01);cout<<"line[0]="<<line[0]<<endl<<"line[1]="<<line[1]<<endl<<"line[2]="<<line[2]<<endl<<"line[3]="<<line[3]<<endl;Point2f Point1[2]={Point2f(100,200),Point2f(int(line[2]),int(line[3]))};circle(image, Point1[1], 2, Scalar(0, 0, 255), 5); double cos_theta = line[0];double sin_theta = line[1];double x0 = line[2], y0 = line[3];double tho = atan2(sin_theta, cos_theta) + PI / 2.0;//angledouble rho = y0 * cos_theta - x0 * sin_theta;cout << "tho = " << tho / PI * 180 << endl;cout << "rho = " << rho << endl;drawLine(image,tho, rho, Scalar(0,0,255));double k = sin_theta / cos_theta;double b = y0 - k * x0;double x = 0;double y = k * x + b;cout <<"k="<< k << endl;//the gradient pf "k" is equal to line[1]/line[0]cout <<"b="<< b << endl;imshow("", image);imwrite("D://vvoo3//iamge.jpg",image);waitKey(0);return 0;}

对简单直线的识别结果:

参考:1./liyuanbhu/article/details/50193947

2./leonid112/article/details/6109277

如果觉得《opencv之fitline直线拟合》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。