opencv 简单的实现HoughLinesP

//两点之间的距离
double juli(int x1,int y1,int x2,int y2)
{
	return sqrt(double((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)));
}
//输入经过霍夫变换得到的直线  存储起点和终点的vector  直线最短距离  点之间间隔最长距离
void HoughLinesP(Mat &img,vector<Vec2f> &lines,vector<Vec4i> &points, double minLineLength=0,double maxLineGap=1)
{
	Vec4i point;
	uchar *p; 
	float r,theta;
	bool start,end;
	int x,y;

	for(size_t i = 0;i < lines.size(); i++)
	{
		r = lines[i][0];
		theta = lines[i][1];
		start = false;
		end = false;
		//水平 极径与x轴90 直线与x轴0
		if(sin(theta) > 0.99999)
		{
			y = cvRound(r);
			p = img.ptr<uchar>(y);
			for(x = 0; x < img.cols; x++)
			{
				if( (p[x] != 0) || (x == img.cols - 1) )
				{
					//起点
					if(start == false)
					{
						point[0] = x;
						point[1] = y;
						start = true;
						continue;
					}
					//终点
					if(end == false)
					{
						//初始一个终点
						if(juli(point[0],point[1],x,y) <= maxLineGap)
						{
							point[2] = x;
							point[3] = y;
							end = true;
						}
						//不符合则重新确立起点
						else
						{
							point[0] = x;
							point[1] = y;
						}
						continue;
					}
					//移动终点
					if(juli(point[2],point[3],x,y) <= maxLineGap)
					{
						point[2] = x;
						point[3] = y;
					}
					else
					{
						//确定一条直线
						if(juli(point[0],point[1],point[2],point[3]) >= minLineLength)
						{
							points.push_back(point);
						}
						start = false;
						end = false;
					}
				}
			}
		}
		else
		{
			for(y = 0; y < img.rows; y++)
			{
				x = cvRound((r-y*sin(theta))/cos(theta));
				p = img.ptr<uchar>(y);
				if( (p[x] != 0) || (y == img.rows - 1) )
				{
					//起点
					if(start == false)
					{
						point[0] = x;
						point[1] = y;
						start = true;
						continue;
					}
					//终点
					if(end == false)
					{
						//初始一个终点
						if(juli(point[0],point[1],x,y) <= maxLineGap)
						{
							point[2] = x;
							point[3] = y;
							end = true;
						}
						//不符合则重新确立起点
						else
						{
							point[0] = x;
							point[1] = y;
						}
						continue;
					}
					//移动终点
					if(juli(point[2],point[3],x,y) <= maxLineGap)
					{
						point[2] = x;
						point[3] = y;
					}
					else
					{
						//确定一条直线
						if(juli(point[0],point[1],point[2],point[3]) >= minLineLength)
						{
							points.push_back(point);
						}
						start = false;
						end = false;
					}
				}
			}
		}
	}
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大米粥哥哥

感谢认可!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值