signed

QiShunwang

“诚信为本、客户至上”

HoughLines(P)霍夫角度检测

2021/3/21 1:27:26   来源:

HoughLines霍夫角度检测
HoughLines(Mat image,lines,rho,CV_PI/180,threshold,0.0,0.0,0.0,CV_PI)
//lines:lines[i][0]为第i条直线的像素角度(rho,一般为1),lines[i][1]为角度角度(theta)
//threshold:形成直线的最小像素,即最小线段长度

HoughLinesP(Mat image,lines,rho,theta,threshold,0,0);
//lines[i]为Vec4i,四维int向量

代码:

//霍夫角度检测
	vector<Vec4f> lines;  //定义一个lines的思维向量存放点
	HoughLinesP(srcImage_roi, lines, 10, CV_PI / 180, 5, 0, 0);
	for (size_t i = 0; i < lines.size(); i++)
	{
		Vec4f plines = lines[i];  //一个plines里边是四个点一条直线
		line(srcImage_roi, Point(plines[0], plines[1]), Point(plines[2], plines[3]), Scalar(125, 0, 255), 1, LINE_AA);//plines[0],[1]为第一个点、plines[2][3]是第二个点
		//circle(srcImage_roi, Point(plines[0], plines[1]), 1, Scalar(230, 255, 255), 0.01, LINE_AA, 0);
	}
	int  anglenum = 0;  //角数
	double angleall = 0; //角度
	Mat DelSrcroiImage;
	srcImage_roi.copyTo(DelSrcroiImage);//copyTo=clone();
	for (size_t j = 0; j < lines.size(); j++)
	{
		Vec4d l = lines[j];
		if (l[0] != l[2] && l[1] != l[3])
		{
			anglenum++;
			Point start = Point(l[0], l[1]); //两点确定一条直线
			Point end = Point(l[2], l[3]);
			line(DelSrcroiImage, start, end, Scalar(255, 0, 0));//画出直线
			double  diagonal_line = l[1] - l[3]; //y
			double Rimmed = l[2] - l[0];//x
			double  radian = atan(diagonal_line / Rimmed); //tan
			double  angle = (radian * 180) / CV_PI; //转换成角度
			angleall = angleall + angle;
		}
	}
	double angleaverage = angleall / anglenum;
	if (angleaverage < 0)  //角度小于0,左边下边
	{
		putText(DelSrcroiImage, "bottom left", Point(30, 300), FONT_HERSHEY_SIMPLEX, 1, Scalar(255, 255, 255), 2, 8);
		imshow("向下左", DelSrcroiImage);
		waitKey(0);
		return 0;
	}