// 5. 用直线拟合一组点------------------------------------------------------
cv::Mat image = cv::imread("../../aTestImage/road2.jpg", 0);//Building
cv::Mat contours;
//阈值1:确定应该包含所有认为是属于明显图像轮廓的边缘像素
//阈值2:定义属于所有重要边缘,剔除异常值(不连续边缘点)
//磁滞阈值化
cv::Canny(image, contours, 125, 350);//主体为白色
cv::namedWindow("contours", 1);
cv::imshow("contours", contours);
LinesFinder finder;
finder.setLineLengthAndGap(100, 20);
finder.setMinVote(80);
//cv::Vec4i : (x0,y0, x1,y1)
std::vector lines = finder.findLines(contours);
int n = 1;//选择contours中的一条线: 如第2条
cv::Mat oneline(contours.size(), CV_8U, cv::Scalar(0));
cv::line(oneline, cv::Point(lines[n][0], lines[n][1]),
cv::Point(lines[n][2], lines[n][3]), cv::Scalar(255), 10);
cv::bitwise_and(contours, oneline, oneline);// 跟轮廓contours作 与 运算
cv::namedWindow("oneline", 1);
cv::imshow("oneline", oneline);
//将oneline中的点放入到cv::points集合中
std::vector points;
for (int y = 0; y < oneline.rows; y++)
{
uchar *rowPtr = oneline.ptr(y);
for (int x = 0; x < oneline.cols; x++)
{
if (rowPtr[x])
{
points.push_back(cv::Point(x, y));
}
}
}
//使用cv::fitline函数 将点数组 拟合成直线
cv::Vec4f line; //(cos, sin, x0,y0)
cv::fitLine(cv::Mat(points), line, CV_DIST_L2, 0, 0.01, 0.01);
std::cout
关注
打赏